tuwunel_service/account_data/
mod.rs1mod direct;
7mod push_rules;
8mod room_tags;
9#[cfg(test)]
10mod tests;
11
12use std::sync::Arc;
13
14use futures::{Stream, StreamExt, TryFutureExt, pin_mut};
15use ruma::{
16 OwnedUserId, RoomId, UserId,
17 events::{
18 AnyGlobalAccountDataEvent, AnyRawAccountDataEvent, AnyRoomAccountDataEvent,
19 GlobalAccountDataEventType, RoomAccountDataEventType,
20 },
21 push::{RuleKind, Ruleset},
22 serde::Raw,
23};
24use serde::Deserialize;
25use serde_json::json;
26use tuwunel_core::{
27 Err, Result, at, err, implement,
28 utils::{MutexMap, ReadyExt, TryReadyExt, result::LogErr, stream::TryIgnore},
29};
30use tuwunel_database::{Deserialized, Handle, Ignore, Interfix, Json, Map};
31
32pub const MAX_RULES: usize = 10_000;
38
39pub const MAX_RULE_ID_BYTES: usize = 300;
44
45pub const MAX_RULE_BYTES: usize = 1024;
49
50pub struct Service {
56 services: Arc<crate::services::OnceServices>,
57 db: Data,
58 updating: MutexMap<OwnedUserId, ()>,
67}
68
69struct Data {
70 roomuserdataid_accountdata: Arc<Map>,
71 roomusertype_roomuserdataid: Arc<Map>,
72}
73
74impl crate::Service for Service {
75 fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
76 Ok(Arc::new(Self {
77 services: args.services.clone(),
78 db: Data {
79 roomuserdataid_accountdata: args.db["roomuserdataid_accountdata"].clone(),
80 roomusertype_roomuserdataid: args.db["roomusertype_roomuserdataid"].clone(),
81 },
82 updating: MutexMap::new(),
83 }))
84 }
85
86 fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
87}
88
89#[must_use]
96pub fn admits_rule(ruleset: &Ruleset, kind: RuleKind, rule_id: &str) -> bool {
97 rule_id.len() <= MAX_RULE_ID_BYTES
98 && (ruleset.get(kind, rule_id).is_some()
99 || ruleset.iter().take(MAX_RULES).count() < MAX_RULES)
100}
101
102#[implement(Service)]
112pub async fn update(
113 &self,
114 room_id: Option<&RoomId>,
115 user_id: &UserId,
116 event_type: RoomAccountDataEventType,
117 data: &serde_json::Value,
118) -> Result {
119 if data.get("type").is_none() || data.get("content").is_none() {
120 return Err!(Request(InvalidParam("Account data doesn't have all required fields.")));
121 }
122
123 let _updating = self.updating.lock(user_id).await;
125
126 let key = (room_id, user_id, &event_type);
127 let prev = self
128 .db
129 .roomusertype_roomuserdataid
130 .qry(&key)
131 .await;
132
133 let count = self.services.globals.next_count();
134 let roomuserdataid = (room_id, user_id, *count, &event_type);
135
136 let mut txn = self.services.db.txn();
137
138 txn.put(&self.db.roomuserdataid_accountdata, roomuserdataid, Json(data));
139 txn.put(&self.db.roomusertype_roomuserdataid, key, roomuserdataid);
140
141 if let Ok(prev) = prev {
142 txn.del_raw(&self.db.roomuserdataid_accountdata, prev);
143 }
144
145 txn.execute();
146
147 Ok(())
148}
149
150#[implement(Service)]
159pub async fn delete(
160 &self,
161 room_id: Option<&RoomId>,
162 user_id: &UserId,
163 event_type: RoomAccountDataEventType,
164) -> Result {
165 let tombstone = json!({
166 "type": event_type.to_string(),
167 "content": {},
168 });
169
170 self.update(room_id, user_id, event_type, &tombstone)
171 .await
172}
173
174#[implement(Service)]
180pub async fn get_global<T>(&self, user_id: &UserId, kind: GlobalAccountDataEventType) -> Result<T>
181where
182 T: for<'de> Deserialize<'de>,
183{
184 self.get_raw(None, user_id, &kind.to_string())
185 .await
186 .deserialized()
187}
188
189#[implement(Service)]
195pub async fn get_room<T>(
196 &self,
197 room_id: &RoomId,
198 user_id: &UserId,
199 kind: RoomAccountDataEventType,
200) -> Result<T>
201where
202 T: for<'de> Deserialize<'de>,
203{
204 self.get_raw(Some(room_id), user_id, &kind.to_string())
205 .await
206 .deserialized()
207}
208
209#[implement(Service)]
214pub async fn get_raw(
215 &self,
216 room_id: Option<&RoomId>,
217 user_id: &UserId,
218 kind: &str,
219) -> Result<Handle<'_>> {
220 let key = (room_id, user_id, kind.to_owned());
221 self.db
222 .roomusertype_roomuserdataid
223 .qry(&key)
224 .and_then(|roomuserdataid| {
225 self.db
226 .roomuserdataid_accountdata
227 .get(&roomuserdataid)
228 })
229 .await
230}
231
232#[implement(Service)]
237pub fn changes_since<'a>(
238 &'a self,
239 room_id: Option<&'a RoomId>,
240 user_id: &'a UserId,
241 since: u64,
242 to: Option<u64>,
243) -> impl Stream<Item = AnyRawAccountDataEvent> + Send + 'a {
244 self.changes_since_fallible(room_id, user_id, since, to)
245 .map(LogErr::log_err)
246 .ignore_err()
247}
248
249#[implement(Service)]
255pub fn changes_since_fallible<'a>(
256 &'a self,
257 room_id: Option<&'a RoomId>,
258 user_id: &'a UserId,
259 since: u64,
260 to: Option<u64>,
261) -> impl Stream<Item = Result<AnyRawAccountDataEvent>> + Send + 'a {
262 type Key<'a> = (Option<&'a RoomId>, &'a UserId, u64, Ignore);
263
264 let first_possible = (room_id, user_id, since.saturating_add(1));
266
267 self.db
268 .roomuserdataid_accountdata
269 .stream_from(&first_possible)
270 .ready_try_take_while(move |((room_id_, user_id_, count, _), _): &(Key<'_>, _)| {
271 Ok(room_id == *room_id_ && user_id == *user_id_ && to.is_none_or(|to| *count <= to))
272 })
273 .ready_and_then(move |(_, v)| {
274 match room_id {
275 | Some(_) => serde_json::from_slice::<Raw<AnyRoomAccountDataEvent>>(v)
276 .map(AnyRawAccountDataEvent::Room),
277 | None => serde_json::from_slice::<Raw<AnyGlobalAccountDataEvent>>(v)
278 .map(AnyRawAccountDataEvent::Global),
279 }
280 .map_err(|e| err!(Database("Database contains invalid account data: {e}")))
281 })
282}
283
284#[implement(Service)]
291pub async fn erase_user(&self, user_id: &UserId, room_id: Option<&RoomId>) {
292 let _updating = self.updating.lock(user_id).await;
293
294 self.erase_rows(user_id, room_id).await;
295}
296
297#[implement(Service)]
298async fn erase_rows(&self, user_id: &UserId, room_id: Option<&RoomId>) {
299 let prefix = (room_id, user_id, Interfix);
300 let mut txn = self.services.db.txn();
301
302 self.db
303 .roomuserdataid_accountdata
304 .keys_prefix_raw(&prefix)
305 .ignore_err()
306 .ready_for_each(|key| txn.del_raw(&self.db.roomuserdataid_accountdata, key))
307 .await;
308
309 self.db
310 .roomusertype_roomuserdataid
311 .keys_prefix_raw(&prefix)
312 .ignore_err()
313 .ready_for_each(|key| txn.del_raw(&self.db.roomusertype_roomuserdataid, key))
314 .await;
315
316 txn.execute();
317}
318
319#[implement(Service)]
324pub async fn last_count<'a>(
325 &'a self,
326 room_id: Option<&'a RoomId>,
327 user_id: &'a UserId,
328 upper: Option<u64>,
329) -> Result<u64> {
330 type Key<'a> = (Option<&'a RoomId>, &'a UserId, u64, Ignore);
331
332 let upper = upper.unwrap_or(u64::MAX);
333 let key = (room_id, user_id, upper, Interfix);
334 let keys = self
335 .db
336 .roomuserdataid_accountdata
337 .rev_keys_from(&key)
338 .ignore_err()
339 .ready_take_while(move |(room_id_, user_id_, ..): &Key<'_>| {
340 room_id == *room_id_ && user_id == *user_id_
341 })
342 .map(at!(2));
343
344 pin_mut!(keys);
345 keys.next()
346 .await
347 .ok_or_else(|| err!(Request(NotFound("No account data found."))))
348}