您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

federation.py 82 KiB

5 年前
5 年前
Stop getting missing `prev_events` after we already know their signature is invalid (#13816) While https://github.com/matrix-org/synapse/pull/13635 stops us from doing the slow thing after we've already done it once, this PR stops us from doing one of the slow things in the first place. Related to - https://github.com/matrix-org/synapse/issues/13622 - https://github.com/matrix-org/synapse/pull/13635 - https://github.com/matrix-org/synapse/issues/13676 Part of https://github.com/matrix-org/synapse/issues/13356 Follow-up to https://github.com/matrix-org/synapse/pull/13815 which tracks event signature failures. With this PR, we avoid the call to the costly `_get_state_ids_after_missing_prev_event` because the signature failure will count as an attempt before and we filter events based on the backoff before calling `_get_state_ids_after_missing_prev_event` now. For example, this will save us 156s out of the 185s total that this `matrix.org` `/messages` request. If you want to see the full Jaeger trace of this, you can drag and drop this `trace.json` into your own Jaeger, https://gist.github.com/MadLittleMods/4b12d0d0afe88c2f65ffcc907306b761 To explain this exact scenario around `/messages` -> backfill, we call `/backfill` and first check the signatures of the 100 events. We see bad signature for `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` and `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` (both member events). Then we process the 98 events remaining that have valid signatures but one of the events references `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` as a `prev_event`. So we have to do the whole `_get_state_ids_after_missing_prev_event` rigmarole which pulls in those same events which fail again because the signatures are still invalid. - `backfill` - `outgoing-federation-request` `/backfill` - `_check_sigs_and_hash_and_fetch` - `_check_sigs_and_hash_and_fetch_one` for each event received over backfill - ❗ `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` fails with `Signature on retrieved event was invalid.`: `unable to verify signature for sender domain xxx: 401: Failed to find any key to satisfy: _FetchKeyRequest(...)` - ❗ `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` fails with `Signature on retrieved event was invalid.`: `unable to verify signature for sender domain xxx: 401: Failed to find any key to satisfy: _FetchKeyRequest(...)` - `_process_pulled_events` - `_process_pulled_event` for each validated event - ❗ Event `$Q0iMdqtz3IJYfZQU2Xk2WjB5NDF8Gg8cFSYYyKQgKJ0` references `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` as a `prev_event` which is missing so we try to get it - `_get_state_ids_after_missing_prev_event` - `outgoing-federation-request` `/state_ids` - ❗ `get_pdu` for `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` which fails the signature check again - ❗ `get_pdu` for `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` which fails the signature check
1年前
5 年前
5 年前
Handle race between persisting an event and un-partial stating a room (#13100) Whenever we want to persist an event, we first compute an event context, which includes the state at the event and a flag indicating whether the state is partial. After a lot of processing, we finally try to store the event in the database, which can fail for partial state events when the containing room has been un-partial stated in the meantime. We detect the race as a foreign key constraint failure in the data store layer and turn it into a special `PartialStateConflictError` exception, which makes its way up to the method in which we computed the event context. To make things difficult, the exception needs to cross a replication request: `/fed_send_events` for events coming over federation and `/send_event` for events from clients. We transport the `PartialStateConflictError` as a `409 Conflict` over replication and turn `409`s back into `PartialStateConflictError`s on the worker making the request. All client events go through `EventCreationHandler.handle_new_client_event`, which is called in *a lot* of places. Instead of trying to update all the code which creates client events, we turn the `PartialStateConflictError` into a `429 Too Many Requests` in `EventCreationHandler.handle_new_client_event` and hope that clients take it as a hint to retry their request. On the federation event side, there are 7 places which compute event contexts. 4 of them use outlier event contexts: `FederationEventHandler._auth_and_persist_outliers_inner`, `FederationHandler.do_knock`, `FederationHandler.on_invite_request` and `FederationHandler.do_remotely_reject_invite`. These events won't have the partial state flag, so we do not need to do anything for then. The remaining 3 paths which create events are `FederationEventHandler.process_remote_join`, `FederationEventHandler.on_send_membership_event` and `FederationEventHandler._process_received_pdu`. We can't experience the race in `process_remote_join`, unless we're handling an additional join into a partial state room, which currently blocks, so we make no attempt to handle it correctly. `on_send_membership_event` is only called by `FederationServer._on_send_membership_event`, so we catch the `PartialStateConflictError` there and retry just once. `_process_received_pdu` is called by `on_receive_pdu` for incoming events and `_process_pulled_event` for backfill. The latter should never try to persist partial state events, so we ignore it. We catch the `PartialStateConflictError` in `on_receive_pdu` and retry just once. Refering to the graph of code paths in https://github.com/matrix-org/synapse/issues/12988#issuecomment-1156857648 may make the above make more sense. Signed-off-by: Sean Quah <seanq@matrix.org>
1年前
Optimize how we calculate `likely_domains` during backfill (#13575) Optimize how we calculate `likely_domains` during backfill because I've seen this take 17s in production just to `get_current_state` which is used to `get_domains_from_state` (see case [*2. Loading tons of events* in the `/messages` investigation issue](https://github.com/matrix-org/synapse/issues/13356)). There are 3 ways we currently calculate hosts that are in the room: 1. `get_current_state` -> `get_domains_from_state` - Used in `backfill` to calculate `likely_domains` and `/timestamp_to_event` because it was cargo-culted from `backfill` - This one is being eliminated in favor of `get_current_hosts_in_room` in this PR 🕳 1. `get_current_hosts_in_room` - Used for other federation things like sending read receipts and typing indicators 1. `get_hosts_in_room_at_events` - Used when pushing out events over federation to other servers in the `_process_event_queue_loop` Fix https://github.com/matrix-org/synapse/issues/13626 Part of https://github.com/matrix-org/synapse/issues/13356 Mentioned in [internal doc](https://docs.google.com/document/d/1lvUoVfYUiy6UaHB6Rb4HicjaJAU40-APue9Q4vzuW3c/edit#bookmark=id.2tvwz3yhcafh) ### Query performance #### Before The query from `get_current_state` sucks just because we have to get all 80k events. And we see almost the exact same performance locally trying to get all of these events (16s vs 17s): ``` synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 16035.612 ms (00:16.036) synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 4243.237 ms (00:04.243) ``` But what about `get_current_hosts_in_room`: When there is 8M rows in the `current_state_events` table, the previous query in `get_current_hosts_in_room` took 13s from complete freshness (when the events were first added). But takes 930ms after a Postgres restart or 390ms if running back to back to back. ```sh $ psql synapse synapse=# \timing on synapse=# SELECT COUNT(DISTINCT substring(state_key FROM '@[^:]*:(.*)$')) FROM current_state_events WHERE type = 'm.room.member' AND membership = 'join' AND room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 4130 (1 row) Time: 13181.598 ms (00:13.182) synapse=# SELECT COUNT(*) from current_state_events where room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 80814 synapse=# SELECT COUNT(*) from current_state_events; count --------- 8162847 synapse=# SELECT pg_size_pretty( pg_total_relation_size('current_state_events') ); pg_size_pretty ---------------- 4702 MB ``` #### After I'm not sure how long it takes from complete freshness as I only really get that opportunity once (maybe restarting computer but that's cumbersome) and it's not really relevant to normal operating times. Maybe you get closer to the fresh times the more access variability there is so that Postgres caches aren't as exact. Update: The longest I've seen this run for is 6.4s and 4.5s after a computer restart. After a Postgres restart, it takes 330ms and running back to back takes 260ms. ```sh $ psql synapse synapse=# \timing on Timing is on. synapse=# SELECT substring(c.state_key FROM '@[^:]*:(.*)$') as host FROM current_state_events c /* Get the depth of the event from the events table */ INNER JOIN events AS e USING (event_id) WHERE c.type = 'm.room.member' AND c.membership = 'join' AND c.room_id = '!OGEhHVWSdvArJzumhm:matrix.org' GROUP BY host ORDER BY min(e.depth) ASC; Time: 333.800 ms ``` #### Going further To improve things further we could add a `limit` parameter to `get_current_hosts_in_room`. Realistically, we don't need 4k domains to choose from because there is no way we're going to query that many before we a) probably get an answer or b) we give up. Another thing we can do is optimize the query to use a index skip scan: - https://wiki.postgresql.org/wiki/Loose_indexscan - Index Skip Scan, https://commitfest.postgresql.org/37/1741/ - https://www.timescale.com/blog/how-we-made-distinct-queries-up-to-8000x-faster-on-postgresql/
1年前
Fix historical messages backfilling in random order on remote homeservers (MSC2716) (#11114) Fix https://github.com/matrix-org/synapse/issues/11091 Fix https://github.com/matrix-org/synapse/issues/10764 (side-stepping the issue because we no longer have to deal with `fake_prev_event_id`) 1. Made the `/backfill` response return messages in `(depth, stream_ordering)` order (previously only sorted by `depth`) - Technically, it shouldn't really matter how `/backfill` returns things but I'm just trying to make the `stream_ordering` a little more consistent from the origin to the remote homeservers in order to get the order of messages from `/messages` consistent ([sorted by `(topological_ordering, stream_ordering)`](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)). - Even now that we return backfilled messages in order, it still doesn't guarantee the same `stream_ordering` (and more importantly the [`/messages` order](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)) on the other server. For example, if a room has a bunch of history imported and someone visits a permalink to a historical message back in time, their homeserver will skip over the historical messages in between and insert the permalink as the next message in the `stream_order` and totally throw off the sort. - This will be even more the case when we add the [MSC3030 jump to date API endpoint](https://github.com/matrix-org/matrix-doc/pull/3030) so the static archives can navigate and jump to a certain date. - We're solving this in the future by switching to [online topological ordering](https://github.com/matrix-org/gomatrixserverlib/issues/187) and [chunking](https://github.com/matrix-org/synapse/issues/3785) which by its nature will apply retroactively to fix any inconsistencies introduced by people permalinking 2. As we're navigating `prev_events` to return in `/backfill`, we order by `depth` first (newest -> oldest) and now also tie-break based on the `stream_ordering` (newest -> oldest). This is technically important because MSC2716 inserts a bunch of historical messages at the same `depth` so it's best to be prescriptive about which ones we should process first. In reality, I think the code already looped over the historical messages as expected because the database is already in order. 3. Making the historical state chain and historical event chain float on their own by having no `prev_events` instead of a fake `prev_event` which caused backfill to get clogged with an unresolvable event. Fixes https://github.com/matrix-org/synapse/issues/11091 and https://github.com/matrix-org/synapse/issues/10764 4. We no longer find connected insertion events by finding a potential `prev_event` connection to the current event we're iterating over. We now solely rely on marker events which when processed, add the insertion event as an extremity and the federating homeserver can ask about it when time calls. - Related discussion, https://github.com/matrix-org/synapse/pull/11114#discussion_r741514793 Before | After --- | --- ![](https://user-images.githubusercontent.com/558581/139218681-b465c862-5c49-4702-a59e-466733b0cf45.png) | ![](https://user-images.githubusercontent.com/558581/146453159-a1609e0a-8324-439d-ae44-e4bce43ac6d1.png) #### Why aren't we sorting topologically when receiving backfill events? > The main reason we're going to opt to not sort topologically when receiving backfill events is because it's probably best to do whatever is easiest to make it just work. People will probably have opinions once they look at [MSC2716](https://github.com/matrix-org/matrix-doc/pull/2716) which could change whatever implementation anyway. > > As mentioned, ideally we would do this but code necessary to make the fake edges but it gets confusing and gives an impression of “just whyyyy” (feels icky). This problem also dissolves with online topological ordering. > > -- https://github.com/matrix-org/synapse/pull/11114#discussion_r741517138 See https://github.com/matrix-org/synapse/pull/11114#discussion_r739610091 for the technical difficulties
2 年前
Fix historical messages backfilling in random order on remote homeservers (MSC2716) (#11114) Fix https://github.com/matrix-org/synapse/issues/11091 Fix https://github.com/matrix-org/synapse/issues/10764 (side-stepping the issue because we no longer have to deal with `fake_prev_event_id`) 1. Made the `/backfill` response return messages in `(depth, stream_ordering)` order (previously only sorted by `depth`) - Technically, it shouldn't really matter how `/backfill` returns things but I'm just trying to make the `stream_ordering` a little more consistent from the origin to the remote homeservers in order to get the order of messages from `/messages` consistent ([sorted by `(topological_ordering, stream_ordering)`](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)). - Even now that we return backfilled messages in order, it still doesn't guarantee the same `stream_ordering` (and more importantly the [`/messages` order](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)) on the other server. For example, if a room has a bunch of history imported and someone visits a permalink to a historical message back in time, their homeserver will skip over the historical messages in between and insert the permalink as the next message in the `stream_order` and totally throw off the sort. - This will be even more the case when we add the [MSC3030 jump to date API endpoint](https://github.com/matrix-org/matrix-doc/pull/3030) so the static archives can navigate and jump to a certain date. - We're solving this in the future by switching to [online topological ordering](https://github.com/matrix-org/gomatrixserverlib/issues/187) and [chunking](https://github.com/matrix-org/synapse/issues/3785) which by its nature will apply retroactively to fix any inconsistencies introduced by people permalinking 2. As we're navigating `prev_events` to return in `/backfill`, we order by `depth` first (newest -> oldest) and now also tie-break based on the `stream_ordering` (newest -> oldest). This is technically important because MSC2716 inserts a bunch of historical messages at the same `depth` so it's best to be prescriptive about which ones we should process first. In reality, I think the code already looped over the historical messages as expected because the database is already in order. 3. Making the historical state chain and historical event chain float on their own by having no `prev_events` instead of a fake `prev_event` which caused backfill to get clogged with an unresolvable event. Fixes https://github.com/matrix-org/synapse/issues/11091 and https://github.com/matrix-org/synapse/issues/10764 4. We no longer find connected insertion events by finding a potential `prev_event` connection to the current event we're iterating over. We now solely rely on marker events which when processed, add the insertion event as an extremity and the federating homeserver can ask about it when time calls. - Related discussion, https://github.com/matrix-org/synapse/pull/11114#discussion_r741514793 Before | After --- | --- ![](https://user-images.githubusercontent.com/558581/139218681-b465c862-5c49-4702-a59e-466733b0cf45.png) | ![](https://user-images.githubusercontent.com/558581/146453159-a1609e0a-8324-439d-ae44-e4bce43ac6d1.png) #### Why aren't we sorting topologically when receiving backfill events? > The main reason we're going to opt to not sort topologically when receiving backfill events is because it's probably best to do whatever is easiest to make it just work. People will probably have opinions once they look at [MSC2716](https://github.com/matrix-org/matrix-doc/pull/2716) which could change whatever implementation anyway. > > As mentioned, ideally we would do this but code necessary to make the fake edges but it gets confusing and gives an impression of “just whyyyy” (feels icky). This problem also dissolves with online topological ordering. > > -- https://github.com/matrix-org/synapse/pull/11114#discussion_r741517138 See https://github.com/matrix-org/synapse/pull/11114#discussion_r739610091 for the technical difficulties
2 年前
Fix historical messages backfilling in random order on remote homeservers (MSC2716) (#11114) Fix https://github.com/matrix-org/synapse/issues/11091 Fix https://github.com/matrix-org/synapse/issues/10764 (side-stepping the issue because we no longer have to deal with `fake_prev_event_id`) 1. Made the `/backfill` response return messages in `(depth, stream_ordering)` order (previously only sorted by `depth`) - Technically, it shouldn't really matter how `/backfill` returns things but I'm just trying to make the `stream_ordering` a little more consistent from the origin to the remote homeservers in order to get the order of messages from `/messages` consistent ([sorted by `(topological_ordering, stream_ordering)`](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)). - Even now that we return backfilled messages in order, it still doesn't guarantee the same `stream_ordering` (and more importantly the [`/messages` order](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)) on the other server. For example, if a room has a bunch of history imported and someone visits a permalink to a historical message back in time, their homeserver will skip over the historical messages in between and insert the permalink as the next message in the `stream_order` and totally throw off the sort. - This will be even more the case when we add the [MSC3030 jump to date API endpoint](https://github.com/matrix-org/matrix-doc/pull/3030) so the static archives can navigate and jump to a certain date. - We're solving this in the future by switching to [online topological ordering](https://github.com/matrix-org/gomatrixserverlib/issues/187) and [chunking](https://github.com/matrix-org/synapse/issues/3785) which by its nature will apply retroactively to fix any inconsistencies introduced by people permalinking 2. As we're navigating `prev_events` to return in `/backfill`, we order by `depth` first (newest -> oldest) and now also tie-break based on the `stream_ordering` (newest -> oldest). This is technically important because MSC2716 inserts a bunch of historical messages at the same `depth` so it's best to be prescriptive about which ones we should process first. In reality, I think the code already looped over the historical messages as expected because the database is already in order. 3. Making the historical state chain and historical event chain float on their own by having no `prev_events` instead of a fake `prev_event` which caused backfill to get clogged with an unresolvable event. Fixes https://github.com/matrix-org/synapse/issues/11091 and https://github.com/matrix-org/synapse/issues/10764 4. We no longer find connected insertion events by finding a potential `prev_event` connection to the current event we're iterating over. We now solely rely on marker events which when processed, add the insertion event as an extremity and the federating homeserver can ask about it when time calls. - Related discussion, https://github.com/matrix-org/synapse/pull/11114#discussion_r741514793 Before | After --- | --- ![](https://user-images.githubusercontent.com/558581/139218681-b465c862-5c49-4702-a59e-466733b0cf45.png) | ![](https://user-images.githubusercontent.com/558581/146453159-a1609e0a-8324-439d-ae44-e4bce43ac6d1.png) #### Why aren't we sorting topologically when receiving backfill events? > The main reason we're going to opt to not sort topologically when receiving backfill events is because it's probably best to do whatever is easiest to make it just work. People will probably have opinions once they look at [MSC2716](https://github.com/matrix-org/matrix-doc/pull/2716) which could change whatever implementation anyway. > > As mentioned, ideally we would do this but code necessary to make the fake edges but it gets confusing and gives an impression of “just whyyyy” (feels icky). This problem also dissolves with online topological ordering. > > -- https://github.com/matrix-org/synapse/pull/11114#discussion_r741517138 See https://github.com/matrix-org/synapse/pull/11114#discussion_r739610091 for the technical difficulties
2 年前
Add support for MSC2716 marker events (#10498) * Make historical messages available to federated servers Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 Follow-up to https://github.com/matrix-org/synapse/pull/9247 * Debug message not available on federation * Add base starting insertion point when no chunk ID is provided * Fix messages from multiple senders in historical chunk Follow-up to https://github.com/matrix-org/synapse/pull/9247 Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 --- Previously, Synapse would throw a 403, `Cannot force another user to join.`, because we were trying to use `?user_id` from a single virtual user which did not match with messages from other users in the chunk. * Remove debug lines * Messing with selecting insertion event extremeties * Move db schema change to new version * Add more better comments * Make a fake requester with just what we need See https://github.com/matrix-org/synapse/pull/10276#discussion_r660999080 * Store insertion events in table * Make base insertion event float off on its own See https://github.com/matrix-org/synapse/pull/10250#issuecomment-875711889 Conflicts: synapse/rest/client/v1/room.py * Validate that the app service can actually control the given user See https://github.com/matrix-org/synapse/pull/10276#issuecomment-876316455 Conflicts: synapse/rest/client/v1/room.py * Add some better comments on what we're trying to check for * Continue debugging * Share validation logic * Add inserted historical messages to /backfill response * Remove debug sql queries * Some marker event implemntation trials * Clean up PR * Rename insertion_event_id to just event_id * Add some better sql comments * More accurate description * Add changelog * Make it clear what MSC the change is part of * Add more detail on which insertion event came through * Address review and improve sql queries * Only use event_id as unique constraint * Fix test case where insertion event is already in the normal DAG * Remove debug changes * Add support for MSC2716 marker events * Process markers when we receive it over federation * WIP: make hs2 backfill historical messages after marker event * hs2 to better ask for insertion event extremity But running into the `sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group` error * Add insertion_event_extremities table * Switch to chunk events so we can auth via power_levels Previously, we were using `content.chunk_id` to connect one chunk to another. But these events can be from any `sender` and we can't tell who should be able to send historical events. We know we only want the application service to do it but these events have the sender of a real historical message, not the application service user ID as the sender. Other federated homeservers also have no indicator which senders are an application service on the originating homeserver. So we want to auth all of the MSC2716 events via power_levels and have them be sent by the application service with proper PL levels in the room. * Switch to chunk events for federation * Add unstable room version to support new historical PL * Messy: Fix undefined state_group for federated historical events ``` 2021-07-13 02:27:57,810 - synapse.handlers.federation - 1248 - ERROR - GET-4 - Failed to backfill from hs1 because NOT NULL constraint failed: event_to_state_groups.state_group Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1216, in try_backfill await self.backfill( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1035, in backfill await self._auth_and_persist_event(dest, event, context, backfilled=True) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2222, in _auth_and_persist_event await self._run_push_actions_and_persist_event(event, context, backfilled) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2244, in _run_push_actions_and_persist_event await self.persist_events_and_notify( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 3290, in persist_events_and_notify events, max_stream_token = await self.storage.persistence.persist_events( File "/usr/local/lib/python3.8/site-packages/synapse/logging/opentracing.py", line 774, in _trace_inner return await func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 320, in persist_events ret_vals = await yieldable_gather_results(enqueue, partitioned.items()) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 237, in handle_queue_loop ret = await self._per_item_callback( File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 577, in _persist_event_batch await self.persist_events_store._persist_events_and_state_updates( File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 176, in _persist_events_and_state_updates await self.db_pool.runInteraction( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 681, in runInteraction result = await self.runWithConnection( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 770, in runWithConnection return await make_deferred_yieldable( File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 238, in inContext result = inContext.theWork() # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 254, in <lambda> inContext.theWork = lambda: context.call( # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 118, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 83, in callWithContext return func(*args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 293, in _runWithConnection compat.reraise(excValue, excTraceback) File "/usr/local/lib/python3.8/site-packages/twisted/python/deprecate.py", line 298, in deprecatedFunction return function(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/twisted/python/compat.py", line 403, in reraise raise exception.with_traceback(traceback) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 284, in _runWithConnection result = func(conn, *args, **kw) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 765, in inner_func return func(db_conn, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 549, in new_transaction r = func(cursor, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/logging/utils.py", line 69, in wrapped return f(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 385, in _persist_events_txn self._store_event_state_mappings_txn(txn, events_and_contexts) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 2065, in _store_event_state_mappings_txn self.db_pool.simple_insert_many_txn( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 923, in simple_insert_many_txn txn.execute_batch(sql, vals) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 280, in execute_batch self.executemany(sql, args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 300, in executemany self._do_execute(self.txn.executemany, sql, *args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 330, in _do_execute return func(sql, *args) sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group ``` * Revert "Messy: Fix undefined state_group for federated historical events" This reverts commit 187ab28611546321e02770944c86f30ee2bc742a. * Fix federated events being rejected for no state_groups Add fix from https://github.com/matrix-org/synapse/pull/10439 until it merges. * Adapting to experimental room version * Some log cleanup * Add better comments around extremity fetching code and why * Rename to be more accurate to what the function returns * Add changelog * Ignore rejected events * Use simplified upsert * Add Erik's explanation of extra event checks See https://github.com/matrix-org/synapse/pull/10498#discussion_r680880332 * Clarify that the depth is not directly correlated to the backwards extremity that we return See https://github.com/matrix-org/synapse/pull/10498#discussion_r681725404 * lock only matters for sqlite See https://github.com/matrix-org/synapse/pull/10498#discussion_r681728061 * Move new SQL changes to its own delta file * Clean up upsert docstring * Bump database schema version (62)
2 年前
Add support for MSC2716 marker events (#10498) * Make historical messages available to federated servers Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 Follow-up to https://github.com/matrix-org/synapse/pull/9247 * Debug message not available on federation * Add base starting insertion point when no chunk ID is provided * Fix messages from multiple senders in historical chunk Follow-up to https://github.com/matrix-org/synapse/pull/9247 Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 --- Previously, Synapse would throw a 403, `Cannot force another user to join.`, because we were trying to use `?user_id` from a single virtual user which did not match with messages from other users in the chunk. * Remove debug lines * Messing with selecting insertion event extremeties * Move db schema change to new version * Add more better comments * Make a fake requester with just what we need See https://github.com/matrix-org/synapse/pull/10276#discussion_r660999080 * Store insertion events in table * Make base insertion event float off on its own See https://github.com/matrix-org/synapse/pull/10250#issuecomment-875711889 Conflicts: synapse/rest/client/v1/room.py * Validate that the app service can actually control the given user See https://github.com/matrix-org/synapse/pull/10276#issuecomment-876316455 Conflicts: synapse/rest/client/v1/room.py * Add some better comments on what we're trying to check for * Continue debugging * Share validation logic * Add inserted historical messages to /backfill response * Remove debug sql queries * Some marker event implemntation trials * Clean up PR * Rename insertion_event_id to just event_id * Add some better sql comments * More accurate description * Add changelog * Make it clear what MSC the change is part of * Add more detail on which insertion event came through * Address review and improve sql queries * Only use event_id as unique constraint * Fix test case where insertion event is already in the normal DAG * Remove debug changes * Add support for MSC2716 marker events * Process markers when we receive it over federation * WIP: make hs2 backfill historical messages after marker event * hs2 to better ask for insertion event extremity But running into the `sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group` error * Add insertion_event_extremities table * Switch to chunk events so we can auth via power_levels Previously, we were using `content.chunk_id` to connect one chunk to another. But these events can be from any `sender` and we can't tell who should be able to send historical events. We know we only want the application service to do it but these events have the sender of a real historical message, not the application service user ID as the sender. Other federated homeservers also have no indicator which senders are an application service on the originating homeserver. So we want to auth all of the MSC2716 events via power_levels and have them be sent by the application service with proper PL levels in the room. * Switch to chunk events for federation * Add unstable room version to support new historical PL * Messy: Fix undefined state_group for federated historical events ``` 2021-07-13 02:27:57,810 - synapse.handlers.federation - 1248 - ERROR - GET-4 - Failed to backfill from hs1 because NOT NULL constraint failed: event_to_state_groups.state_group Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1216, in try_backfill await self.backfill( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1035, in backfill await self._auth_and_persist_event(dest, event, context, backfilled=True) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2222, in _auth_and_persist_event await self._run_push_actions_and_persist_event(event, context, backfilled) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2244, in _run_push_actions_and_persist_event await self.persist_events_and_notify( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 3290, in persist_events_and_notify events, max_stream_token = await self.storage.persistence.persist_events( File "/usr/local/lib/python3.8/site-packages/synapse/logging/opentracing.py", line 774, in _trace_inner return await func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 320, in persist_events ret_vals = await yieldable_gather_results(enqueue, partitioned.items()) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 237, in handle_queue_loop ret = await self._per_item_callback( File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 577, in _persist_event_batch await self.persist_events_store._persist_events_and_state_updates( File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 176, in _persist_events_and_state_updates await self.db_pool.runInteraction( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 681, in runInteraction result = await self.runWithConnection( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 770, in runWithConnection return await make_deferred_yieldable( File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 238, in inContext result = inContext.theWork() # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 254, in <lambda> inContext.theWork = lambda: context.call( # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 118, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 83, in callWithContext return func(*args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 293, in _runWithConnection compat.reraise(excValue, excTraceback) File "/usr/local/lib/python3.8/site-packages/twisted/python/deprecate.py", line 298, in deprecatedFunction return function(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/twisted/python/compat.py", line 403, in reraise raise exception.with_traceback(traceback) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 284, in _runWithConnection result = func(conn, *args, **kw) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 765, in inner_func return func(db_conn, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 549, in new_transaction r = func(cursor, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/logging/utils.py", line 69, in wrapped return f(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 385, in _persist_events_txn self._store_event_state_mappings_txn(txn, events_and_contexts) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 2065, in _store_event_state_mappings_txn self.db_pool.simple_insert_many_txn( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 923, in simple_insert_many_txn txn.execute_batch(sql, vals) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 280, in execute_batch self.executemany(sql, args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 300, in executemany self._do_execute(self.txn.executemany, sql, *args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 330, in _do_execute return func(sql, *args) sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group ``` * Revert "Messy: Fix undefined state_group for federated historical events" This reverts commit 187ab28611546321e02770944c86f30ee2bc742a. * Fix federated events being rejected for no state_groups Add fix from https://github.com/matrix-org/synapse/pull/10439 until it merges. * Adapting to experimental room version * Some log cleanup * Add better comments around extremity fetching code and why * Rename to be more accurate to what the function returns * Add changelog * Ignore rejected events * Use simplified upsert * Add Erik's explanation of extra event checks See https://github.com/matrix-org/synapse/pull/10498#discussion_r680880332 * Clarify that the depth is not directly correlated to the backwards extremity that we return See https://github.com/matrix-org/synapse/pull/10498#discussion_r681725404 * lock only matters for sqlite See https://github.com/matrix-org/synapse/pull/10498#discussion_r681728061 * Move new SQL changes to its own delta file * Clean up upsert docstring * Bump database schema version (62)
2 年前
Add support for MSC2716 marker events (#10498) * Make historical messages available to federated servers Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 Follow-up to https://github.com/matrix-org/synapse/pull/9247 * Debug message not available on federation * Add base starting insertion point when no chunk ID is provided * Fix messages from multiple senders in historical chunk Follow-up to https://github.com/matrix-org/synapse/pull/9247 Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 --- Previously, Synapse would throw a 403, `Cannot force another user to join.`, because we were trying to use `?user_id` from a single virtual user which did not match with messages from other users in the chunk. * Remove debug lines * Messing with selecting insertion event extremeties * Move db schema change to new version * Add more better comments * Make a fake requester with just what we need See https://github.com/matrix-org/synapse/pull/10276#discussion_r660999080 * Store insertion events in table * Make base insertion event float off on its own See https://github.com/matrix-org/synapse/pull/10250#issuecomment-875711889 Conflicts: synapse/rest/client/v1/room.py * Validate that the app service can actually control the given user See https://github.com/matrix-org/synapse/pull/10276#issuecomment-876316455 Conflicts: synapse/rest/client/v1/room.py * Add some better comments on what we're trying to check for * Continue debugging * Share validation logic * Add inserted historical messages to /backfill response * Remove debug sql queries * Some marker event implemntation trials * Clean up PR * Rename insertion_event_id to just event_id * Add some better sql comments * More accurate description * Add changelog * Make it clear what MSC the change is part of * Add more detail on which insertion event came through * Address review and improve sql queries * Only use event_id as unique constraint * Fix test case where insertion event is already in the normal DAG * Remove debug changes * Add support for MSC2716 marker events * Process markers when we receive it over federation * WIP: make hs2 backfill historical messages after marker event * hs2 to better ask for insertion event extremity But running into the `sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group` error * Add insertion_event_extremities table * Switch to chunk events so we can auth via power_levels Previously, we were using `content.chunk_id` to connect one chunk to another. But these events can be from any `sender` and we can't tell who should be able to send historical events. We know we only want the application service to do it but these events have the sender of a real historical message, not the application service user ID as the sender. Other federated homeservers also have no indicator which senders are an application service on the originating homeserver. So we want to auth all of the MSC2716 events via power_levels and have them be sent by the application service with proper PL levels in the room. * Switch to chunk events for federation * Add unstable room version to support new historical PL * Messy: Fix undefined state_group for federated historical events ``` 2021-07-13 02:27:57,810 - synapse.handlers.federation - 1248 - ERROR - GET-4 - Failed to backfill from hs1 because NOT NULL constraint failed: event_to_state_groups.state_group Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1216, in try_backfill await self.backfill( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1035, in backfill await self._auth_and_persist_event(dest, event, context, backfilled=True) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2222, in _auth_and_persist_event await self._run_push_actions_and_persist_event(event, context, backfilled) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2244, in _run_push_actions_and_persist_event await self.persist_events_and_notify( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 3290, in persist_events_and_notify events, max_stream_token = await self.storage.persistence.persist_events( File "/usr/local/lib/python3.8/site-packages/synapse/logging/opentracing.py", line 774, in _trace_inner return await func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 320, in persist_events ret_vals = await yieldable_gather_results(enqueue, partitioned.items()) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 237, in handle_queue_loop ret = await self._per_item_callback( File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 577, in _persist_event_batch await self.persist_events_store._persist_events_and_state_updates( File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 176, in _persist_events_and_state_updates await self.db_pool.runInteraction( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 681, in runInteraction result = await self.runWithConnection( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 770, in runWithConnection return await make_deferred_yieldable( File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 238, in inContext result = inContext.theWork() # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 254, in <lambda> inContext.theWork = lambda: context.call( # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 118, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 83, in callWithContext return func(*args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 293, in _runWithConnection compat.reraise(excValue, excTraceback) File "/usr/local/lib/python3.8/site-packages/twisted/python/deprecate.py", line 298, in deprecatedFunction return function(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/twisted/python/compat.py", line 403, in reraise raise exception.with_traceback(traceback) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 284, in _runWithConnection result = func(conn, *args, **kw) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 765, in inner_func return func(db_conn, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 549, in new_transaction r = func(cursor, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/logging/utils.py", line 69, in wrapped return f(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 385, in _persist_events_txn self._store_event_state_mappings_txn(txn, events_and_contexts) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 2065, in _store_event_state_mappings_txn self.db_pool.simple_insert_many_txn( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 923, in simple_insert_many_txn txn.execute_batch(sql, vals) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 280, in execute_batch self.executemany(sql, args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 300, in executemany self._do_execute(self.txn.executemany, sql, *args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 330, in _do_execute return func(sql, *args) sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group ``` * Revert "Messy: Fix undefined state_group for federated historical events" This reverts commit 187ab28611546321e02770944c86f30ee2bc742a. * Fix federated events being rejected for no state_groups Add fix from https://github.com/matrix-org/synapse/pull/10439 until it merges. * Adapting to experimental room version * Some log cleanup * Add better comments around extremity fetching code and why * Rename to be more accurate to what the function returns * Add changelog * Ignore rejected events * Use simplified upsert * Add Erik's explanation of extra event checks See https://github.com/matrix-org/synapse/pull/10498#discussion_r680880332 * Clarify that the depth is not directly correlated to the backwards extremity that we return See https://github.com/matrix-org/synapse/pull/10498#discussion_r681725404 * lock only matters for sqlite See https://github.com/matrix-org/synapse/pull/10498#discussion_r681728061 * Move new SQL changes to its own delta file * Clean up upsert docstring * Bump database schema version (62)
2 年前
Add support for MSC2716 marker events (#10498) * Make historical messages available to federated servers Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 Follow-up to https://github.com/matrix-org/synapse/pull/9247 * Debug message not available on federation * Add base starting insertion point when no chunk ID is provided * Fix messages from multiple senders in historical chunk Follow-up to https://github.com/matrix-org/synapse/pull/9247 Part of MSC2716: https://github.com/matrix-org/matrix-doc/pull/2716 --- Previously, Synapse would throw a 403, `Cannot force another user to join.`, because we were trying to use `?user_id` from a single virtual user which did not match with messages from other users in the chunk. * Remove debug lines * Messing with selecting insertion event extremeties * Move db schema change to new version * Add more better comments * Make a fake requester with just what we need See https://github.com/matrix-org/synapse/pull/10276#discussion_r660999080 * Store insertion events in table * Make base insertion event float off on its own See https://github.com/matrix-org/synapse/pull/10250#issuecomment-875711889 Conflicts: synapse/rest/client/v1/room.py * Validate that the app service can actually control the given user See https://github.com/matrix-org/synapse/pull/10276#issuecomment-876316455 Conflicts: synapse/rest/client/v1/room.py * Add some better comments on what we're trying to check for * Continue debugging * Share validation logic * Add inserted historical messages to /backfill response * Remove debug sql queries * Some marker event implemntation trials * Clean up PR * Rename insertion_event_id to just event_id * Add some better sql comments * More accurate description * Add changelog * Make it clear what MSC the change is part of * Add more detail on which insertion event came through * Address review and improve sql queries * Only use event_id as unique constraint * Fix test case where insertion event is already in the normal DAG * Remove debug changes * Add support for MSC2716 marker events * Process markers when we receive it over federation * WIP: make hs2 backfill historical messages after marker event * hs2 to better ask for insertion event extremity But running into the `sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group` error * Add insertion_event_extremities table * Switch to chunk events so we can auth via power_levels Previously, we were using `content.chunk_id` to connect one chunk to another. But these events can be from any `sender` and we can't tell who should be able to send historical events. We know we only want the application service to do it but these events have the sender of a real historical message, not the application service user ID as the sender. Other federated homeservers also have no indicator which senders are an application service on the originating homeserver. So we want to auth all of the MSC2716 events via power_levels and have them be sent by the application service with proper PL levels in the room. * Switch to chunk events for federation * Add unstable room version to support new historical PL * Messy: Fix undefined state_group for federated historical events ``` 2021-07-13 02:27:57,810 - synapse.handlers.federation - 1248 - ERROR - GET-4 - Failed to backfill from hs1 because NOT NULL constraint failed: event_to_state_groups.state_group Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1216, in try_backfill await self.backfill( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 1035, in backfill await self._auth_and_persist_event(dest, event, context, backfilled=True) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2222, in _auth_and_persist_event await self._run_push_actions_and_persist_event(event, context, backfilled) File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 2244, in _run_push_actions_and_persist_event await self.persist_events_and_notify( File "/usr/local/lib/python3.8/site-packages/synapse/handlers/federation.py", line 3290, in persist_events_and_notify events, max_stream_token = await self.storage.persistence.persist_events( File "/usr/local/lib/python3.8/site-packages/synapse/logging/opentracing.py", line 774, in _trace_inner return await func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 320, in persist_events ret_vals = await yieldable_gather_results(enqueue, partitioned.items()) File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 237, in handle_queue_loop ret = await self._per_item_callback( File "/usr/local/lib/python3.8/site-packages/synapse/storage/persist_events.py", line 577, in _persist_event_batch await self.persist_events_store._persist_events_and_state_updates( File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 176, in _persist_events_and_state_updates await self.db_pool.runInteraction( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 681, in runInteraction result = await self.runWithConnection( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 770, in runWithConnection return await make_deferred_yieldable( File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 238, in inContext result = inContext.theWork() # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/threadpool.py", line 254, in <lambda> inContext.theWork = lambda: context.call( # type: ignore[attr-defined] File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 118, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/python/context.py", line 83, in callWithContext return func(*args, **kw) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 293, in _runWithConnection compat.reraise(excValue, excTraceback) File "/usr/local/lib/python3.8/site-packages/twisted/python/deprecate.py", line 298, in deprecatedFunction return function(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/twisted/python/compat.py", line 403, in reraise raise exception.with_traceback(traceback) File "/usr/local/lib/python3.8/site-packages/twisted/enterprise/adbapi.py", line 284, in _runWithConnection result = func(conn, *args, **kw) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 765, in inner_func return func(db_conn, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 549, in new_transaction r = func(cursor, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/logging/utils.py", line 69, in wrapped return f(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 385, in _persist_events_txn self._store_event_state_mappings_txn(txn, events_and_contexts) File "/usr/local/lib/python3.8/site-packages/synapse/storage/databases/main/events.py", line 2065, in _store_event_state_mappings_txn self.db_pool.simple_insert_many_txn( File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 923, in simple_insert_many_txn txn.execute_batch(sql, vals) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 280, in execute_batch self.executemany(sql, args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 300, in executemany self._do_execute(self.txn.executemany, sql, *args) File "/usr/local/lib/python3.8/site-packages/synapse/storage/database.py", line 330, in _do_execute return func(sql, *args) sqlite3.IntegrityError: NOT NULL constraint failed: event_to_state_groups.state_group ``` * Revert "Messy: Fix undefined state_group for federated historical events" This reverts commit 187ab28611546321e02770944c86f30ee2bc742a. * Fix federated events being rejected for no state_groups Add fix from https://github.com/matrix-org/synapse/pull/10439 until it merges. * Adapting to experimental room version * Some log cleanup * Add better comments around extremity fetching code and why * Rename to be more accurate to what the function returns * Add changelog * Ignore rejected events * Use simplified upsert * Add Erik's explanation of extra event checks See https://github.com/matrix-org/synapse/pull/10498#discussion_r680880332 * Clarify that the depth is not directly correlated to the backwards extremity that we return See https://github.com/matrix-org/synapse/pull/10498#discussion_r681725404 * lock only matters for sqlite See https://github.com/matrix-org/synapse/pull/10498#discussion_r681728061 * Move new SQL changes to its own delta file * Clean up upsert docstring * Bump database schema version (62)
2 年前
Optimize how we calculate `likely_domains` during backfill (#13575) Optimize how we calculate `likely_domains` during backfill because I've seen this take 17s in production just to `get_current_state` which is used to `get_domains_from_state` (see case [*2. Loading tons of events* in the `/messages` investigation issue](https://github.com/matrix-org/synapse/issues/13356)). There are 3 ways we currently calculate hosts that are in the room: 1. `get_current_state` -> `get_domains_from_state` - Used in `backfill` to calculate `likely_domains` and `/timestamp_to_event` because it was cargo-culted from `backfill` - This one is being eliminated in favor of `get_current_hosts_in_room` in this PR 🕳 1. `get_current_hosts_in_room` - Used for other federation things like sending read receipts and typing indicators 1. `get_hosts_in_room_at_events` - Used when pushing out events over federation to other servers in the `_process_event_queue_loop` Fix https://github.com/matrix-org/synapse/issues/13626 Part of https://github.com/matrix-org/synapse/issues/13356 Mentioned in [internal doc](https://docs.google.com/document/d/1lvUoVfYUiy6UaHB6Rb4HicjaJAU40-APue9Q4vzuW3c/edit#bookmark=id.2tvwz3yhcafh) ### Query performance #### Before The query from `get_current_state` sucks just because we have to get all 80k events. And we see almost the exact same performance locally trying to get all of these events (16s vs 17s): ``` synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 16035.612 ms (00:16.036) synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 4243.237 ms (00:04.243) ``` But what about `get_current_hosts_in_room`: When there is 8M rows in the `current_state_events` table, the previous query in `get_current_hosts_in_room` took 13s from complete freshness (when the events were first added). But takes 930ms after a Postgres restart or 390ms if running back to back to back. ```sh $ psql synapse synapse=# \timing on synapse=# SELECT COUNT(DISTINCT substring(state_key FROM '@[^:]*:(.*)$')) FROM current_state_events WHERE type = 'm.room.member' AND membership = 'join' AND room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 4130 (1 row) Time: 13181.598 ms (00:13.182) synapse=# SELECT COUNT(*) from current_state_events where room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 80814 synapse=# SELECT COUNT(*) from current_state_events; count --------- 8162847 synapse=# SELECT pg_size_pretty( pg_total_relation_size('current_state_events') ); pg_size_pretty ---------------- 4702 MB ``` #### After I'm not sure how long it takes from complete freshness as I only really get that opportunity once (maybe restarting computer but that's cumbersome) and it's not really relevant to normal operating times. Maybe you get closer to the fresh times the more access variability there is so that Postgres caches aren't as exact. Update: The longest I've seen this run for is 6.4s and 4.5s after a computer restart. After a Postgres restart, it takes 330ms and running back to back takes 260ms. ```sh $ psql synapse synapse=# \timing on Timing is on. synapse=# SELECT substring(c.state_key FROM '@[^:]*:(.*)$') as host FROM current_state_events c /* Get the depth of the event from the events table */ INNER JOIN events AS e USING (event_id) WHERE c.type = 'm.room.member' AND c.membership = 'join' AND c.room_id = '!OGEhHVWSdvArJzumhm:matrix.org' GROUP BY host ORDER BY min(e.depth) ASC; Time: 333.800 ms ``` #### Going further To improve things further we could add a `limit` parameter to `get_current_hosts_in_room`. Realistically, we don't need 4k domains to choose from because there is no way we're going to query that many before we a) probably get an answer or b) we give up. Another thing we can do is optimize the query to use a index skip scan: - https://wiki.postgresql.org/wiki/Loose_indexscan - Index Skip Scan, https://commitfest.postgresql.org/37/1741/ - https://www.timescale.com/blog/how-we-made-distinct-queries-up-to-8000x-faster-on-postgresql/
1年前
Optimize how we calculate `likely_domains` during backfill (#13575) Optimize how we calculate `likely_domains` during backfill because I've seen this take 17s in production just to `get_current_state` which is used to `get_domains_from_state` (see case [*2. Loading tons of events* in the `/messages` investigation issue](https://github.com/matrix-org/synapse/issues/13356)). There are 3 ways we currently calculate hosts that are in the room: 1. `get_current_state` -> `get_domains_from_state` - Used in `backfill` to calculate `likely_domains` and `/timestamp_to_event` because it was cargo-culted from `backfill` - This one is being eliminated in favor of `get_current_hosts_in_room` in this PR 🕳 1. `get_current_hosts_in_room` - Used for other federation things like sending read receipts and typing indicators 1. `get_hosts_in_room_at_events` - Used when pushing out events over federation to other servers in the `_process_event_queue_loop` Fix https://github.com/matrix-org/synapse/issues/13626 Part of https://github.com/matrix-org/synapse/issues/13356 Mentioned in [internal doc](https://docs.google.com/document/d/1lvUoVfYUiy6UaHB6Rb4HicjaJAU40-APue9Q4vzuW3c/edit#bookmark=id.2tvwz3yhcafh) ### Query performance #### Before The query from `get_current_state` sucks just because we have to get all 80k events. And we see almost the exact same performance locally trying to get all of these events (16s vs 17s): ``` synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 16035.612 ms (00:16.036) synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 4243.237 ms (00:04.243) ``` But what about `get_current_hosts_in_room`: When there is 8M rows in the `current_state_events` table, the previous query in `get_current_hosts_in_room` took 13s from complete freshness (when the events were first added). But takes 930ms after a Postgres restart or 390ms if running back to back to back. ```sh $ psql synapse synapse=# \timing on synapse=# SELECT COUNT(DISTINCT substring(state_key FROM '@[^:]*:(.*)$')) FROM current_state_events WHERE type = 'm.room.member' AND membership = 'join' AND room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 4130 (1 row) Time: 13181.598 ms (00:13.182) synapse=# SELECT COUNT(*) from current_state_events where room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 80814 synapse=# SELECT COUNT(*) from current_state_events; count --------- 8162847 synapse=# SELECT pg_size_pretty( pg_total_relation_size('current_state_events') ); pg_size_pretty ---------------- 4702 MB ``` #### After I'm not sure how long it takes from complete freshness as I only really get that opportunity once (maybe restarting computer but that's cumbersome) and it's not really relevant to normal operating times. Maybe you get closer to the fresh times the more access variability there is so that Postgres caches aren't as exact. Update: The longest I've seen this run for is 6.4s and 4.5s after a computer restart. After a Postgres restart, it takes 330ms and running back to back takes 260ms. ```sh $ psql synapse synapse=# \timing on Timing is on. synapse=# SELECT substring(c.state_key FROM '@[^:]*:(.*)$') as host FROM current_state_events c /* Get the depth of the event from the events table */ INNER JOIN events AS e USING (event_id) WHERE c.type = 'm.room.member' AND c.membership = 'join' AND c.room_id = '!OGEhHVWSdvArJzumhm:matrix.org' GROUP BY host ORDER BY min(e.depth) ASC; Time: 333.800 ms ``` #### Going further To improve things further we could add a `limit` parameter to `get_current_hosts_in_room`. Realistically, we don't need 4k domains to choose from because there is no way we're going to query that many before we a) probably get an answer or b) we give up. Another thing we can do is optimize the query to use a index skip scan: - https://wiki.postgresql.org/wiki/Loose_indexscan - Index Skip Scan, https://commitfest.postgresql.org/37/1741/ - https://www.timescale.com/blog/how-we-made-distinct-queries-up-to-8000x-faster-on-postgresql/
1年前
Optimize how we calculate `likely_domains` during backfill (#13575) Optimize how we calculate `likely_domains` during backfill because I've seen this take 17s in production just to `get_current_state` which is used to `get_domains_from_state` (see case [*2. Loading tons of events* in the `/messages` investigation issue](https://github.com/matrix-org/synapse/issues/13356)). There are 3 ways we currently calculate hosts that are in the room: 1. `get_current_state` -> `get_domains_from_state` - Used in `backfill` to calculate `likely_domains` and `/timestamp_to_event` because it was cargo-culted from `backfill` - This one is being eliminated in favor of `get_current_hosts_in_room` in this PR 🕳 1. `get_current_hosts_in_room` - Used for other federation things like sending read receipts and typing indicators 1. `get_hosts_in_room_at_events` - Used when pushing out events over federation to other servers in the `_process_event_queue_loop` Fix https://github.com/matrix-org/synapse/issues/13626 Part of https://github.com/matrix-org/synapse/issues/13356 Mentioned in [internal doc](https://docs.google.com/document/d/1lvUoVfYUiy6UaHB6Rb4HicjaJAU40-APue9Q4vzuW3c/edit#bookmark=id.2tvwz3yhcafh) ### Query performance #### Before The query from `get_current_state` sucks just because we have to get all 80k events. And we see almost the exact same performance locally trying to get all of these events (16s vs 17s): ``` synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 16035.612 ms (00:16.036) synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 4243.237 ms (00:04.243) ``` But what about `get_current_hosts_in_room`: When there is 8M rows in the `current_state_events` table, the previous query in `get_current_hosts_in_room` took 13s from complete freshness (when the events were first added). But takes 930ms after a Postgres restart or 390ms if running back to back to back. ```sh $ psql synapse synapse=# \timing on synapse=# SELECT COUNT(DISTINCT substring(state_key FROM '@[^:]*:(.*)$')) FROM current_state_events WHERE type = 'm.room.member' AND membership = 'join' AND room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 4130 (1 row) Time: 13181.598 ms (00:13.182) synapse=# SELECT COUNT(*) from current_state_events where room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 80814 synapse=# SELECT COUNT(*) from current_state_events; count --------- 8162847 synapse=# SELECT pg_size_pretty( pg_total_relation_size('current_state_events') ); pg_size_pretty ---------------- 4702 MB ``` #### After I'm not sure how long it takes from complete freshness as I only really get that opportunity once (maybe restarting computer but that's cumbersome) and it's not really relevant to normal operating times. Maybe you get closer to the fresh times the more access variability there is so that Postgres caches aren't as exact. Update: The longest I've seen this run for is 6.4s and 4.5s after a computer restart. After a Postgres restart, it takes 330ms and running back to back takes 260ms. ```sh $ psql synapse synapse=# \timing on Timing is on. synapse=# SELECT substring(c.state_key FROM '@[^:]*:(.*)$') as host FROM current_state_events c /* Get the depth of the event from the events table */ INNER JOIN events AS e USING (event_id) WHERE c.type = 'm.room.member' AND c.membership = 'join' AND c.room_id = '!OGEhHVWSdvArJzumhm:matrix.org' GROUP BY host ORDER BY min(e.depth) ASC; Time: 333.800 ms ``` #### Going further To improve things further we could add a `limit` parameter to `get_current_hosts_in_room`. Realistically, we don't need 4k domains to choose from because there is no way we're going to query that many before we a) probably get an answer or b) we give up. Another thing we can do is optimize the query to use a index skip scan: - https://wiki.postgresql.org/wiki/Loose_indexscan - Index Skip Scan, https://commitfest.postgresql.org/37/1741/ - https://www.timescale.com/blog/how-we-made-distinct-queries-up-to-8000x-faster-on-postgresql/
1年前
Optimize how we calculate `likely_domains` during backfill (#13575) Optimize how we calculate `likely_domains` during backfill because I've seen this take 17s in production just to `get_current_state` which is used to `get_domains_from_state` (see case [*2. Loading tons of events* in the `/messages` investigation issue](https://github.com/matrix-org/synapse/issues/13356)). There are 3 ways we currently calculate hosts that are in the room: 1. `get_current_state` -> `get_domains_from_state` - Used in `backfill` to calculate `likely_domains` and `/timestamp_to_event` because it was cargo-culted from `backfill` - This one is being eliminated in favor of `get_current_hosts_in_room` in this PR 🕳 1. `get_current_hosts_in_room` - Used for other federation things like sending read receipts and typing indicators 1. `get_hosts_in_room_at_events` - Used when pushing out events over federation to other servers in the `_process_event_queue_loop` Fix https://github.com/matrix-org/synapse/issues/13626 Part of https://github.com/matrix-org/synapse/issues/13356 Mentioned in [internal doc](https://docs.google.com/document/d/1lvUoVfYUiy6UaHB6Rb4HicjaJAU40-APue9Q4vzuW3c/edit#bookmark=id.2tvwz3yhcafh) ### Query performance #### Before The query from `get_current_state` sucks just because we have to get all 80k events. And we see almost the exact same performance locally trying to get all of these events (16s vs 17s): ``` synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 16035.612 ms (00:16.036) synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 4243.237 ms (00:04.243) ``` But what about `get_current_hosts_in_room`: When there is 8M rows in the `current_state_events` table, the previous query in `get_current_hosts_in_room` took 13s from complete freshness (when the events were first added). But takes 930ms after a Postgres restart or 390ms if running back to back to back. ```sh $ psql synapse synapse=# \timing on synapse=# SELECT COUNT(DISTINCT substring(state_key FROM '@[^:]*:(.*)$')) FROM current_state_events WHERE type = 'm.room.member' AND membership = 'join' AND room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 4130 (1 row) Time: 13181.598 ms (00:13.182) synapse=# SELECT COUNT(*) from current_state_events where room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 80814 synapse=# SELECT COUNT(*) from current_state_events; count --------- 8162847 synapse=# SELECT pg_size_pretty( pg_total_relation_size('current_state_events') ); pg_size_pretty ---------------- 4702 MB ``` #### After I'm not sure how long it takes from complete freshness as I only really get that opportunity once (maybe restarting computer but that's cumbersome) and it's not really relevant to normal operating times. Maybe you get closer to the fresh times the more access variability there is so that Postgres caches aren't as exact. Update: The longest I've seen this run for is 6.4s and 4.5s after a computer restart. After a Postgres restart, it takes 330ms and running back to back takes 260ms. ```sh $ psql synapse synapse=# \timing on Timing is on. synapse=# SELECT substring(c.state_key FROM '@[^:]*:(.*)$') as host FROM current_state_events c /* Get the depth of the event from the events table */ INNER JOIN events AS e USING (event_id) WHERE c.type = 'm.room.member' AND c.membership = 'join' AND c.room_id = '!OGEhHVWSdvArJzumhm:matrix.org' GROUP BY host ORDER BY min(e.depth) ASC; Time: 333.800 ms ``` #### Going further To improve things further we could add a `limit` parameter to `get_current_hosts_in_room`. Realistically, we don't need 4k domains to choose from because there is no way we're going to query that many before we a) probably get an answer or b) we give up. Another thing we can do is optimize the query to use a index skip scan: - https://wiki.postgresql.org/wiki/Loose_indexscan - Index Skip Scan, https://commitfest.postgresql.org/37/1741/ - https://www.timescale.com/blog/how-we-made-distinct-queries-up-to-8000x-faster-on-postgresql/
1年前
Optimize how we calculate `likely_domains` during backfill (#13575) Optimize how we calculate `likely_domains` during backfill because I've seen this take 17s in production just to `get_current_state` which is used to `get_domains_from_state` (see case [*2. Loading tons of events* in the `/messages` investigation issue](https://github.com/matrix-org/synapse/issues/13356)). There are 3 ways we currently calculate hosts that are in the room: 1. `get_current_state` -> `get_domains_from_state` - Used in `backfill` to calculate `likely_domains` and `/timestamp_to_event` because it was cargo-culted from `backfill` - This one is being eliminated in favor of `get_current_hosts_in_room` in this PR 🕳 1. `get_current_hosts_in_room` - Used for other federation things like sending read receipts and typing indicators 1. `get_hosts_in_room_at_events` - Used when pushing out events over federation to other servers in the `_process_event_queue_loop` Fix https://github.com/matrix-org/synapse/issues/13626 Part of https://github.com/matrix-org/synapse/issues/13356 Mentioned in [internal doc](https://docs.google.com/document/d/1lvUoVfYUiy6UaHB6Rb4HicjaJAU40-APue9Q4vzuW3c/edit#bookmark=id.2tvwz3yhcafh) ### Query performance #### Before The query from `get_current_state` sucks just because we have to get all 80k events. And we see almost the exact same performance locally trying to get all of these events (16s vs 17s): ``` synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 16035.612 ms (00:16.036) synapse=# SELECT type, state_key, event_id FROM current_state_events WHERE room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; Time: 4243.237 ms (00:04.243) ``` But what about `get_current_hosts_in_room`: When there is 8M rows in the `current_state_events` table, the previous query in `get_current_hosts_in_room` took 13s from complete freshness (when the events were first added). But takes 930ms after a Postgres restart or 390ms if running back to back to back. ```sh $ psql synapse synapse=# \timing on synapse=# SELECT COUNT(DISTINCT substring(state_key FROM '@[^:]*:(.*)$')) FROM current_state_events WHERE type = 'm.room.member' AND membership = 'join' AND room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 4130 (1 row) Time: 13181.598 ms (00:13.182) synapse=# SELECT COUNT(*) from current_state_events where room_id = '!OGEhHVWSdvArJzumhm:matrix.org'; count ------- 80814 synapse=# SELECT COUNT(*) from current_state_events; count --------- 8162847 synapse=# SELECT pg_size_pretty( pg_total_relation_size('current_state_events') ); pg_size_pretty ---------------- 4702 MB ``` #### After I'm not sure how long it takes from complete freshness as I only really get that opportunity once (maybe restarting computer but that's cumbersome) and it's not really relevant to normal operating times. Maybe you get closer to the fresh times the more access variability there is so that Postgres caches aren't as exact. Update: The longest I've seen this run for is 6.4s and 4.5s after a computer restart. After a Postgres restart, it takes 330ms and running back to back takes 260ms. ```sh $ psql synapse synapse=# \timing on Timing is on. synapse=# SELECT substring(c.state_key FROM '@[^:]*:(.*)$') as host FROM current_state_events c /* Get the depth of the event from the events table */ INNER JOIN events AS e USING (event_id) WHERE c.type = 'm.room.member' AND c.membership = 'join' AND c.room_id = '!OGEhHVWSdvArJzumhm:matrix.org' GROUP BY host ORDER BY min(e.depth) ASC; Time: 333.800 ms ``` #### Going further To improve things further we could add a `limit` parameter to `get_current_hosts_in_room`. Realistically, we don't need 4k domains to choose from because there is no way we're going to query that many before we a) probably get an answer or b) we give up. Another thing we can do is optimize the query to use a index skip scan: - https://wiki.postgresql.org/wiki/Loose_indexscan - Index Skip Scan, https://commitfest.postgresql.org/37/1741/ - https://www.timescale.com/blog/how-we-made-distinct-queries-up-to-8000x-faster-on-postgresql/
1年前
Handle race between persisting an event and un-partial stating a room (#13100) Whenever we want to persist an event, we first compute an event context, which includes the state at the event and a flag indicating whether the state is partial. After a lot of processing, we finally try to store the event in the database, which can fail for partial state events when the containing room has been un-partial stated in the meantime. We detect the race as a foreign key constraint failure in the data store layer and turn it into a special `PartialStateConflictError` exception, which makes its way up to the method in which we computed the event context. To make things difficult, the exception needs to cross a replication request: `/fed_send_events` for events coming over federation and `/send_event` for events from clients. We transport the `PartialStateConflictError` as a `409 Conflict` over replication and turn `409`s back into `PartialStateConflictError`s on the worker making the request. All client events go through `EventCreationHandler.handle_new_client_event`, which is called in *a lot* of places. Instead of trying to update all the code which creates client events, we turn the `PartialStateConflictError` into a `429 Too Many Requests` in `EventCreationHandler.handle_new_client_event` and hope that clients take it as a hint to retry their request. On the federation event side, there are 7 places which compute event contexts. 4 of them use outlier event contexts: `FederationEventHandler._auth_and_persist_outliers_inner`, `FederationHandler.do_knock`, `FederationHandler.on_invite_request` and `FederationHandler.do_remotely_reject_invite`. These events won't have the partial state flag, so we do not need to do anything for then. The remaining 3 paths which create events are `FederationEventHandler.process_remote_join`, `FederationEventHandler.on_send_membership_event` and `FederationEventHandler._process_received_pdu`. We can't experience the race in `process_remote_join`, unless we're handling an additional join into a partial state room, which currently blocks, so we make no attempt to handle it correctly. `on_send_membership_event` is only called by `FederationServer._on_send_membership_event`, so we catch the `PartialStateConflictError` there and retry just once. `_process_received_pdu` is called by `on_receive_pdu` for incoming events and `_process_pulled_event` for backfill. The latter should never try to persist partial state events, so we ignore it. We catch the `PartialStateConflictError` in `on_receive_pdu` and retry just once. Refering to the graph of code paths in https://github.com/matrix-org/synapse/issues/12988#issuecomment-1156857648 may make the above make more sense. Signed-off-by: Sean Quah <seanq@matrix.org>
1年前
7 年前
7 年前
7 年前
Fix historical messages backfilling in random order on remote homeservers (MSC2716) (#11114) Fix https://github.com/matrix-org/synapse/issues/11091 Fix https://github.com/matrix-org/synapse/issues/10764 (side-stepping the issue because we no longer have to deal with `fake_prev_event_id`) 1. Made the `/backfill` response return messages in `(depth, stream_ordering)` order (previously only sorted by `depth`) - Technically, it shouldn't really matter how `/backfill` returns things but I'm just trying to make the `stream_ordering` a little more consistent from the origin to the remote homeservers in order to get the order of messages from `/messages` consistent ([sorted by `(topological_ordering, stream_ordering)`](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)). - Even now that we return backfilled messages in order, it still doesn't guarantee the same `stream_ordering` (and more importantly the [`/messages` order](https://github.com/matrix-org/synapse/blob/develop/docs/development/room-dag-concepts.md#depth-and-stream-ordering)) on the other server. For example, if a room has a bunch of history imported and someone visits a permalink to a historical message back in time, their homeserver will skip over the historical messages in between and insert the permalink as the next message in the `stream_order` and totally throw off the sort. - This will be even more the case when we add the [MSC3030 jump to date API endpoint](https://github.com/matrix-org/matrix-doc/pull/3030) so the static archives can navigate and jump to a certain date. - We're solving this in the future by switching to [online topological ordering](https://github.com/matrix-org/gomatrixserverlib/issues/187) and [chunking](https://github.com/matrix-org/synapse/issues/3785) which by its nature will apply retroactively to fix any inconsistencies introduced by people permalinking 2. As we're navigating `prev_events` to return in `/backfill`, we order by `depth` first (newest -> oldest) and now also tie-break based on the `stream_ordering` (newest -> oldest). This is technically important because MSC2716 inserts a bunch of historical messages at the same `depth` so it's best to be prescriptive about which ones we should process first. In reality, I think the code already looped over the historical messages as expected because the database is already in order. 3. Making the historical state chain and historical event chain float on their own by having no `prev_events` instead of a fake `prev_event` which caused backfill to get clogged with an unresolvable event. Fixes https://github.com/matrix-org/synapse/issues/11091 and https://github.com/matrix-org/synapse/issues/10764 4. We no longer find connected insertion events by finding a potential `prev_event` connection to the current event we're iterating over. We now solely rely on marker events which when processed, add the insertion event as an extremity and the federating homeserver can ask about it when time calls. - Related discussion, https://github.com/matrix-org/synapse/pull/11114#discussion_r741514793 Before | After --- | --- ![](https://user-images.githubusercontent.com/558581/139218681-b465c862-5c49-4702-a59e-466733b0cf45.png) | ![](https://user-images.githubusercontent.com/558581/146453159-a1609e0a-8324-439d-ae44-e4bce43ac6d1.png) #### Why aren't we sorting topologically when receiving backfill events? > The main reason we're going to opt to not sort topologically when receiving backfill events is because it's probably best to do whatever is easiest to make it just work. People will probably have opinions once they look at [MSC2716](https://github.com/matrix-org/matrix-doc/pull/2716) which could change whatever implementation anyway. > > As mentioned, ideally we would do this but code necessary to make the fake edges but it gets confusing and gives an impression of “just whyyyy” (feels icky). This problem also dissolves with online topological ordering. > > -- https://github.com/matrix-org/synapse/pull/11114#discussion_r741517138 See https://github.com/matrix-org/synapse/pull/11114#discussion_r739610091 for the technical difficulties
2 年前
4 年前
4 年前
Stop getting missing `prev_events` after we already know their signature is invalid (#13816) While https://github.com/matrix-org/synapse/pull/13635 stops us from doing the slow thing after we've already done it once, this PR stops us from doing one of the slow things in the first place. Related to - https://github.com/matrix-org/synapse/issues/13622 - https://github.com/matrix-org/synapse/pull/13635 - https://github.com/matrix-org/synapse/issues/13676 Part of https://github.com/matrix-org/synapse/issues/13356 Follow-up to https://github.com/matrix-org/synapse/pull/13815 which tracks event signature failures. With this PR, we avoid the call to the costly `_get_state_ids_after_missing_prev_event` because the signature failure will count as an attempt before and we filter events based on the backoff before calling `_get_state_ids_after_missing_prev_event` now. For example, this will save us 156s out of the 185s total that this `matrix.org` `/messages` request. If you want to see the full Jaeger trace of this, you can drag and drop this `trace.json` into your own Jaeger, https://gist.github.com/MadLittleMods/4b12d0d0afe88c2f65ffcc907306b761 To explain this exact scenario around `/messages` -> backfill, we call `/backfill` and first check the signatures of the 100 events. We see bad signature for `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` and `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` (both member events). Then we process the 98 events remaining that have valid signatures but one of the events references `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` as a `prev_event`. So we have to do the whole `_get_state_ids_after_missing_prev_event` rigmarole which pulls in those same events which fail again because the signatures are still invalid. - `backfill` - `outgoing-federation-request` `/backfill` - `_check_sigs_and_hash_and_fetch` - `_check_sigs_and_hash_and_fetch_one` for each event received over backfill - ❗ `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` fails with `Signature on retrieved event was invalid.`: `unable to verify signature for sender domain xxx: 401: Failed to find any key to satisfy: _FetchKeyRequest(...)` - ❗ `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` fails with `Signature on retrieved event was invalid.`: `unable to verify signature for sender domain xxx: 401: Failed to find any key to satisfy: _FetchKeyRequest(...)` - `_process_pulled_events` - `_process_pulled_event` for each validated event - ❗ Event `$Q0iMdqtz3IJYfZQU2Xk2WjB5NDF8Gg8cFSYYyKQgKJ0` references `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` as a `prev_event` which is missing so we try to get it - `_get_state_ids_after_missing_prev_event` - `outgoing-federation-request` `/state_ids` - ❗ `get_pdu` for `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` which fails the signature check again - ❗ `get_pdu` for `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` which fails the signature check
1年前
Stop getting missing `prev_events` after we already know their signature is invalid (#13816) While https://github.com/matrix-org/synapse/pull/13635 stops us from doing the slow thing after we've already done it once, this PR stops us from doing one of the slow things in the first place. Related to - https://github.com/matrix-org/synapse/issues/13622 - https://github.com/matrix-org/synapse/pull/13635 - https://github.com/matrix-org/synapse/issues/13676 Part of https://github.com/matrix-org/synapse/issues/13356 Follow-up to https://github.com/matrix-org/synapse/pull/13815 which tracks event signature failures. With this PR, we avoid the call to the costly `_get_state_ids_after_missing_prev_event` because the signature failure will count as an attempt before and we filter events based on the backoff before calling `_get_state_ids_after_missing_prev_event` now. For example, this will save us 156s out of the 185s total that this `matrix.org` `/messages` request. If you want to see the full Jaeger trace of this, you can drag and drop this `trace.json` into your own Jaeger, https://gist.github.com/MadLittleMods/4b12d0d0afe88c2f65ffcc907306b761 To explain this exact scenario around `/messages` -> backfill, we call `/backfill` and first check the signatures of the 100 events. We see bad signature for `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` and `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` (both member events). Then we process the 98 events remaining that have valid signatures but one of the events references `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` as a `prev_event`. So we have to do the whole `_get_state_ids_after_missing_prev_event` rigmarole which pulls in those same events which fail again because the signatures are still invalid. - `backfill` - `outgoing-federation-request` `/backfill` - `_check_sigs_and_hash_and_fetch` - `_check_sigs_and_hash_and_fetch_one` for each event received over backfill - ❗ `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` fails with `Signature on retrieved event was invalid.`: `unable to verify signature for sender domain xxx: 401: Failed to find any key to satisfy: _FetchKeyRequest(...)` - ❗ `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` fails with `Signature on retrieved event was invalid.`: `unable to verify signature for sender domain xxx: 401: Failed to find any key to satisfy: _FetchKeyRequest(...)` - `_process_pulled_events` - `_process_pulled_event` for each validated event - ❗ Event `$Q0iMdqtz3IJYfZQU2Xk2WjB5NDF8Gg8cFSYYyKQgKJ0` references `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` as a `prev_event` which is missing so we try to get it - `_get_state_ids_after_missing_prev_event` - `outgoing-federation-request` `/state_ids` - ❗ `get_pdu` for `$luA4l7QHhf_jadH3mI-AyFqho0U2Q-IXXUbGSMq6h6M` which fails the signature check again - ❗ `get_pdu` for `$zuOn2Rd2vsC7SUia3Hp3r6JSkSFKcc5j3QTTqW_0jDw` which fails the signature check
1年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  1. # Copyright 2014-2022 The Matrix.org Foundation C.I.C.
  2. # Copyright 2020 Sorunome
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contains handlers for federation events."""
  16. import enum
  17. import itertools
  18. import logging
  19. from enum import Enum
  20. from http import HTTPStatus
  21. from typing import (
  22. TYPE_CHECKING,
  23. Collection,
  24. Dict,
  25. Iterable,
  26. List,
  27. Optional,
  28. Set,
  29. Tuple,
  30. Union,
  31. )
  32. import attr
  33. from prometheus_client import Histogram
  34. from signedjson.key import decode_verify_key_bytes
  35. from signedjson.sign import verify_signed_json
  36. from unpaddedbase64 import decode_base64
  37. from synapse import event_auth
  38. from synapse.api.constants import MAX_DEPTH, EventContentFields, EventTypes, Membership
  39. from synapse.api.errors import (
  40. AuthError,
  41. CodeMessageException,
  42. Codes,
  43. FederationDeniedError,
  44. FederationError,
  45. FederationPullAttemptBackoffError,
  46. HttpResponseException,
  47. NotFoundError,
  48. RequestSendFailed,
  49. SynapseError,
  50. )
  51. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
  52. from synapse.crypto.event_signing import compute_event_signature
  53. from synapse.event_auth import validate_event_for_room_version
  54. from synapse.events import EventBase
  55. from synapse.events.snapshot import EventContext
  56. from synapse.events.validator import EventValidator
  57. from synapse.federation.federation_client import InvalidResponseError
  58. from synapse.http.servlet import assert_params_in_dict
  59. from synapse.logging.context import nested_logging_context
  60. from synapse.logging.opentracing import SynapseTags, set_tag, tag_args, trace
  61. from synapse.metrics.background_process_metrics import run_as_background_process
  62. from synapse.module_api import NOT_SPAM
  63. from synapse.replication.http.federation import (
  64. ReplicationCleanRoomRestServlet,
  65. ReplicationStoreRoomOnOutlierMembershipRestServlet,
  66. )
  67. from synapse.storage.databases.main.events import PartialStateConflictError
  68. from synapse.storage.databases.main.events_worker import EventRedactBehaviour
  69. from synapse.types import JsonDict, get_domain_from_id
  70. from synapse.types.state import StateFilter
  71. from synapse.util.async_helpers import Linearizer
  72. from synapse.util.retryutils import NotRetryingDestination
  73. from synapse.visibility import filter_events_for_server
  74. if TYPE_CHECKING:
  75. from synapse.server import HomeServer
  76. logger = logging.getLogger(__name__)
  77. # Added to debug performance and track progress on optimizations
  78. backfill_processing_before_timer = Histogram(
  79. "synapse_federation_backfill_processing_before_time_seconds",
  80. "sec",
  81. [],
  82. buckets=(
  83. 0.1,
  84. 0.5,
  85. 1.0,
  86. 2.5,
  87. 5.0,
  88. 7.5,
  89. 10.0,
  90. 15.0,
  91. 20.0,
  92. 30.0,
  93. 40.0,
  94. 60.0,
  95. 80.0,
  96. "+Inf",
  97. ),
  98. )
  99. class _BackfillPointType(Enum):
  100. # a regular backwards extremity (ie, an event which we don't yet have, but which
  101. # is referred to by other events in the DAG)
  102. BACKWARDS_EXTREMITY = enum.auto()
  103. # an MSC2716 "insertion event"
  104. INSERTION_PONT = enum.auto()
  105. @attr.s(slots=True, auto_attribs=True, frozen=True)
  106. class _BackfillPoint:
  107. """A potential point we might backfill from"""
  108. event_id: str
  109. depth: int
  110. type: _BackfillPointType
  111. class FederationHandler:
  112. """Handles general incoming federation requests
  113. Incoming events are *not* handled here, for which see FederationEventHandler.
  114. """
  115. def __init__(self, hs: "HomeServer"):
  116. self.hs = hs
  117. self.clock = hs.get_clock()
  118. self.store = hs.get_datastores().main
  119. self._storage_controllers = hs.get_storage_controllers()
  120. self._state_storage_controller = self._storage_controllers.state
  121. self.federation_client = hs.get_federation_client()
  122. self.state_handler = hs.get_state_handler()
  123. self.server_name = hs.hostname
  124. self.keyring = hs.get_keyring()
  125. self.is_mine_id = hs.is_mine_id
  126. self.spam_checker = hs.get_spam_checker()
  127. self.event_creation_handler = hs.get_event_creation_handler()
  128. self.event_builder_factory = hs.get_event_builder_factory()
  129. self._event_auth_handler = hs.get_event_auth_handler()
  130. self._server_notices_mxid = hs.config.servernotices.server_notices_mxid
  131. self.config = hs.config
  132. self.http_client = hs.get_proxied_blacklisted_http_client()
  133. self._replication = hs.get_replication_data_handler()
  134. self._federation_event_handler = hs.get_federation_event_handler()
  135. self._device_handler = hs.get_device_handler()
  136. self._bulk_push_rule_evaluator = hs.get_bulk_push_rule_evaluator()
  137. self._notifier = hs.get_notifier()
  138. self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
  139. hs
  140. )
  141. if hs.config.worker.worker_app:
  142. self._maybe_store_room_on_outlier_membership = (
  143. ReplicationStoreRoomOnOutlierMembershipRestServlet.make_client(hs)
  144. )
  145. else:
  146. self._maybe_store_room_on_outlier_membership = (
  147. self.store.maybe_store_room_on_outlier_membership
  148. )
  149. self._room_backfill = Linearizer("room_backfill")
  150. self.third_party_event_rules = hs.get_third_party_event_rules()
  151. # Tracks running partial state syncs by room ID.
  152. # Partial state syncs currently only run on the main process, so it's okay to
  153. # track them in-memory for now.
  154. self._active_partial_state_syncs: Set[str] = set()
  155. # Tracks partial state syncs we may want to restart.
  156. # A dictionary mapping room IDs to (initial destination, other destinations)
  157. # tuples.
  158. self._partial_state_syncs_maybe_needing_restart: Dict[
  159. str, Tuple[Optional[str], Collection[str]]
  160. ] = {}
  161. # A lock guarding the partial state flag for rooms.
  162. # When the lock is held for a given room, no other concurrent code may
  163. # partial state or un-partial state the room.
  164. self._is_partial_state_room_linearizer = Linearizer(
  165. name="_is_partial_state_room_linearizer"
  166. )
  167. # if this is the main process, fire off a background process to resume
  168. # any partial-state-resync operations which were in flight when we
  169. # were shut down.
  170. if not hs.config.worker.worker_app:
  171. run_as_background_process(
  172. "resume_sync_partial_state_room", self._resume_partial_state_room_sync
  173. )
  174. @trace
  175. async def maybe_backfill(
  176. self, room_id: str, current_depth: int, limit: int
  177. ) -> bool:
  178. """Checks the database to see if we should backfill before paginating,
  179. and if so do.
  180. Args:
  181. room_id
  182. current_depth: The depth from which we're paginating from. This is
  183. used to decide if we should backfill and what extremities to
  184. use.
  185. limit: The number of events that the pagination request will
  186. return. This is used as part of the heuristic to decide if we
  187. should back paginate.
  188. """
  189. # Starting the processing time here so we can include the room backfill
  190. # linearizer lock queue in the timing
  191. processing_start_time = self.clock.time_msec()
  192. async with self._room_backfill.queue(room_id):
  193. return await self._maybe_backfill_inner(
  194. room_id,
  195. current_depth,
  196. limit,
  197. processing_start_time=processing_start_time,
  198. )
  199. async def _maybe_backfill_inner(
  200. self,
  201. room_id: str,
  202. current_depth: int,
  203. limit: int,
  204. *,
  205. processing_start_time: Optional[int],
  206. ) -> bool:
  207. """
  208. Checks whether the `current_depth` is at or approaching any backfill
  209. points in the room and if so, will backfill. We only care about
  210. checking backfill points that happened before the `current_depth`
  211. (meaning less than or equal to the `current_depth`).
  212. Args:
  213. room_id: The room to backfill in.
  214. current_depth: The depth to check at for any upcoming backfill points.
  215. limit: The max number of events to request from the remote federated server.
  216. processing_start_time: The time when `maybe_backfill` started processing.
  217. Only used for timing. If `None`, no timing observation will be made.
  218. """
  219. backwards_extremities = [
  220. _BackfillPoint(event_id, depth, _BackfillPointType.BACKWARDS_EXTREMITY)
  221. for event_id, depth in await self.store.get_backfill_points_in_room(
  222. room_id=room_id,
  223. current_depth=current_depth,
  224. # We only need to end up with 5 extremities combined with the
  225. # insertion event extremities to make the `/backfill` request
  226. # but fetch an order of magnitude more to make sure there is
  227. # enough even after we filter them by whether visible in the
  228. # history. This isn't fool-proof as all backfill points within
  229. # our limit could be filtered out but seems like a good amount
  230. # to try with at least.
  231. limit=50,
  232. )
  233. ]
  234. insertion_events_to_be_backfilled: List[_BackfillPoint] = []
  235. if self.hs.config.experimental.msc2716_enabled:
  236. insertion_events_to_be_backfilled = [
  237. _BackfillPoint(event_id, depth, _BackfillPointType.INSERTION_PONT)
  238. for event_id, depth in await self.store.get_insertion_event_backward_extremities_in_room(
  239. room_id=room_id,
  240. current_depth=current_depth,
  241. # We only need to end up with 5 extremities combined with
  242. # the backfill points to make the `/backfill` request ...
  243. # (see the other comment above for more context).
  244. limit=50,
  245. )
  246. ]
  247. logger.debug(
  248. "_maybe_backfill_inner: backwards_extremities=%s insertion_events_to_be_backfilled=%s",
  249. backwards_extremities,
  250. insertion_events_to_be_backfilled,
  251. )
  252. # we now have a list of potential places to backpaginate from. We prefer to
  253. # start with the most recent (ie, max depth), so let's sort the list.
  254. sorted_backfill_points: List[_BackfillPoint] = sorted(
  255. itertools.chain(
  256. backwards_extremities,
  257. insertion_events_to_be_backfilled,
  258. ),
  259. key=lambda e: -int(e.depth),
  260. )
  261. logger.debug(
  262. "_maybe_backfill_inner: room_id: %s: current_depth: %s, limit: %s, "
  263. "backfill points (%d): %s",
  264. room_id,
  265. current_depth,
  266. limit,
  267. len(sorted_backfill_points),
  268. sorted_backfill_points,
  269. )
  270. # If we have no backfill points lower than the `current_depth` then
  271. # either we can a) bail or b) still attempt to backfill. We opt to try
  272. # backfilling anyway just in case we do get relevant events.
  273. if not sorted_backfill_points and current_depth != MAX_DEPTH:
  274. logger.debug(
  275. "_maybe_backfill_inner: all backfill points are *after* current depth. Trying again with later backfill points."
  276. )
  277. return await self._maybe_backfill_inner(
  278. room_id=room_id,
  279. # We use `MAX_DEPTH` so that we find all backfill points next
  280. # time (all events are below the `MAX_DEPTH`)
  281. current_depth=MAX_DEPTH,
  282. limit=limit,
  283. # We don't want to start another timing observation from this
  284. # nested recursive call. The top-most call can record the time
  285. # overall otherwise the smaller one will throw off the results.
  286. processing_start_time=None,
  287. )
  288. # Even after recursing with `MAX_DEPTH`, we didn't find any
  289. # backward extremities to backfill from.
  290. if not sorted_backfill_points:
  291. logger.debug(
  292. "_maybe_backfill_inner: Not backfilling as no backward extremeties found."
  293. )
  294. return False
  295. # If we're approaching an extremity we trigger a backfill, otherwise we
  296. # no-op.
  297. #
  298. # We chose twice the limit here as then clients paginating backwards
  299. # will send pagination requests that trigger backfill at least twice
  300. # using the most recent extremity before it gets removed (see below). We
  301. # chose more than one times the limit in case of failure, but choosing a
  302. # much larger factor will result in triggering a backfill request much
  303. # earlier than necessary.
  304. max_depth_of_backfill_points = sorted_backfill_points[0].depth
  305. if current_depth - 2 * limit > max_depth_of_backfill_points:
  306. logger.debug(
  307. "Not backfilling as we don't need to. %d < %d - 2 * %d",
  308. max_depth_of_backfill_points,
  309. current_depth,
  310. limit,
  311. )
  312. return False
  313. # For performance's sake, we only want to paginate from a particular extremity
  314. # if we can actually see the events we'll get. Otherwise, we'd just spend a lot
  315. # of resources to get redacted events. We check each extremity in turn and
  316. # ignore those which users on our server wouldn't be able to see.
  317. #
  318. # Additionally, we limit ourselves to backfilling from at most 5 extremities,
  319. # for two reasons:
  320. #
  321. # - The check which determines if we can see an extremity's events can be
  322. # expensive (we load the full state for the room at each of the backfill
  323. # points, or (worse) their successors)
  324. # - We want to avoid the server-server API request URI becoming too long.
  325. #
  326. # *Note*: the spec wants us to keep backfilling until we reach the start
  327. # of the room in case we are allowed to see some of the history. However,
  328. # in practice that causes more issues than its worth, as (a) it's
  329. # relatively rare for there to be any visible history and (b) even when
  330. # there is it's often sufficiently long ago that clients would stop
  331. # attempting to paginate before backfill reached the visible history.
  332. extremities_to_request: List[str] = []
  333. for bp in sorted_backfill_points:
  334. if len(extremities_to_request) >= 5:
  335. break
  336. # For regular backwards extremities, we don't have the extremity events
  337. # themselves, so we need to actually check the events that reference them -
  338. # their "successor" events.
  339. #
  340. # TODO: Correctly handle the case where we are allowed to see the
  341. # successor event but not the backward extremity, e.g. in the case of
  342. # initial join of the server where we are allowed to see the join
  343. # event but not anything before it. This would require looking at the
  344. # state *before* the event, ignoring the special casing certain event
  345. # types have.
  346. if bp.type == _BackfillPointType.INSERTION_PONT:
  347. event_ids_to_check = [bp.event_id]
  348. else:
  349. event_ids_to_check = await self.store.get_successor_events(bp.event_id)
  350. events_to_check = await self.store.get_events_as_list(
  351. event_ids_to_check,
  352. redact_behaviour=EventRedactBehaviour.as_is,
  353. get_prev_content=False,
  354. )
  355. # We set `check_history_visibility_only` as we might otherwise get false
  356. # positives from users having been erased.
  357. filtered_extremities = await filter_events_for_server(
  358. self._storage_controllers,
  359. self.server_name,
  360. self.server_name,
  361. events_to_check,
  362. redact=False,
  363. check_history_visibility_only=True,
  364. )
  365. if filtered_extremities:
  366. extremities_to_request.append(bp.event_id)
  367. else:
  368. logger.debug(
  369. "_maybe_backfill_inner: skipping extremity %s as it would not be visible",
  370. bp,
  371. )
  372. if not extremities_to_request:
  373. logger.debug(
  374. "_maybe_backfill_inner: found no extremities which would be visible"
  375. )
  376. return False
  377. logger.debug(
  378. "_maybe_backfill_inner: extremities_to_request %s", extremities_to_request
  379. )
  380. set_tag(
  381. SynapseTags.RESULT_PREFIX + "extremities_to_request",
  382. str(extremities_to_request),
  383. )
  384. set_tag(
  385. SynapseTags.RESULT_PREFIX + "extremities_to_request.length",
  386. str(len(extremities_to_request)),
  387. )
  388. # Now we need to decide which hosts to hit first.
  389. # First we try hosts that are already in the room.
  390. # TODO: HEURISTIC ALERT.
  391. likely_domains = (
  392. await self._storage_controllers.state.get_current_hosts_in_room_ordered(
  393. room_id
  394. )
  395. )
  396. async def try_backfill(domains: Collection[str]) -> bool:
  397. # TODO: Should we try multiple of these at a time?
  398. # Number of contacted remote homeservers that have denied our backfill
  399. # request with a 4xx code.
  400. denied_count = 0
  401. # Maximum number of contacted remote homeservers that can deny our
  402. # backfill request with 4xx codes before we give up.
  403. max_denied_count = 5
  404. for dom in domains:
  405. # We don't want to ask our own server for information we don't have
  406. if dom == self.server_name:
  407. continue
  408. try:
  409. await self._federation_event_handler.backfill(
  410. dom, room_id, limit=100, extremities=extremities_to_request
  411. )
  412. # If this succeeded then we probably already have the
  413. # appropriate stuff.
  414. # TODO: We can probably do something more intelligent here.
  415. return True
  416. except NotRetryingDestination as e:
  417. logger.info("_maybe_backfill_inner: %s", e)
  418. continue
  419. except FederationDeniedError:
  420. logger.info(
  421. "_maybe_backfill_inner: Not attempting to backfill from %s because the homeserver is not on our federation whitelist",
  422. dom,
  423. )
  424. continue
  425. except (SynapseError, InvalidResponseError) as e:
  426. logger.info("Failed to backfill from %s because %s", dom, e)
  427. continue
  428. except HttpResponseException as e:
  429. if 400 <= e.code < 500:
  430. logger.warning(
  431. "Backfill denied from %s because %s [%d/%d]",
  432. dom,
  433. e,
  434. denied_count,
  435. max_denied_count,
  436. )
  437. denied_count += 1
  438. if denied_count >= max_denied_count:
  439. return False
  440. continue
  441. logger.info("Failed to backfill from %s because %s", dom, e)
  442. continue
  443. except CodeMessageException as e:
  444. if 400 <= e.code < 500:
  445. logger.warning(
  446. "Backfill denied from %s because %s [%d/%d]",
  447. dom,
  448. e,
  449. denied_count,
  450. max_denied_count,
  451. )
  452. denied_count += 1
  453. if denied_count >= max_denied_count:
  454. return False
  455. continue
  456. logger.info("Failed to backfill from %s because %s", dom, e)
  457. continue
  458. except RequestSendFailed as e:
  459. logger.info("Failed to get backfill from %s because %s", dom, e)
  460. continue
  461. except Exception as e:
  462. logger.exception("Failed to backfill from %s because %s", dom, e)
  463. continue
  464. return False
  465. # If we have the `processing_start_time`, then we can make an
  466. # observation. We wouldn't have the `processing_start_time` in the case
  467. # where `_maybe_backfill_inner` is recursively called to find any
  468. # backfill points regardless of `current_depth`.
  469. if processing_start_time is not None:
  470. processing_end_time = self.clock.time_msec()
  471. backfill_processing_before_timer.observe(
  472. (processing_end_time - processing_start_time) / 1000
  473. )
  474. success = await try_backfill(likely_domains)
  475. if success:
  476. return True
  477. # TODO: we could also try servers which were previously in the room, but
  478. # are no longer.
  479. return False
  480. async def send_invite(self, target_host: str, event: EventBase) -> EventBase:
  481. """Sends the invite to the remote server for signing.
  482. Invites must be signed by the invitee's server before distribution.
  483. """
  484. try:
  485. pdu = await self.federation_client.send_invite(
  486. destination=target_host,
  487. room_id=event.room_id,
  488. event_id=event.event_id,
  489. pdu=event,
  490. )
  491. except RequestSendFailed:
  492. raise SynapseError(502, f"Can't connect to server {target_host}")
  493. return pdu
  494. async def on_event_auth(self, event_id: str) -> List[EventBase]:
  495. event = await self.store.get_event(event_id)
  496. auth = await self.store.get_auth_chain(
  497. event.room_id, list(event.auth_event_ids()), include_given=True
  498. )
  499. return list(auth)
  500. async def do_invite_join(
  501. self, target_hosts: Iterable[str], room_id: str, joinee: str, content: JsonDict
  502. ) -> Tuple[str, int]:
  503. """Attempts to join the `joinee` to the room `room_id` via the
  504. servers contained in `target_hosts`.
  505. This first triggers a /make_join/ request that returns a partial
  506. event that we can fill out and sign. This is then sent to the
  507. remote server via /send_join/ which responds with the state at that
  508. event and the auth_chains.
  509. We suspend processing of any received events from this room until we
  510. have finished processing the join.
  511. Args:
  512. target_hosts: List of servers to attempt to join the room with.
  513. room_id: The ID of the room to join.
  514. joinee: The User ID of the joining user.
  515. content: The event content to use for the join event.
  516. """
  517. # TODO: We should be able to call this on workers, but the upgrading of
  518. # room stuff after join currently doesn't work on workers.
  519. # TODO: Before we relax this condition, we need to allow re-syncing of
  520. # partial room state to happen on workers.
  521. assert self.config.worker.worker_app is None
  522. logger.debug("Joining %s to %s", joinee, room_id)
  523. origin, event, room_version_obj = await self._make_and_verify_event(
  524. target_hosts,
  525. room_id,
  526. joinee,
  527. "join",
  528. content,
  529. params={"ver": KNOWN_ROOM_VERSIONS},
  530. )
  531. # This shouldn't happen, because the RoomMemberHandler has a
  532. # linearizer lock which only allows one operation per user per room
  533. # at a time - so this is just paranoia.
  534. assert room_id not in self._federation_event_handler.room_queues
  535. self._federation_event_handler.room_queues[room_id] = []
  536. is_host_joined = await self.store.is_host_joined(room_id, self.server_name)
  537. if not is_host_joined:
  538. # We may have old forward extremities lying around if the homeserver left
  539. # the room completely in the past. Clear them out.
  540. #
  541. # Note that this check-then-clear is subject to races where
  542. # * the homeserver is in the room and stops being in the room just after
  543. # the check. We won't reset the forward extremities, but that's okay,
  544. # since they will be almost up to date.
  545. # * the homeserver is not in the room and starts being in the room just
  546. # after the check. This can't happen, since `RoomMemberHandler` has a
  547. # linearizer lock which prevents concurrent remote joins into the same
  548. # room.
  549. # In short, the races either have an acceptable outcome or should be
  550. # impossible.
  551. await self._clean_room_for_join(room_id)
  552. try:
  553. # Try the host we successfully got a response to /make_join/
  554. # request first.
  555. host_list = list(target_hosts)
  556. try:
  557. host_list.remove(origin)
  558. host_list.insert(0, origin)
  559. except ValueError:
  560. pass
  561. async with self._is_partial_state_room_linearizer.queue(room_id):
  562. already_partial_state_room = await self.store.is_partial_state_room(
  563. room_id
  564. )
  565. ret = await self.federation_client.send_join(
  566. host_list,
  567. event,
  568. room_version_obj,
  569. # Perform a full join when we are already in the room and it is a
  570. # full state room, since we are not allowed to persist a partial
  571. # state join event in a full state room. In the future, we could
  572. # optimize this by always performing a partial state join and
  573. # computing the state ourselves or retrieving it from the remote
  574. # homeserver if necessary.
  575. #
  576. # There's a race where we leave the room, then perform a full join
  577. # anyway. This should end up being fast anyway, since we would
  578. # already have the full room state and auth chain persisted.
  579. partial_state=not is_host_joined or already_partial_state_room,
  580. )
  581. event = ret.event
  582. origin = ret.origin
  583. state = ret.state
  584. auth_chain = ret.auth_chain
  585. auth_chain.sort(key=lambda e: e.depth)
  586. logger.debug("do_invite_join auth_chain: %s", auth_chain)
  587. logger.debug("do_invite_join state: %s", state)
  588. logger.debug("do_invite_join event: %s", event)
  589. # if this is the first time we've joined this room, it's time to add
  590. # a row to `rooms` with the correct room version. If there's already a
  591. # row there, we should override it, since it may have been populated
  592. # based on an invite request which lied about the room version.
  593. #
  594. # federation_client.send_join has already checked that the room
  595. # version in the received create event is the same as room_version_obj,
  596. # so we can rely on it now.
  597. #
  598. await self.store.upsert_room_on_join(
  599. room_id=room_id,
  600. room_version=room_version_obj,
  601. state_events=state,
  602. )
  603. if ret.partial_state and not already_partial_state_room:
  604. # Mark the room as having partial state.
  605. # The background process is responsible for unmarking this flag,
  606. # even if the join fails.
  607. # TODO(faster_joins):
  608. # We may want to reset the partial state info if it's from an
  609. # old, failed partial state join.
  610. # https://github.com/matrix-org/synapse/issues/13000
  611. await self.store.store_partial_state_room(
  612. room_id=room_id,
  613. servers=ret.servers_in_room,
  614. device_lists_stream_id=self.store.get_device_stream_token(),
  615. joined_via=origin,
  616. )
  617. try:
  618. max_stream_id = (
  619. await self._federation_event_handler.process_remote_join(
  620. origin,
  621. room_id,
  622. auth_chain,
  623. state,
  624. event,
  625. room_version_obj,
  626. partial_state=ret.partial_state,
  627. )
  628. )
  629. except PartialStateConflictError:
  630. # This should be impossible, since we hold the lock on the room's
  631. # partial statedness.
  632. logger.error(
  633. "Room %s was un-partial stated while processing remote join.",
  634. room_id,
  635. )
  636. raise
  637. else:
  638. # Record the join event id for future use (when we finish the full
  639. # join). We have to do this after persisting the event to keep
  640. # foreign key constraints intact.
  641. if ret.partial_state and not already_partial_state_room:
  642. # TODO(faster_joins):
  643. # We may want to reset the partial state info if it's from
  644. # an old, failed partial state join.
  645. # https://github.com/matrix-org/synapse/issues/13000
  646. await self.store.write_partial_state_rooms_join_event_id(
  647. room_id, event.event_id
  648. )
  649. finally:
  650. # Always kick off the background process that asynchronously fetches
  651. # state for the room.
  652. # If the join failed, the background process is responsible for
  653. # cleaning up — including unmarking the room as a partial state
  654. # room.
  655. if ret.partial_state:
  656. # Kick off the process of asynchronously fetching the state for
  657. # this room.
  658. self._start_partial_state_room_sync(
  659. initial_destination=origin,
  660. other_destinations=ret.servers_in_room,
  661. room_id=room_id,
  662. )
  663. # We wait here until this instance has seen the events come down
  664. # replication (if we're using replication) as the below uses caches.
  665. await self._replication.wait_for_stream_position(
  666. self.config.worker.events_shard_config.get_instance(room_id),
  667. "events",
  668. max_stream_id,
  669. )
  670. # Check whether this room is the result of an upgrade of a room we already know
  671. # about. If so, migrate over user information
  672. predecessor = await self.store.get_room_predecessor(room_id)
  673. if not predecessor or not isinstance(predecessor.get("room_id"), str):
  674. return event.event_id, max_stream_id
  675. old_room_id = predecessor["room_id"]
  676. logger.debug(
  677. "Found predecessor for %s during remote join: %s", room_id, old_room_id
  678. )
  679. # We retrieve the room member handler here as to not cause a cyclic dependency
  680. member_handler = self.hs.get_room_member_handler()
  681. await member_handler.transfer_room_state_on_room_upgrade(
  682. old_room_id, room_id
  683. )
  684. logger.debug("Finished joining %s to %s", joinee, room_id)
  685. return event.event_id, max_stream_id
  686. finally:
  687. room_queue = self._federation_event_handler.room_queues[room_id]
  688. del self._federation_event_handler.room_queues[room_id]
  689. # we don't need to wait for the queued events to be processed -
  690. # it's just a best-effort thing at this point. We do want to do
  691. # them roughly in order, though, otherwise we'll end up making
  692. # lots of requests for missing prev_events which we do actually
  693. # have. Hence we fire off the background task, but don't wait for it.
  694. run_as_background_process(
  695. "handle_queued_pdus", self._handle_queued_pdus, room_queue
  696. )
  697. async def do_knock(
  698. self,
  699. target_hosts: List[str],
  700. room_id: str,
  701. knockee: str,
  702. content: JsonDict,
  703. ) -> Tuple[str, int]:
  704. """Sends the knock to the remote server.
  705. This first triggers a make_knock request that returns a partial
  706. event that we can fill out and sign. This is then sent to the
  707. remote server via send_knock.
  708. Knock events must be signed by the knockee's server before distributing.
  709. Args:
  710. target_hosts: A list of hosts that we want to try knocking through.
  711. room_id: The ID of the room to knock on.
  712. knockee: The ID of the user who is knocking.
  713. content: The content of the knock event.
  714. Returns:
  715. A tuple of (event ID, stream ID).
  716. Raises:
  717. SynapseError: If the chosen remote server returns a 3xx/4xx code.
  718. RuntimeError: If no servers were reachable.
  719. """
  720. logger.debug("Knocking on room %s on behalf of user %s", room_id, knockee)
  721. # Inform the remote server of the room versions we support
  722. supported_room_versions = list(KNOWN_ROOM_VERSIONS.keys())
  723. # Ask the remote server to create a valid knock event for us. Once received,
  724. # we sign the event
  725. params: Dict[str, Iterable[str]] = {"ver": supported_room_versions}
  726. origin, event, event_format_version = await self._make_and_verify_event(
  727. target_hosts, room_id, knockee, Membership.KNOCK, content, params=params
  728. )
  729. # Mark the knock as an outlier as we don't yet have the state at this point in
  730. # the DAG.
  731. event.internal_metadata.outlier = True
  732. # ... but tell /sync to send it to clients anyway.
  733. event.internal_metadata.out_of_band_membership = True
  734. # Record the room ID and its version so that we have a record of the room
  735. await self._maybe_store_room_on_outlier_membership(
  736. room_id=event.room_id, room_version=event_format_version
  737. )
  738. # Initially try the host that we successfully called /make_knock on
  739. try:
  740. target_hosts.remove(origin)
  741. target_hosts.insert(0, origin)
  742. except ValueError:
  743. pass
  744. # Send the signed event back to the room, and potentially receive some
  745. # further information about the room in the form of partial state events
  746. knock_response = await self.federation_client.send_knock(target_hosts, event)
  747. # Store any stripped room state events in the "unsigned" key of the event.
  748. # This is a bit of a hack and is cribbing off of invites. Basically we
  749. # store the room state here and retrieve it again when this event appears
  750. # in the invitee's sync stream. It is stripped out for all other local users.
  751. stripped_room_state = (
  752. knock_response.get("knock_room_state")
  753. # Since v1.37, Synapse incorrectly used "knock_state_events" for this field.
  754. # Thus, we also check for a 'knock_state_events' to support old instances.
  755. # See https://github.com/matrix-org/synapse/issues/14088.
  756. or knock_response.get("knock_state_events")
  757. )
  758. if stripped_room_state is None:
  759. raise KeyError(
  760. "Missing 'knock_room_state' (or legacy 'knock_state_events') field in "
  761. "send_knock response"
  762. )
  763. event.unsigned["knock_room_state"] = stripped_room_state
  764. context = EventContext.for_outlier(self._storage_controllers)
  765. stream_id = await self._federation_event_handler.persist_events_and_notify(
  766. event.room_id, [(event, context)]
  767. )
  768. return event.event_id, stream_id
  769. async def _handle_queued_pdus(
  770. self, room_queue: List[Tuple[EventBase, str]]
  771. ) -> None:
  772. """Process PDUs which got queued up while we were busy send_joining.
  773. Args:
  774. room_queue: list of PDUs to be processed and the servers that sent them
  775. """
  776. for p, origin in room_queue:
  777. try:
  778. logger.info(
  779. "Processing queued PDU %s which was received while we were joining",
  780. p,
  781. )
  782. with nested_logging_context(p.event_id):
  783. await self._federation_event_handler.on_receive_pdu(origin, p)
  784. except Exception as e:
  785. logger.warning(
  786. "Error handling queued PDU %s from %s: %s", p.event_id, origin, e
  787. )
  788. async def on_make_join_request(
  789. self, origin: str, room_id: str, user_id: str
  790. ) -> EventBase:
  791. """We've received a /make_join/ request, so we create a partial
  792. join event for the room and return that. We do *not* persist or
  793. process it until the other server has signed it and sent it back.
  794. Args:
  795. origin: The (verified) server name of the requesting server.
  796. room_id: Room to create join event in
  797. user_id: The user to create the join for
  798. """
  799. if get_domain_from_id(user_id) != origin:
  800. logger.info(
  801. "Got /make_join request for user %r from different origin %s, ignoring",
  802. user_id,
  803. origin,
  804. )
  805. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  806. # checking the room version will check that we've actually heard of the room
  807. # (and return a 404 otherwise)
  808. room_version = await self.store.get_room_version(room_id)
  809. if await self.store.is_partial_state_room(room_id):
  810. # If our server is still only partially joined, we can't give a complete
  811. # response to /make_join, so return a 404 as we would if we weren't in the
  812. # room at all.
  813. # The main reason we can't respond properly is that we need to know about
  814. # the auth events for the join event that we would return.
  815. # We also should not bother entertaining the /make_join since we cannot
  816. # handle the /send_join.
  817. logger.info(
  818. "Rejecting /make_join to %s because it's a partial state room", room_id
  819. )
  820. raise SynapseError(
  821. 404,
  822. "Unable to handle /make_join right now; this server is not fully joined.",
  823. errcode=Codes.NOT_FOUND,
  824. )
  825. # now check that we are *still* in the room
  826. is_in_room = await self._event_auth_handler.is_host_in_room(
  827. room_id, self.server_name
  828. )
  829. if not is_in_room:
  830. logger.info(
  831. "Got /make_join request for room %s we are no longer in",
  832. room_id,
  833. )
  834. raise NotFoundError("Not an active room on this server")
  835. event_content = {"membership": Membership.JOIN}
  836. # If the current room is using restricted join rules, additional information
  837. # may need to be included in the event content in order to efficiently
  838. # validate the event.
  839. #
  840. # Note that this requires the /send_join request to come back to the
  841. # same server.
  842. if room_version.msc3083_join_rules:
  843. state_ids = await self._state_storage_controller.get_current_state_ids(
  844. room_id
  845. )
  846. if await self._event_auth_handler.has_restricted_join_rules(
  847. state_ids, room_version
  848. ):
  849. prev_member_event_id = state_ids.get((EventTypes.Member, user_id), None)
  850. # If the user is invited or joined to the room already, then
  851. # no additional info is needed.
  852. include_auth_user_id = True
  853. if prev_member_event_id:
  854. prev_member_event = await self.store.get_event(prev_member_event_id)
  855. include_auth_user_id = prev_member_event.membership not in (
  856. Membership.JOIN,
  857. Membership.INVITE,
  858. )
  859. if include_auth_user_id:
  860. event_content[
  861. EventContentFields.AUTHORISING_USER
  862. ] = await self._event_auth_handler.get_user_which_could_invite(
  863. room_id,
  864. state_ids,
  865. )
  866. builder = self.event_builder_factory.for_room_version(
  867. room_version,
  868. {
  869. "type": EventTypes.Member,
  870. "content": event_content,
  871. "room_id": room_id,
  872. "sender": user_id,
  873. "state_key": user_id,
  874. },
  875. )
  876. try:
  877. event, context = await self.event_creation_handler.create_new_client_event(
  878. builder=builder
  879. )
  880. except SynapseError as e:
  881. logger.warning("Failed to create join to %s because %s", room_id, e)
  882. raise
  883. # Ensure the user can even join the room.
  884. await self._federation_event_handler.check_join_restrictions(context, event)
  885. # The remote hasn't signed it yet, obviously. We'll do the full checks
  886. # when we get the event back in `on_send_join_request`
  887. await self._event_auth_handler.check_auth_rules_from_context(event)
  888. return event
  889. async def on_invite_request(
  890. self, origin: str, event: EventBase, room_version: RoomVersion
  891. ) -> EventBase:
  892. """We've got an invite event. Process and persist it. Sign it.
  893. Respond with the now signed event.
  894. """
  895. if event.state_key is None:
  896. raise SynapseError(400, "The invite event did not have a state key")
  897. is_blocked = await self.store.is_room_blocked(event.room_id)
  898. if is_blocked:
  899. raise SynapseError(403, "This room has been blocked on this server")
  900. if self.hs.config.server.block_non_admin_invites:
  901. raise SynapseError(403, "This server does not accept room invites")
  902. spam_check = await self.spam_checker.user_may_invite(
  903. event.sender, event.state_key, event.room_id
  904. )
  905. if spam_check != NOT_SPAM:
  906. raise SynapseError(
  907. 403,
  908. "This user is not permitted to send invites to this server/user",
  909. errcode=spam_check[0],
  910. additional_fields=spam_check[1],
  911. )
  912. membership = event.content.get("membership")
  913. if event.type != EventTypes.Member or membership != Membership.INVITE:
  914. raise SynapseError(400, "The event was not an m.room.member invite event")
  915. sender_domain = get_domain_from_id(event.sender)
  916. if sender_domain != origin:
  917. raise SynapseError(
  918. 400, "The invite event was not from the server sending it"
  919. )
  920. if not self.is_mine_id(event.state_key):
  921. raise SynapseError(400, "The invite event must be for this server")
  922. # block any attempts to invite the server notices mxid
  923. if event.state_key == self._server_notices_mxid:
  924. raise SynapseError(HTTPStatus.FORBIDDEN, "Cannot invite this user")
  925. # We retrieve the room member handler here as to not cause a cyclic dependency
  926. member_handler = self.hs.get_room_member_handler()
  927. # We don't rate limit based on room ID, as that should be done by
  928. # sending server.
  929. await member_handler.ratelimit_invite(None, None, event.state_key)
  930. # keep a record of the room version, if we don't yet know it.
  931. # (this may get overwritten if we later get a different room version in a
  932. # join dance).
  933. await self._maybe_store_room_on_outlier_membership(
  934. room_id=event.room_id, room_version=room_version
  935. )
  936. event.internal_metadata.outlier = True
  937. event.internal_metadata.out_of_band_membership = True
  938. event.signatures.update(
  939. compute_event_signature(
  940. room_version,
  941. event.get_pdu_json(),
  942. self.hs.hostname,
  943. self.hs.signing_key,
  944. )
  945. )
  946. context = EventContext.for_outlier(self._storage_controllers)
  947. await self._bulk_push_rule_evaluator.action_for_events_by_user(
  948. [(event, context)]
  949. )
  950. try:
  951. await self._federation_event_handler.persist_events_and_notify(
  952. event.room_id, [(event, context)]
  953. )
  954. except Exception:
  955. await self.store.remove_push_actions_from_staging(event.event_id)
  956. raise
  957. return event
  958. async def do_remotely_reject_invite(
  959. self, target_hosts: Iterable[str], room_id: str, user_id: str, content: JsonDict
  960. ) -> Tuple[EventBase, int]:
  961. origin, event, room_version = await self._make_and_verify_event(
  962. target_hosts, room_id, user_id, "leave", content=content
  963. )
  964. # Mark as outlier as we don't have any state for this event; we're not
  965. # even in the room.
  966. event.internal_metadata.outlier = True
  967. event.internal_metadata.out_of_band_membership = True
  968. # Try the host that we successfully called /make_leave/ on first for
  969. # the /send_leave/ request.
  970. host_list = list(target_hosts)
  971. try:
  972. host_list.remove(origin)
  973. host_list.insert(0, origin)
  974. except ValueError:
  975. pass
  976. await self.federation_client.send_leave(host_list, event)
  977. context = EventContext.for_outlier(self._storage_controllers)
  978. stream_id = await self._federation_event_handler.persist_events_and_notify(
  979. event.room_id, [(event, context)]
  980. )
  981. return event, stream_id
  982. async def _make_and_verify_event(
  983. self,
  984. target_hosts: Iterable[str],
  985. room_id: str,
  986. user_id: str,
  987. membership: str,
  988. content: JsonDict,
  989. params: Optional[Dict[str, Union[str, Iterable[str]]]] = None,
  990. ) -> Tuple[str, EventBase, RoomVersion]:
  991. (
  992. origin,
  993. event,
  994. room_version,
  995. ) = await self.federation_client.make_membership_event(
  996. target_hosts, room_id, user_id, membership, content, params=params
  997. )
  998. logger.debug("Got response to make_%s: %s", membership, event)
  999. # We should assert some things.
  1000. # FIXME: Do this in a nicer way
  1001. assert event.type == EventTypes.Member
  1002. assert event.user_id == user_id
  1003. assert event.state_key == user_id
  1004. assert event.room_id == room_id
  1005. return origin, event, room_version
  1006. async def on_make_leave_request(
  1007. self, origin: str, room_id: str, user_id: str
  1008. ) -> EventBase:
  1009. """We've received a /make_leave/ request, so we create a partial
  1010. leave event for the room and return that. We do *not* persist or
  1011. process it until the other server has signed it and sent it back.
  1012. Args:
  1013. origin: The (verified) server name of the requesting server.
  1014. room_id: Room to create leave event in
  1015. user_id: The user to create the leave for
  1016. """
  1017. if get_domain_from_id(user_id) != origin:
  1018. logger.info(
  1019. "Got /make_leave request for user %r from different origin %s, ignoring",
  1020. user_id,
  1021. origin,
  1022. )
  1023. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1024. room_version_obj = await self.store.get_room_version(room_id)
  1025. builder = self.event_builder_factory.for_room_version(
  1026. room_version_obj,
  1027. {
  1028. "type": EventTypes.Member,
  1029. "content": {"membership": Membership.LEAVE},
  1030. "room_id": room_id,
  1031. "sender": user_id,
  1032. "state_key": user_id,
  1033. },
  1034. )
  1035. event, context = await self.event_creation_handler.create_new_client_event(
  1036. builder=builder
  1037. )
  1038. try:
  1039. # The remote hasn't signed it yet, obviously. We'll do the full checks
  1040. # when we get the event back in `on_send_leave_request`
  1041. await self._event_auth_handler.check_auth_rules_from_context(event)
  1042. except AuthError as e:
  1043. logger.warning("Failed to create new leave %r because %s", event, e)
  1044. raise e
  1045. return event
  1046. async def on_make_knock_request(
  1047. self, origin: str, room_id: str, user_id: str
  1048. ) -> EventBase:
  1049. """We've received a make_knock request, so we create a partial
  1050. knock event for the room and return that. We do *not* persist or
  1051. process it until the other server has signed it and sent it back.
  1052. Args:
  1053. origin: The (verified) server name of the requesting server.
  1054. room_id: The room to create the knock event in.
  1055. user_id: The user to create the knock for.
  1056. Returns:
  1057. The partial knock event.
  1058. """
  1059. if get_domain_from_id(user_id) != origin:
  1060. logger.info(
  1061. "Get /make_knock request for user %r from different origin %s, ignoring",
  1062. user_id,
  1063. origin,
  1064. )
  1065. raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
  1066. room_version_obj = await self.store.get_room_version(room_id)
  1067. builder = self.event_builder_factory.for_room_version(
  1068. room_version_obj,
  1069. {
  1070. "type": EventTypes.Member,
  1071. "content": {"membership": Membership.KNOCK},
  1072. "room_id": room_id,
  1073. "sender": user_id,
  1074. "state_key": user_id,
  1075. },
  1076. )
  1077. event, context = await self.event_creation_handler.create_new_client_event(
  1078. builder=builder
  1079. )
  1080. event_allowed, _ = await self.third_party_event_rules.check_event_allowed(
  1081. event, context
  1082. )
  1083. if not event_allowed:
  1084. logger.warning("Creation of knock %s forbidden by third-party rules", event)
  1085. raise SynapseError(
  1086. 403, "This event is not allowed in this context", Codes.FORBIDDEN
  1087. )
  1088. try:
  1089. # The remote hasn't signed it yet, obviously. We'll do the full checks
  1090. # when we get the event back in `on_send_knock_request`
  1091. await self._event_auth_handler.check_auth_rules_from_context(event)
  1092. except AuthError as e:
  1093. logger.warning("Failed to create new knock %r because %s", event, e)
  1094. raise e
  1095. return event
  1096. @trace
  1097. @tag_args
  1098. async def get_state_ids_for_pdu(self, room_id: str, event_id: str) -> List[str]:
  1099. """Returns the state at the event. i.e. not including said event."""
  1100. event = await self.store.get_event(event_id, check_room_id=room_id)
  1101. if event.internal_metadata.outlier:
  1102. raise NotFoundError("State not known at event %s" % (event_id,))
  1103. state_groups = await self._state_storage_controller.get_state_groups_ids(
  1104. room_id, [event_id]
  1105. )
  1106. # get_state_groups_ids should return exactly one result
  1107. assert len(state_groups) == 1
  1108. state_map = next(iter(state_groups.values()))
  1109. state_key = event.get_state_key()
  1110. if state_key is not None:
  1111. # the event was not rejected (get_event raises a NotFoundError for rejected
  1112. # events) so the state at the event should include the event itself.
  1113. assert (
  1114. state_map.get((event.type, state_key)) == event.event_id
  1115. ), "State at event did not include event itself"
  1116. # ... but we need the state *before* that event
  1117. if "replaces_state" in event.unsigned:
  1118. prev_id = event.unsigned["replaces_state"]
  1119. state_map[(event.type, state_key)] = prev_id
  1120. else:
  1121. del state_map[(event.type, state_key)]
  1122. return list(state_map.values())
  1123. async def on_backfill_request(
  1124. self, origin: str, room_id: str, pdu_list: List[str], limit: int
  1125. ) -> List[EventBase]:
  1126. # We allow partially joined rooms since in this case we are filtering out
  1127. # non-local events in `filter_events_for_server`.
  1128. await self._event_auth_handler.assert_host_in_room(room_id, origin, True)
  1129. # Synapse asks for 100 events per backfill request. Do not allow more.
  1130. limit = min(limit, 100)
  1131. events = await self.store.get_backfill_events(room_id, pdu_list, limit)
  1132. logger.debug(
  1133. "on_backfill_request: backfill events=%s",
  1134. [
  1135. "event_id=%s,depth=%d,body=%s,prevs=%s\n"
  1136. % (
  1137. event.event_id,
  1138. event.depth,
  1139. event.content.get("body", event.type),
  1140. event.prev_event_ids(),
  1141. )
  1142. for event in events
  1143. ],
  1144. )
  1145. events = await filter_events_for_server(
  1146. self._storage_controllers, origin, self.server_name, events
  1147. )
  1148. return events
  1149. async def get_persisted_pdu(
  1150. self, origin: str, event_id: str
  1151. ) -> Optional[EventBase]:
  1152. """Get an event from the database for the given server.
  1153. Args:
  1154. origin: hostname of server which is requesting the event; we
  1155. will check that the server is allowed to see it.
  1156. event_id: id of the event being requested
  1157. Returns:
  1158. None if we know nothing about the event; otherwise the (possibly-redacted) event.
  1159. Raises:
  1160. AuthError if the server is not currently in the room
  1161. """
  1162. event = await self.store.get_event(
  1163. event_id, allow_none=True, allow_rejected=True
  1164. )
  1165. if not event:
  1166. return None
  1167. await self._event_auth_handler.assert_host_in_room(event.room_id, origin)
  1168. events = await filter_events_for_server(
  1169. self._storage_controllers, origin, self.server_name, [event]
  1170. )
  1171. event = events[0]
  1172. return event
  1173. async def on_get_missing_events(
  1174. self,
  1175. origin: str,
  1176. room_id: str,
  1177. earliest_events: List[str],
  1178. latest_events: List[str],
  1179. limit: int,
  1180. ) -> List[EventBase]:
  1181. # We allow partially joined rooms since in this case we are filtering out
  1182. # non-local events in `filter_events_for_server`.
  1183. await self._event_auth_handler.assert_host_in_room(room_id, origin, True)
  1184. # Only allow up to 20 events to be retrieved per request.
  1185. limit = min(limit, 20)
  1186. missing_events = await self.store.get_missing_events(
  1187. room_id=room_id,
  1188. earliest_events=earliest_events,
  1189. latest_events=latest_events,
  1190. limit=limit,
  1191. )
  1192. missing_events = await filter_events_for_server(
  1193. self._storage_controllers, origin, self.server_name, missing_events
  1194. )
  1195. return missing_events
  1196. async def exchange_third_party_invite(
  1197. self, sender_user_id: str, target_user_id: str, room_id: str, signed: JsonDict
  1198. ) -> None:
  1199. third_party_invite = {"signed": signed}
  1200. event_dict = {
  1201. "type": EventTypes.Member,
  1202. "content": {
  1203. "membership": Membership.INVITE,
  1204. "third_party_invite": third_party_invite,
  1205. },
  1206. "room_id": room_id,
  1207. "sender": sender_user_id,
  1208. "state_key": target_user_id,
  1209. }
  1210. if await self._event_auth_handler.is_host_in_room(room_id, self.hs.hostname):
  1211. room_version_obj = await self.store.get_room_version(room_id)
  1212. builder = self.event_builder_factory.for_room_version(
  1213. room_version_obj, event_dict
  1214. )
  1215. EventValidator().validate_builder(builder)
  1216. # Try several times, it could fail with PartialStateConflictError
  1217. # in send_membership_event, cf comment in except block.
  1218. max_retries = 5
  1219. for i in range(max_retries):
  1220. try:
  1221. (
  1222. event,
  1223. context,
  1224. ) = await self.event_creation_handler.create_new_client_event(
  1225. builder=builder
  1226. )
  1227. event, context = await self.add_display_name_to_third_party_invite(
  1228. room_version_obj, event_dict, event, context
  1229. )
  1230. EventValidator().validate_new(event, self.config)
  1231. # We need to tell the transaction queue to send this out, even
  1232. # though the sender isn't a local user.
  1233. event.internal_metadata.send_on_behalf_of = self.hs.hostname
  1234. try:
  1235. validate_event_for_room_version(event)
  1236. await self._event_auth_handler.check_auth_rules_from_context(
  1237. event
  1238. )
  1239. except AuthError as e:
  1240. logger.warning(
  1241. "Denying new third party invite %r because %s", event, e
  1242. )
  1243. raise e
  1244. await self._check_signature(event, context)
  1245. # We retrieve the room member handler here as to not cause a cyclic dependency
  1246. member_handler = self.hs.get_room_member_handler()
  1247. await member_handler.send_membership_event(None, event, context)
  1248. break
  1249. except PartialStateConflictError as e:
  1250. # Persisting couldn't happen because the room got un-partial stated
  1251. # in the meantime and context needs to be recomputed, so let's do so.
  1252. if i == max_retries - 1:
  1253. raise e
  1254. pass
  1255. else:
  1256. destinations = {x.split(":", 1)[-1] for x in (sender_user_id, room_id)}
  1257. try:
  1258. await self.federation_client.forward_third_party_invite(
  1259. destinations, room_id, event_dict
  1260. )
  1261. except (RequestSendFailed, HttpResponseException):
  1262. raise SynapseError(502, "Failed to forward third party invite")
  1263. async def on_exchange_third_party_invite_request(
  1264. self, event_dict: JsonDict
  1265. ) -> None:
  1266. """Handle an exchange_third_party_invite request from a remote server
  1267. The remote server will call this when it wants to turn a 3pid invite
  1268. into a normal m.room.member invite.
  1269. Args:
  1270. event_dict: Dictionary containing the event body.
  1271. """
  1272. assert_params_in_dict(event_dict, ["room_id"])
  1273. room_version_obj = await self.store.get_room_version(event_dict["room_id"])
  1274. # NB: event_dict has a particular specced format we might need to fudge
  1275. # if we change event formats too much.
  1276. builder = self.event_builder_factory.for_room_version(
  1277. room_version_obj, event_dict
  1278. )
  1279. # Try several times, it could fail with PartialStateConflictError
  1280. # in send_membership_event, cf comment in except block.
  1281. max_retries = 5
  1282. for i in range(max_retries):
  1283. try:
  1284. (
  1285. event,
  1286. context,
  1287. ) = await self.event_creation_handler.create_new_client_event(
  1288. builder=builder
  1289. )
  1290. event, context = await self.add_display_name_to_third_party_invite(
  1291. room_version_obj, event_dict, event, context
  1292. )
  1293. try:
  1294. validate_event_for_room_version(event)
  1295. await self._event_auth_handler.check_auth_rules_from_context(event)
  1296. except AuthError as e:
  1297. logger.warning("Denying third party invite %r because %s", event, e)
  1298. raise e
  1299. await self._check_signature(event, context)
  1300. # We need to tell the transaction queue to send this out, even
  1301. # though the sender isn't a local user.
  1302. event.internal_metadata.send_on_behalf_of = get_domain_from_id(
  1303. event.sender
  1304. )
  1305. # We retrieve the room member handler here as to not cause a cyclic dependency
  1306. member_handler = self.hs.get_room_member_handler()
  1307. await member_handler.send_membership_event(None, event, context)
  1308. break
  1309. except PartialStateConflictError as e:
  1310. # Persisting couldn't happen because the room got un-partial stated
  1311. # in the meantime and context needs to be recomputed, so let's do so.
  1312. if i == max_retries - 1:
  1313. raise e
  1314. pass
  1315. async def add_display_name_to_third_party_invite(
  1316. self,
  1317. room_version_obj: RoomVersion,
  1318. event_dict: JsonDict,
  1319. event: EventBase,
  1320. context: EventContext,
  1321. ) -> Tuple[EventBase, EventContext]:
  1322. key = (
  1323. EventTypes.ThirdPartyInvite,
  1324. event.content["third_party_invite"]["signed"]["token"],
  1325. )
  1326. original_invite = None
  1327. prev_state_ids = await context.get_prev_state_ids(
  1328. StateFilter.from_types([(EventTypes.ThirdPartyInvite, None)])
  1329. )
  1330. original_invite_id = prev_state_ids.get(key)
  1331. if original_invite_id:
  1332. original_invite = await self.store.get_event(
  1333. original_invite_id, allow_none=True
  1334. )
  1335. if original_invite:
  1336. # If the m.room.third_party_invite event's content is empty, it means the
  1337. # invite has been revoked. In this case, we don't have to raise an error here
  1338. # because the auth check will fail on the invite (because it's not able to
  1339. # fetch public keys from the m.room.third_party_invite event's content, which
  1340. # is empty).
  1341. display_name = original_invite.content.get("display_name")
  1342. event_dict["content"]["third_party_invite"]["display_name"] = display_name
  1343. else:
  1344. logger.info(
  1345. "Could not find invite event for third_party_invite: %r", event_dict
  1346. )
  1347. # We don't discard here as this is not the appropriate place to do
  1348. # auth checks. If we need the invite and don't have it then the
  1349. # auth check code will explode appropriately.
  1350. builder = self.event_builder_factory.for_room_version(
  1351. room_version_obj, event_dict
  1352. )
  1353. EventValidator().validate_builder(builder)
  1354. event, context = await self.event_creation_handler.create_new_client_event(
  1355. builder=builder
  1356. )
  1357. EventValidator().validate_new(event, self.config)
  1358. return event, context
  1359. async def _check_signature(self, event: EventBase, context: EventContext) -> None:
  1360. """
  1361. Checks that the signature in the event is consistent with its invite.
  1362. Args:
  1363. event: The m.room.member event to check
  1364. context:
  1365. Raises:
  1366. AuthError: if signature didn't match any keys, or key has been
  1367. revoked,
  1368. SynapseError: if a transient error meant a key couldn't be checked
  1369. for revocation.
  1370. """
  1371. signed = event.content["third_party_invite"]["signed"]
  1372. token = signed["token"]
  1373. prev_state_ids = await context.get_prev_state_ids(
  1374. StateFilter.from_types([(EventTypes.ThirdPartyInvite, None)])
  1375. )
  1376. invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
  1377. invite_event = None
  1378. if invite_event_id:
  1379. invite_event = await self.store.get_event(invite_event_id, allow_none=True)
  1380. if not invite_event:
  1381. raise AuthError(403, "Could not find invite")
  1382. logger.debug("Checking auth on event %r", event.content)
  1383. last_exception: Optional[Exception] = None
  1384. # for each public key in the 3pid invite event
  1385. for public_key_object in event_auth.get_public_keys(invite_event):
  1386. try:
  1387. # for each sig on the third_party_invite block of the actual invite
  1388. for server, signature_block in signed["signatures"].items():
  1389. for key_name in signature_block.keys():
  1390. if not key_name.startswith("ed25519:"):
  1391. continue
  1392. logger.debug(
  1393. "Attempting to verify sig with key %s from %r "
  1394. "against pubkey %r",
  1395. key_name,
  1396. server,
  1397. public_key_object,
  1398. )
  1399. try:
  1400. public_key = public_key_object["public_key"]
  1401. verify_key = decode_verify_key_bytes(
  1402. key_name, decode_base64(public_key)
  1403. )
  1404. verify_signed_json(signed, server, verify_key)
  1405. logger.debug(
  1406. "Successfully verified sig with key %s from %r "
  1407. "against pubkey %r",
  1408. key_name,
  1409. server,
  1410. public_key_object,
  1411. )
  1412. except Exception:
  1413. logger.info(
  1414. "Failed to verify sig with key %s from %r "
  1415. "against pubkey %r",
  1416. key_name,
  1417. server,
  1418. public_key_object,
  1419. )
  1420. raise
  1421. try:
  1422. if "key_validity_url" in public_key_object:
  1423. await self._check_key_revocation(
  1424. public_key, public_key_object["key_validity_url"]
  1425. )
  1426. except Exception:
  1427. logger.info(
  1428. "Failed to query key_validity_url %s",
  1429. public_key_object["key_validity_url"],
  1430. )
  1431. raise
  1432. return
  1433. except Exception as e:
  1434. last_exception = e
  1435. if last_exception is None:
  1436. # we can only get here if get_public_keys() returned an empty list
  1437. # TODO: make this better
  1438. raise RuntimeError("no public key in invite event")
  1439. raise last_exception
  1440. async def _check_key_revocation(self, public_key: str, url: str) -> None:
  1441. """
  1442. Checks whether public_key has been revoked.
  1443. Args:
  1444. public_key: base-64 encoded public key.
  1445. url: Key revocation URL.
  1446. Raises:
  1447. AuthError: if they key has been revoked.
  1448. SynapseError: if a transient error meant a key couldn't be checked
  1449. for revocation.
  1450. """
  1451. try:
  1452. response = await self.http_client.get_json(url, {"public_key": public_key})
  1453. except Exception:
  1454. raise SynapseError(502, "Third party certificate could not be checked")
  1455. if "valid" not in response or not response["valid"]:
  1456. raise AuthError(403, "Third party certificate was invalid")
  1457. async def _clean_room_for_join(self, room_id: str) -> None:
  1458. """Called to clean up any data in DB for a given room, ready for the
  1459. server to join the room.
  1460. Args:
  1461. room_id
  1462. """
  1463. if self.config.worker.worker_app:
  1464. await self._clean_room_for_join_client(room_id)
  1465. else:
  1466. await self.store.clean_room_for_join(room_id)
  1467. async def get_room_complexity(
  1468. self, remote_room_hosts: List[str], room_id: str
  1469. ) -> Optional[dict]:
  1470. """
  1471. Fetch the complexity of a remote room over federation.
  1472. Args:
  1473. remote_room_hosts: The remote servers to ask.
  1474. room_id: The room ID to ask about.
  1475. Returns:
  1476. Dict contains the complexity
  1477. metric versions, while None means we could not fetch the complexity.
  1478. """
  1479. for host in remote_room_hosts:
  1480. res = await self.federation_client.get_room_complexity(host, room_id)
  1481. # We got a result, return it.
  1482. if res:
  1483. return res
  1484. # We fell off the bottom, couldn't get the complexity from anyone. Oh
  1485. # well.
  1486. return None
  1487. async def _resume_partial_state_room_sync(self) -> None:
  1488. """Resumes resyncing of all partial-state rooms after a restart."""
  1489. assert not self.config.worker.worker_app
  1490. partial_state_rooms = await self.store.get_partial_state_room_resync_info()
  1491. for room_id, resync_info in partial_state_rooms.items():
  1492. self._start_partial_state_room_sync(
  1493. initial_destination=resync_info.joined_via,
  1494. other_destinations=resync_info.servers_in_room,
  1495. room_id=room_id,
  1496. )
  1497. def _start_partial_state_room_sync(
  1498. self,
  1499. initial_destination: Optional[str],
  1500. other_destinations: Collection[str],
  1501. room_id: str,
  1502. ) -> None:
  1503. """Starts the background process to resync the state of a partial state room,
  1504. if it is not already running.
  1505. Args:
  1506. initial_destination: the initial homeserver to pull the state from
  1507. other_destinations: other homeservers to try to pull the state from, if
  1508. `initial_destination` is unavailable
  1509. room_id: room to be resynced
  1510. """
  1511. async def _sync_partial_state_room_wrapper() -> None:
  1512. if room_id in self._active_partial_state_syncs:
  1513. # Another local user has joined the room while there is already a
  1514. # partial state sync running. This implies that there is a new join
  1515. # event to un-partial state. We might find ourselves in one of a few
  1516. # scenarios:
  1517. # 1. There is an existing partial state sync. The partial state sync
  1518. # un-partial states the new join event before completing and all is
  1519. # well.
  1520. # 2. Before the latest join, the homeserver was no longer in the room
  1521. # and there is an existing partial state sync from our previous
  1522. # membership of the room. The partial state sync may have:
  1523. # a) succeeded, but not yet terminated. The room will not be
  1524. # un-partial stated again unless we restart the partial state
  1525. # sync.
  1526. # b) failed, because we were no longer in the room and remote
  1527. # homeservers were refusing our requests, but not yet
  1528. # terminated. After the latest join, remote homeservers may
  1529. # start answering our requests again, so we should restart the
  1530. # partial state sync.
  1531. # In the cases where we would want to restart the partial state sync,
  1532. # the room would have the partial state flag when the partial state sync
  1533. # terminates.
  1534. self._partial_state_syncs_maybe_needing_restart[room_id] = (
  1535. initial_destination,
  1536. other_destinations,
  1537. )
  1538. return
  1539. self._active_partial_state_syncs.add(room_id)
  1540. try:
  1541. await self._sync_partial_state_room(
  1542. initial_destination=initial_destination,
  1543. other_destinations=other_destinations,
  1544. room_id=room_id,
  1545. )
  1546. finally:
  1547. # Read the room's partial state flag while we still hold the claim to
  1548. # being the active partial state sync (so that another partial state
  1549. # sync can't come along and mess with it under us).
  1550. # Normally, the partial state flag will be gone. If it isn't, then we
  1551. # may find ourselves in scenario 2a or 2b as described in the comment
  1552. # above, where we want to restart the partial state sync.
  1553. is_still_partial_state_room = await self.store.is_partial_state_room(
  1554. room_id
  1555. )
  1556. self._active_partial_state_syncs.remove(room_id)
  1557. if room_id in self._partial_state_syncs_maybe_needing_restart:
  1558. (
  1559. restart_initial_destination,
  1560. restart_other_destinations,
  1561. ) = self._partial_state_syncs_maybe_needing_restart.pop(room_id)
  1562. if is_still_partial_state_room:
  1563. self._start_partial_state_room_sync(
  1564. initial_destination=restart_initial_destination,
  1565. other_destinations=restart_other_destinations,
  1566. room_id=room_id,
  1567. )
  1568. run_as_background_process(
  1569. desc="sync_partial_state_room", func=_sync_partial_state_room_wrapper
  1570. )
  1571. async def _sync_partial_state_room(
  1572. self,
  1573. initial_destination: Optional[str],
  1574. other_destinations: Collection[str],
  1575. room_id: str,
  1576. ) -> None:
  1577. """Background process to resync the state of a partial-state room
  1578. Args:
  1579. initial_destination: the initial homeserver to pull the state from
  1580. other_destinations: other homeservers to try to pull the state from, if
  1581. `initial_destination` is unavailable
  1582. room_id: room to be resynced
  1583. """
  1584. # Assume that we run on the main process for now.
  1585. # TODO(faster_joins,multiple workers)
  1586. # When moving the sync to workers, we need to ensure that
  1587. # * `_start_partial_state_room_sync` still prevents duplicate resyncs
  1588. # * `_is_partial_state_room_linearizer` correctly guards partial state flags
  1589. # for rooms between the workers doing remote joins and resync.
  1590. assert not self.config.worker.worker_app
  1591. # TODO(faster_joins): do we need to lock to avoid races? What happens if other
  1592. # worker processes kick off a resync in parallel? Perhaps we should just elect
  1593. # a single worker to do the resync.
  1594. # https://github.com/matrix-org/synapse/issues/12994
  1595. #
  1596. # TODO(faster_joins): what happens if we leave the room during a resync? if we
  1597. # really leave, that might mean we have difficulty getting the room state over
  1598. # federation.
  1599. # https://github.com/matrix-org/synapse/issues/12802
  1600. # Make an infinite iterator of destinations to try. Once we find a working
  1601. # destination, we'll stick with it until it flakes.
  1602. destinations = _prioritise_destinations_for_partial_state_resync(
  1603. initial_destination, other_destinations, room_id
  1604. )
  1605. destination_iter = itertools.cycle(destinations)
  1606. # `destination` is the current remote homeserver we're pulling from.
  1607. destination = next(destination_iter)
  1608. logger.info("Syncing state for room %s via %s", room_id, destination)
  1609. # we work through the queue in order of increasing stream ordering.
  1610. while True:
  1611. batch = await self.store.get_partial_state_events_batch(room_id)
  1612. if not batch:
  1613. # all the events are updated, so we can update current state and
  1614. # clear the lazy-loading flag.
  1615. logger.info("Updating current state for %s", room_id)
  1616. # TODO(faster_joins): notify workers in notify_room_un_partial_stated
  1617. # https://github.com/matrix-org/synapse/issues/12994
  1618. await self.state_handler.update_current_state(room_id)
  1619. logger.info("Handling any pending device list updates")
  1620. await self._device_handler.handle_room_un_partial_stated(room_id)
  1621. async with self._is_partial_state_room_linearizer.queue(room_id):
  1622. logger.info("Clearing partial-state flag for %s", room_id)
  1623. success = await self.store.clear_partial_state_room(room_id)
  1624. # Poke the notifier so that other workers see the write to
  1625. # the un-partial-stated rooms stream.
  1626. self._notifier.notify_replication()
  1627. if success:
  1628. logger.info("State resync complete for %s", room_id)
  1629. self._storage_controllers.state.notify_room_un_partial_stated(
  1630. room_id
  1631. )
  1632. # TODO(faster_joins) update room stats and user directory?
  1633. # https://github.com/matrix-org/synapse/issues/12814
  1634. # https://github.com/matrix-org/synapse/issues/12815
  1635. return
  1636. # we raced against more events arriving with partial state. Go round
  1637. # the loop again. We've already logged a warning, so no need for more.
  1638. continue
  1639. events = await self.store.get_events_as_list(
  1640. batch,
  1641. redact_behaviour=EventRedactBehaviour.as_is,
  1642. allow_rejected=True,
  1643. )
  1644. for event in events:
  1645. for attempt in itertools.count():
  1646. try:
  1647. await self._federation_event_handler.update_state_for_partial_state_event(
  1648. destination, event
  1649. )
  1650. break
  1651. except FederationPullAttemptBackoffError as exc:
  1652. # Log a warning about why we failed to process the event (the error message
  1653. # for `FederationPullAttemptBackoffError` is pretty good)
  1654. logger.warning("_sync_partial_state_room: %s", exc)
  1655. # We do not record a failed pull attempt when we backoff fetching a missing
  1656. # `prev_event` because not being able to fetch the `prev_events` just means
  1657. # we won't be able to de-outlier the pulled event. But we can still use an
  1658. # `outlier` in the state/auth chain for another event. So we shouldn't stop
  1659. # a downstream event from trying to pull it.
  1660. #
  1661. # This avoids a cascade of backoff for all events in the DAG downstream from
  1662. # one event backoff upstream.
  1663. except FederationError as e:
  1664. # TODO: We should `record_event_failed_pull_attempt` here,
  1665. # see https://github.com/matrix-org/synapse/issues/13700
  1666. if attempt == len(destinations) - 1:
  1667. # We have tried every remote server for this event. Give up.
  1668. # TODO(faster_joins) giving up isn't the right thing to do
  1669. # if there's a temporary network outage. retrying
  1670. # indefinitely is also not the right thing to do if we can
  1671. # reach all homeservers and they all claim they don't have
  1672. # the state we want.
  1673. # https://github.com/matrix-org/synapse/issues/13000
  1674. logger.error(
  1675. "Failed to get state for %s at %s from %s because %s, "
  1676. "giving up!",
  1677. room_id,
  1678. event,
  1679. destination,
  1680. e,
  1681. )
  1682. raise
  1683. # Try the next remote server.
  1684. logger.info(
  1685. "Failed to get state for %s at %s from %s because %s",
  1686. room_id,
  1687. event,
  1688. destination,
  1689. e,
  1690. )
  1691. destination = next(destination_iter)
  1692. logger.info(
  1693. "Syncing state for room %s via %s instead",
  1694. room_id,
  1695. destination,
  1696. )
  1697. def _prioritise_destinations_for_partial_state_resync(
  1698. initial_destination: Optional[str],
  1699. other_destinations: Collection[str],
  1700. room_id: str,
  1701. ) -> Collection[str]:
  1702. """Work out the order in which we should ask servers to resync events.
  1703. If an `initial_destination` is given, it takes top priority. Otherwise
  1704. all servers are treated equally.
  1705. :raises ValueError: if no destination is provided at all.
  1706. """
  1707. if initial_destination is None and len(other_destinations) == 0:
  1708. raise ValueError(f"Cannot resync state of {room_id}: no destinations provided")
  1709. if initial_destination is None:
  1710. return other_destinations
  1711. # Move `initial_destination` to the front of the list.
  1712. destinations = list(other_destinations)
  1713. if initial_destination in destinations:
  1714. destinations.remove(initial_destination)
  1715. destinations = [initial_destination] + destinations
  1716. return destinations