Hot-Reloading Refactor

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-05-09 15:59:08 -07:00 committed by June 🍓🦴
parent ae1a4fd283
commit 6c1434c165
212 changed files with 5679 additions and 4206 deletions

View file

@ -2,7 +2,7 @@ use ruma::{OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId};
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
/// Creates or updates the alias to the given room id.
fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()>;

View file

@ -1,37 +1,37 @@
mod data;
pub(crate) use data::Data;
use std::sync::Arc;
pub use data::Data;
use ruma::{OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId};
use crate::Result;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
#[tracing::instrument(skip(self))]
pub(crate) fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()> {
self.db.set_alias(alias, room_id)
}
pub fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()> { self.db.set_alias(alias, room_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> { self.db.remove_alias(alias) }
pub fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> { self.db.remove_alias(alias) }
#[tracing::instrument(skip(self))]
pub(crate) fn resolve_local_alias(&self, alias: &RoomAliasId) -> Result<Option<OwnedRoomId>> {
pub fn resolve_local_alias(&self, alias: &RoomAliasId) -> Result<Option<OwnedRoomId>> {
self.db.resolve_local_alias(alias)
}
#[tracing::instrument(skip(self))]
pub(crate) fn local_aliases_for_room<'a>(
pub fn local_aliases_for_room<'a>(
&'a self, room_id: &RoomId,
) -> Box<dyn Iterator<Item = Result<OwnedRoomAliasId>> + 'a> {
self.db.local_aliases_for_room(room_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn all_local_aliases<'a>(&'a self) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> {
pub fn all_local_aliases<'a>(&'a self) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> {
self.db.all_local_aliases()
}
}

View file

@ -2,7 +2,7 @@ use std::sync::Arc;
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn get_cached_eventid_authchain(&self, shorteventid: &[u64]) -> Result<Option<Arc<[u64]>>>;
fn cache_auth_chain(&self, shorteventid: Vec<u64>, auth_chain: Arc<[u64]>) -> Result<()>;
}

View file

@ -4,18 +4,18 @@ use std::{
sync::Arc,
};
pub(crate) use data::Data;
pub use data::Data;
use ruma::{api::client::error::ErrorKind, EventId, RoomId};
use tracing::{debug, error, trace, warn};
use crate::{services, utils::debug_slice_truncated, Error, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
pub(crate) async fn event_ids_iter<'a>(
pub async fn event_ids_iter<'a>(
&self, room_id: &RoomId, starting_events_: Vec<Arc<EventId>>,
) -> Result<impl Iterator<Item = Arc<EventId>> + 'a> {
let mut starting_events: Vec<&EventId> = Vec::with_capacity(starting_events_.len());
@ -31,7 +31,7 @@ impl Service {
}
#[tracing::instrument(skip(self), fields(starting_events = debug_slice_truncated(starting_events, 5)))]
pub(crate) async fn get_auth_chain(&self, room_id: &RoomId, starting_events: &[&EventId]) -> Result<Vec<u64>> {
pub async fn get_auth_chain(&self, room_id: &RoomId, starting_events: &[&EventId]) -> Result<Vec<u64>> {
const NUM_BUCKETS: usize = 50; //TODO: change possible w/o disrupting db?
const BUCKET: BTreeSet<(u64, &EventId)> = BTreeSet::new();
@ -172,18 +172,18 @@ impl Service {
Ok(found)
}
pub(crate) fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<[u64]>>> {
pub fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<[u64]>>> {
self.db.get_cached_eventid_authchain(key)
}
#[tracing::instrument(skip(self))]
pub(crate) fn cache_auth_chain(&self, key: Vec<u64>, auth_chain: &HashSet<u64>) -> Result<()> {
pub fn cache_auth_chain(&self, key: Vec<u64>, auth_chain: &HashSet<u64>) -> Result<()> {
self.db
.cache_auth_chain(key, auth_chain.iter().copied().collect::<Arc<[u64]>>())
}
#[tracing::instrument(skip(self))]
pub(crate) fn cache_auth_chain_vec(&self, key: Vec<u64>, auth_chain: &Vec<u64>) -> Result<()> {
pub fn cache_auth_chain_vec(&self, key: Vec<u64>, auth_chain: &Vec<u64>) -> Result<()> {
self.db
.cache_auth_chain(key, auth_chain.iter().copied().collect::<Arc<[u64]>>())
}

View file

@ -2,7 +2,7 @@ use ruma::{OwnedRoomId, RoomId};
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
/// Adds the room to the public room directory
fn set_public(&self, room_id: &RoomId) -> Result<()>;

View file

@ -1,24 +1,26 @@
mod data;
pub(crate) use data::Data;
use std::sync::Arc;
pub use data::Data;
use ruma::{OwnedRoomId, RoomId};
use crate::Result;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
#[tracing::instrument(skip(self))]
pub(crate) fn set_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_public(room_id) }
pub fn set_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_public(room_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn set_not_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_not_public(room_id) }
pub fn set_not_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_not_public(room_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn is_public_room(&self, room_id: &RoomId) -> Result<bool> { self.db.is_public_room(room_id) }
pub fn is_public_room(&self, room_id: &RoomId) -> Result<bool> { self.db.is_public_room(room_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn public_rooms(&self) -> impl Iterator<Item = Result<OwnedRoomId>> + '_ { self.db.public_rooms() }
pub fn public_rooms(&self) -> impl Iterator<Item = Result<OwnedRoomId>> + '_ { self.db.public_rooms() }
}

View file

@ -1,11 +1,17 @@
mod parse_incoming_pdu;
mod signing_keys;
pub struct Service;
use std::{
cmp,
collections::{hash_map, HashSet},
collections::{hash_map, BTreeMap, HashMap, HashSet},
pin::Pin,
sync::Arc,
time::{Duration, Instant},
};
use futures_util::Future;
pub use parse_incoming_pdu::parse_incoming_pdu;
use ruma::{
api::{
client::error::ErrorKind,
@ -24,14 +30,7 @@ use tokio::sync::RwLock;
use tracing::{debug, error, info, trace, warn};
use super::state_compressor::CompressedStateEvent;
use crate::{
debug_error, debug_info,
service::{pdu, Arc, BTreeMap, HashMap, Result},
services, Error, PduEvent,
};
mod signing_keys;
pub(crate) struct Service;
use crate::{debug_error, debug_info, pdu, services, Error, PduEvent, Result};
// We use some AsyncRecursiveType hacks here so we can call async funtion
// recursively.
@ -70,7 +69,7 @@ impl Service {
/// 14. Check if the event passes auth based on the "current state" of the
/// room, if not soft fail it
#[tracing::instrument(skip(self, origin, value, is_timeline_event, pub_key_map), name = "pdu")]
pub(crate) async fn handle_incoming_pdu<'a>(
pub async fn handle_incoming_pdu<'a>(
&self, origin: &'a ServerName, room_id: &'a RoomId, event_id: &'a EventId,
value: BTreeMap<String, CanonicalJsonValue>, is_timeline_event: bool,
pub_key_map: &'a RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
@ -207,7 +206,7 @@ impl Service {
skip(self, origin, event_id, room_id, pub_key_map, eventid_info, create_event, first_pdu_in_room),
name = "prev"
)]
pub(crate) async fn handle_prev_pdu<'a>(
pub async fn handle_prev_pdu<'a>(
&self, origin: &'a ServerName, event_id: &'a EventId, room_id: &'a RoomId,
pub_key_map: &'a RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
eventid_info: &mut HashMap<Arc<EventId>, (Arc<PduEvent>, BTreeMap<String, CanonicalJsonValue>)>,
@ -427,7 +426,7 @@ impl Service {
})
}
pub(crate) async fn upgrade_outlier_to_timeline_pdu(
pub async fn upgrade_outlier_to_timeline_pdu(
&self, incoming_pdu: Arc<PduEvent>, val: BTreeMap<String, CanonicalJsonValue>, create_event: &PduEvent,
origin: &ServerName, room_id: &RoomId, pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
) -> Result<Option<Vec<u8>>> {
@ -748,7 +747,7 @@ impl Service {
// TODO: if we know the prev_events of the incoming event we can avoid the
// request and build the state from a known point and resolve if > 1 prev_event
#[tracing::instrument(skip_all, name = "state")]
pub(crate) async fn state_at_incoming_degree_one(
pub async fn state_at_incoming_degree_one(
&self, incoming_pdu: &Arc<PduEvent>,
) -> Result<Option<HashMap<u64, Arc<EventId>>>> {
let prev_event = &*incoming_pdu.prev_events[0];
@ -796,7 +795,7 @@ impl Service {
}
#[tracing::instrument(skip_all, name = "state")]
pub(crate) async fn state_at_incoming_resolved(
pub async fn state_at_incoming_resolved(
&self, incoming_pdu: &Arc<PduEvent>, room_id: &RoomId, room_version_id: &RoomVersionId,
) -> Result<Option<HashMap<u64, Arc<EventId>>>> {
debug!("Calculating state at event using state res");
@ -988,7 +987,7 @@ impl Service {
/// b. Look at outlier pdu tree
/// c. Ask origin server over federation
/// d. TODO: Ask other servers over federation?
pub(crate) fn fetch_and_handle_outliers<'a>(
pub fn fetch_and_handle_outliers<'a>(
&'a self, origin: &'a ServerName, events: &'a [Arc<EventId>], create_event: &'a PduEvent, room_id: &'a RoomId,
room_version_id: &'a RoomVersionId, pub_key_map: &'a RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
) -> AsyncRecursiveCanonicalJsonVec<'a> {
@ -1275,7 +1274,7 @@ impl Service {
/// Returns Ok if the acl allows the server
#[tracing::instrument(skip_all)]
pub(crate) fn acl_check(&self, server_name: &ServerName, room_id: &RoomId) -> Result<()> {
pub fn acl_check(&self, server_name: &ServerName, room_id: &RoomId) -> Result<()> {
let acl_event = if let Some(acl) =
services()
.rooms

View file

@ -0,0 +1,31 @@
use ruma::{api::client::error::ErrorKind, CanonicalJsonObject, OwnedEventId, OwnedRoomId, RoomId};
use serde_json::value::RawValue as RawJsonValue;
use tracing::warn;
use crate::{service::pdu::gen_event_id_canonical_json, services, Error, Result};
pub fn parse_incoming_pdu(pdu: &RawJsonValue) -> Result<(OwnedEventId, CanonicalJsonObject, OwnedRoomId)> {
let value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| {
warn!("Error parsing incoming event {:?}: {:?}", pdu, e);
Error::BadServerResponse("Invalid PDU in server response")
})?;
let room_id: OwnedRoomId = value
.get("room_id")
.and_then(|id| RoomId::parse(id.as_str()?).ok())
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid room id in pdu"))?;
let Ok(room_version_id) = services().rooms.state.get_room_version(&room_id) else {
return Err(Error::Err(format!("Server is not in room {room_id}")));
};
let Ok((event_id, value)) = gen_event_id_canonical_json(pdu, &room_version_id) else {
// Event could not be converted to canonical json
return Err(Error::BadRequest(
ErrorKind::InvalidParam,
"Could not convert event to canonical json.",
));
};
Ok((event_id, value, room_id))
}

View file

@ -1,5 +1,5 @@
use std::{
collections::HashSet,
collections::{BTreeMap, HashMap, HashSet},
time::{Duration, SystemTime},
};
@ -21,13 +21,10 @@ use serde_json::value::RawValue as RawJsonValue;
use tokio::sync::{RwLock, RwLockWriteGuard};
use tracing::{debug, error, info, trace, warn};
use crate::{
service::{BTreeMap, HashMap, Result},
services, Error,
};
use crate::{services, Error, Result};
impl super::Service {
pub(crate) async fn fetch_required_signing_keys<'a, E>(
pub async fn fetch_required_signing_keys<'a, E>(
&'a self, events: E, pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
) -> Result<()>
where
@ -265,7 +262,7 @@ impl super::Service {
Ok(())
}
pub(crate) async fn fetch_join_signing_keys(
pub async fn fetch_join_signing_keys(
&self, event: &create_join_event::v2::Response, room_version: &RoomVersionId,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
) -> Result<()> {
@ -342,7 +339,7 @@ impl super::Service {
/// Search the DB for the signing keys of the given server, if we don't have
/// them fetch them from the server and save to our DB.
#[tracing::instrument(skip_all)]
pub(crate) async fn fetch_signing_keys_for_server(
pub async fn fetch_signing_keys_for_server(
&self, origin: &ServerName, signature_ids: Vec<String>,
) -> Result<BTreeMap<String, Base64>> {
let contains_all_ids = |keys: &BTreeMap<String, Base64>| signature_ids.iter().all(|id| keys.contains_key(id));

View file

@ -2,7 +2,7 @@ use ruma::{DeviceId, RoomId, UserId};
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn lazy_load_was_sent_before(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, ll_user: &UserId,
) -> Result<bool>;

View file

@ -1,24 +1,25 @@
mod data;
use std::collections::{HashMap, HashSet};
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
pub(crate) use data::Data;
pub use data::Data;
use ruma::{DeviceId, OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId};
use tokio::sync::Mutex;
use super::timeline::PduCount;
use crate::Result;
use crate::{PduCount, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
#[allow(clippy::type_complexity)]
pub(crate) lazy_load_waiting:
Mutex<HashMap<(OwnedUserId, OwnedDeviceId, OwnedRoomId, PduCount), HashSet<OwnedUserId>>>,
pub lazy_load_waiting: Mutex<HashMap<(OwnedUserId, OwnedDeviceId, OwnedRoomId, PduCount), HashSet<OwnedUserId>>>,
}
impl Service {
#[tracing::instrument(skip(self))]
pub(crate) fn lazy_load_was_sent_before(
pub fn lazy_load_was_sent_before(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, ll_user: &UserId,
) -> Result<bool> {
self.db
@ -26,7 +27,7 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub(crate) async fn lazy_load_mark_sent(
pub async fn lazy_load_mark_sent(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, lazy_load: HashSet<OwnedUserId>,
count: PduCount,
) {
@ -37,7 +38,7 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub(crate) async fn lazy_load_confirm_delivery(
pub async fn lazy_load_confirm_delivery(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, since: PduCount,
) -> Result<()> {
if let Some(user_ids) = self.lazy_load_waiting.lock().await.remove(&(
@ -56,7 +57,7 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub(crate) fn lazy_load_reset(&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId) -> Result<()> {
pub fn lazy_load_reset(&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId) -> Result<()> {
self.db.lazy_load_reset(user_id, device_id, room_id)
}
}

View file

@ -2,7 +2,7 @@ use ruma::{OwnedRoomId, RoomId};
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn exists(&self, room_id: &RoomId) -> Result<bool>;
fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a>;
fn is_disabled(&self, room_id: &RoomId) -> Result<bool>;

View file

@ -1,32 +1,36 @@
mod data;
pub(crate) use data::Data;
use std::sync::Arc;
pub use data::Data;
use ruma::{OwnedRoomId, RoomId};
use crate::Result;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
/// Checks if a room exists.
#[tracing::instrument(skip(self))]
pub(crate) fn exists(&self, room_id: &RoomId) -> Result<bool> { self.db.exists(room_id) }
pub fn exists(&self, room_id: &RoomId) -> Result<bool> { self.db.exists(room_id) }
pub(crate) fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { self.db.iter_ids() }
#[must_use]
pub fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { self.db.iter_ids() }
pub(crate) fn is_disabled(&self, room_id: &RoomId) -> Result<bool> { self.db.is_disabled(room_id) }
pub fn is_disabled(&self, room_id: &RoomId) -> Result<bool> { self.db.is_disabled(room_id) }
pub(crate) fn disable_room(&self, room_id: &RoomId, disabled: bool) -> Result<()> {
pub fn disable_room(&self, room_id: &RoomId, disabled: bool) -> Result<()> {
self.db.disable_room(room_id, disabled)
}
pub(crate) fn is_banned(&self, room_id: &RoomId) -> Result<bool> { self.db.is_banned(room_id) }
pub fn is_banned(&self, room_id: &RoomId) -> Result<bool> { self.db.is_banned(room_id) }
pub(crate) fn ban_room(&self, room_id: &RoomId, banned: bool) -> Result<()> { self.db.ban_room(room_id, banned) }
pub fn ban_room(&self, room_id: &RoomId, banned: bool) -> Result<()> { self.db.ban_room(room_id, banned) }
pub(crate) fn list_banned_rooms<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
#[must_use]
pub fn list_banned_rooms<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
self.db.list_banned_rooms()
}
}

View file

@ -1,25 +1,25 @@
pub(crate) mod alias;
pub(crate) mod auth_chain;
pub(crate) mod directory;
pub(crate) mod event_handler;
pub(crate) mod lazy_loading;
pub(crate) mod metadata;
pub(crate) mod outlier;
pub(crate) mod pdu_metadata;
pub(crate) mod read_receipt;
pub(crate) mod search;
pub(crate) mod short;
pub(crate) mod spaces;
pub(crate) mod state;
pub(crate) mod state_accessor;
pub(crate) mod state_cache;
pub(crate) mod state_compressor;
pub(crate) mod threads;
pub(crate) mod timeline;
pub(crate) mod typing;
pub(crate) mod user;
pub mod alias;
pub mod auth_chain;
pub mod directory;
pub mod event_handler;
pub mod lazy_loading;
pub mod metadata;
pub mod outlier;
pub mod pdu_metadata;
pub mod read_receipt;
pub mod search;
pub mod short;
pub mod spaces;
pub mod state;
pub mod state_accessor;
pub mod state_cache;
pub mod state_compressor;
pub mod threads;
pub mod timeline;
pub mod typing;
pub mod user;
pub(crate) trait Data:
pub trait Data:
alias::Data
+ auth_chain::Data
+ directory::Data
@ -40,25 +40,25 @@ pub(crate) trait Data:
{
}
pub(crate) struct Service {
pub(crate) alias: alias::Service,
pub(crate) auth_chain: auth_chain::Service,
pub(crate) directory: directory::Service,
pub(crate) event_handler: event_handler::Service,
pub(crate) lazy_loading: lazy_loading::Service,
pub(crate) metadata: metadata::Service,
pub(crate) outlier: outlier::Service,
pub(crate) pdu_metadata: pdu_metadata::Service,
pub(crate) read_receipt: read_receipt::Service,
pub(crate) search: search::Service,
pub(crate) short: short::Service,
pub(crate) state: state::Service,
pub(crate) state_accessor: state_accessor::Service,
pub(crate) state_cache: state_cache::Service,
pub(crate) state_compressor: state_compressor::Service,
pub(crate) timeline: timeline::Service,
pub(crate) threads: threads::Service,
pub(crate) typing: typing::Service,
pub(crate) spaces: spaces::Service,
pub(crate) user: user::Service,
pub struct Service {
pub alias: alias::Service,
pub auth_chain: auth_chain::Service,
pub directory: directory::Service,
pub event_handler: event_handler::Service,
pub lazy_loading: lazy_loading::Service,
pub metadata: metadata::Service,
pub outlier: outlier::Service,
pub pdu_metadata: pdu_metadata::Service,
pub read_receipt: read_receipt::Service,
pub search: search::Service,
pub short: short::Service,
pub state: state::Service,
pub state_accessor: state_accessor::Service,
pub state_cache: state_cache::Service,
pub state_compressor: state_compressor::Service,
pub timeline: timeline::Service,
pub threads: threads::Service,
pub typing: typing::Service,
pub spaces: spaces::Service,
pub user: user::Service,
}

View file

@ -2,7 +2,7 @@ use ruma::{CanonicalJsonObject, EventId};
use crate::{PduEvent, Result};
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>>;
fn get_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>>;
fn add_pdu_outlier(&self, event_id: &EventId, pdu: &CanonicalJsonObject) -> Result<()>;

View file

@ -1,17 +1,19 @@
mod data;
pub(crate) use data::Data;
use std::sync::Arc;
pub use data::Data;
use ruma::{CanonicalJsonObject, EventId};
use crate::{PduEvent, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
/// Returns the pdu from the outlier tree.
pub(crate) fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
pub fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
self.db.get_outlier_pdu_json(event_id)
}
@ -19,13 +21,11 @@ impl Service {
///
/// TODO: use this?
#[allow(dead_code)]
pub(crate) fn get_pdu_outlier(&self, event_id: &EventId) -> Result<Option<PduEvent>> {
self.db.get_outlier_pdu(event_id)
}
pub fn get_pdu_outlier(&self, event_id: &EventId) -> Result<Option<PduEvent>> { self.db.get_outlier_pdu(event_id) }
/// Append the PDU as an outlier.
#[tracing::instrument(skip(self, pdu))]
pub(crate) fn add_pdu_outlier(&self, event_id: &EventId, pdu: &CanonicalJsonObject) -> Result<()> {
pub fn add_pdu_outlier(&self, event_id: &EventId, pdu: &CanonicalJsonObject) -> Result<()> {
self.db.add_pdu_outlier(event_id, pdu)
}
}

View file

@ -2,9 +2,9 @@ use std::sync::Arc;
use ruma::{EventId, RoomId, UserId};
use crate::{service::rooms::timeline::PduCount, PduEvent, Result};
use crate::{PduCount, PduEvent, Result};
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn add_relation(&self, from: u64, to: u64) -> Result<()>;
#[allow(clippy::type_complexity)]
fn relations_until<'a>(

View file

@ -1,7 +1,8 @@
mod data;
use std::sync::Arc;
pub(crate) use data::Data;
pub use data::Data;
use ruma::{
api::{client::relations::get_relating_events, Direction},
events::{relation::RelationType, TimelineEventType},
@ -9,11 +10,10 @@ use ruma::{
};
use serde::Deserialize;
use super::timeline::PduCount;
use crate::{services, PduEvent, Result};
use crate::{services, PduCount, PduEvent, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
#[derive(Clone, Debug, Deserialize)]
@ -28,7 +28,7 @@ struct ExtractRelatesToEventId {
impl Service {
#[tracing::instrument(skip(self, from, to))]
pub(crate) fn add_relation(&self, from: PduCount, to: PduCount) -> Result<()> {
pub fn add_relation(&self, from: PduCount, to: PduCount) -> Result<()> {
match (from, to) {
(PduCount::Normal(f), PduCount::Normal(t)) => self.db.add_relation(f, t),
_ => {
@ -40,7 +40,7 @@ impl Service {
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn paginate_relations_with_filter(
pub fn paginate_relations_with_filter(
&self, sender_user: &UserId, room_id: &RoomId, target: &EventId, filter_event_type: &Option<TimelineEventType>,
filter_rel_type: &Option<RelationType>, from: &Option<String>, to: &Option<String>, limit: &Option<UInt>,
recurse: bool, dir: Direction,
@ -174,7 +174,7 @@ impl Service {
}
}
pub(crate) fn relations_until<'a>(
pub fn relations_until<'a>(
&'a self, user_id: &'a UserId, room_id: &'a RoomId, target: &'a EventId, until: PduCount, max_depth: u8,
) -> Result<Vec<(PduCount, PduEvent)>> {
let room_id = services().rooms.short.get_or_create_shortroomid(room_id)?;
@ -216,22 +216,18 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id, event_ids))]
pub(crate) fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Arc<EventId>]) -> Result<()> {
pub fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Arc<EventId>]) -> Result<()> {
self.db.mark_as_referenced(room_id, event_ids)
}
#[tracing::instrument(skip(self))]
pub(crate) fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
pub fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
self.db.is_event_referenced(room_id, event_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn mark_event_soft_failed(&self, event_id: &EventId) -> Result<()> {
self.db.mark_event_soft_failed(event_id)
}
pub fn mark_event_soft_failed(&self, event_id: &EventId) -> Result<()> { self.db.mark_event_soft_failed(event_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn is_event_soft_failed(&self, event_id: &EventId) -> Result<bool> {
self.db.is_event_soft_failed(event_id)
}
pub fn is_event_soft_failed(&self, event_id: &EventId) -> Result<bool> { self.db.is_event_soft_failed(event_id) }
}

View file

@ -9,7 +9,7 @@ use crate::Result;
type AnySyncEphemeralRoomEventIter<'a> =
Box<dyn Iterator<Item = Result<(OwnedUserId, u64, Raw<AnySyncEphemeralRoomEvent>)>> + 'a>;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
/// Replaces the previous read receipt.
fn readreceipt_update(&self, user_id: &UserId, room_id: &RoomId, event: ReceiptEvent) -> Result<()>;

View file

@ -1,17 +1,19 @@
mod data;
pub(crate) use data::Data;
use std::sync::Arc;
pub use data::Data;
use ruma::{events::receipt::ReceiptEvent, serde::Raw, OwnedUserId, RoomId, UserId};
use crate::{services, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
/// Replaces the previous read receipt.
pub(crate) fn readreceipt_update(&self, user_id: &UserId, room_id: &RoomId, event: ReceiptEvent) -> Result<()> {
pub fn readreceipt_update(&self, user_id: &UserId, room_id: &RoomId, event: ReceiptEvent) -> Result<()> {
self.db.readreceipt_update(user_id, room_id, event)?;
services().sending.flush_room(room_id)?;
@ -21,7 +23,7 @@ impl Service {
/// Returns an iterator over the most recent read_receipts in a room that
/// happened after the event with id `since`.
#[tracing::instrument(skip(self))]
pub(crate) fn readreceipts_since<'a>(
pub fn readreceipts_since<'a>(
&'a self, room_id: &RoomId, since: u64,
) -> impl Iterator<Item = Result<(OwnedUserId, u64, Raw<ruma::events::AnySyncEphemeralRoomEvent>)>> + 'a {
self.db.readreceipts_since(room_id, since)
@ -29,18 +31,18 @@ impl Service {
/// Sets a private read marker at `count`.
#[tracing::instrument(skip(self))]
pub(crate) fn private_read_set(&self, room_id: &RoomId, user_id: &UserId, count: u64) -> Result<()> {
pub fn private_read_set(&self, room_id: &RoomId, user_id: &UserId, count: u64) -> Result<()> {
self.db.private_read_set(room_id, user_id, count)
}
/// Returns the private read marker.
#[tracing::instrument(skip(self))]
pub(crate) fn private_read_get(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
pub fn private_read_get(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
self.db.private_read_get(room_id, user_id)
}
/// Returns the count of the last typing update in this room.
pub(crate) fn last_privateread_update(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub fn last_privateread_update(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
self.db.last_privateread_update(user_id, room_id)
}
}

View file

@ -4,7 +4,7 @@ use crate::Result;
type SearchPdusResult<'a> = Result<Option<(Box<dyn Iterator<Item = Vec<u8>> + 'a>, Vec<String>)>>;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn index_pdu(&self, shortroomid: u64, pdu_id: &[u8], message_body: &str) -> Result<()>;
fn search_pdus<'a>(&'a self, room_id: &RoomId, search_string: &str) -> SearchPdusResult<'a>;

View file

@ -1,22 +1,24 @@
mod data;
pub(crate) use data::Data;
use std::sync::Arc;
pub use data::Data;
use ruma::RoomId;
use crate::Result;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
#[tracing::instrument(skip(self))]
pub(crate) fn index_pdu(&self, shortroomid: u64, pdu_id: &[u8], message_body: &str) -> Result<()> {
pub fn index_pdu(&self, shortroomid: u64, pdu_id: &[u8], message_body: &str) -> Result<()> {
self.db.index_pdu(shortroomid, pdu_id, message_body)
}
#[tracing::instrument(skip(self))]
pub(crate) fn search_pdus<'a>(
pub fn search_pdus<'a>(
&'a self, room_id: &RoomId, search_string: &str,
) -> Result<Option<(impl Iterator<Item = Vec<u8>> + 'a, Vec<String>)>> {
self.db.search_pdus(room_id, search_string)

View file

@ -4,7 +4,7 @@ use ruma::{events::StateEventType, EventId, RoomId};
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result<u64>;
fn multi_get_or_create_shorteventid(&self, event_id: &[&EventId]) -> Result<Vec<u64>>;

View file

@ -1,48 +1,48 @@
mod data;
use std::sync::Arc;
pub(crate) use data::Data;
pub use data::Data;
use ruma::{events::StateEventType, EventId, RoomId};
use crate::Result;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
pub(crate) fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result<u64> {
pub fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result<u64> {
self.db.get_or_create_shorteventid(event_id)
}
pub(crate) fn multi_get_or_create_shorteventid(&self, event_ids: &[&EventId]) -> Result<Vec<u64>> {
pub fn multi_get_or_create_shorteventid(&self, event_ids: &[&EventId]) -> Result<Vec<u64>> {
self.db.multi_get_or_create_shorteventid(event_ids)
}
pub(crate) fn get_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<Option<u64>> {
pub fn get_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<Option<u64>> {
self.db.get_shortstatekey(event_type, state_key)
}
pub(crate) fn get_or_create_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<u64> {
pub fn get_or_create_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<u64> {
self.db.get_or_create_shortstatekey(event_type, state_key)
}
pub(crate) fn get_eventid_from_short(&self, shorteventid: u64) -> Result<Arc<EventId>> {
pub fn get_eventid_from_short(&self, shorteventid: u64) -> Result<Arc<EventId>> {
self.db.get_eventid_from_short(shorteventid)
}
pub(crate) fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(StateEventType, String)> {
pub fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(StateEventType, String)> {
self.db.get_statekey_from_short(shortstatekey)
}
/// Returns (shortstatehash, already_existed)
pub(crate) fn get_or_create_shortstatehash(&self, state_hash: &[u8]) -> Result<(u64, bool)> {
pub fn get_or_create_shortstatehash(&self, state_hash: &[u8]) -> Result<(u64, bool)> {
self.db.get_or_create_shortstatehash(state_hash)
}
pub(crate) fn get_shortroomid(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.get_shortroomid(room_id) }
pub fn get_shortroomid(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.get_shortroomid(room_id) }
pub(crate) fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result<u64> {
pub fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result<u64> {
self.db.get_or_create_shortroomid(room_id)
}
}

View file

@ -32,9 +32,9 @@ use ruma::{
use tokio::sync::Mutex;
use tracing::{debug, error, warn};
use crate::{debug_info, services, utils::server_name::server_is_ours, Error, Result};
use crate::{debug_info, server_is_ours, services, Error, Result};
pub(crate) struct CachedSpaceHierarchySummary {
pub struct CachedSpaceHierarchySummary {
summary: SpaceHierarchyParentSummary,
}
@ -235,11 +235,11 @@ impl Arena {
// Note: perhaps use some better form of token rather than just room count
#[derive(Debug, PartialEq)]
pub(crate) struct PagnationToken {
pub(crate) skip: UInt,
pub(crate) limit: UInt,
pub(crate) max_depth: UInt,
pub(crate) suggested_only: bool,
pub struct PagnationToken {
pub skip: UInt,
pub limit: UInt,
pub max_depth: UInt,
pub suggested_only: bool,
}
impl FromStr for PagnationToken {
@ -294,8 +294,8 @@ enum Identifier<'a> {
None,
}
pub(crate) struct Service {
pub(crate) roomid_spacehierarchy_cache: Mutex<LruCache<OwnedRoomId, Option<CachedSpaceHierarchySummary>>>,
pub struct Service {
pub roomid_spacehierarchy_cache: Mutex<LruCache<OwnedRoomId, Option<CachedSpaceHierarchySummary>>>,
}
// Here because cannot implement `From` across ruma-federation-api and
@ -338,7 +338,7 @@ impl Service {
///
///Panics if the room does not exist, so a check if the room exists should
/// be done
pub(crate) async fn get_federation_hierarchy(
pub async fn get_federation_hierarchy(
&self, room_id: &RoomId, server_name: &ServerName, suggested_only: bool,
) -> Result<federation::space::get_hierarchy::v1::Response> {
match self
@ -624,7 +624,7 @@ impl Service {
}
// TODO: make this a lot less messy
pub(crate) async fn get_client_hierarchy(
pub async fn get_client_hierarchy(
&self, sender_user: &UserId, room_id: &RoomId, limit: usize, skip: usize, max_depth: usize,
suggested_only: bool,
) -> Result<client::space::get_hierarchy::v1::Response> {

View file

@ -5,7 +5,7 @@ use tokio::sync::MutexGuard;
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
/// Returns the last state hash key added to the db for the given room.
fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result<Option<u64>>;

View file

@ -4,7 +4,7 @@ use std::{
sync::Arc,
};
pub(crate) use data::Data;
pub use data::Data;
use ruma::{
api::client::error::ErrorKind,
events::{
@ -21,13 +21,13 @@ use tracing::warn;
use super::state_compressor::CompressedStateEvent;
use crate::{services, utils::calculate_hash, Error, PduEvent, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
/// Set the room to the given statehash and update caches.
pub(crate) async fn force_state(
pub async fn force_state(
&self,
room_id: &RoomId,
shortstatehash: u64,
@ -104,7 +104,7 @@ impl Service {
/// This adds all current state events (not including the incoming event)
/// to `stateid_pduid` and adds the incoming event to `eventid_statehash`.
#[tracing::instrument(skip(self, state_ids_compressed))]
pub(crate) fn set_event_state(
pub fn set_event_state(
&self, event_id: &EventId, room_id: &RoomId, state_ids_compressed: Arc<HashSet<CompressedStateEvent>>,
) -> Result<u64> {
let shorteventid = services()
@ -172,7 +172,7 @@ impl Service {
/// This adds all current state events (not including the incoming event)
/// to `stateid_pduid` and adds the incoming event to `eventid_statehash`.
#[tracing::instrument(skip(self, new_pdu))]
pub(crate) fn append_to_state(&self, new_pdu: &PduEvent) -> Result<u64> {
pub fn append_to_state(&self, new_pdu: &PduEvent) -> Result<u64> {
let shorteventid = services()
.rooms
.short
@ -244,7 +244,7 @@ impl Service {
}
#[tracing::instrument(skip(self, invite_event))]
pub(crate) fn calculate_invite_state(&self, invite_event: &PduEvent) -> Result<Vec<Raw<AnyStrippedStateEvent>>> {
pub fn calculate_invite_state(&self, invite_event: &PduEvent) -> Result<Vec<Raw<AnyStrippedStateEvent>>> {
let mut state = Vec::new();
// Add recommended events
if let Some(e) =
@ -300,7 +300,7 @@ impl Service {
/// Set the state hash to a new version, but does not update state_cache.
#[tracing::instrument(skip(self))]
pub(crate) fn set_room_state(
pub fn set_room_state(
&self,
room_id: &RoomId,
shortstatehash: u64,
@ -311,7 +311,7 @@ impl Service {
/// Returns the room's version.
#[tracing::instrument(skip(self))]
pub(crate) fn get_room_version(&self, room_id: &RoomId) -> Result<RoomVersionId> {
pub fn get_room_version(&self, room_id: &RoomId) -> Result<RoomVersionId> {
let create_event = services()
.rooms
.state_accessor
@ -331,15 +331,15 @@ impl Service {
Ok(create_event_content.room_version)
}
pub(crate) fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result<Option<u64>> {
pub fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.db.get_room_shortstatehash(room_id)
}
pub(crate) fn get_forward_extremities(&self, room_id: &RoomId) -> Result<HashSet<Arc<EventId>>> {
pub fn get_forward_extremities(&self, room_id: &RoomId) -> Result<HashSet<Arc<EventId>>> {
self.db.get_forward_extremities(room_id)
}
pub(crate) fn set_forward_extremities(
pub fn set_forward_extremities(
&self,
room_id: &RoomId,
event_ids: Vec<OwnedEventId>,
@ -351,7 +351,7 @@ impl Service {
/// This fetches auth events from the current state.
#[tracing::instrument(skip(self))]
pub(crate) fn get_auth_events(
pub fn get_auth_events(
&self, room_id: &RoomId, kind: &TimelineEventType, sender: &UserId, state_key: Option<&str>,
content: &serde_json::value::RawValue,
) -> Result<StateMap<Arc<PduEvent>>> {

View file

@ -6,7 +6,7 @@ use ruma::{events::StateEventType, EventId, RoomId};
use crate::{PduEvent, Result};
#[async_trait]
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
/// Builds a StateMap by iterating over all keys that start
/// with state_hash, this gives the full state for the given state_hash.
#[allow(unused_qualifications)] // async traits

View file

@ -4,7 +4,7 @@ use std::{
sync::{Arc, Mutex},
};
pub(crate) use data::Data;
pub use data::Data;
use lru_cache::LruCache;
use ruma::{
events::{
@ -24,30 +24,28 @@ use tracing::{error, warn};
use crate::{service::pdu::PduBuilder, services, Error, PduEvent, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub(crate) server_visibility_cache: Mutex<LruCache<(OwnedServerName, u64), bool>>,
pub(crate) user_visibility_cache: Mutex<LruCache<(OwnedUserId, u64), bool>>,
pub struct Service {
pub db: Arc<dyn Data>,
pub server_visibility_cache: Mutex<LruCache<(OwnedServerName, u64), bool>>,
pub user_visibility_cache: Mutex<LruCache<(OwnedUserId, u64), bool>>,
}
impl Service {
/// Builds a StateMap by iterating over all keys that start
/// with state_hash, this gives the full state for the given state_hash.
#[tracing::instrument(skip(self))]
pub(crate) async fn state_full_ids(&self, shortstatehash: u64) -> Result<HashMap<u64, Arc<EventId>>> {
pub async fn state_full_ids(&self, shortstatehash: u64) -> Result<HashMap<u64, Arc<EventId>>> {
self.db.state_full_ids(shortstatehash).await
}
pub(crate) async fn state_full(
&self, shortstatehash: u64,
) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
pub async fn state_full(&self, shortstatehash: u64) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
self.db.state_full(shortstatehash).await
}
/// Returns a single PDU from `room_id` with key (`event_type`,
/// `state_key`).
#[tracing::instrument(skip(self))]
pub(crate) fn state_get_id(
pub fn state_get_id(
&self, shortstatehash: u64, event_type: &StateEventType, state_key: &str,
) -> Result<Option<Arc<EventId>>> {
self.db.state_get_id(shortstatehash, event_type, state_key)
@ -55,7 +53,7 @@ impl Service {
/// Returns a single PDU from `room_id` with key (`event_type`,
/// `state_key`).
pub(crate) fn state_get(
pub fn state_get(
&self, shortstatehash: u64, event_type: &StateEventType, state_key: &str,
) -> Result<Option<Arc<PduEvent>>> {
self.db.state_get(shortstatehash, event_type, state_key)
@ -90,9 +88,7 @@ impl Service {
/// Whether a server is allowed to see an event through federation, based on
/// the room's history_visibility at that event's state.
#[tracing::instrument(skip(self, origin, room_id, event_id))]
pub(crate) fn server_can_see_event(
&self, origin: &ServerName, room_id: &RoomId, event_id: &EventId,
) -> Result<bool> {
pub fn server_can_see_event(&self, origin: &ServerName, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
let Some(shortstatehash) = self.pdu_shortstatehash(event_id)? else {
return Ok(true);
};
@ -155,7 +151,7 @@ impl Service {
/// Whether a user is allowed to see an event, based on
/// the room's history_visibility at that event's state.
#[tracing::instrument(skip(self, user_id, room_id, event_id))]
pub(crate) fn user_can_see_event(&self, user_id: &UserId, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
pub fn user_can_see_event(&self, user_id: &UserId, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
let Some(shortstatehash) = self.pdu_shortstatehash(event_id)? else {
return Ok(true);
};
@ -214,7 +210,7 @@ impl Service {
/// Whether a user is allowed to see an event, based on
/// the room's history_visibility at that event's state.
#[tracing::instrument(skip(self, user_id, room_id))]
pub(crate) fn user_can_see_state_events(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
pub fn user_can_see_state_events(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
let currently_member = services().rooms.state_cache.is_joined(user_id, room_id)?;
let history_visibility = self
@ -236,22 +232,18 @@ impl Service {
}
/// Returns the state hash for this pdu.
pub(crate) fn pdu_shortstatehash(&self, event_id: &EventId) -> Result<Option<u64>> {
self.db.pdu_shortstatehash(event_id)
}
pub fn pdu_shortstatehash(&self, event_id: &EventId) -> Result<Option<u64>> { self.db.pdu_shortstatehash(event_id) }
/// Returns the full room state.
#[tracing::instrument(skip(self))]
pub(crate) async fn room_state_full(
&self, room_id: &RoomId,
) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
pub async fn room_state_full(&self, room_id: &RoomId) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
self.db.room_state_full(room_id).await
}
/// Returns a single PDU from `room_id` with key (`event_type`,
/// `state_key`).
#[tracing::instrument(skip(self))]
pub(crate) fn room_state_get_id(
pub fn room_state_get_id(
&self, room_id: &RoomId, event_type: &StateEventType, state_key: &str,
) -> Result<Option<Arc<EventId>>> {
self.db.room_state_get_id(room_id, event_type, state_key)
@ -260,13 +252,13 @@ impl Service {
/// Returns a single PDU from `room_id` with key (`event_type`,
/// `state_key`).
#[tracing::instrument(skip(self))]
pub(crate) fn room_state_get(
pub fn room_state_get(
&self, room_id: &RoomId, event_type: &StateEventType, state_key: &str,
) -> Result<Option<Arc<PduEvent>>> {
self.db.room_state_get(room_id, event_type, state_key)
}
pub(crate) fn get_name(&self, room_id: &RoomId) -> Result<Option<String>> {
pub fn get_name(&self, room_id: &RoomId) -> Result<Option<String>> {
services()
.rooms
.state_accessor
@ -276,7 +268,7 @@ impl Service {
})
}
pub(crate) fn get_avatar(&self, room_id: &RoomId) -> Result<ruma::JsOption<RoomAvatarEventContent>> {
pub fn get_avatar(&self, room_id: &RoomId) -> Result<ruma::JsOption<RoomAvatarEventContent>> {
services()
.rooms
.state_accessor
@ -287,7 +279,7 @@ impl Service {
})
}
pub(crate) fn get_member(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<RoomMemberEventContent>> {
pub fn get_member(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<RoomMemberEventContent>> {
services()
.rooms
.state_accessor
@ -298,7 +290,7 @@ impl Service {
})
}
pub(crate) async fn user_can_invite(
pub async fn user_can_invite(
&self, room_id: &RoomId, sender: &UserId, target_user: &UserId, state_lock: &MutexGuard<'_, ()>,
) -> Result<bool> {
let content = to_raw_value(&RoomMemberEventContent::new(MembershipState::Invite))

View file

@ -12,7 +12,7 @@ type StrippedStateEventIter<'a> = Box<dyn Iterator<Item = Result<(OwnedRoomId, V
type AnySyncStateEventIter<'a> = Box<dyn Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnySyncStateEvent>>)>> + 'a>;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn mark_as_once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<()>;
fn mark_as_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<()>;
fn mark_as_invited(

View file

@ -1,6 +1,6 @@
use std::{collections::HashSet, sync::Arc};
pub(crate) use data::Data;
pub use data::Data;
use itertools::Itertools;
use ruma::{
events::{
@ -19,19 +19,19 @@ use ruma::{
};
use tracing::{error, warn};
use crate::{service::appservice::RegistrationInfo, services, utils::user_id::user_is_local, Error, Result};
use crate::{service::appservice::RegistrationInfo, services, user_is_local, Error, Result};
mod data;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
/// Update current membership data.
#[tracing::instrument(skip(self, last_state))]
#[allow(clippy::too_many_arguments)]
pub(crate) fn update_membership(
pub fn update_membership(
&self, room_id: &RoomId, user_id: &UserId, membership_event: RoomMemberEventContent, sender: &UserId,
last_state: Option<Vec<Raw<AnyStrippedStateEvent>>>, invite_via: Option<Vec<OwnedServerName>>,
update_joined_count: bool,
@ -210,43 +210,43 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id))]
pub(crate) fn update_joined_count(&self, room_id: &RoomId) -> Result<()> { self.db.update_joined_count(room_id) }
pub fn update_joined_count(&self, room_id: &RoomId) -> Result<()> { self.db.update_joined_count(room_id) }
#[tracing::instrument(skip(self, room_id))]
pub(crate) fn get_our_real_users(&self, room_id: &RoomId) -> Result<Arc<HashSet<OwnedUserId>>> {
pub fn get_our_real_users(&self, room_id: &RoomId) -> Result<Arc<HashSet<OwnedUserId>>> {
self.db.get_our_real_users(room_id)
}
#[tracing::instrument(skip(self, room_id, appservice))]
pub(crate) fn appservice_in_room(&self, room_id: &RoomId, appservice: &RegistrationInfo) -> Result<bool> {
pub fn appservice_in_room(&self, room_id: &RoomId, appservice: &RegistrationInfo) -> Result<bool> {
self.db.appservice_in_room(room_id, appservice)
}
/// Makes a user forget a room.
#[tracing::instrument(skip(self))]
pub(crate) fn forget(&self, room_id: &RoomId, user_id: &UserId) -> Result<()> { self.db.forget(room_id, user_id) }
pub fn forget(&self, room_id: &RoomId, user_id: &UserId) -> Result<()> { self.db.forget(room_id, user_id) }
/// Returns an iterator of all servers participating in this room.
#[tracing::instrument(skip(self))]
pub(crate) fn room_servers<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedServerName>> + 'a {
pub fn room_servers<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedServerName>> + 'a {
self.db.room_servers(room_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result<bool> {
pub fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result<bool> {
self.db.server_in_room(server, room_id)
}
/// Returns an iterator of all rooms a server participates in (as far as we
/// know).
#[tracing::instrument(skip(self))]
pub(crate) fn server_rooms<'a>(&'a self, server: &ServerName) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
pub fn server_rooms<'a>(&'a self, server: &ServerName) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
self.db.server_rooms(server)
}
/// Returns true if server can see user by sharing at least one room.
#[tracing::instrument(skip(self))]
pub(crate) fn server_sees_user(&self, server: &ServerName, user_id: &UserId) -> Result<bool> {
pub fn server_sees_user(&self, server: &ServerName, user_id: &UserId) -> Result<bool> {
Ok(self
.server_rooms(server)
.filter_map(Result::ok)
@ -255,7 +255,7 @@ impl Service {
/// Returns true if user_a and user_b share at least one room.
#[tracing::instrument(skip(self))]
pub(crate) fn user_sees_user(&self, user_a: &UserId, user_b: &UserId) -> Result<bool> {
pub fn user_sees_user(&self, user_a: &UserId, user_b: &UserId) -> Result<bool> {
// Minimize number of point-queries by iterating user with least nr rooms
let (a, b) = if self.rooms_joined(user_a).count() < self.rooms_joined(user_b).count() {
(user_a, user_b)
@ -271,104 +271,88 @@ impl Service {
/// Returns an iterator over all joined members of a room.
#[tracing::instrument(skip(self))]
pub(crate) fn room_members<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
pub fn room_members<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
self.db.room_members(room_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn room_joined_count(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.db.room_joined_count(room_id)
}
pub fn room_joined_count(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.room_joined_count(room_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn room_invited_count(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.db.room_invited_count(room_id)
}
pub fn room_invited_count(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.room_invited_count(room_id) }
/// Returns an iterator over all User IDs who ever joined a room.
#[tracing::instrument(skip(self))]
pub(crate) fn room_useroncejoined<'a>(
&'a self, room_id: &RoomId,
) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
pub fn room_useroncejoined<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
self.db.room_useroncejoined(room_id)
}
/// Returns an iterator over all invited members of a room.
#[tracing::instrument(skip(self))]
pub(crate) fn room_members_invited<'a>(
&'a self, room_id: &RoomId,
) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
pub fn room_members_invited<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
self.db.room_members_invited(room_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn get_invite_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
pub fn get_invite_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
self.db.get_invite_count(room_id, user_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn get_left_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
pub fn get_left_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
self.db.get_left_count(room_id, user_id)
}
/// Returns an iterator over all rooms this user joined.
#[tracing::instrument(skip(self))]
pub(crate) fn rooms_joined<'a>(&'a self, user_id: &UserId) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
pub fn rooms_joined<'a>(&'a self, user_id: &UserId) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
self.db.rooms_joined(user_id)
}
/// Returns an iterator over all rooms a user was invited to.
#[tracing::instrument(skip(self))]
pub(crate) fn rooms_invited<'a>(
pub fn rooms_invited<'a>(
&'a self, user_id: &UserId,
) -> impl Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnyStrippedStateEvent>>)>> + 'a {
self.db.rooms_invited(user_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn invite_state(
&self, user_id: &UserId, room_id: &RoomId,
) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
pub fn invite_state(&self, user_id: &UserId, room_id: &RoomId) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
self.db.invite_state(user_id, room_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn left_state(
&self, user_id: &UserId, room_id: &RoomId,
) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
pub fn left_state(&self, user_id: &UserId, room_id: &RoomId) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
self.db.left_state(user_id, room_id)
}
/// Returns an iterator over all rooms a user left.
#[tracing::instrument(skip(self))]
pub(crate) fn rooms_left<'a>(
pub fn rooms_left<'a>(
&'a self, user_id: &UserId,
) -> impl Iterator<Item = Result<(OwnedRoomId, Vec<Raw<AnySyncStateEvent>>)>> + 'a {
self.db.rooms_left(user_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
pub fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
self.db.once_joined(user_id, room_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
self.db.is_joined(user_id, room_id)
}
pub fn is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { self.db.is_joined(user_id, room_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
pub fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
self.db.is_invited(user_id, room_id)
}
#[tracing::instrument(skip(self))]
pub(crate) fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
self.db.is_left(user_id, room_id)
}
pub fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { self.db.is_left(user_id, room_id) }
#[tracing::instrument(skip(self))]
pub(crate) fn servers_invite_via(&self, room_id: &RoomId) -> Result<Option<Vec<OwnedServerName>>> {
pub fn servers_invite_via(&self, room_id: &RoomId) -> Result<Option<Vec<OwnedServerName>>> {
self.db.servers_invite_via(room_id)
}
@ -377,7 +361,7 @@ impl Service {
///
/// See <https://spec.matrix.org/v1.10/appendices/#routing>
#[tracing::instrument(skip(self))]
pub(crate) fn servers_route_via(&self, room_id: &RoomId) -> Result<Vec<OwnedServerName>> {
pub fn servers_route_via(&self, room_id: &RoomId) -> Result<Vec<OwnedServerName>> {
let most_powerful_user_server = services()
.rooms
.state_accessor

View file

@ -3,13 +3,13 @@ use std::{collections::HashSet, sync::Arc};
use super::CompressedStateEvent;
use crate::Result;
pub(crate) struct StateDiff {
pub(crate) parent: Option<u64>,
pub(crate) added: Arc<HashSet<CompressedStateEvent>>,
pub(crate) removed: Arc<HashSet<CompressedStateEvent>>,
pub struct StateDiff {
pub parent: Option<u64>,
pub added: Arc<HashSet<CompressedStateEvent>>,
pub removed: Arc<HashSet<CompressedStateEvent>>,
}
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn get_statediff(&self, shortstatehash: u64) -> Result<StateDiff>;
fn save_statediff(&self, shortstatehash: u64, diff: StateDiff) -> Result<()>;
}

View file

@ -1,11 +1,11 @@
pub(crate) mod data;
pub mod data;
use std::{
collections::HashSet,
mem::size_of,
sync::{Arc, Mutex},
};
pub(crate) use data::Data;
pub use data::Data;
use lru_cache::LruCache;
use ruma::{EventId, RoomId};
@ -42,19 +42,19 @@ type ParentStatesVec = Vec<(
type HashSetCompressStateEvent = Result<(u64, Arc<HashSet<CompressedStateEvent>>, Arc<HashSet<CompressedStateEvent>>)>;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
pub(crate) stateinfo_cache: StateInfoLruCache,
pub stateinfo_cache: StateInfoLruCache,
}
pub(crate) type CompressedStateEvent = [u8; 2 * size_of::<u64>()];
pub type CompressedStateEvent = [u8; 2 * size_of::<u64>()];
impl Service {
/// Returns a stack with info on shortstatehash, full state, added diff and
/// removed diff for the selected shortstatehash and each parent layer.
#[tracing::instrument(skip(self))]
pub(crate) fn load_shortstatehash_info(&self, shortstatehash: u64) -> ShortStateInfoResult {
pub fn load_shortstatehash_info(&self, shortstatehash: u64) -> ShortStateInfoResult {
if let Some(r) = self
.stateinfo_cache
.lock()
@ -97,7 +97,7 @@ impl Service {
}
}
pub(crate) fn compress_state_event(&self, shortstatekey: u64, event_id: &EventId) -> Result<CompressedStateEvent> {
pub fn compress_state_event(&self, shortstatekey: u64, event_id: &EventId) -> Result<CompressedStateEvent> {
let mut v = shortstatekey.to_be_bytes().to_vec();
v.extend_from_slice(
&services()
@ -110,9 +110,7 @@ impl Service {
}
/// Returns shortstatekey, event id
pub(crate) fn parse_compressed_state_event(
&self, compressed_event: &CompressedStateEvent,
) -> Result<(u64, Arc<EventId>)> {
pub fn parse_compressed_state_event(&self, compressed_event: &CompressedStateEvent) -> Result<(u64, Arc<EventId>)> {
Ok((
utils::u64_from_bytes(&compressed_event[0..size_of::<u64>()]).expect("bytes have right length"),
services().rooms.short.get_eventid_from_short(
@ -140,7 +138,7 @@ impl Service {
/// * `parent_states` - A stack with info on shortstatehash, full state,
/// added diff and removed diff for each parent layer
#[tracing::instrument(skip(self, statediffnew, statediffremoved, diff_to_sibling, parent_states))]
pub(crate) fn save_state_from_diff(
pub fn save_state_from_diff(
&self, shortstatehash: u64, statediffnew: Arc<HashSet<CompressedStateEvent>>,
statediffremoved: Arc<HashSet<CompressedStateEvent>>, diff_to_sibling: usize,
mut parent_states: ParentStatesVec,
@ -252,7 +250,7 @@ impl Service {
/// Returns the new shortstatehash, and the state diff from the previous
/// room state
pub(crate) fn save_state(
pub fn save_state(
&self, room_id: &RoomId, new_state_ids_compressed: Arc<HashSet<CompressedStateEvent>>,
) -> HashSetCompressStateEvent {
let previous_shortstatehash = services().rooms.state.get_room_shortstatehash(room_id)?;

View file

@ -4,7 +4,7 @@ use crate::{PduEvent, Result};
type PduEventIterResult<'a> = Result<Box<dyn Iterator<Item = Result<(u64, PduEvent)>> + 'a>>;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn threads_until<'a>(
&'a self, user_id: &'a UserId, room_id: &'a RoomId, until: u64, include: &'a IncludeThreads,
) -> PduEventIterResult<'a>;

View file

@ -1,8 +1,8 @@
mod data;
use std::collections::BTreeMap;
use std::{collections::BTreeMap, sync::Arc};
pub(crate) use data::Data;
pub use data::Data;
use ruma::{
api::client::{error::ErrorKind, threads::get_threads::v1::IncludeThreads},
events::relation::BundledThread,
@ -12,18 +12,18 @@ use serde_json::json;
use crate::{services, Error, PduEvent, Result};
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
pub(crate) fn threads_until<'a>(
pub fn threads_until<'a>(
&'a self, user_id: &'a UserId, room_id: &'a RoomId, until: u64, include: &'a IncludeThreads,
) -> Result<impl Iterator<Item = Result<(u64, PduEvent)>> + 'a> {
self.db.threads_until(user_id, room_id, until, include)
}
pub(crate) fn add_to_thread(&self, root_event_id: &EventId, pdu: &PduEvent) -> Result<()> {
pub fn add_to_thread(&self, root_event_id: &EventId, pdu: &PduEvent) -> Result<()> {
let root_id = &services()
.rooms
.timeline

View file

@ -5,7 +5,7 @@ use ruma::{CanonicalJsonObject, EventId, OwnedUserId, RoomId, UserId};
use super::PduCount;
use crate::{PduEvent, Result};
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount>;
/// Returns the `count` of this pdu's id.

View file

@ -1,12 +1,11 @@
pub(crate) mod data;
pub mod data;
use std::{
cmp::Ordering,
collections::{BTreeMap, HashMap, HashSet},
sync::Arc,
};
pub(crate) use data::Data;
pub use data::Data;
use rand::prelude::SliceRandom;
use ruma::{
api::{client::error::ErrorKind, federation},
@ -35,60 +34,22 @@ use tracing::{debug, error, info, warn};
use super::state_compressor::CompressedStateEvent;
use crate::{
api::server_server,
server_is_ours,
//api::server_server,
service::{
self,
appservice::NamespaceRegex,
pdu::{EventHash, PduBuilder},
rooms::event_handler::parse_incoming_pdu,
},
services,
utils::{self, server_name::server_is_ours},
Error, PduEvent, Result,
utils::{self},
Error,
PduCount,
PduEvent,
Result,
};
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
pub(crate) enum PduCount {
Backfilled(u64),
Normal(u64),
}
impl PduCount {
pub(crate) fn min() -> Self { Self::Backfilled(u64::MAX) }
pub(crate) fn max() -> Self { Self::Normal(u64::MAX) }
pub(crate) fn try_from_string(token: &str) -> Result<Self> {
if let Some(stripped_token) = token.strip_prefix('-') {
stripped_token.parse().map(PduCount::Backfilled)
} else {
token.parse().map(PduCount::Normal)
}
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid pagination token."))
}
pub(crate) fn stringify(&self) -> String {
match self {
PduCount::Backfilled(x) => format!("-{x}"),
PduCount::Normal(x) => x.to_string(),
}
}
}
impl PartialOrd for PduCount {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}
impl Ord for PduCount {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(PduCount::Normal(s), PduCount::Normal(o)) => s.cmp(o),
(PduCount::Backfilled(s), PduCount::Backfilled(o)) => o.cmp(s),
(PduCount::Normal(_), PduCount::Backfilled(_)) => Ordering::Greater,
(PduCount::Backfilled(_), PduCount::Normal(_)) => Ordering::Less,
}
}
}
// Update Relationships
#[derive(Deserialize)]
struct ExtractRelatesTo {
@ -106,15 +67,15 @@ struct ExtractRelatesToEventId {
relates_to: ExtractEventId,
}
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
pub(crate) lasttimelinecount_cache: Mutex<HashMap<OwnedRoomId, PduCount>>,
pub lasttimelinecount_cache: Mutex<HashMap<OwnedRoomId, PduCount>>,
}
impl Service {
#[tracing::instrument(skip(self))]
pub(crate) fn first_pdu_in_room(&self, room_id: &RoomId) -> Result<Option<Arc<PduEvent>>> {
pub fn first_pdu_in_room(&self, room_id: &RoomId) -> Result<Option<Arc<PduEvent>>> {
self.all_pdus(user_id!("@doesntmatter:conduit.rs"), room_id)?
.next()
.map(|o| o.map(|(_, p)| Arc::new(p)))
@ -122,19 +83,17 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub(crate) fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount> {
pub fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount> {
self.db.last_timeline_count(sender_user, room_id)
}
/// Returns the `count` of this pdu's id.
pub(crate) fn get_pdu_count(&self, event_id: &EventId) -> Result<Option<PduCount>> {
self.db.get_pdu_count(event_id)
}
pub fn get_pdu_count(&self, event_id: &EventId) -> Result<Option<PduCount>> { self.db.get_pdu_count(event_id) }
// TODO Is this the same as the function above?
/*
#[tracing::instrument(skip(self))]
pub(crate) fn latest_pdu_count(&self, room_id: &RoomId) -> Result<u64> {
pub fn latest_pdu_count(&self, room_id: &RoomId) -> Result<u64> {
let prefix = self
.get_shortroomid(room_id)?
.expect("room exists")
@ -158,7 +117,7 @@ impl Service {
///
/// TODO: use this?
#[allow(dead_code)]
pub(crate) fn get_room_version(&self, room_id: &RoomId) -> Result<Option<RoomVersionId>> {
pub fn get_room_version(&self, room_id: &RoomId) -> Result<Option<RoomVersionId>> {
let create_event = services()
.rooms
.state_accessor
@ -178,17 +137,17 @@ impl Service {
}
/// Returns the json of a pdu.
pub(crate) fn get_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
pub fn get_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
self.db.get_pdu_json(event_id)
}
/// Returns the json of a pdu.
pub(crate) fn get_non_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
pub fn get_non_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
self.db.get_non_outlier_pdu_json(event_id)
}
/// Returns the pdu's id.
pub(crate) fn get_pdu_id(&self, event_id: &EventId) -> Result<Option<Vec<u8>>> { self.db.get_pdu_id(event_id) }
pub fn get_pdu_id(&self, event_id: &EventId) -> Result<Option<Vec<u8>>> { self.db.get_pdu_id(event_id) }
/// Returns the pdu.
///
@ -196,28 +155,28 @@ impl Service {
///
/// TODO: use this?
#[allow(dead_code)]
pub(crate) fn get_non_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>> {
pub fn get_non_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>> {
self.db.get_non_outlier_pdu(event_id)
}
/// Returns the pdu.
///
/// Checks the `eventid_outlierpdu` Tree if not found in the timeline.
pub(crate) fn get_pdu(&self, event_id: &EventId) -> Result<Option<Arc<PduEvent>>> { self.db.get_pdu(event_id) }
pub fn get_pdu(&self, event_id: &EventId) -> Result<Option<Arc<PduEvent>>> { self.db.get_pdu(event_id) }
/// Returns the pdu.
///
/// This does __NOT__ check the outliers `Tree`.
pub(crate) fn get_pdu_from_id(&self, pdu_id: &[u8]) -> Result<Option<PduEvent>> { self.db.get_pdu_from_id(pdu_id) }
pub fn get_pdu_from_id(&self, pdu_id: &[u8]) -> Result<Option<PduEvent>> { self.db.get_pdu_from_id(pdu_id) }
/// Returns the pdu as a `BTreeMap<String, CanonicalJsonValue>`.
pub(crate) fn get_pdu_json_from_id(&self, pdu_id: &[u8]) -> Result<Option<CanonicalJsonObject>> {
pub fn get_pdu_json_from_id(&self, pdu_id: &[u8]) -> Result<Option<CanonicalJsonObject>> {
self.db.get_pdu_json_from_id(pdu_id)
}
/// Removes a pdu and creates a new one with the same id.
#[tracing::instrument(skip(self))]
pub(crate) fn replace_pdu(&self, pdu_id: &[u8], pdu_json: &CanonicalJsonObject, pdu: &PduEvent) -> Result<()> {
pub fn replace_pdu(&self, pdu_id: &[u8], pdu_json: &CanonicalJsonObject, pdu: &PduEvent) -> Result<()> {
self.db.replace_pdu(pdu_id, pdu_json, pdu)
}
@ -228,7 +187,7 @@ impl Service {
///
/// Returns pdu id
#[tracing::instrument(skip(self, pdu, pdu_json, leaves))]
pub(crate) async fn append_pdu(
pub async fn append_pdu(
&self,
pdu: &PduEvent,
mut pdu_json: CanonicalJsonObject,
@ -513,7 +472,6 @@ impl Service {
// This will evaluate to false if the emergency password is set up so that
// the administrator can execute commands as conduit
let from_conduit = pdu.sender == server_user && services().globals.emergency_password().is_none();
if let Some(admin_room) = service::admin::Service::get_admin_room().await? {
if to_conduit && !from_conduit && admin_room == pdu.room_id {
services()
@ -628,7 +586,7 @@ impl Service {
Ok(pdu_id)
}
pub(crate) fn create_hash_and_sign_event(
pub fn create_hash_and_sign_event(
&self,
pdu_builder: PduBuilder,
sender: &UserId,
@ -811,7 +769,7 @@ impl Service {
/// takes a roomid_mutex_state, meaning that only this function is able to
/// mutate the room state.
#[tracing::instrument(skip(self, state_lock))]
pub(crate) async fn build_and_append_pdu(
pub async fn build_and_append_pdu(
&self,
pdu_builder: PduBuilder,
sender: &UserId,
@ -819,7 +777,6 @@ impl Service {
state_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex
) -> Result<Arc<EventId>> {
let (pdu, pdu_json) = self.create_hash_and_sign_event(pdu_builder, sender, room_id, state_lock)?;
if let Some(admin_room) = service::admin::Service::get_admin_room().await? {
if admin_room == room_id {
match pdu.event_type() {
@ -951,7 +908,7 @@ impl Service {
/// Append the incoming event setting the state snapshot to the state from
/// the server that sent the event.
#[tracing::instrument(skip_all)]
pub(crate) async fn append_incoming_pdu(
pub async fn append_incoming_pdu(
&self,
pdu: &PduEvent,
pdu_json: CanonicalJsonObject,
@ -990,7 +947,7 @@ impl Service {
}
/// Returns an iterator over all PDUs in a room.
pub(crate) fn all_pdus<'a>(
pub fn all_pdus<'a>(
&'a self, user_id: &UserId, room_id: &RoomId,
) -> Result<impl Iterator<Item = Result<(PduCount, PduEvent)>> + 'a> {
self.pdus_after(user_id, room_id, PduCount::min())
@ -1000,7 +957,7 @@ impl Service {
/// happened before the event with id `until` in reverse-chronological
/// order.
#[tracing::instrument(skip(self))]
pub(crate) fn pdus_until<'a>(
pub fn pdus_until<'a>(
&'a self, user_id: &UserId, room_id: &RoomId, until: PduCount,
) -> Result<impl Iterator<Item = Result<(PduCount, PduEvent)>> + 'a> {
self.db.pdus_until(user_id, room_id, until)
@ -1009,7 +966,7 @@ impl Service {
/// Returns an iterator over all events and their token in a room that
/// happened after the event with id `from` in chronological order.
#[tracing::instrument(skip(self))]
pub(crate) fn pdus_after<'a>(
pub fn pdus_after<'a>(
&'a self, user_id: &UserId, room_id: &RoomId, from: PduCount,
) -> Result<impl Iterator<Item = Result<(PduCount, PduEvent)>> + 'a> {
self.db.pdus_after(user_id, room_id, from)
@ -1017,7 +974,7 @@ impl Service {
/// Replace a PDU with the redacted form.
#[tracing::instrument(skip(self, reason))]
pub(crate) fn redact_pdu(&self, event_id: &EventId, reason: &PduEvent) -> Result<()> {
pub fn redact_pdu(&self, event_id: &EventId, reason: &PduEvent) -> Result<()> {
// TODO: Don't reserialize, keep original json
if let Some(pdu_id) = self.get_pdu_id(event_id)? {
let mut pdu = self
@ -1039,7 +996,7 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id))]
pub(crate) async fn backfill_if_required(&self, room_id: &RoomId, from: PduCount) -> Result<()> {
pub async fn backfill_if_required(&self, room_id: &RoomId, from: PduCount) -> Result<()> {
let first_pdu = self
.all_pdus(user_id!("@doesntmatter:conduit.rs"), room_id)?
.next()
@ -1154,11 +1111,11 @@ impl Service {
}
#[tracing::instrument(skip(self, pdu, pub_key_map))]
pub(crate) async fn backfill_pdu(
pub async fn backfill_pdu(
&self, origin: &ServerName, pdu: Box<RawJsonValue>,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
) -> Result<()> {
let (event_id, value, room_id) = server_server::parse_incoming_pdu(&pdu)?;
let (event_id, value, room_id) = parse_incoming_pdu(&pdu)?;
// Lock so we cannot backfill the same pdu twice at the same time
let mutex = Arc::clone(

View file

@ -8,23 +8,23 @@ use ruma::{
use tokio::sync::{broadcast, RwLock};
use crate::{
debug_info, services,
utils::{self, user_id::user_is_local},
debug_info, services, user_is_local,
utils::{self},
Result,
};
pub(crate) struct Service {
pub(crate) typing: RwLock<BTreeMap<OwnedRoomId, BTreeMap<OwnedUserId, u64>>>, // u64 is unix timestamp of timeout
pub(crate) last_typing_update: RwLock<BTreeMap<OwnedRoomId, u64>>, /* timestamp of the last change to
* typing
* users */
pub(crate) typing_update_sender: broadcast::Sender<OwnedRoomId>,
pub struct Service {
pub typing: RwLock<BTreeMap<OwnedRoomId, BTreeMap<OwnedUserId, u64>>>, // u64 is unix timestamp of timeout
pub last_typing_update: RwLock<BTreeMap<OwnedRoomId, u64>>, /* timestamp of the last change to
* typing
* users */
pub typing_update_sender: broadcast::Sender<OwnedRoomId>,
}
impl Service {
/// Sets a user as typing until the timeout timestamp is reached or
/// roomtyping_remove is called.
pub(crate) async fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> {
pub async fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> {
debug_info!("typing started {:?} in {:?} timeout:{:?}", user_id, room_id, timeout);
// update clients
self.typing
@ -48,7 +48,7 @@ impl Service {
}
/// Removes a user from typing before the timeout is reached.
pub(crate) async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
pub async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
debug_info!("typing stopped {:?} in {:?}", user_id, room_id);
// update clients
self.typing
@ -71,7 +71,7 @@ impl Service {
Ok(())
}
pub(crate) async fn wait_for_update(&self, room_id: &RoomId) -> Result<()> {
pub async fn wait_for_update(&self, room_id: &RoomId) -> Result<()> {
let mut receiver = self.typing_update_sender.subscribe();
while let Ok(next) = receiver.recv().await {
if next == room_id {
@ -128,7 +128,7 @@ impl Service {
}
/// Returns the count of the last typing update in this room.
pub(crate) async fn last_typing_update(&self, room_id: &RoomId) -> Result<u64> {
pub async fn last_typing_update(&self, room_id: &RoomId) -> Result<u64> {
self.typings_maintain(room_id).await?;
Ok(self
.last_typing_update
@ -140,7 +140,7 @@ impl Service {
}
/// Returns a new typing EDU.
pub(crate) async fn typings_all(
pub async fn typings_all(
&self, room_id: &RoomId,
) -> Result<SyncEphemeralRoomEvent<ruma::events::typing::TypingEventContent>> {
Ok(SyncEphemeralRoomEvent {

View file

@ -2,7 +2,7 @@ use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
use crate::Result;
pub(crate) trait Data: Send + Sync {
pub trait Data: Send + Sync {
fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) -> Result<()>;
fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64>;

View file

@ -1,45 +1,43 @@
mod data;
pub(crate) use data::Data;
use std::sync::Arc;
pub use data::Data;
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
use crate::Result;
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub struct Service {
pub db: Arc<dyn Data>,
}
impl Service {
pub(crate) fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
pub fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
self.db.reset_notification_counts(user_id, room_id)
}
pub(crate) fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
self.db.notification_count(user_id, room_id)
}
pub(crate) fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
self.db.highlight_count(user_id, room_id)
}
pub(crate) fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
self.db.last_notification_read(user_id, room_id)
}
pub(crate) fn associate_token_shortstatehash(
&self, room_id: &RoomId, token: u64, shortstatehash: u64,
) -> Result<()> {
pub fn associate_token_shortstatehash(&self, room_id: &RoomId, token: u64, shortstatehash: u64) -> Result<()> {
self.db
.associate_token_shortstatehash(room_id, token, shortstatehash)
}
pub(crate) fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result<Option<u64>> {
pub fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result<Option<u64>> {
self.db.get_token_shortstatehash(room_id, token)
}
pub(crate) fn get_shared_rooms(
&self, users: Vec<OwnedUserId>,
) -> Result<impl Iterator<Item = Result<OwnedRoomId>>> {
pub fn get_shared_rooms(&self, users: Vec<OwnedUserId>) -> Result<impl Iterator<Item = Result<OwnedRoomId>> + '_> {
self.db.get_shared_rooms(users)
}
}