grapevine/src/service/account_data.rs
Olivia Lee b82458a460
use event content in account_data service api instead of full events
This eliminates the possibility of passing an event that has a
mismatching type, reducing the space of possible invalid states.
2025-06-02 11:07:21 -07:00

225 lines
6.9 KiB
Rust

use std::collections::HashMap;
use ruma::{
events::{
AnyGlobalAccountDataEvent, AnyGlobalAccountDataEventContent,
AnyRoomAccountDataEvent, AnyRoomAccountDataEventContent,
GlobalAccountDataEventType, RoomAccountDataEventType,
},
serde::Raw,
RoomId, UserId,
};
use serde::{Deserialize, Serialize};
use crate::{Error, Result};
mod data;
pub(crate) use data::Data;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
pub(crate) fn raw_global_event_to_parts(
event: &Raw<AnyGlobalAccountDataEvent>,
) -> serde_json::Result<(
GlobalAccountDataEventType,
Raw<AnyGlobalAccountDataEventContent>,
)> {
#[derive(Deserialize)]
struct Parts {
#[serde(rename = "type")]
event_type: GlobalAccountDataEventType,
content: Raw<AnyGlobalAccountDataEventContent>,
}
let parts = event.deserialize_as::<Parts>()?;
Ok((parts.event_type, parts.content))
}
pub(crate) fn raw_global_event_from_parts(
event_type: &GlobalAccountDataEventType,
content: &Raw<AnyGlobalAccountDataEventContent>,
) -> Raw<AnyGlobalAccountDataEvent> {
#[derive(Serialize)]
struct Parts<'a> {
#[serde(rename = "type")]
event_type: &'a GlobalAccountDataEventType,
content: &'a Raw<AnyGlobalAccountDataEventContent>,
}
Raw::new(&Parts {
event_type,
content,
})
.expect("json serialization should always succeed")
.cast::<AnyGlobalAccountDataEvent>()
}
pub(crate) fn raw_room_event_to_parts(
event: &Raw<AnyRoomAccountDataEvent>,
) -> serde_json::Result<(
RoomAccountDataEventType,
Raw<AnyRoomAccountDataEventContent>,
)> {
#[derive(Deserialize)]
struct Parts {
#[serde(rename = "type")]
event_type: RoomAccountDataEventType,
content: Raw<AnyRoomAccountDataEventContent>,
}
let parts = event.deserialize_as::<Parts>()?;
Ok((parts.event_type, parts.content))
}
pub(crate) fn raw_room_event_from_parts(
event_type: &RoomAccountDataEventType,
content: &Raw<AnyRoomAccountDataEventContent>,
) -> Raw<AnyRoomAccountDataEvent> {
#[derive(Serialize)]
struct Parts<'a> {
#[serde(rename = "type")]
event_type: &'a RoomAccountDataEventType,
content: &'a Raw<AnyRoomAccountDataEventContent>,
}
Raw::new(&Parts {
event_type,
content,
})
.expect("json serialization should always succeed")
.cast::<AnyRoomAccountDataEvent>()
}
impl Service {
pub(crate) fn new(db: &'static dyn Data) -> Self {
Self {
db,
}
}
/// Places one event in the global account data of the user and removes the
/// previous entry.
#[tracing::instrument(skip(self, user_id, content))]
pub(crate) fn update_global(
&self,
user_id: &UserId,
event_type: &GlobalAccountDataEventType,
content: &Raw<AnyGlobalAccountDataEventContent>,
) -> Result<()> {
let event = raw_global_event_from_parts(event_type, content);
self.db.update(None, user_id, &event_type.to_string(), event.json())
}
/// Places one event in the room account data of the user and removes the
/// previous entry for that room.
#[tracing::instrument(skip(self, room_id, user_id, content))]
pub(crate) fn update_room(
&self,
room_id: &RoomId,
user_id: &UserId,
event_type: &RoomAccountDataEventType,
content: &Raw<AnyRoomAccountDataEventContent>,
) -> Result<()> {
let event = raw_room_event_from_parts(event_type, content);
self.db.update(
Some(room_id),
user_id,
&event_type.to_string(),
event.json(),
)
}
/// Searches the global account data for a specific kind.
#[tracing::instrument(skip(self, user_id, event_type))]
pub(crate) fn get_global(
&self,
user_id: &UserId,
event_type: &GlobalAccountDataEventType,
) -> Result<Option<Raw<AnyGlobalAccountDataEventContent>>> {
let Some(event) =
self.db.get(None, user_id, &event_type.to_string())?
else {
return Ok(None);
};
let event = Raw::<AnyGlobalAccountDataEvent>::from_json(event);
let (_, content) = raw_global_event_to_parts(&event).map_err(|_| {
Error::bad_database("Invalid account data event in db.")
})?;
Ok(Some(content))
}
/// Searches the room account data for a specific kind.
#[tracing::instrument(skip(self, room_id, user_id, event_type))]
pub(crate) fn get_room(
&self,
room_id: &RoomId,
user_id: &UserId,
event_type: &RoomAccountDataEventType,
) -> Result<Option<Raw<AnyRoomAccountDataEventContent>>> {
let Some(event) =
self.db.get(Some(room_id), user_id, &event_type.to_string())?
else {
return Ok(None);
};
let event = Raw::<AnyRoomAccountDataEvent>::from_json(event);
let (_, content) = raw_room_event_to_parts(&event).map_err(|_| {
Error::bad_database("Invalid account data event in db.")
})?;
Ok(Some(content))
}
/// Returns all changes to global account data that happened after `since`.
///
/// When there have been multiple changes to the same event type, returned
/// map contains the most recent value.
#[tracing::instrument(skip(self, user_id, since))]
pub(crate) fn global_changes_since(
&self,
user_id: &UserId,
since: u64,
) -> Result<
HashMap<
GlobalAccountDataEventType,
Raw<AnyGlobalAccountDataEventContent>,
>,
> {
self.db
.changes_since(None, user_id, since)?
.into_values()
.map(|event| {
let event = Raw::<AnyGlobalAccountDataEvent>::from_json(event);
raw_global_event_to_parts(&event).map_err(|_| {
Error::bad_database("Invalid account data event in db")
})
})
.collect()
}
/// Returns all changes to room account data that happened after `since`.
///
/// When there have been multiple changes to the same event type, returned
/// map contains the most recent value.
#[tracing::instrument(skip(self, room_id, user_id, since))]
pub(crate) fn room_changes_since(
&self,
user_id: &UserId,
room_id: &RoomId,
since: u64,
) -> Result<
HashMap<RoomAccountDataEventType, Raw<AnyRoomAccountDataEventContent>>,
> {
self.db
.changes_since(Some(room_id), user_id, since)?
.into_values()
.map(|event| {
let event = Raw::<AnyRoomAccountDataEvent>::from_json(event);
raw_room_event_to_parts(&event).map_err(|_| {
Error::bad_database("Invalid account data event in db")
})
})
.collect()
}
}