Skip to main content

tuwunel_service/federation/
format.rs

1//! Outgoing federation event formatting.
2//!
3//! The formatter converts a canonical event object, or a stored event read by
4//! its ID, into the room-version shape expected by ruma's outgoing federation
5//! response types.
6
7use futures::future::OptionFuture;
8use ruma::{CanonicalJsonObject, CanonicalJsonValue, EventId, RoomId, RoomVersionId};
9use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
10use tuwunel_core::{Result, implement, utils::result::FlatOk};
11use tuwunel_matrix::pdu;
12
13/// Reads a stored event and formats it for an outgoing federation response.
14///
15/// The read's error is returned unchanged, so each caller keeps its own policy
16/// for an event it cannot serve; the formatting itself cannot fail.
17#[implement(super::Service)]
18pub async fn get_pdu_into(
19	&self,
20	event_id: &EventId,
21	room_version: Option<&RoomVersionId>,
22) -> Result<Box<RawJsonValue>> {
23	let pdu_json = self
24		.services
25		.timeline
26		.get_pdu_json(event_id)
27		.await?;
28
29	Ok(self.format_pdu_into(pdu_json, room_version).await)
30}
31
32/// Formats an event object for an outgoing federation response.
33///
34/// The supplied room version takes precedence; otherwise the room ID is used to
35/// look it up. When no version can be resolved, only `event_id` is removed.
36/// The returned raw JSON satisfies ruma's response type and is not a full PDU.
37#[implement(super::Service)]
38pub async fn format_pdu_into(
39	&self,
40	mut pdu_json: CanonicalJsonObject,
41	room_version: Option<&RoomVersionId>,
42) -> Box<RawJsonValue> {
43	let room_id = pdu_json
44		.get("room_id")
45		.and_then(CanonicalJsonValue::as_str)
46		.map(RoomId::parse)
47		.flat_ok();
48
49	let query_room_version: OptionFuture<_> = room_id
50		.filter(|_| room_version.is_none())
51		.map(async |room_id| {
52			self.services
53				.state
54				.get_room_version(&room_id)
55				.await
56				.ok()
57		})
58		.into();
59
60	if let Some(room_version) = query_room_version
61		.await
62		.flatten()
63		.as_ref()
64		.or(room_version)
65	{
66		pdu_json = pdu::into_outgoing_federation(pdu_json, room_version);
67	} else {
68		pdu_json.remove("event_id");
69	}
70
71	to_raw_value(&pdu_json).expect("CanonicalJson is valid serde_json::Value")
72}