Skip to main content

tuwunel_service/sending/
device.rs

1use std::iter::once;
2
3use futures::StreamExt;
4use ruma::{DeviceId, OwnedRoomId, UserId};
5use serde::Serialize;
6use tuwunel_core::{Result, implement, utils::stream::BroadbandExt};
7
8use super::{Destination, EduBuf, SendingEvent, Service, TAG_DEVICE_LIST_CHANGED, TAG_TO_DEVICE};
9use crate::appservice::{RegistrationInfo, receivers};
10
11/// One recipient device of a to-device event paired with its inbox count.
12///
13/// The count uniquifies the appservice transaction hash.
14type Delivery<'a> = (&'a DeviceId, u64);
15
16/// Wire shape of one `de.sorunome.msc2409.to_device` entry (MSC4203).
17///
18/// The stored to-device event is flattened with the recipient's identifiers.
19/// The ruma `AnyAppserviceToDeviceEvent` deliberately has no `Serialize`, so
20/// the send side writes this local struct.
21#[derive(Serialize)]
22struct AsToDeviceEvent<'a> {
23	#[serde(rename = "type")]
24	kind: &'a str,
25	sender: &'a UserId,
26	content: &'a serde_json::Value,
27	to_user_id: &'a UserId,
28	to_device_id: &'a DeviceId,
29}
30
31/// Queue stored to-device events for delivery to interested appservices
32/// (MSC4203).
33///
34/// `deliveries` are the concrete recipient devices already written to the
35/// inbox, after `AllDevices` expansion. Each delivery becomes one queue row
36/// per interested appservice with a URL, written under one cork; with no such
37/// appservice nothing is serialized.
38#[implement(Service)]
39#[tracing::instrument(
40	skip(self, deliveries, content),
41	level = "debug",
42	fields(
43		%target_user,
44	),
45)]
46pub async fn send_to_device_appservices<'a, I>(
47	&self,
48	sender: &'a UserId,
49	target_user: &'a UserId,
50	deliveries: I,
51	event_type: &'a str,
52	content: &'a serde_json::Value,
53) -> Result
54where
55	I: Iterator<Item = Delivery<'a>> + Send + 'a,
56{
57	let registrations = self.services.appservice.read().await;
58	let interested = || receivers(&registrations).filter(|info| info.is_user_match(target_user));
59
60	// Serialize once, and only when an appservice will receive the events.
61	if interested().next().is_none() {
62		return Ok(());
63	}
64
65	let _cork = self.db.db.cork();
66
67	to_device_payloads(sender, target_user, deliveries, event_type, content)
68		.flat_map(|buf| interested().map(move |info| (info, buf.clone())))
69		.try_for_each(|(info, buf)| {
70			let dest = Destination::Appservice(info.registration.id.clone());
71
72			self.queue_and_dispatch(dest, SendingEvent::ToDevice(buf))
73		})
74}
75
76/// Queue a `device_lists.changed` marker (MSC3202) for delivery to
77/// appservices that have a URL, opted into transaction extensions, and are
78/// interested in `user_id`.
79///
80/// The caller passes the count it already allocated so the marker uniquifies
81/// the transaction hash.
82#[implement(Service)]
83#[tracing::instrument(
84	skip(self),
85	level = "debug",
86	fields(
87		%user_id,
88	),
89)]
90pub async fn send_device_list_appservices(&self, user_id: &UserId, count: u64) -> Result {
91	let registrations = self.services.appservice.read().await;
92	let extended = || {
93		receivers(&registrations).filter(|info| info.registration.msc3202_transaction_extensions)
94	};
95
96	if extended().next().is_none() {
97		return Ok(());
98	}
99
100	let payload = device_list_payload(user_id, count);
101	let _cork = self.db.db.cork();
102
103	for info in extended() {
104		if !info.is_user_match(user_id) && !self.shares_device_list_room(user_id, info).await {
105			continue;
106		}
107
108		let dest = Destination::Appservice(info.registration.id.clone());
109
110		self.queue_and_dispatch(dest, SendingEvent::DeviceListChanged(payload.clone()))?;
111	}
112
113	Ok(())
114}
115
116/// Whether `user_id` shares a device-list-interesting room with `info`.
117///
118/// A joined room the appservice participates in counts when it is encrypted,
119/// or unconditionally when `encryption.device_key_update_encrypted_rooms_only` is
120/// off.
121#[implement(Service)]
122async fn shares_device_list_room(&self, user_id: &UserId, info: &RegistrationInfo) -> bool {
123	let update_all_rooms = !self
124		.services
125		.config
126		.encryption
127		.device_key_update_encrypted_rooms_only;
128
129	self.services
130		.state_cache
131		.rooms_joined(user_id)
132		.map(ToOwned::to_owned)
133		.broad_any(async |room_id: OwnedRoomId| {
134			if !update_all_rooms
135				&& !self
136					.services
137					.state_accessor
138					.is_encrypted_room(&room_id)
139					.await
140			{
141				return false;
142			}
143
144			self.services
145				.state_cache
146				.appservice_in_room(&room_id, info)
147				.await
148		})
149		.await
150}
151
152fn to_device_payloads<'a>(
153	sender: &'a UserId,
154	target_user: &'a UserId,
155	deliveries: impl Iterator<Item = Delivery<'a>> + 'a,
156	event_type: &'a str,
157	content: &'a serde_json::Value,
158) -> impl Iterator<Item = EduBuf> + 'a {
159	deliveries.map(move |(to_device_id, count)| {
160		let event = AsToDeviceEvent {
161			kind: event_type,
162			sender,
163			content,
164			to_user_id: target_user,
165			to_device_id,
166		};
167
168		tagged_json(TAG_TO_DEVICE, count, &event)
169	})
170}
171
172/// A tagged queue row value whose body is `value` serialized as JSON.
173///
174/// The body is written straight into the inline buffer after the prefix.
175fn tagged_json(tag: u8, count: u64, value: &impl Serialize) -> EduBuf {
176	let mut buf = tag_prefix(tag, count); // serde_json::to_writer out-param
177
178	serde_json::to_writer(&mut buf, value).expect("tagged queue row value serializes");
179	buf
180}
181
182fn device_list_payload(user_id: &UserId, count: u64) -> EduBuf {
183	let mut buf = tag_prefix(TAG_DEVICE_LIST_CHANGED, count);
184
185	buf.extend_from_slice(user_id.as_bytes());
186	buf
187}
188
189/// The `[tag][count]` head every tagged queue row value starts with.
190///
191/// The count is written big-endian so the prefix is `TAG_PREFIX_LEN` bytes.
192fn tag_prefix(tag: u8, count: u64) -> EduBuf { once(tag).chain(count.to_be_bytes()).collect() }