tuwunel_service/rooms/timeline/checked.rs
1//! Check-only reads of timeline events.
2//!
3//! The live readers panic on an `eventid_pduid` mapping of the wrong length, so
4//! integrity checks read through here, where that mapping is `Mapped::Damaged`.
5//! `get_checked` reads as `get` does, racing the accepted branch (the mapping,
6//! then the row) against the outlier copy, so a check reports a damaged mapping
7//! only where `get` would panic and misses it when an outlier copy is found
8//! first. `get_checked_keeping` reads the accepted branch before the outlier as
9//! `get_room_version` does, so it always reports one. A copy is decoded as a
10//! release build of the live readers decodes it, without a debug build's
11//! assertion that no further record follows the event's.
12
13use futures::{FutureExt, TryFutureExt, future::try_join};
14use ruma::EventId;
15use serde::Deserialize;
16use tuwunel_core::{Error, Result, implement, result::NotFound};
17
18use super::{RawPduId, Service};
19use crate::integrity::leading_json;
20
21/// Where the timeline places an event, its mapping decoded without trusting it.
22///
23/// A mapping that does not decode is told apart from an absent one, since
24/// `get_pdu_id` panics on it.
25pub(crate) enum Position {
26 /// The event has no timeline position.
27 Absent,
28
29 /// The mapping does not decode as a PDU id.
30 Damaged,
31
32 /// The event's PDU id.
33 At(RawPduId),
34}
35
36/// What a check-only read found, or damage on its way there.
37///
38/// An absent or undecodable event fails as the live reader fails, so a check
39/// classifies those errors as it did before. Each route names the damage it
40/// reports.
41#[derive(Clone)]
42pub(crate) enum Mapped<T> {
43 /// The event, or what was read on the way to it.
44 Event(T),
45
46 /// A row on the way, such as the event's timeline mapping, is damaged.
47 Damaged,
48}
49
50/// Deserializes an event from accepted or outlier storage as `get` does,
51/// following its timeline mapping untrusted.
52///
53/// The accepted branch reads the mapping and then the row, while the outlier copy
54/// is read beside it from the start, and the first found wins, as there. A
55/// mapping that does not decode ends the race as `Mapped::Damaged` at the point
56/// where `get` panics, so an outlier copy found before it is returned and the
57/// damage goes unreported, as `get` returns that copy. When both fail, the
58/// accepted error is returned unless its row is missing.
59#[implement(Service)]
60#[tracing::instrument(level = "debug", skip_all)]
61pub(crate) async fn get_checked<T>(&self, event_id: &EventId) -> Result<Mapped<T>>
62where
63 T: for<'de> Deserialize<'de>,
64{
65 let accepted = async {
66 let pdu_id = match self.pdu_id_checked(event_id).await {
67 | Mapped::Damaged => return Ok(Mapped::Damaged),
68 | Mapped::Event(pdu_id) => pdu_id?,
69 };
70
71 self.get_from_id_checked(&pdu_id)
72 .map_ok(Mapped::Event)
73 .await
74 };
75
76 // Success takes the short-circuiting branch; only two failures are joined.
77 let invert = |result: Result<Mapped<T>>| result.map_or_else(Ok, Err);
78 let accepted = accepted.map(invert);
79 let outlier = self
80 .get_outlier_checked(event_id)
81 .map_ok(Mapped::Event)
82 .map(invert);
83
84 try_join(accepted, outlier)
85 .map(|result| match result {
86 | Err(found) => Ok(found),
87 | Ok((accepted, outlier)) if accepted.is_missing() => Err(outlier),
88 | Ok((accepted, _)) => Err(accepted),
89 })
90 .await
91}
92
93/// Deserializes an event from accepted storage, or from outlier storage when
94/// that fails, following its timeline mapping untrusted.
95///
96/// This is the read `get_room_version` makes through `get_non_outlier` and then
97/// `get_outlier`: the accepted copy wins whenever it is read, and when both fail
98/// `keep` says whether the accepted error is returned over the outlier's. A
99/// mapping that does not decode is `Mapped::Damaged` before the outlier is read,
100/// where `get_non_outlier` panics, and a failed or absent mapping fails the
101/// accepted read, as there.
102#[implement(Service)]
103#[tracing::instrument(level = "debug", skip_all)]
104pub(crate) async fn get_checked_keeping<T, K>(
105 &self,
106 event_id: &EventId,
107 keep: K,
108) -> Result<Mapped<T>>
109where
110 T: for<'de> Deserialize<'de>,
111 K: FnOnce(&Error) -> bool,
112{
113 let Mapped::Event(pdu_id) = self.pdu_id_checked(event_id).await else {
114 return Ok(Mapped::Damaged);
115 };
116
117 let accepted = match pdu_id {
118 | Ok(pdu_id) => self.get_from_id_checked(&pdu_id).await,
119 | Err(error) => Err(error),
120 };
121
122 let accepted = match accepted {
123 | Ok(event) => return Ok(Mapped::Event(event)),
124 | Err(error) => error,
125 };
126
127 self.get_outlier_checked(event_id)
128 .map_ok(Mapped::Event)
129 .map_err(|outlier| match keep(&accepted) {
130 | true => accepted,
131 | false => outlier,
132 })
133 .await
134}
135
136/// Reads an event's timeline mapping as `get_pdu_id` does, decoding it untrusted.
137///
138/// A failed or absent read keeps its error, as there, and a mapping that does not
139/// decode is `Mapped::Damaged` where that function panics.
140#[implement(Service)]
141#[tracing::instrument(level = "debug", skip_all)]
142async fn pdu_id_checked(&self, event_id: &EventId) -> Mapped<Result<RawPduId>> {
143 match self.db.eventid_pduid.get(event_id).await {
144 | Err(error) => Mapped::Event(Err(error)),
145 | Ok(pdu_id) => RawPduId::try_from_bytes(&pdu_id)
146 .map_or(Mapped::Damaged, |pdu_id| Mapped::Event(Ok(pdu_id))),
147 }
148}
149
150/// Deserializes an accepted timeline row by PDU id as `get_from_id` does in a
151/// release build.
152///
153/// A debug build of that function panics on a row holding a further record after
154/// the event's, beyond one trailing separator, while this reads such a row as a
155/// release build reads it.
156#[implement(Service)]
157#[tracing::instrument(level = "debug", skip_all)]
158pub(crate) async fn get_from_id_checked<T>(&self, pdu_id: &RawPduId) -> Result<T>
159where
160 T: for<'de> Deserialize<'de>,
161{
162 let pdu = self.db.pduid_pdu.get(pdu_id).await?;
163
164 leading_json(&pdu)
165}
166
167/// Deserializes an event from outlier storage as `get_outlier` does in a release
168/// build.
169///
170/// Like `get_from_id_checked`, it reads a row holding a further record after the
171/// event's as a release build reads it, where a debug build panics.
172#[implement(Service)]
173#[tracing::instrument(level = "debug", skip_all)]
174async fn get_outlier_checked<T>(&self, event_id: &EventId) -> Result<T>
175where
176 T: for<'de> Deserialize<'de>,
177{
178 let pdu = self.db.eventid_outlierpdu.get(event_id).await?;
179
180 leading_json(&pdu)
181}
182
183/// Reads where the timeline places an event, decoding the mapping untrusted.
184///
185/// `get_pdu_id` panics on a mapping that is not a PDU id, which this reports.
186#[implement(Service)]
187#[tracing::instrument(level = "debug", skip_all)]
188pub(crate) async fn pdu_position(&self, event_id: &EventId) -> Result<Position> {
189 let position = self
190 .db
191 .eventid_pduid
192 .get(event_id)
193 .await
194 .optional()?
195 .map_or(Position::Absent, |pdu_id| {
196 RawPduId::try_from_bytes(&pdu_id).map_or(Position::Damaged, Position::At)
197 });
198
199 Ok(position)
200}
201
202/// Transforms the event a read found, keeping a damaged mapping as it is.
203///
204/// A route reading part of an event, such as its content, maps the event it
205/// found while the damage passes through untouched.
206#[implement(Mapped, generics = "<T>", params = "<T>")]
207pub(crate) fn map<U, F>(self, f: F) -> Mapped<U>
208where
209 F: FnOnce(T) -> U,
210{
211 match self {
212 | Self::Event(event) => Mapped::Event(f(event)),
213 | Self::Damaged => Mapped::Damaged,
214 }
215}