Skip to main content

tuwunel_service/rooms/event_handler/
mod.rs

1//! Incoming event handling, from the first signature check to the timeline.
2//!
3//! The service authorizes incoming PDUs, fetches the events they depend on,
4//! derives their state and appends them. Observability counters cover the
5//! local state build, the previous-event walk and the backoff verdicts. A
6//! per-room history keeps the previous-event walk passes for up to three days.
7
8mod acl_check;
9mod backoff;
10mod fetch_auth;
11mod fetch_prev;
12mod fetch_state;
13mod handle_incoming_pdu;
14mod handle_outlier_pdu;
15mod handle_prev_pdu;
16mod outlier_state;
17mod parse_incoming_pdu;
18mod policy_server;
19mod prev_walk;
20mod resolve_state;
21mod state_at_incoming;
22mod state_local_build;
23mod upgrade_outlier_pdu;
24
25use std::{fmt::Write, num::NonZeroUsize, sync::Arc};
26
27use async_trait::async_trait;
28use ruma::{EventId, OwnedRoomId, RoomVersionId, events::AnyStrippedStateEvent, serde::Raw};
29use tuwunel_core::{Result, implement, utils::MutexMap};
30use tuwunel_database::Map;
31use tuwunel_matrix::PduEvent;
32
33use self::{
34	backoff::BackoffCounters,
35	prev_walk::{InFlightWalks, PrevWalkCounters},
36	state_local_build::StateLocalCounters,
37};
38pub use self::{
39	backoff::{BackoffMetrics, Verdicts},
40	policy_server::PolicyCheck,
41	prev_walk::{
42		InFlightWalk, Outcome as PrevWalkOutcome, PrevWalkMetrics, PrevWalkPass, PrevWalkRoom,
43		Walk,
44	},
45	state_local_build::{LocalBuildReport, StateLocalMetrics},
46};
47use crate::service::make_name;
48
49/// Handles incoming events: authorization, fetching missing events, state
50/// resolution and upgrade into the timeline.
51///
52/// Federation transactions, joins, invites and backfill all route their PDUs
53/// through it.
54pub struct Service {
55	/// Serializes room federation as the outermost per-room operation.
56	///
57	/// Acquire it before the state or timeline insertion mutex for the same
58	/// room. The canonical order is federation, state, then insertion.
59	pub mutex_federation: RoomMutexMap,
60	services: Arc<crate::services::OnceServices>,
61	db: Data,
62	state_local: Arc<StateLocalCounters>,
63	prev_walk: PrevWalkCounters,
64
65	/// Gapped incoming events whose passes are in flight.
66	///
67	/// An entry lives exactly as long as its pass. Top-level timeline passes run
68	/// under the room's `mutex_federation` except for remote invites and a local
69	/// join's federation fallback, so entries stay within one per room holding its
70	/// federation mutex, plus any passes those two callers have in flight.
71	prev_walks_in_flight: InFlightWalks,
72
73	backoff: BackoffCounters,
74}
75
76struct Data {
77	eventid_backoff: Arc<Map>,
78	eventid_policysigstate: Arc<Map>,
79	eventid_resolvedstate: Arc<Map>,
80	roomtseventid_prevwalk: Arc<Map>,
81}
82
83type RoomMutexMap = MutexMap<OwnedRoomId, ()>;
84
85// Distinct candidate servers tried per fetch, not retries per server.
86const EVENT_FETCH_ATTEMPT_LIMIT: NonZeroUsize = NonZeroUsize::new(3).unwrap();
87
88#[async_trait]
89impl crate::Service for Service {
90	fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
91		Ok(Arc::new(Self {
92			mutex_federation: RoomMutexMap::new(),
93			services: args.services.clone(),
94			state_local: Arc::new(StateLocalCounters::default()),
95			prev_walk: PrevWalkCounters::default(),
96			prev_walks_in_flight: InFlightWalks::default(),
97			backoff: BackoffCounters::default(),
98			db: Data {
99				eventid_backoff: args.db["eventid_backoff"].clone(),
100				eventid_policysigstate: args.db["eventid_policysigstate"].clone(),
101				eventid_resolvedstate: args.db["eventid_resolvedstate"].clone(),
102				roomtseventid_prevwalk: args.db["roomtseventid_prevwalk"].clone(),
103			},
104		}))
105	}
106
107	async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result {
108		let mutex_federation = self.mutex_federation.len();
109
110		writeln!(out, "- federation_mutex: {mutex_federation}")?;
111
112		let prev_walks_in_flight = self.prev_walks_in_flight_count();
113
114		writeln!(out, "- prev_walks_in_flight: {prev_walks_in_flight}")?;
115
116		Ok(())
117	}
118
119	async fn clear_cache(&self) {
120		self.db.eventid_backoff.clear().await;
121		self.db.eventid_resolvedstate.clear().await;
122	}
123
124	fn name(&self) -> &str { make_name(module_path!()) }
125}
126
127#[implement(Service)]
128#[tracing::instrument(
129	name = "fetch",
130	level = "trace",
131	skip_all,
132	fields(%event_id)
133)]
134async fn event_fetch(&self, event_id: &EventId) -> Result<PduEvent> {
135	self.services.timeline.get_pdu(event_id).await
136}
137
138/// Extract a room's version from the create event in a stripped-state list (as
139/// stored for an out-of-band invite or knock).
140fn room_version_of(stripped: &[Raw<AnyStrippedStateEvent>]) -> Option<RoomVersionId> {
141	stripped
142		.iter()
143		.find_map(|event| match event.deserialize() {
144			| Ok(AnyStrippedStateEvent::RoomCreate(create)) => Some(create.content.room_version),
145			| _ => None,
146		})
147}