make everything pub(crate) instead of pub

conduwuit is not a library

Signed-off-by: strawberry <strawberry@puppygock.gay>
This commit is contained in:
strawberry 2024-04-22 23:48:57 -04:00 committed by June
parent 472c32f453
commit 66bb88a03a
135 changed files with 1366 additions and 1247 deletions

View file

@ -8,7 +8,7 @@ use ruma::{
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
/// Places one event in the account data of the user and removes the
/// previous entry.
fn update(

View file

@ -11,15 +11,15 @@ use ruma::{
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
/// Places one event in the account data of the user and removes the
/// previous entry.
#[tracing::instrument(skip(self, room_id, user_id, event_type, data))]
pub fn update(
pub(crate) fn update(
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType,
data: &serde_json::Value,
) -> Result<()> {
@ -28,7 +28,7 @@ impl Service {
/// Searches the account data for a specific kind.
#[tracing::instrument(skip(self, room_id, user_id, event_type))]
pub fn get(
pub(crate) fn get(
&self, room_id: Option<&RoomId>, user_id: &UserId, event_type: RoomAccountDataEventType,
) -> Result<Option<Box<serde_json::value::RawValue>>> {
self.db.get(room_id, user_id, event_type)
@ -36,7 +36,7 @@ impl Service {
/// Returns all changes to the account data that happened after `since`.
#[tracing::instrument(skip(self, room_id, user_id, since))]
pub fn changes_since(
pub(crate) fn changes_since(
&self, room_id: Option<&RoomId>, user_id: &UserId, since: u64,
) -> Result<HashMap<RoomAccountDataEventType, Raw<AnyEphemeralRoomEvent>>> {
self.db.changes_since(room_id, user_id, since)

View file

@ -2,7 +2,7 @@ use ruma::{api::appservice::Registration, events::room::message::RoomMessageEven
use crate::{service::admin::escape_html, services, Result};
pub(super) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let appservice_config = body[1..body.len() - 1].join("\n");
let parsed_config = serde_yaml::from_str::<Registration>(&appservice_config);
@ -26,7 +26,7 @@ pub(super) async fn register(body: Vec<&str>) -> Result<RoomMessageEventContent>
}
}
pub(super) async fn unregister(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
pub(crate) async fn unregister(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
match services()
.appservice
.unregister_appservice(&appservice_identifier)
@ -39,7 +39,7 @@ pub(super) async fn unregister(_body: Vec<&str>, appservice_identifier: String)
}
}
pub(super) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
pub(crate) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Result<RoomMessageEventContent> {
match services()
.appservice
.get_registration(&appservice_identifier)
@ -59,7 +59,7 @@ pub(super) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Res
}
}
pub(super) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
let appservices = services().appservice.iter_ids().await;
let output = format!("Appservices ({}): {}", appservices.len(), appservices.join(", "));
Ok(RoomMessageEventContent::text_plain(output))

View file

@ -10,7 +10,7 @@ use tracing_subscriber::EnvFilter;
use crate::{api::server_server::parse_incoming_pdu, services, utils::HtmlEscape, Error, PduEvent, Result};
pub(super) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
pub(crate) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
let event_id = Arc::<EventId>::from(event_id);
if let Some(event) = services().rooms.timeline.get_pdu_json(&event_id)? {
let room_id_str = event
@ -36,7 +36,7 @@ pub(super) async fn get_auth_chain(_body: Vec<&str>, event_id: Box<EventId>) ->
}
}
pub(super) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) {
@ -62,7 +62,7 @@ pub(super) async fn parse_pdu(body: Vec<&str>) -> Result<RoomMessageEventContent
}
}
pub(super) async fn get_pdu(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
pub(crate) async fn get_pdu(_body: Vec<&str>, event_id: Box<EventId>) -> Result<RoomMessageEventContent> {
let mut outlier = false;
let mut pdu_json = services()
.rooms
@ -100,7 +100,7 @@ pub(super) async fn get_pdu(_body: Vec<&str>, event_id: Box<EventId>) -> Result<
}
}
pub(super) async fn get_remote_pdu_list(
pub(crate) async fn get_remote_pdu_list(
body: Vec<&str>, server: Box<ServerName>, force: bool,
) -> Result<RoomMessageEventContent> {
if !services().globals.config.allow_federation {
@ -138,7 +138,7 @@ pub(super) async fn get_remote_pdu_list(
))
}
pub(super) async fn get_remote_pdu(
pub(crate) async fn get_remote_pdu(
_body: Vec<&str>, event_id: Box<EventId>, server: Box<ServerName>,
) -> Result<RoomMessageEventContent> {
if !services().globals.config.allow_federation {
@ -228,7 +228,7 @@ pub(super) async fn get_remote_pdu(
}
}
pub(super) async fn get_room_state(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
pub(crate) async fn get_room_state(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
let room_state = services()
.rooms
.state_accessor
@ -261,7 +261,7 @@ pub(super) async fn get_room_state(_body: Vec<&str>, room_id: Box<RoomId>) -> Re
))
}
pub(super) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<RoomMessageEventContent> {
pub(crate) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<RoomMessageEventContent> {
if server == services().globals.server_name() {
return Ok(RoomMessageEventContent::text_plain(
"Not allowed to send federation requests to ourselves.",
@ -305,7 +305,7 @@ pub(super) async fn ping(_body: Vec<&str>, server: Box<ServerName>) -> Result<Ro
}
}
pub(super) async fn force_device_list_updates(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn force_device_list_updates(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
// Force E2EE device list updates for all users
for user_id in services().users.iter().filter_map(Result::ok) {
services().users.mark_device_key_update(&user_id)?;
@ -315,7 +315,7 @@ pub(super) async fn force_device_list_updates(_body: Vec<&str>) -> Result<RoomMe
))
}
pub(super) async fn change_log_level(
pub(crate) async fn change_log_level(
_body: Vec<&str>, filter: Option<String>, reset: bool,
) -> Result<RoomMessageEventContent> {
if reset {
@ -376,7 +376,7 @@ pub(super) async fn change_log_level(
Ok(RoomMessageEventContent::text_plain("No log level was specified."))
}
pub(super) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) {
@ -399,7 +399,7 @@ pub(super) async fn sign_json(body: Vec<&str>) -> Result<RoomMessageEventContent
}
}
pub(super) async fn verify_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn verify_json(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let string = body[1..body.len() - 1].join("\n");
match serde_json::from_str(&string) {

View file

@ -4,17 +4,17 @@ use ruma::{events::room::message::RoomMessageEventContent, RoomId, ServerName};
use crate::{services, utils::HtmlEscape, Result};
pub(super) async fn disable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
pub(crate) async fn disable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
services().rooms.metadata.disable_room(&room_id, true)?;
Ok(RoomMessageEventContent::text_plain("Room disabled."))
}
pub(super) async fn enable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
pub(crate) async fn enable_room(_body: Vec<&str>, room_id: Box<RoomId>) -> Result<RoomMessageEventContent> {
services().rooms.metadata.disable_room(&room_id, false)?;
Ok(RoomMessageEventContent::text_plain("Room enabled."))
}
pub(super) async fn incoming_federeation(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn incoming_federeation(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
let map = services().globals.roomid_federationhandletime.read().await;
let mut msg = format!("Handling {} incoming pdus:\n", map.len());
@ -25,7 +25,7 @@ pub(super) async fn incoming_federeation(_body: Vec<&str>) -> Result<RoomMessage
Ok(RoomMessageEventContent::text_plain(&msg))
}
pub(super) async fn fetch_support_well_known(
pub(crate) async fn fetch_support_well_known(
_body: Vec<&str>, server_name: Box<ServerName>,
) -> Result<RoomMessageEventContent> {
let response = services()

View file

@ -5,7 +5,7 @@ use crate::{services, Result};
/// Uses the iterator in `src/database/key_value/users.rs` to iterator over
/// every user in our database (remote and local). Reports total count, any
/// errors if there were any, etc
pub(super) async fn check_all_users(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn check_all_users(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
let timer = tokio::time::Instant::now();
let results = services().users.db.iter();
let query_time = timer.elapsed();

View file

@ -3,7 +3,7 @@ use tracing::{debug, info};
use crate::{service::admin::MxcUri, services, Result};
pub(super) async fn delete(
pub(crate) async fn delete(
_body: Vec<&str>, mxc: Option<Box<MxcUri>>, event_id: Option<Box<EventId>>,
) -> Result<RoomMessageEventContent> {
if event_id.is_some() && mxc.is_some() {
@ -137,7 +137,7 @@ pub(super) async fn delete(
))
}
pub(super) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let mxc_list = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
@ -159,7 +159,7 @@ pub(super) async fn delete_list(body: Vec<&str>) -> Result<RoomMessageEventConte
))
}
pub(super) async fn delete_past_remote_media(_body: Vec<&str>, duration: String) -> Result<RoomMessageEventContent> {
pub(crate) async fn delete_past_remote_media(_body: Vec<&str>, duration: String) -> Result<RoomMessageEventContent> {
let deleted_count = services()
.media
.delete_all_remote_media_at_after_time(duration)

View file

@ -90,18 +90,18 @@ enum AdminCommand {
}
#[derive(Debug)]
pub enum AdminRoomEvent {
pub(crate) enum AdminRoomEvent {
ProcessMessage(String, Arc<EventId>),
SendMessage(RoomMessageEventContent),
}
pub struct Service {
pub sender: loole::Sender<AdminRoomEvent>,
pub(crate) struct Service {
pub(crate) sender: loole::Sender<AdminRoomEvent>,
receiver: Mutex<loole::Receiver<AdminRoomEvent>>,
}
impl Service {
pub fn build() -> Arc<Self> {
pub(crate) fn build() -> Arc<Self> {
let (sender, receiver) = loole::unbounded();
Arc::new(Self {
sender,
@ -109,7 +109,7 @@ impl Service {
})
}
pub fn start_handler(self: &Arc<Self>) {
pub(crate) fn start_handler(self: &Arc<Self>) {
let self2 = Arc::clone(self);
tokio::spawn(async move {
self2
@ -201,13 +201,13 @@ impl Service {
Ok(())
}
pub fn process_message(&self, room_message: String, event_id: Arc<EventId>) {
pub(crate) fn process_message(&self, room_message: String, event_id: Arc<EventId>) {
self.sender
.send(AdminRoomEvent::ProcessMessage(room_message, event_id))
.unwrap();
}
pub fn send_message(&self, message_content: RoomMessageEventContent) {
pub(crate) fn send_message(&self, message_content: RoomMessageEventContent) {
self.sender
.send(AdminRoomEvent::SendMessage(message_content))
.unwrap();

View file

@ -4,7 +4,7 @@ use super::AccountData;
use crate::{services, Result};
/// All the getters and iterators from src/database/key_value/account_data.rs
pub(super) async fn account_data(subcommand: AccountData) -> Result<RoomMessageEventContent> {
pub(crate) async fn account_data(subcommand: AccountData) -> Result<RoomMessageEventContent> {
match subcommand {
AccountData::ChangesSince {
user_id,

View file

@ -4,7 +4,7 @@ use super::Appservice;
use crate::{services, Result};
/// All the getters and iterators from src/database/key_value/appservice.rs
pub(super) async fn appservice(subcommand: Appservice) -> Result<RoomMessageEventContent> {
pub(crate) async fn appservice(subcommand: Appservice) -> Result<RoomMessageEventContent> {
match subcommand {
Appservice::GetRegistration {
appservice_id,

View file

@ -4,7 +4,7 @@ use super::Globals;
use crate::{services, Result};
/// All the getters and iterators from src/database/key_value/globals.rs
pub(super) async fn globals(subcommand: Globals) -> Result<RoomMessageEventContent> {
pub(crate) async fn globals(subcommand: Globals) -> Result<RoomMessageEventContent> {
match subcommand {
Globals::DatabaseVersion => {
let timer = tokio::time::Instant::now();

View file

@ -4,7 +4,7 @@ use super::Presence;
use crate::{services, Result};
/// All the getters and iterators in key_value/presence.rs
pub(super) async fn presence(subcommand: Presence) -> Result<RoomMessageEventContent> {
pub(crate) async fn presence(subcommand: Presence) -> Result<RoomMessageEventContent> {
match subcommand {
Presence::GetPresence {
user_id,

View file

@ -4,7 +4,7 @@ use super::RoomAlias;
use crate::{services, Result};
/// All the getters and iterators in src/database/key_value/rooms/alias.rs
pub(super) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEventContent> {
pub(crate) async fn room_alias(subcommand: RoomAlias) -> Result<RoomMessageEventContent> {
match subcommand {
RoomAlias::ResolveLocalAlias {
alias,

View file

@ -4,7 +4,7 @@ use super::Sending;
use crate::{service::sending::Destination, services, Result};
/// All the getters and iterators in key_value/sending.rs
pub(super) async fn sending(subcommand: Sending) -> Result<RoomMessageEventContent> {
pub(crate) async fn sending(subcommand: Sending) -> Result<RoomMessageEventContent> {
match subcommand {
Sending::ActiveRequests => {
let timer = tokio::time::Instant::now();

View file

@ -4,7 +4,7 @@ use super::Users;
use crate::{services, Result};
/// All the getters and iterators in key_value/users.rs
pub(super) async fn users(subcommand: Users) -> Result<RoomMessageEventContent> {
pub(crate) async fn users(subcommand: Users) -> Result<RoomMessageEventContent> {
match subcommand {
Users::Iter => {
let timer = tokio::time::Instant::now();

View file

@ -7,7 +7,7 @@ use crate::{
services, Result,
};
pub(super) async fn list(_body: Vec<&str>, page: Option<usize>) -> Result<RoomMessageEventContent> {
pub(crate) async fn list(_body: Vec<&str>, page: Option<usize>) -> Result<RoomMessageEventContent> {
// TODO: i know there's a way to do this with clap, but i can't seem to find it
let page = page.unwrap_or(1);
let mut rooms = services()

View file

@ -2,12 +2,12 @@ use ruma::events::room::message::RoomMessageEventContent;
use crate::{services, Result};
pub(super) async fn show_config(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn show_config(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
// Construct and send the response
Ok(RoomMessageEventContent::text_plain(format!("{}", services().globals.config)))
}
pub(super) async fn memory_usage(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn memory_usage(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
let response1 = services().memory_usage().await;
let response2 = services().globals.db.memory_usage();
@ -16,19 +16,19 @@ pub(super) async fn memory_usage(_body: Vec<&str>) -> Result<RoomMessageEventCon
)))
}
pub(super) async fn clear_database_caches(_body: Vec<&str>, amount: u32) -> Result<RoomMessageEventContent> {
pub(crate) async fn clear_database_caches(_body: Vec<&str>, amount: u32) -> Result<RoomMessageEventContent> {
services().globals.db.clear_caches(amount);
Ok(RoomMessageEventContent::text_plain("Done."))
}
pub(super) async fn clear_service_caches(_body: Vec<&str>, amount: u32) -> Result<RoomMessageEventContent> {
pub(crate) async fn clear_service_caches(_body: Vec<&str>, amount: u32) -> Result<RoomMessageEventContent> {
services().clear_caches(amount).await;
Ok(RoomMessageEventContent::text_plain("Done."))
}
pub(super) async fn list_backups(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn list_backups(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
let result = services().globals.db.backup_list()?;
if result.is_empty() {
@ -38,7 +38,7 @@ pub(super) async fn list_backups(_body: Vec<&str>) -> Result<RoomMessageEventCon
}
}
pub(super) async fn backup_database(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn backup_database(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
if !cfg!(feature = "rocksdb") {
return Ok(RoomMessageEventContent::text_plain(
"Only RocksDB supports online backups in conduwuit.",
@ -59,7 +59,7 @@ pub(super) async fn backup_database(_body: Vec<&str>) -> Result<RoomMessageEvent
Ok(RoomMessageEventContent::text_plain(&result))
}
pub(super) async fn list_database_files(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn list_database_files(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
if !cfg!(feature = "rocksdb") {
return Ok(RoomMessageEventContent::text_plain(
"Only RocksDB supports listing files in conduwuit.",

View file

@ -10,7 +10,7 @@ use crate::{
services, utils, Result,
};
pub(super) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
pub(crate) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
match services().users.list_local_users() {
Ok(users) => {
let mut msg = format!("Found {} local user account(s):\n", users.len());
@ -21,7 +21,7 @@ pub(super) async fn list(_body: Vec<&str>) -> Result<RoomMessageEventContent> {
}
}
pub(super) async fn create(
pub(crate) async fn create(
_body: Vec<&str>, username: String, password: Option<String>,
) -> Result<RoomMessageEventContent> {
let password = password.unwrap_or_else(|| utils::random_string(AUTO_GEN_PASSWORD_LENGTH));
@ -119,7 +119,7 @@ pub(super) async fn create(
)))
}
pub(super) async fn deactivate(
pub(crate) async fn deactivate(
_body: Vec<&str>, leave_rooms: bool, user_id: String,
) -> Result<RoomMessageEventContent> {
// Validate user id
@ -168,7 +168,7 @@ pub(super) async fn deactivate(
}
}
pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result<RoomMessageEventContent> {
pub(crate) async fn reset_password(_body: Vec<&str>, username: String) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id =
match UserId::parse_with_server_name(username.as_str().to_lowercase(), services().globals.server_name()) {
@ -210,7 +210,7 @@ pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result
}
}
pub(super) async fn deactivate_all(body: Vec<&str>, leave_rooms: bool, force: bool) -> Result<RoomMessageEventContent> {
pub(crate) async fn deactivate_all(body: Vec<&str>, leave_rooms: bool, force: bool) -> Result<RoomMessageEventContent> {
if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" {
let usernames = body.clone().drain(1..body.len() - 1).collect::<Vec<_>>();
@ -292,7 +292,7 @@ pub(super) async fn deactivate_all(body: Vec<&str>, leave_rooms: bool, force: bo
}
}
pub(super) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
pub(crate) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result<RoomMessageEventContent> {
// Validate user id
let user_id =
match UserId::parse_with_server_name(user_id.as_str().to_lowercase(), services().globals.server_name()) {

View file

@ -2,7 +2,7 @@ use ruma::api::appservice::Registration;
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
/// Registers an appservice and returns the ID to the caller
fn register_appservice(&self, yaml: Registration) -> Result<String>;

View file

@ -15,14 +15,14 @@ use crate::{services, Result};
/// Compiled regular expressions for a namespace
#[derive(Clone, Debug)]
pub struct NamespaceRegex {
pub exclusive: Option<RegexSet>,
pub non_exclusive: Option<RegexSet>,
pub(crate) struct NamespaceRegex {
pub(crate) exclusive: Option<RegexSet>,
pub(crate) non_exclusive: Option<RegexSet>,
}
impl NamespaceRegex {
/// Checks if this namespace has rights to a namespace
pub fn is_match(&self, heystack: &str) -> bool {
pub(crate) fn is_match(&self, heystack: &str) -> bool {
if self.is_exclusive_match(heystack) {
return true;
}
@ -36,7 +36,7 @@ impl NamespaceRegex {
}
/// Checks if this namespace has exlusive rights to a namespace
pub fn is_exclusive_match(&self, heystack: &str) -> bool {
pub(crate) fn is_exclusive_match(&self, heystack: &str) -> bool {
if let Some(exclusive) = &self.exclusive {
if exclusive.is_match(heystack) {
return true;
@ -47,11 +47,11 @@ impl NamespaceRegex {
}
impl RegistrationInfo {
pub fn is_user_match(&self, user_id: &UserId) -> bool {
pub(crate) fn is_user_match(&self, user_id: &UserId) -> bool {
self.users.is_match(user_id.as_str()) || self.registration.sender_localpart == user_id.localpart()
}
pub fn is_exclusive_user_match(&self, user_id: &UserId) -> bool {
pub(crate) fn is_exclusive_user_match(&self, user_id: &UserId) -> bool {
self.users.is_exclusive_match(user_id.as_str()) || self.registration.sender_localpart == user_id.localpart()
}
}
@ -88,11 +88,11 @@ impl TryFrom<Vec<Namespace>> for NamespaceRegex {
/// Appservice registration combined with its compiled regular expressions.
#[derive(Clone, Debug)]
pub struct RegistrationInfo {
pub registration: Registration,
pub users: NamespaceRegex,
pub aliases: NamespaceRegex,
pub rooms: NamespaceRegex,
pub(crate) struct RegistrationInfo {
pub(crate) registration: Registration,
pub(crate) users: NamespaceRegex,
pub(crate) aliases: NamespaceRegex,
pub(crate) rooms: NamespaceRegex,
}
impl TryFrom<Registration> for RegistrationInfo {
@ -108,13 +108,13 @@ impl TryFrom<Registration> for RegistrationInfo {
}
}
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
registration_info: RwLock<BTreeMap<String, RegistrationInfo>>,
}
impl Service {
pub fn build(db: &'static dyn Data) -> Result<Self> {
pub(crate) fn build(db: &'static dyn Data) -> Result<Self> {
let mut registration_info = BTreeMap::new();
// Inserting registrations into cache
for appservice in db.all()? {
@ -134,7 +134,7 @@ impl Service {
}
/// Registers an appservice and returns the ID to the caller
pub async fn register_appservice(&self, yaml: Registration) -> Result<String> {
pub(crate) async fn register_appservice(&self, yaml: Registration) -> Result<String> {
//TODO: Check for collisions between exclusive appservice namespaces
services()
.appservice
@ -151,7 +151,7 @@ impl Service {
/// # Arguments
///
/// * `service_name` - the name you send to register the service previously
pub async fn unregister_appservice(&self, service_name: &str) -> Result<()> {
pub(crate) async fn unregister_appservice(&self, service_name: &str) -> Result<()> {
services()
.appservice
.registration_info
@ -163,7 +163,7 @@ impl Service {
self.db.unregister_appservice(service_name)
}
pub async fn get_registration(&self, id: &str) -> Option<Registration> {
pub(crate) async fn get_registration(&self, id: &str) -> Option<Registration> {
self.registration_info
.read()
.await
@ -172,7 +172,7 @@ impl Service {
.map(|info| info.registration)
}
pub async fn iter_ids(&self) -> Vec<String> {
pub(crate) async fn iter_ids(&self) -> Vec<String> {
self.registration_info
.read()
.await
@ -181,7 +181,7 @@ impl Service {
.collect()
}
pub async fn find_from_token(&self, token: &str) -> Option<RegistrationInfo> {
pub(crate) async fn find_from_token(&self, token: &str) -> Option<RegistrationInfo> {
self.read()
.await
.values()
@ -190,7 +190,7 @@ impl Service {
}
/// Checks if a given user id matches any exclusive appservice regex
pub async fn is_exclusive_user_id(&self, user_id: &UserId) -> bool {
pub(crate) async fn is_exclusive_user_id(&self, user_id: &UserId) -> bool {
self.read()
.await
.values()
@ -198,7 +198,7 @@ impl Service {
}
/// Checks if a given room alias matches any exclusive appservice regex
pub async fn is_exclusive_alias(&self, alias: &RoomAliasId) -> bool {
pub(crate) async fn is_exclusive_alias(&self, alias: &RoomAliasId) -> bool {
self.read()
.await
.values()
@ -206,14 +206,16 @@ impl Service {
}
/// Checks if a given room id matches any exclusive appservice regex
pub async fn is_exclusive_room_id(&self, room_id: &RoomId) -> bool {
pub(crate) async fn is_exclusive_room_id(&self, room_id: &RoomId) -> bool {
self.read()
.await
.values()
.any(|info| info.rooms.is_exclusive_match(room_id.as_str()))
}
pub fn read(&self) -> impl Future<Output = tokio::sync::RwLockReadGuard<'_, BTreeMap<String, RegistrationInfo>>> {
pub(crate) fn read(
&self,
) -> impl Future<Output = tokio::sync::RwLockReadGuard<'_, BTreeMap<String, RegistrationInfo>>> {
self.registration_info.read()
}
}

View file

@ -4,18 +4,18 @@ use reqwest::redirect;
use crate::{service::globals::resolver, Config, Result};
pub struct Client {
pub default: reqwest::Client,
pub url_preview: reqwest::Client,
pub well_known: reqwest::Client,
pub federation: reqwest::Client,
pub sender: reqwest::Client,
pub appservice: reqwest::Client,
pub pusher: reqwest::Client,
pub(crate) struct Client {
pub(crate) default: reqwest::Client,
pub(crate) url_preview: reqwest::Client,
pub(crate) well_known: reqwest::Client,
pub(crate) federation: reqwest::Client,
pub(crate) sender: reqwest::Client,
pub(crate) appservice: reqwest::Client,
pub(crate) pusher: reqwest::Client,
}
impl Client {
pub fn new(config: &Config, resolver: &Arc<resolver::Resolver>) -> Client {
pub(crate) fn new(config: &Config, resolver: &Arc<resolver::Resolver>) -> Client {
Client {
default: Self::base(config)
.unwrap()

View file

@ -10,7 +10,7 @@ use ruma::{
use crate::{database::Cork, Result};
#[async_trait]
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
fn next_count(&self) -> Result<u64>;
fn current_count(&self) -> Result<u64>;
fn last_check_for_updates_id(&self) -> Result<u64>;

View file

@ -12,7 +12,7 @@ use std::{
use argon2::Argon2;
use base64::{engine::general_purpose, Engine as _};
pub use data::Data;
pub(crate) use data::Data;
use hickory_resolver::TokioAsyncResolver;
use ipaddress::IPAddress;
use regex::RegexSet;
@ -32,9 +32,9 @@ use url::Url;
use crate::{services, Config, Result};
pub mod client;
mod client;
mod data;
pub mod resolver;
mod resolver;
type RateLimitState = (Instant, u32); // Time if last failed try, number of failed tries
type SyncHandle = (
@ -42,32 +42,32 @@ type SyncHandle = (
Receiver<Option<Result<sync_events::v3::Response>>>, // rx
);
pub struct Service<'a> {
pub db: &'static dyn Data,
pub(crate) struct Service<'a> {
pub(crate) db: &'static dyn Data,
pub tracing_reload_handle: tracing_subscriber::reload::Handle<EnvFilter, Registry>,
pub config: Config,
pub cidr_range_denylist: Vec<IPAddress>,
pub(crate) tracing_reload_handle: tracing_subscriber::reload::Handle<EnvFilter, Registry>,
pub(crate) config: Config,
pub(crate) cidr_range_denylist: Vec<IPAddress>,
keypair: Arc<ruma::signatures::Ed25519KeyPair>,
jwt_decoding_key: Option<jsonwebtoken::DecodingKey>,
pub resolver: Arc<resolver::Resolver>,
pub client: client::Client,
pub stable_room_versions: Vec<RoomVersionId>,
pub unstable_room_versions: Vec<RoomVersionId>,
pub bad_event_ratelimiter: Arc<RwLock<HashMap<OwnedEventId, RateLimitState>>>,
pub bad_signature_ratelimiter: Arc<RwLock<HashMap<Vec<String>, RateLimitState>>>,
pub bad_query_ratelimiter: Arc<RwLock<HashMap<OwnedServerName, RateLimitState>>>,
pub servername_ratelimiter: Arc<RwLock<HashMap<OwnedServerName, Arc<Semaphore>>>>,
pub sync_receivers: RwLock<HashMap<(OwnedUserId, OwnedDeviceId), SyncHandle>>,
pub roomid_mutex_insert: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>,
pub roomid_mutex_state: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>,
pub roomid_mutex_federation: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>, // this lock will be held longer
pub roomid_federationhandletime: RwLock<HashMap<OwnedRoomId, (OwnedEventId, Instant)>>,
pub stateres_mutex: Arc<Mutex<()>>,
pub(crate) resolver: Arc<resolver::Resolver>,
pub(crate) client: client::Client,
pub(crate) stable_room_versions: Vec<RoomVersionId>,
pub(crate) unstable_room_versions: Vec<RoomVersionId>,
pub(crate) bad_event_ratelimiter: Arc<RwLock<HashMap<OwnedEventId, RateLimitState>>>,
pub(crate) bad_signature_ratelimiter: Arc<RwLock<HashMap<Vec<String>, RateLimitState>>>,
pub(crate) bad_query_ratelimiter: Arc<RwLock<HashMap<OwnedServerName, RateLimitState>>>,
pub(crate) servername_ratelimiter: Arc<RwLock<HashMap<OwnedServerName, Arc<Semaphore>>>>,
pub(crate) sync_receivers: RwLock<HashMap<(OwnedUserId, OwnedDeviceId), SyncHandle>>,
pub(crate) roomid_mutex_insert: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>,
pub(crate) roomid_mutex_state: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>,
pub(crate) roomid_mutex_federation: RwLock<HashMap<OwnedRoomId, Arc<Mutex<()>>>>, // this lock will be held longer
pub(crate) roomid_federationhandletime: RwLock<HashMap<OwnedRoomId, (OwnedEventId, Instant)>>,
pub(crate) stateres_mutex: Arc<Mutex<()>>,
pub(crate) rotate: RotationHandler,
pub shutdown: AtomicBool,
pub argon: Argon2<'a>,
pub(crate) shutdown: AtomicBool,
pub(crate) argon: Argon2<'a>,
}
/// Handles "rotation" of long-polling requests. "Rotation" in this context is
@ -78,12 +78,12 @@ pub struct Service<'a> {
pub(crate) struct RotationHandler(broadcast::Sender<()>, ());
impl RotationHandler {
pub fn new() -> Self {
fn new() -> Self {
let (s, _r) = broadcast::channel(1);
Self(s, ())
}
pub fn watch(&self) -> impl Future<Output = ()> {
pub(crate) fn watch(&self) -> impl Future<Output = ()> {
let mut r = self.0.subscribe();
async move {
@ -91,7 +91,7 @@ impl RotationHandler {
}
}
pub fn fire(&self) { _ = self.0.send(()); }
fn fire(&self) { _ = self.0.send(()); }
}
impl Default for RotationHandler {
@ -99,7 +99,7 @@ impl Default for RotationHandler {
}
impl Service<'_> {
pub fn load(
pub(crate) fn load(
db: &'static dyn Data, config: &Config,
tracing_reload_handle: tracing_subscriber::reload::Handle<EnvFilter, Registry>,
) -> Result<Self> {
@ -187,171 +187,179 @@ impl Service<'_> {
}
/// Returns this server's keypair.
pub fn keypair(&self) -> &ruma::signatures::Ed25519KeyPair { &self.keypair }
pub(crate) fn keypair(&self) -> &ruma::signatures::Ed25519KeyPair { &self.keypair }
#[tracing::instrument(skip(self))]
pub fn next_count(&self) -> Result<u64> { self.db.next_count() }
pub(crate) fn next_count(&self) -> Result<u64> { self.db.next_count() }
#[tracing::instrument(skip(self))]
pub fn current_count(&self) -> Result<u64> { self.db.current_count() }
pub(crate) fn current_count(&self) -> Result<u64> { self.db.current_count() }
#[tracing::instrument(skip(self))]
pub fn last_check_for_updates_id(&self) -> Result<u64> { self.db.last_check_for_updates_id() }
pub(crate) fn last_check_for_updates_id(&self) -> Result<u64> { self.db.last_check_for_updates_id() }
#[tracing::instrument(skip(self))]
pub fn update_check_for_updates_id(&self, id: u64) -> Result<()> { self.db.update_check_for_updates_id(id) }
pub(crate) fn update_check_for_updates_id(&self, id: u64) -> Result<()> { self.db.update_check_for_updates_id(id) }
pub async fn watch(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
pub(crate) async fn watch(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
self.db.watch(user_id, device_id).await
}
pub fn cleanup(&self) -> Result<()> { self.db.cleanup() }
pub(crate) fn cleanup(&self) -> Result<()> { self.db.cleanup() }
pub fn flush(&self) -> Result<()> { self.db.flush() }
pub(crate) fn flush(&self) -> Result<()> { self.db.flush() }
pub fn server_name(&self) -> &ServerName { self.config.server_name.as_ref() }
pub(crate) fn server_name(&self) -> &ServerName { self.config.server_name.as_ref() }
pub fn max_request_size(&self) -> u32 { self.config.max_request_size }
pub(crate) fn max_request_size(&self) -> u32 { self.config.max_request_size }
pub fn max_fetch_prev_events(&self) -> u16 { self.config.max_fetch_prev_events }
pub(crate) fn max_fetch_prev_events(&self) -> u16 { self.config.max_fetch_prev_events }
pub fn allow_registration(&self) -> bool { self.config.allow_registration }
pub(crate) fn allow_registration(&self) -> bool { self.config.allow_registration }
pub fn allow_guest_registration(&self) -> bool { self.config.allow_guest_registration }
pub(crate) fn allow_guest_registration(&self) -> bool { self.config.allow_guest_registration }
pub fn allow_guests_auto_join_rooms(&self) -> bool { self.config.allow_guests_auto_join_rooms }
pub(crate) fn allow_guests_auto_join_rooms(&self) -> bool { self.config.allow_guests_auto_join_rooms }
pub fn log_guest_registrations(&self) -> bool { self.config.log_guest_registrations }
pub(crate) fn log_guest_registrations(&self) -> bool { self.config.log_guest_registrations }
pub fn allow_encryption(&self) -> bool { self.config.allow_encryption }
pub(crate) fn allow_encryption(&self) -> bool { self.config.allow_encryption }
pub fn allow_federation(&self) -> bool { self.config.allow_federation }
pub(crate) fn allow_federation(&self) -> bool { self.config.allow_federation }
pub fn allow_public_room_directory_over_federation(&self) -> bool {
pub(crate) fn allow_public_room_directory_over_federation(&self) -> bool {
self.config.allow_public_room_directory_over_federation
}
pub fn allow_public_room_directory_without_auth(&self) -> bool {
pub(crate) fn allow_public_room_directory_without_auth(&self) -> bool {
self.config.allow_public_room_directory_without_auth
}
pub fn allow_device_name_federation(&self) -> bool { self.config.allow_device_name_federation }
pub(crate) fn allow_device_name_federation(&self) -> bool { self.config.allow_device_name_federation }
pub fn allow_room_creation(&self) -> bool { self.config.allow_room_creation }
pub(crate) fn allow_room_creation(&self) -> bool { self.config.allow_room_creation }
pub fn allow_unstable_room_versions(&self) -> bool { self.config.allow_unstable_room_versions }
pub(crate) fn allow_unstable_room_versions(&self) -> bool { self.config.allow_unstable_room_versions }
pub fn default_room_version(&self) -> RoomVersionId { self.config.default_room_version.clone() }
pub(crate) fn default_room_version(&self) -> RoomVersionId { self.config.default_room_version.clone() }
pub fn new_user_displayname_suffix(&self) -> &String { &self.config.new_user_displayname_suffix }
pub(crate) fn new_user_displayname_suffix(&self) -> &String { &self.config.new_user_displayname_suffix }
pub fn allow_check_for_updates(&self) -> bool { self.config.allow_check_for_updates }
pub(crate) fn allow_check_for_updates(&self) -> bool { self.config.allow_check_for_updates }
pub fn trusted_servers(&self) -> &[OwnedServerName] { &self.config.trusted_servers }
pub(crate) fn trusted_servers(&self) -> &[OwnedServerName] { &self.config.trusted_servers }
pub fn query_trusted_key_servers_first(&self) -> bool { self.config.query_trusted_key_servers_first }
pub(crate) fn query_trusted_key_servers_first(&self) -> bool { self.config.query_trusted_key_servers_first }
pub fn dns_resolver(&self) -> &TokioAsyncResolver { &self.resolver.resolver }
pub(crate) fn dns_resolver(&self) -> &TokioAsyncResolver { &self.resolver.resolver }
pub fn query_all_nameservers(&self) -> bool { self.config.query_all_nameservers }
pub(crate) fn query_all_nameservers(&self) -> bool { self.config.query_all_nameservers }
pub fn actual_destinations(&self) -> &Arc<RwLock<resolver::WellKnownMap>> { &self.resolver.destinations }
pub(crate) fn actual_destinations(&self) -> &Arc<RwLock<resolver::WellKnownMap>> { &self.resolver.destinations }
pub fn jwt_decoding_key(&self) -> Option<&jsonwebtoken::DecodingKey> { self.jwt_decoding_key.as_ref() }
pub(crate) fn jwt_decoding_key(&self) -> Option<&jsonwebtoken::DecodingKey> { self.jwt_decoding_key.as_ref() }
pub fn turn_password(&self) -> &String { &self.config.turn_password }
pub(crate) fn turn_password(&self) -> &String { &self.config.turn_password }
pub fn turn_ttl(&self) -> u64 { self.config.turn_ttl }
pub(crate) fn turn_ttl(&self) -> u64 { self.config.turn_ttl }
pub fn turn_uris(&self) -> &[String] { &self.config.turn_uris }
pub(crate) fn turn_uris(&self) -> &[String] { &self.config.turn_uris }
pub fn turn_username(&self) -> &String { &self.config.turn_username }
pub(crate) fn turn_username(&self) -> &String { &self.config.turn_username }
pub fn turn_secret(&self) -> &String { &self.config.turn_secret }
pub(crate) fn turn_secret(&self) -> &String { &self.config.turn_secret }
pub fn auto_join_rooms(&self) -> &[OwnedRoomId] { &self.config.auto_join_rooms }
pub(crate) fn auto_join_rooms(&self) -> &[OwnedRoomId] { &self.config.auto_join_rooms }
pub fn allow_profile_lookup_federation_requests(&self) -> bool {
pub(crate) fn allow_profile_lookup_federation_requests(&self) -> bool {
self.config.allow_profile_lookup_federation_requests
}
pub fn notification_push_path(&self) -> &String { &self.config.notification_push_path }
pub(crate) fn notification_push_path(&self) -> &String { &self.config.notification_push_path }
pub fn emergency_password(&self) -> &Option<String> { &self.config.emergency_password }
pub(crate) fn emergency_password(&self) -> &Option<String> { &self.config.emergency_password }
pub fn url_preview_domain_contains_allowlist(&self) -> &Vec<String> {
pub(crate) fn url_preview_domain_contains_allowlist(&self) -> &Vec<String> {
&self.config.url_preview_domain_contains_allowlist
}
pub fn url_preview_domain_explicit_allowlist(&self) -> &Vec<String> {
pub(crate) fn url_preview_domain_explicit_allowlist(&self) -> &Vec<String> {
&self.config.url_preview_domain_explicit_allowlist
}
pub fn url_preview_domain_explicit_denylist(&self) -> &Vec<String> {
pub(crate) fn url_preview_domain_explicit_denylist(&self) -> &Vec<String> {
&self.config.url_preview_domain_explicit_denylist
}
pub fn url_preview_url_contains_allowlist(&self) -> &Vec<String> { &self.config.url_preview_url_contains_allowlist }
pub(crate) fn url_preview_url_contains_allowlist(&self) -> &Vec<String> {
&self.config.url_preview_url_contains_allowlist
}
pub fn url_preview_max_spider_size(&self) -> usize { self.config.url_preview_max_spider_size }
pub(crate) fn url_preview_max_spider_size(&self) -> usize { self.config.url_preview_max_spider_size }
pub fn url_preview_check_root_domain(&self) -> bool { self.config.url_preview_check_root_domain }
pub(crate) fn url_preview_check_root_domain(&self) -> bool { self.config.url_preview_check_root_domain }
pub fn forbidden_alias_names(&self) -> &RegexSet { &self.config.forbidden_alias_names }
pub(crate) fn forbidden_alias_names(&self) -> &RegexSet { &self.config.forbidden_alias_names }
pub fn forbidden_usernames(&self) -> &RegexSet { &self.config.forbidden_usernames }
pub(crate) fn forbidden_usernames(&self) -> &RegexSet { &self.config.forbidden_usernames }
pub fn allow_local_presence(&self) -> bool { self.config.allow_local_presence }
pub(crate) fn allow_local_presence(&self) -> bool { self.config.allow_local_presence }
pub fn allow_incoming_presence(&self) -> bool { self.config.allow_incoming_presence }
pub(crate) fn allow_incoming_presence(&self) -> bool { self.config.allow_incoming_presence }
pub fn allow_outgoing_presence(&self) -> bool { self.config.allow_outgoing_presence }
pub(crate) fn allow_outgoing_presence(&self) -> bool { self.config.allow_outgoing_presence }
pub fn presence_idle_timeout_s(&self) -> u64 { self.config.presence_idle_timeout_s }
pub(crate) fn presence_idle_timeout_s(&self) -> u64 { self.config.presence_idle_timeout_s }
pub fn presence_offline_timeout_s(&self) -> u64 { self.config.presence_offline_timeout_s }
pub(crate) fn presence_offline_timeout_s(&self) -> u64 { self.config.presence_offline_timeout_s }
pub fn allow_incoming_read_receipts(&self) -> bool { self.config.allow_incoming_read_receipts }
pub(crate) fn allow_incoming_read_receipts(&self) -> bool { self.config.allow_incoming_read_receipts }
pub fn allow_outgoing_read_receipts(&self) -> bool { self.config.allow_outgoing_read_receipts }
pub(crate) fn allow_outgoing_read_receipts(&self) -> bool { self.config.allow_outgoing_read_receipts }
pub fn rocksdb_log_level(&self) -> &String { &self.config.rocksdb_log_level }
pub(crate) fn rocksdb_log_level(&self) -> &String { &self.config.rocksdb_log_level }
pub fn rocksdb_max_log_file_size(&self) -> usize { self.config.rocksdb_max_log_file_size }
pub(crate) fn rocksdb_max_log_file_size(&self) -> usize { self.config.rocksdb_max_log_file_size }
pub fn rocksdb_log_time_to_roll(&self) -> usize { self.config.rocksdb_log_time_to_roll }
pub(crate) fn rocksdb_log_time_to_roll(&self) -> usize { self.config.rocksdb_log_time_to_roll }
pub fn rocksdb_optimize_for_spinning_disks(&self) -> bool { self.config.rocksdb_optimize_for_spinning_disks }
pub(crate) fn rocksdb_optimize_for_spinning_disks(&self) -> bool { self.config.rocksdb_optimize_for_spinning_disks }
pub fn rocksdb_parallelism_threads(&self) -> usize { self.config.rocksdb_parallelism_threads }
pub(crate) fn rocksdb_parallelism_threads(&self) -> usize { self.config.rocksdb_parallelism_threads }
pub fn rocksdb_compression_algo(&self) -> &String { &self.config.rocksdb_compression_algo }
pub(crate) fn rocksdb_compression_algo(&self) -> &String { &self.config.rocksdb_compression_algo }
pub fn rocksdb_compression_level(&self) -> i32 { self.config.rocksdb_compression_level }
pub(crate) fn rocksdb_compression_level(&self) -> i32 { self.config.rocksdb_compression_level }
pub fn rocksdb_bottommost_compression_level(&self) -> i32 { self.config.rocksdb_bottommost_compression_level }
pub(crate) fn rocksdb_bottommost_compression_level(&self) -> i32 {
self.config.rocksdb_bottommost_compression_level
}
pub fn prevent_media_downloads_from(&self) -> &[OwnedServerName] { &self.config.prevent_media_downloads_from }
pub(crate) fn prevent_media_downloads_from(&self) -> &[OwnedServerName] {
&self.config.prevent_media_downloads_from
}
pub fn forbidden_remote_server_names(&self) -> &[OwnedServerName] { &self.config.forbidden_remote_server_names }
pub(crate) fn forbidden_remote_server_names(&self) -> &[OwnedServerName] {
&self.config.forbidden_remote_server_names
}
pub fn forbidden_remote_room_directory_server_names(&self) -> &[OwnedServerName] {
pub(crate) fn forbidden_remote_room_directory_server_names(&self) -> &[OwnedServerName] {
&self.config.forbidden_remote_room_directory_server_names
}
pub fn ip_range_denylist(&self) -> &[String] { &self.config.ip_range_denylist }
pub(crate) fn ip_range_denylist(&self) -> &[String] { &self.config.ip_range_denylist }
pub fn well_known_support_page(&self) -> &Option<Url> { &self.config.well_known.support_page }
pub(crate) fn well_known_support_page(&self) -> &Option<Url> { &self.config.well_known.support_page }
pub fn well_known_support_role(&self) -> &Option<ContactRole> { &self.config.well_known.support_role }
pub(crate) fn well_known_support_role(&self) -> &Option<ContactRole> { &self.config.well_known.support_role }
pub fn well_known_support_email(&self) -> &Option<String> { &self.config.well_known.support_email }
pub(crate) fn well_known_support_email(&self) -> &Option<String> { &self.config.well_known.support_email }
pub fn well_known_support_mxid(&self) -> &Option<OwnedUserId> { &self.config.well_known.support_mxid }
pub(crate) fn well_known_support_mxid(&self) -> &Option<OwnedUserId> { &self.config.well_known.support_mxid }
pub fn block_non_admin_invites(&self) -> bool { self.config.block_non_admin_invites }
pub(crate) fn block_non_admin_invites(&self) -> bool { self.config.block_non_admin_invites }
pub fn supported_room_versions(&self) -> Vec<RoomVersionId> {
pub(crate) fn supported_room_versions(&self) -> Vec<RoomVersionId> {
let mut room_versions: Vec<RoomVersionId> = vec![];
room_versions.extend(self.stable_room_versions.clone());
if self.allow_unstable_room_versions() {
@ -367,7 +375,7 @@ impl Service<'_> {
///
/// This doesn't actually check that the keys provided are newer than the
/// old set.
pub fn add_signing_key(
pub(crate) fn add_signing_key(
&self, origin: &ServerName, new_keys: ServerSigningKeys,
) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
self.db.add_signing_key(origin, new_keys)
@ -375,7 +383,7 @@ impl Service<'_> {
/// This returns an empty `Ok(BTreeMap<..>)` when there are no keys found
/// for the server.
pub fn signing_keys_for(&self, origin: &ServerName) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
pub(crate) fn signing_keys_for(&self, origin: &ServerName) -> Result<BTreeMap<OwnedServerSigningKeyId, VerifyKey>> {
let mut keys = self.db.signing_keys_for(origin)?;
if origin == self.server_name() {
keys.insert(
@ -391,11 +399,13 @@ impl Service<'_> {
Ok(keys)
}
pub fn database_version(&self) -> Result<u64> { self.db.database_version() }
pub(crate) fn database_version(&self) -> Result<u64> { self.db.database_version() }
pub fn bump_database_version(&self, new_version: u64) -> Result<()> { self.db.bump_database_version(new_version) }
pub(crate) fn bump_database_version(&self, new_version: u64) -> Result<()> {
self.db.bump_database_version(new_version)
}
pub fn get_media_folder(&self) -> PathBuf {
pub(crate) fn get_media_folder(&self) -> PathBuf {
let mut r = PathBuf::new();
r.push(self.config.database_path.clone());
r.push("media");
@ -406,7 +416,7 @@ impl Service<'_> {
/// flag enabled and database migrated uses SHA256 hash of the base64 key as
/// the file name
#[cfg(feature = "sha256_media")]
pub fn get_media_file_new(&self, key: &[u8]) -> PathBuf {
pub(crate) fn get_media_file_new(&self, key: &[u8]) -> PathBuf {
let mut r = PathBuf::new();
r.push(self.config.database_path.clone());
r.push("media");
@ -420,7 +430,7 @@ impl Service<'_> {
/// old base64 file name media function
/// This is the old version of `get_media_file` that uses the full base64
/// key as the filename.
pub fn get_media_file(&self, key: &[u8]) -> PathBuf {
pub(crate) fn get_media_file(&self, key: &[u8]) -> PathBuf {
let mut r = PathBuf::new();
r.push(self.config.database_path.clone());
r.push("media");
@ -428,13 +438,13 @@ impl Service<'_> {
r
}
pub fn well_known_client(&self) -> &Option<Url> { &self.config.well_known.client }
pub(crate) fn well_known_client(&self) -> &Option<Url> { &self.config.well_known.client }
pub fn well_known_server(&self) -> &Option<OwnedServerName> { &self.config.well_known.server }
pub(crate) fn well_known_server(&self) -> &Option<OwnedServerName> { &self.config.well_known.server }
pub fn unix_socket_path(&self) -> &Option<PathBuf> { &self.config.unix_socket_path }
pub(crate) fn unix_socket_path(&self) -> &Option<PathBuf> { &self.config.unix_socket_path }
pub fn valid_cidr_range(&self, ip: &IPAddress) -> bool {
pub(crate) fn valid_cidr_range(&self, ip: &IPAddress) -> bool {
for cidr in &self.cidr_range_denylist {
if cidr.includes(ip) {
return false;
@ -444,7 +454,7 @@ impl Service<'_> {
true
}
pub fn shutdown(&self) {
pub(crate) fn shutdown(&self) {
self.shutdown.store(true, atomic::Ordering::Relaxed);
// On shutdown

View file

@ -14,19 +14,19 @@ use tracing::error;
use crate::{service::sending::FedDest, Config, Error};
pub type WellKnownMap = HashMap<OwnedServerName, (FedDest, String)>;
pub type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>;
pub(crate) type WellKnownMap = HashMap<OwnedServerName, (FedDest, String)>;
type TlsNameMap = HashMap<String, (Vec<IpAddr>, u16)>;
pub struct Resolver {
pub destinations: Arc<RwLock<WellKnownMap>>, // actual_destination, host
pub overrides: Arc<StdRwLock<TlsNameMap>>,
pub resolver: Arc<TokioAsyncResolver>,
pub hooked: Arc<Hooked>,
pub(crate) struct Resolver {
pub(crate) destinations: Arc<RwLock<WellKnownMap>>, // actual_destination, host
pub(crate) overrides: Arc<StdRwLock<TlsNameMap>>,
pub(crate) resolver: Arc<TokioAsyncResolver>,
pub(crate) hooked: Arc<Hooked>,
}
pub struct Hooked {
pub overrides: Arc<StdRwLock<TlsNameMap>>,
pub resolver: Arc<TokioAsyncResolver>,
pub(crate) struct Hooked {
pub(crate) overrides: Arc<StdRwLock<TlsNameMap>>,
pub(crate) resolver: Arc<TokioAsyncResolver>,
}
impl Resolver {

View file

@ -8,7 +8,7 @@ use ruma::{
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
fn create_backup(&self, user_id: &UserId, backup_metadata: &Raw<BackupAlgorithm>) -> Result<String>;
fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()>;

View file

@ -10,73 +10,79 @@ use ruma::{
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
pub fn create_backup(&self, user_id: &UserId, backup_metadata: &Raw<BackupAlgorithm>) -> Result<String> {
pub(crate) fn create_backup(&self, user_id: &UserId, backup_metadata: &Raw<BackupAlgorithm>) -> Result<String> {
self.db.create_backup(user_id, backup_metadata)
}
pub fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()> {
pub(crate) fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()> {
self.db.delete_backup(user_id, version)
}
pub fn update_backup(
pub(crate) fn update_backup(
&self, user_id: &UserId, version: &str, backup_metadata: &Raw<BackupAlgorithm>,
) -> Result<String> {
self.db.update_backup(user_id, version, backup_metadata)
}
pub fn get_latest_backup_version(&self, user_id: &UserId) -> Result<Option<String>> {
pub(crate) fn get_latest_backup_version(&self, user_id: &UserId) -> Result<Option<String>> {
self.db.get_latest_backup_version(user_id)
}
pub fn get_latest_backup(&self, user_id: &UserId) -> Result<Option<(String, Raw<BackupAlgorithm>)>> {
pub(crate) fn get_latest_backup(&self, user_id: &UserId) -> Result<Option<(String, Raw<BackupAlgorithm>)>> {
self.db.get_latest_backup(user_id)
}
pub fn get_backup(&self, user_id: &UserId, version: &str) -> Result<Option<Raw<BackupAlgorithm>>> {
pub(crate) fn get_backup(&self, user_id: &UserId, version: &str) -> Result<Option<Raw<BackupAlgorithm>>> {
self.db.get_backup(user_id, version)
}
pub fn add_key(
pub(crate) fn add_key(
&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str, key_data: &Raw<KeyBackupData>,
) -> Result<()> {
self.db
.add_key(user_id, version, room_id, session_id, key_data)
}
pub fn count_keys(&self, user_id: &UserId, version: &str) -> Result<usize> { self.db.count_keys(user_id, version) }
pub(crate) fn count_keys(&self, user_id: &UserId, version: &str) -> Result<usize> {
self.db.count_keys(user_id, version)
}
pub fn get_etag(&self, user_id: &UserId, version: &str) -> Result<String> { self.db.get_etag(user_id, version) }
pub(crate) fn get_etag(&self, user_id: &UserId, version: &str) -> Result<String> {
self.db.get_etag(user_id, version)
}
pub fn get_all(&self, user_id: &UserId, version: &str) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> {
pub(crate) fn get_all(&self, user_id: &UserId, version: &str) -> Result<BTreeMap<OwnedRoomId, RoomKeyBackup>> {
self.db.get_all(user_id, version)
}
pub fn get_room(
pub(crate) fn get_room(
&self, user_id: &UserId, version: &str, room_id: &RoomId,
) -> Result<BTreeMap<String, Raw<KeyBackupData>>> {
self.db.get_room(user_id, version, room_id)
}
pub fn get_session(
pub(crate) fn get_session(
&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str,
) -> Result<Option<Raw<KeyBackupData>>> {
self.db.get_session(user_id, version, room_id, session_id)
}
pub fn delete_all_keys(&self, user_id: &UserId, version: &str) -> Result<()> {
pub(crate) fn delete_all_keys(&self, user_id: &UserId, version: &str) -> Result<()> {
self.db.delete_all_keys(user_id, version)
}
pub fn delete_room_keys(&self, user_id: &UserId, version: &str, room_id: &RoomId) -> Result<()> {
pub(crate) fn delete_room_keys(&self, user_id: &UserId, version: &str, room_id: &RoomId) -> Result<()> {
self.db.delete_room_keys(user_id, version, room_id)
}
pub fn delete_room_key(&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str) -> Result<()> {
pub(crate) fn delete_room_key(
&self, user_id: &UserId, version: &str, room_id: &RoomId, session_id: &str,
) -> Result<()> {
self.db
.delete_room_key(user_id, version, room_id, session_id)
}

View file

@ -1,6 +1,6 @@
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
fn create_file_metadata(
&self, sender_user: Option<&str>, mxc: String, width: u32, height: u32, content_disposition: Option<&str>,
content_type: Option<&str>,

View file

@ -15,36 +15,36 @@ use tracing::{debug, error};
use crate::{services, utils, Error, Result};
#[derive(Debug)]
pub struct FileMeta {
pub content_disposition: Option<String>,
pub content_type: Option<String>,
pub file: Vec<u8>,
pub(crate) struct FileMeta {
pub(crate) content_disposition: Option<String>,
pub(crate) content_type: Option<String>,
pub(crate) file: Vec<u8>,
}
#[derive(Serialize, Default)]
pub struct UrlPreviewData {
pub(crate) struct UrlPreviewData {
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:title"))]
pub title: Option<String>,
pub(crate) title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:description"))]
pub description: Option<String>,
pub(crate) description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))]
pub image: Option<String>,
pub(crate) image: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))]
pub image_size: Option<usize>,
pub(crate) image_size: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:width"))]
pub image_width: Option<u32>,
pub(crate) image_width: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:height"))]
pub image_height: Option<u32>,
pub(crate) image_height: Option<u32>,
}
pub struct Service {
pub db: &'static dyn Data,
pub url_preview_mutex: RwLock<HashMap<String, Arc<Mutex<()>>>>,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub(crate) url_preview_mutex: RwLock<HashMap<String, Arc<Mutex<()>>>>,
}
impl Service {
/// Uploads a file.
pub async fn create(
pub(crate) async fn create(
&self, sender_user: Option<OwnedUserId>, mxc: String, content_disposition: Option<&str>,
content_type: Option<&str>, file: &[u8],
) -> Result<()> {
@ -78,7 +78,7 @@ impl Service {
}
/// Deletes a file in the database and from the media directory via an MXC
pub async fn delete(&self, mxc: String) -> Result<()> {
pub(crate) async fn delete(&self, mxc: String) -> Result<()> {
if let Ok(keys) = self.db.search_mxc_metadata_prefix(mxc.clone()) {
for key in keys {
let file_path;
@ -115,7 +115,7 @@ impl Service {
/// Uploads or replaces a file thumbnail.
#[allow(clippy::too_many_arguments)]
pub async fn upload_thumbnail(
pub(crate) async fn upload_thumbnail(
&self, sender_user: Option<OwnedUserId>, mxc: String, content_disposition: Option<&str>,
content_type: Option<&str>, width: u32, height: u32, file: &[u8],
) -> Result<()> {
@ -148,7 +148,7 @@ impl Service {
}
/// Downloads a file.
pub async fn get(&self, mxc: String) -> Result<Option<FileMeta>> {
pub(crate) async fn get(&self, mxc: String) -> Result<Option<FileMeta>> {
if let Ok((content_disposition, content_type, key)) = self.db.search_file_metadata(mxc, 0, 0) {
let path;
@ -181,7 +181,7 @@ impl Service {
/// Deletes all remote only media files in the given at or after
/// time/duration. Returns a u32 with the amount of media files deleted.
pub async fn delete_all_remote_media_at_after_time(&self, time: String) -> Result<u32> {
pub(crate) async fn delete_all_remote_media_at_after_time(&self, time: String) -> Result<u32> {
if let Ok(all_keys) = self.db.get_all_media_keys() {
let user_duration: SystemTime = match cyborgtime::parse_duration(&time) {
Ok(duration) => {
@ -286,7 +286,7 @@ impl Service {
/// Returns width, height of the thumbnail and whether it should be cropped.
/// Returns None when the server should send the original file.
pub fn thumbnail_properties(&self, width: u32, height: u32) -> Option<(u32, u32, bool)> {
pub(crate) fn thumbnail_properties(&self, width: u32, height: u32) -> Option<(u32, u32, bool)> {
match (width, height) {
(0..=32, 0..=32) => Some((32, 32, true)),
(0..=96, 0..=96) => Some((96, 96, true)),
@ -310,7 +310,7 @@ impl Service {
///
/// For width,height <= 96 the server uses another thumbnailing algorithm
/// which crops the image afterwards.
pub async fn get_thumbnail(&self, mxc: String, width: u32, height: u32) -> Result<Option<FileMeta>> {
pub(crate) async fn get_thumbnail(&self, mxc: String, width: u32, height: u32) -> Result<Option<FileMeta>> {
let (width, height, crop) = self
.thumbnail_properties(width, height)
.unwrap_or((0, 0, false)); // 0, 0 because that's the original file
@ -457,14 +457,14 @@ impl Service {
}
}
pub async fn get_url_preview(&self, url: &str) -> Option<UrlPreviewData> { self.db.get_url_preview(url) }
pub(crate) async fn get_url_preview(&self, url: &str) -> Option<UrlPreviewData> { self.db.get_url_preview(url) }
pub async fn remove_url_preview(&self, url: &str) -> Result<()> {
pub(crate) async fn remove_url_preview(&self, url: &str) -> Result<()> {
// TODO: also remove the downloaded image
self.db.remove_url_preview(url)
}
pub async fn set_url_preview(&self, url: &str, data: &UrlPreviewData) -> Result<()> {
pub(crate) async fn set_url_preview(&self, url: &str, data: &UrlPreviewData) -> Result<()> {
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("valid system time");

View file

@ -23,24 +23,24 @@ pub(crate) mod transaction_ids;
pub(crate) mod uiaa;
pub(crate) mod users;
pub struct Services<'a> {
pub appservice: appservice::Service,
pub pusher: pusher::Service,
pub rooms: rooms::Service,
pub transaction_ids: transaction_ids::Service,
pub uiaa: uiaa::Service,
pub users: users::Service,
pub account_data: account_data::Service,
pub presence: Arc<presence::Service>,
pub admin: Arc<admin::Service>,
pub globals: globals::Service<'a>,
pub key_backups: key_backups::Service,
pub media: media::Service,
pub sending: Arc<sending::Service>,
pub(crate) struct Services<'a> {
pub(crate) appservice: appservice::Service,
pub(crate) pusher: pusher::Service,
pub(crate) rooms: rooms::Service,
pub(crate) transaction_ids: transaction_ids::Service,
pub(crate) uiaa: uiaa::Service,
pub(crate) users: users::Service,
pub(crate) account_data: account_data::Service,
pub(crate) presence: Arc<presence::Service>,
pub(crate) admin: Arc<admin::Service>,
pub(crate) globals: globals::Service<'a>,
pub(crate) key_backups: key_backups::Service,
pub(crate) media: media::Service,
pub(crate) sending: Arc<sending::Service>,
}
impl Services<'_> {
pub fn build<
pub(crate) fn build<
D: appservice::Data
+ pusher::Data
+ rooms::Data

View file

@ -23,39 +23,40 @@ use crate::{services, Error};
/// Content hashes of a PDU.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct EventHash {
pub(crate) struct EventHash {
/// The SHA-256 hash.
pub sha256: String,
pub(crate) sha256: String,
}
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct PduEvent {
pub event_id: Arc<EventId>,
pub room_id: OwnedRoomId,
pub sender: OwnedUserId,
pub(crate) struct PduEvent {
pub(crate) event_id: Arc<EventId>,
pub(crate) room_id: OwnedRoomId,
pub(crate) sender: OwnedUserId,
#[serde(skip_serializing_if = "Option::is_none")]
pub origin: Option<String>,
pub origin_server_ts: UInt,
pub(crate) origin: Option<String>,
pub(crate) origin_server_ts: UInt,
#[serde(rename = "type")]
pub kind: TimelineEventType,
pub content: Box<RawJsonValue>,
pub(crate) kind: TimelineEventType,
pub(crate) content: Box<RawJsonValue>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state_key: Option<String>,
pub prev_events: Vec<Arc<EventId>>,
pub depth: UInt,
pub auth_events: Vec<Arc<EventId>>,
pub(crate) state_key: Option<String>,
pub(crate) prev_events: Vec<Arc<EventId>>,
pub(crate) depth: UInt,
pub(crate) auth_events: Vec<Arc<EventId>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub redacts: Option<Arc<EventId>>,
pub(crate) redacts: Option<Arc<EventId>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unsigned: Option<Box<RawJsonValue>>,
pub hashes: EventHash,
pub(crate) unsigned: Option<Box<RawJsonValue>>,
pub(crate) hashes: EventHash,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signatures: Option<Box<RawJsonValue>>, // BTreeMap<Box<ServerName>, BTreeMap<ServerSigningKeyId, String>>
pub(crate) signatures: Option<Box<RawJsonValue>>, /* BTreeMap<Box<ServerName>, BTreeMap<ServerSigningKeyId,
* String>> */
}
impl PduEvent {
#[tracing::instrument(skip(self))]
pub fn redact(&mut self, room_version_id: RoomVersionId, reason: &PduEvent) -> crate::Result<()> {
pub(crate) fn redact(&mut self, room_version_id: RoomVersionId, reason: &PduEvent) -> crate::Result<()> {
self.unsigned = None;
let mut content = serde_json::from_str(self.content.get())
@ -75,7 +76,7 @@ impl PduEvent {
Ok(())
}
pub fn remove_transaction_id(&mut self) -> crate::Result<()> {
pub(crate) fn remove_transaction_id(&mut self) -> crate::Result<()> {
if let Some(unsigned) = &self.unsigned {
let mut unsigned: BTreeMap<String, Box<RawJsonValue>> = serde_json::from_str(unsigned.get())
.map_err(|_| Error::bad_database("Invalid unsigned in pdu event"))?;
@ -86,7 +87,7 @@ impl PduEvent {
Ok(())
}
pub fn add_age(&mut self) -> crate::Result<()> {
pub(crate) fn add_age(&mut self) -> crate::Result<()> {
let mut unsigned: BTreeMap<String, Box<RawJsonValue>> = self
.unsigned
.as_ref()
@ -117,7 +118,7 @@ impl PduEvent {
/// > serving
/// > such events over the Client-Server API.
#[must_use]
pub fn copy_redacts(&self) -> (Option<Arc<EventId>>, Box<RawJsonValue>) {
pub(crate) fn copy_redacts(&self) -> (Option<Arc<EventId>>, Box<RawJsonValue>) {
if self.kind == TimelineEventType::RoomRedaction {
if let Ok(mut content) = serde_json::from_str::<RoomRedactionEventContent>(self.content.get()) {
if let Some(redacts) = content.redacts {
@ -136,7 +137,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_sync_room_event(&self) -> Raw<AnySyncTimelineEvent> {
pub(crate) fn to_sync_room_event(&self) -> Raw<AnySyncTimelineEvent> {
let (redacts, content) = self.copy_redacts();
let mut json = json!({
"content": content,
@ -161,7 +162,7 @@ impl PduEvent {
/// This only works for events that are also AnyRoomEvents.
#[tracing::instrument(skip(self))]
pub fn to_any_event(&self) -> Raw<AnyEphemeralRoomEvent> {
pub(crate) fn to_any_event(&self) -> Raw<AnyEphemeralRoomEvent> {
let (redacts, content) = self.copy_redacts();
let mut json = json!({
"content": content,
@ -186,7 +187,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_room_event(&self) -> Raw<AnyTimelineEvent> {
pub(crate) fn to_room_event(&self) -> Raw<AnyTimelineEvent> {
let (redacts, content) = self.copy_redacts();
let mut json = json!({
"content": content,
@ -211,7 +212,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_message_like_event(&self) -> Raw<AnyMessageLikeEvent> {
pub(crate) fn to_message_like_event(&self) -> Raw<AnyMessageLikeEvent> {
let (redacts, content) = self.copy_redacts();
let mut json = json!({
"content": content,
@ -236,7 +237,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_state_event(&self) -> Raw<AnyStateEvent> {
pub(crate) fn to_state_event(&self) -> Raw<AnyStateEvent> {
let mut json = json!({
"content": self.content,
"type": self.kind,
@ -255,7 +256,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_sync_state_event(&self) -> Raw<AnySyncStateEvent> {
pub(crate) fn to_sync_state_event(&self) -> Raw<AnySyncStateEvent> {
let mut json = json!({
"content": self.content,
"type": self.kind,
@ -273,7 +274,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_stripped_state_event(&self) -> Raw<AnyStrippedStateEvent> {
pub(crate) fn to_stripped_state_event(&self) -> Raw<AnyStrippedStateEvent> {
let json = json!({
"content": self.content,
"type": self.kind,
@ -285,7 +286,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_stripped_spacechild_state_event(&self) -> Raw<HierarchySpaceChildEvent> {
pub(crate) fn to_stripped_spacechild_state_event(&self) -> Raw<HierarchySpaceChildEvent> {
let json = json!({
"content": self.content,
"type": self.kind,
@ -298,7 +299,7 @@ impl PduEvent {
}
#[tracing::instrument(skip(self))]
pub fn to_member_event(&self) -> Raw<StateEvent<RoomMemberEventContent>> {
pub(crate) fn to_member_event(&self) -> Raw<StateEvent<RoomMemberEventContent>> {
let mut json = json!({
"content": self.content,
"type": self.kind,
@ -319,7 +320,7 @@ impl PduEvent {
/// This does not return a full `Pdu` it is only to satisfy ruma's types.
#[tracing::instrument]
pub fn convert_to_outgoing_federation_event(mut pdu_json: CanonicalJsonObject) -> Box<RawJsonValue> {
pub(crate) fn convert_to_outgoing_federation_event(mut pdu_json: CanonicalJsonObject) -> Box<RawJsonValue> {
if let Some(unsigned) = pdu_json
.get_mut("unsigned")
.and_then(|val| val.as_object_mut())
@ -356,7 +357,7 @@ impl PduEvent {
to_raw_value(&pdu_json).expect("CanonicalJson is valid serde_json::Value")
}
pub fn from_id_val(event_id: &EventId, mut json: CanonicalJsonObject) -> Result<Self, serde_json::Error> {
pub(crate) fn from_id_val(event_id: &EventId, mut json: CanonicalJsonObject) -> Result<Self, serde_json::Error> {
json.insert("event_id".to_owned(), CanonicalJsonValue::String(event_id.as_str().to_owned()));
serde_json::from_value(serde_json::to_value(json).expect("valid JSON"))
@ -425,11 +426,11 @@ pub(crate) fn gen_event_id_canonical_json(
/// Build the start of a PDU in order to add it to the Database.
#[derive(Debug, Deserialize)]
pub struct PduBuilder {
pub(crate) struct PduBuilder {
#[serde(rename = "type")]
pub event_type: TimelineEventType,
pub content: Box<RawJsonValue>,
pub unsigned: Option<BTreeMap<String, serde_json::Value>>,
pub state_key: Option<String>,
pub redacts: Option<Arc<EventId>>,
pub(crate) event_type: TimelineEventType,
pub(crate) content: Box<RawJsonValue>,
pub(crate) unsigned: Option<BTreeMap<String, serde_json::Value>>,
pub(crate) state_key: Option<String>,
pub(crate) redacts: Option<Arc<EventId>>,
}

View file

@ -2,7 +2,7 @@ use ruma::{events::presence::PresenceEvent, presence::PresenceState, OwnedUserId
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
/// Returns the latest presence event for the given user.
fn get_presence(&self, user_id: &UserId) -> Result<Option<(u64, PresenceEvent)>>;

View file

@ -2,7 +2,7 @@ mod data;
use std::{sync::Arc, time::Duration};
pub use data::Data;
pub(crate) use data::Data;
use futures_util::{stream::FuturesUnordered, StreamExt};
use ruma::{
events::presence::{PresenceEvent, PresenceEventContent},
@ -18,15 +18,17 @@ use crate::{services, utils, Config, Error, Result};
/// Represents data required to be kept in order to implement the presence
/// specification.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Presence {
pub state: PresenceState,
pub currently_active: bool,
pub last_active_ts: u64,
pub status_msg: Option<String>,
pub(crate) struct Presence {
state: PresenceState,
currently_active: bool,
last_active_ts: u64,
status_msg: Option<String>,
}
impl Presence {
pub fn new(state: PresenceState, currently_active: bool, last_active_ts: u64, status_msg: Option<String>) -> Self {
pub(crate) fn new(
state: PresenceState, currently_active: bool, last_active_ts: u64, status_msg: Option<String>,
) -> Self {
Self {
state,
currently_active,
@ -35,21 +37,21 @@ impl Presence {
}
}
pub fn from_json_bytes_to_event(bytes: &[u8], user_id: &UserId) -> Result<PresenceEvent> {
pub(crate) fn from_json_bytes_to_event(bytes: &[u8], user_id: &UserId) -> Result<PresenceEvent> {
let presence = Self::from_json_bytes(bytes)?;
presence.to_presence_event(user_id)
}
pub fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
pub(crate) fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
serde_json::from_slice(bytes).map_err(|_| Error::bad_database("Invalid presence data in database"))
}
pub fn to_json_bytes(&self) -> Result<Vec<u8>> {
pub(crate) fn to_json_bytes(&self) -> Result<Vec<u8>> {
serde_json::to_vec(self).map_err(|_| Error::bad_database("Could not serialize Presence to JSON"))
}
/// Creates a PresenceEvent from available data.
pub fn to_presence_event(&self, user_id: &UserId) -> Result<PresenceEvent> {
pub(crate) fn to_presence_event(&self, user_id: &UserId) -> Result<PresenceEvent> {
let now = utils::millis_since_unix_epoch();
let last_active_ago = if self.currently_active {
None
@ -71,15 +73,15 @@ impl Presence {
}
}
pub struct Service {
pub db: &'static dyn Data,
pub timer_sender: loole::Sender<(OwnedUserId, Duration)>,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub(crate) timer_sender: loole::Sender<(OwnedUserId, Duration)>,
timer_receiver: Mutex<loole::Receiver<(OwnedUserId, Duration)>>,
timeout_remote_users: bool,
}
impl Service {
pub fn build(db: &'static dyn Data, config: &Config) -> Arc<Self> {
pub(crate) fn build(db: &'static dyn Data, config: &Config) -> Arc<Self> {
let (timer_sender, timer_receiver) = loole::unbounded();
Arc::new(Self {
@ -90,7 +92,7 @@ impl Service {
})
}
pub fn start_handler(self: &Arc<Self>) {
pub(crate) fn start_handler(self: &Arc<Self>) {
let self_ = Arc::clone(self);
tokio::spawn(async move {
self_
@ -101,7 +103,7 @@ impl Service {
}
/// Returns the latest presence event for the given user.
pub fn get_presence(&self, user_id: &UserId) -> Result<Option<PresenceEvent>> {
pub(crate) fn get_presence(&self, user_id: &UserId) -> Result<Option<PresenceEvent>> {
if let Some((_, presence)) = self.db.get_presence(user_id)? {
Ok(Some(presence))
} else {
@ -111,7 +113,7 @@ impl Service {
/// Pings the presence of the given user in the given room, setting the
/// specified state.
pub fn ping_presence(&self, user_id: &UserId, new_state: &PresenceState) -> Result<()> {
pub(crate) fn ping_presence(&self, user_id: &UserId, new_state: &PresenceState) -> Result<()> {
const REFRESH_TIMEOUT: u64 = 60 * 25 * 1000;
let last_presence = self.db.get_presence(user_id)?;
@ -140,7 +142,7 @@ impl Service {
}
/// Adds a presence event which will be saved until a new event replaces it.
pub fn set_presence(
pub(crate) fn set_presence(
&self, user_id: &UserId, state: &PresenceState, currently_active: Option<bool>, last_active_ago: Option<UInt>,
status_msg: Option<String>,
) -> Result<()> {
@ -170,11 +172,14 @@ impl Service {
}
/// Removes the presence record for the given user from the database.
pub fn remove_presence(&self, user_id: &UserId) -> Result<()> { self.db.remove_presence(user_id) }
///
/// TODO: Why is this not used?
#[allow(dead_code)]
pub(crate) fn remove_presence(&self, user_id: &UserId) -> Result<()> { self.db.remove_presence(user_id) }
/// Returns the most recent presence updates that happened after the event
/// with id `since`.
pub fn presence_since(&self, since: u64) -> Box<dyn Iterator<Item = (OwnedUserId, u64, Vec<u8>)>> {
pub(crate) fn presence_since(&self, since: u64) -> Box<dyn Iterator<Item = (OwnedUserId, u64, Vec<u8>)>> {
self.db.presence_since(since)
}

View file

@ -5,7 +5,7 @@ use ruma::{
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
fn set_pusher(&self, sender: &UserId, pusher: set_pusher::v3::PusherAction) -> Result<()>;
fn get_pusher(&self, sender: &UserId, pushkey: &str) -> Result<Option<Pusher>>;

View file

@ -2,7 +2,7 @@ mod data;
use std::{fmt::Debug, mem};
use bytes::BytesMut;
pub use data::Data;
pub(crate) use data::Data;
use ipaddress::IPAddress;
use ruma::{
api::{
@ -24,27 +24,27 @@ use tracing::{info, trace, warn};
use crate::{services, Error, PduEvent, Result};
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
pub fn set_pusher(&self, sender: &UserId, pusher: set_pusher::v3::PusherAction) -> Result<()> {
pub(crate) fn set_pusher(&self, sender: &UserId, pusher: set_pusher::v3::PusherAction) -> Result<()> {
self.db.set_pusher(sender, pusher)
}
pub fn get_pusher(&self, sender: &UserId, pushkey: &str) -> Result<Option<Pusher>> {
pub(crate) fn get_pusher(&self, sender: &UserId, pushkey: &str) -> Result<Option<Pusher>> {
self.db.get_pusher(sender, pushkey)
}
pub fn get_pushers(&self, sender: &UserId) -> Result<Vec<Pusher>> { self.db.get_pushers(sender) }
pub(crate) fn get_pushers(&self, sender: &UserId) -> Result<Vec<Pusher>> { self.db.get_pushers(sender) }
pub fn get_pushkeys(&self, sender: &UserId) -> Box<dyn Iterator<Item = Result<String>>> {
pub(crate) fn get_pushkeys(&self, sender: &UserId) -> Box<dyn Iterator<Item = Result<String>>> {
self.db.get_pushkeys(sender)
}
#[tracing::instrument(skip(self, destination, request))]
pub async fn send_request<T>(&self, destination: &str, request: T) -> Result<T::IncomingResponse>
pub(crate) async fn send_request<T>(&self, destination: &str, request: T) -> Result<T::IncomingResponse>
where
T: OutgoingRequest + Debug,
{
@ -138,7 +138,7 @@ impl Service {
}
#[tracing::instrument(skip(self, user, unread, pusher, ruleset, pdu))]
pub async fn send_push_notice(
pub(crate) async fn send_push_notice(
&self, user: &UserId, unread: UInt, pusher: &Pusher, ruleset: Ruleset, pdu: &PduEvent,
) -> Result<()> {
let mut notify = None;
@ -183,7 +183,7 @@ impl Service {
}
#[tracing::instrument(skip(self, user, ruleset, pdu))]
pub fn get_actions<'a>(
pub(crate) fn get_actions<'a>(
&self, user: &UserId, ruleset: &'a Ruleset, power_levels: &RoomPowerLevelsEventContent,
pdu: &Raw<AnySyncTimelineEvent>, room_id: &RoomId,
) -> Result<&'a [Action]> {

View file

@ -2,7 +2,7 @@ use ruma::{OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId};
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) 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,35 +1,37 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId};
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
#[tracing::instrument(skip(self))]
pub fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()> { self.db.set_alias(alias, room_id) }
pub(crate) fn set_alias(&self, alias: &RoomAliasId, room_id: &RoomId) -> Result<()> {
self.db.set_alias(alias, room_id)
}
#[tracing::instrument(skip(self))]
pub fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> { self.db.remove_alias(alias) }
pub(crate) fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> { self.db.remove_alias(alias) }
#[tracing::instrument(skip(self))]
pub fn resolve_local_alias(&self, alias: &RoomAliasId) -> Result<Option<OwnedRoomId>> {
pub(crate) fn resolve_local_alias(&self, alias: &RoomAliasId) -> Result<Option<OwnedRoomId>> {
self.db.resolve_local_alias(alias)
}
#[tracing::instrument(skip(self))]
pub fn local_aliases_for_room<'a>(
pub(crate) 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 fn all_local_aliases<'a>(&'a self) -> Box<dyn Iterator<Item = Result<(OwnedRoomId, String)>> + 'a> {
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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 use data::Data;
pub(crate) use data::Data;
use ruma::{api::client::error::ErrorKind, EventId, RoomId};
use tracing::{debug, error, warn};
use crate::{services, Error, Result};
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
pub async fn event_ids_iter<'a>(
pub(crate) 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());
@ -30,7 +30,7 @@ impl Service {
.filter_map(move |sid| services().rooms.short.get_eventid_from_short(sid).ok()))
}
pub async fn get_auth_chain(&self, room_id: &RoomId, starting_events: &[&EventId]) -> Result<Vec<u64>> {
pub(crate) 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();
@ -165,18 +165,18 @@ impl Service {
Ok(found)
}
pub fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<[u64]>>> {
pub(crate) fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<[u64]>>> {
self.db.get_cached_eventid_authchain(key)
}
#[tracing::instrument(skip(self))]
pub fn cache_auth_chain(&self, key: Vec<u64>, auth_chain: &HashSet<u64>) -> Result<()> {
pub(crate) 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 fn cache_auth_chain_vec(&self, key: Vec<u64>, auth_chain: &Vec<u64>) -> Result<()> {
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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,24 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{OwnedRoomId, RoomId};
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
#[tracing::instrument(skip(self))]
pub fn set_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_public(room_id) }
pub(crate) fn set_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_public(room_id) }
#[tracing::instrument(skip(self))]
pub fn set_not_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_not_public(room_id) }
pub(crate) fn set_not_public(&self, room_id: &RoomId) -> Result<()> { self.db.set_not_public(room_id) }
#[tracing::instrument(skip(self))]
pub fn is_public_room(&self, room_id: &RoomId) -> Result<bool> { self.db.is_public_room(room_id) }
pub(crate) fn is_public_room(&self, room_id: &RoomId) -> Result<bool> { self.db.is_public_room(room_id) }
#[tracing::instrument(skip(self))]
pub fn public_rooms(&self) -> impl Iterator<Item = Result<OwnedRoomId>> + '_ { self.db.public_rooms() }
pub(crate) fn public_rooms(&self) -> impl Iterator<Item = Result<OwnedRoomId>> + '_ { self.db.public_rooms() }
}

View file

@ -29,8 +29,8 @@ use crate::{
services, Error, PduEvent,
};
pub mod signing_keys;
pub struct Service;
mod signing_keys;
pub(crate) struct Service;
// We use some AsyncRecursiveType hacks here so we can call async funtion
// recursively.
@ -425,7 +425,7 @@ impl Service {
})
}
pub async fn upgrade_outlier_to_timeline_pdu(
pub(crate) 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>>> {
@ -746,7 +746,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 async fn state_at_incoming_degree_one(
pub(crate) 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];
@ -794,7 +794,7 @@ impl Service {
}
#[tracing::instrument(skip_all, name = "state")]
pub async fn state_at_incoming_resolved(
pub(crate) 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");
@ -1275,7 +1275,7 @@ impl Service {
/// Returns Ok if the acl allows the server
#[tracing::instrument(skip_all)]
pub fn acl_check(&self, server_name: &ServerName, room_id: &RoomId) -> Result<()> {
pub(crate) fn acl_check(&self, server_name: &ServerName, room_id: &RoomId) -> Result<()> {
let acl_event = if let Some(acl) =
services()
.rooms

View file

@ -367,7 +367,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 async fn fetch_signing_keys_for_server(
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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,23 +1,24 @@
mod data;
use std::collections::{HashMap, HashSet};
pub use data::Data;
pub(crate) use data::Data;
use ruma::{DeviceId, OwnedDeviceId, OwnedRoomId, OwnedUserId, RoomId, UserId};
use tokio::sync::Mutex;
use super::timeline::PduCount;
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
#[allow(clippy::type_complexity)]
pub lazy_load_waiting: Mutex<HashMap<(OwnedUserId, OwnedDeviceId, OwnedRoomId, PduCount), HashSet<OwnedUserId>>>,
pub(crate) lazy_load_waiting:
Mutex<HashMap<(OwnedUserId, OwnedDeviceId, OwnedRoomId, PduCount), HashSet<OwnedUserId>>>,
}
impl Service {
#[tracing::instrument(skip(self))]
pub fn lazy_load_was_sent_before(
pub(crate) fn lazy_load_was_sent_before(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, ll_user: &UserId,
) -> Result<bool> {
self.db
@ -25,7 +26,7 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub async fn lazy_load_mark_sent(
pub(crate) async fn lazy_load_mark_sent(
&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId, lazy_load: HashSet<OwnedUserId>,
count: PduCount,
) {
@ -36,7 +37,7 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub async fn lazy_load_confirm_delivery(
pub(crate) 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(&(
@ -55,7 +56,7 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub fn lazy_load_reset(&self, user_id: &UserId, device_id: &DeviceId, room_id: &RoomId) -> Result<()> {
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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,32 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{OwnedRoomId, RoomId};
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
/// Checks if a room exists.
#[tracing::instrument(skip(self))]
pub fn exists(&self, room_id: &RoomId) -> Result<bool> { self.db.exists(room_id) }
pub(crate) fn exists(&self, room_id: &RoomId) -> Result<bool> { self.db.exists(room_id) }
pub fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { self.db.iter_ids() }
pub(crate) fn iter_ids<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> { self.db.iter_ids() }
pub fn is_disabled(&self, room_id: &RoomId) -> Result<bool> { self.db.is_disabled(room_id) }
pub(crate) fn is_disabled(&self, room_id: &RoomId) -> Result<bool> { self.db.is_disabled(room_id) }
pub fn disable_room(&self, room_id: &RoomId, disabled: bool) -> Result<()> {
pub(crate) fn disable_room(&self, room_id: &RoomId, disabled: bool) -> Result<()> {
self.db.disable_room(room_id, disabled)
}
pub fn is_banned(&self, room_id: &RoomId) -> Result<bool> { self.db.is_banned(room_id) }
pub(crate) fn is_banned(&self, room_id: &RoomId) -> Result<bool> { self.db.is_banned(room_id) }
pub fn ban_room(&self, room_id: &RoomId, banned: bool) -> Result<()> { self.db.ban_room(room_id, banned) }
pub(crate) fn ban_room(&self, room_id: &RoomId, banned: bool) -> Result<()> { self.db.ban_room(room_id, banned) }
pub fn list_banned_rooms<'a>(&'a self) -> Box<dyn Iterator<Item = Result<OwnedRoomId>> + 'a> {
pub(crate) 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 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) 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 trait Data:
pub(crate) trait Data:
alias::Data
+ auth_chain::Data
+ directory::Data
@ -40,25 +40,25 @@ pub trait Data:
{
}
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,
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,
}

View file

@ -2,7 +2,7 @@ use ruma::{CanonicalJsonObject, EventId};
use crate::{PduEvent, Result};
pub trait Data: Send + Sync {
pub(crate) 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,26 +1,28 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{CanonicalJsonObject, EventId};
use crate::{PduEvent, Result};
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
/// Returns the pdu from the outlier tree.
pub fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
pub(crate) fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
self.db.get_outlier_pdu_json(event_id)
}
/// Returns the pdu from the outlier tree.
pub fn get_pdu_outlier(&self, event_id: &EventId) -> Result<Option<PduEvent>> { self.db.get_outlier_pdu(event_id) }
pub(crate) 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 fn add_pdu_outlier(&self, event_id: &EventId, pdu: &CanonicalJsonObject) -> Result<()> {
pub(crate) fn add_pdu_outlier(&self, event_id: &EventId, pdu: &CanonicalJsonObject) -> Result<()> {
self.db.add_pdu_outlier(event_id, pdu)
}
}

View file

@ -4,7 +4,7 @@ use ruma::{EventId, RoomId, UserId};
use crate::{service::rooms::timeline::PduCount, PduEvent, Result};
pub trait Data: Send + Sync {
pub(crate) 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,7 @@
mod data;
use std::sync::Arc;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{
api::{client::relations::get_relating_events, Direction},
events::{relation::RelationType, TimelineEventType},
@ -12,8 +12,8 @@ use serde::Deserialize;
use super::timeline::PduCount;
use crate::{services, PduEvent, Result};
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
#[derive(Clone, Debug, Deserialize)]
@ -28,7 +28,7 @@ struct ExtractRelatesToEventId {
impl Service {
#[tracing::instrument(skip(self, from, to))]
pub fn add_relation(&self, from: PduCount, to: PduCount) -> Result<()> {
pub(crate) 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 fn paginate_relations_with_filter(
pub(crate) 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,
@ -173,7 +173,7 @@ impl Service {
}
}
pub fn relations_until<'a>(
pub(crate) 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)?;
@ -215,18 +215,22 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id, event_ids))]
pub fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Arc<EventId>]) -> Result<()> {
pub(crate) 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 fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
pub(crate) 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 fn mark_event_soft_failed(&self, event_id: &EventId) -> Result<()> { self.db.mark_event_soft_failed(event_id) }
pub(crate) fn mark_event_soft_failed(&self, event_id: &EventId) -> Result<()> {
self.db.mark_event_soft_failed(event_id)
}
#[tracing::instrument(skip(self))]
pub fn is_event_soft_failed(&self, event_id: &EventId) -> Result<bool> { self.db.is_event_soft_failed(event_id) }
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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,17 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{events::receipt::ReceiptEvent, serde::Raw, OwnedUserId, RoomId, UserId};
use crate::{services, Result};
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
/// Replaces the previous read receipt.
pub fn readreceipt_update(&self, user_id: &UserId, room_id: &RoomId, event: ReceiptEvent) -> Result<()> {
pub(crate) 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 +21,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 fn readreceipts_since<'a>(
pub(crate) 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 +29,18 @@ impl Service {
/// Sets a private read marker at `count`.
#[tracing::instrument(skip(self))]
pub fn private_read_set(&self, room_id: &RoomId, user_id: &UserId, count: u64) -> Result<()> {
pub(crate) 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 fn private_read_get(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
pub(crate) 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 fn last_privateread_update(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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,22 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::RoomId;
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
#[tracing::instrument(skip(self))]
pub fn index_pdu(&self, shortroomid: u64, pdu_id: &[u8], message_body: &str) -> Result<()> {
pub(crate) 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 fn search_pdus<'a>(
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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 use data::Data;
pub(crate) use data::Data;
use ruma::{events::StateEventType, EventId, RoomId};
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
pub fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result<u64> {
pub(crate) fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result<u64> {
self.db.get_or_create_shorteventid(event_id)
}
pub fn multi_get_or_create_shorteventid(&self, event_ids: &[&EventId]) -> Result<Vec<u64>> {
pub(crate) fn multi_get_or_create_shorteventid(&self, event_ids: &[&EventId]) -> Result<Vec<u64>> {
self.db.multi_get_or_create_shorteventid(event_ids)
}
pub fn get_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<Option<u64>> {
pub(crate) fn get_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<Option<u64>> {
self.db.get_shortstatekey(event_type, state_key)
}
pub fn get_or_create_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result<u64> {
pub(crate) 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 fn get_eventid_from_short(&self, shorteventid: u64) -> Result<Arc<EventId>> {
pub(crate) fn get_eventid_from_short(&self, shorteventid: u64) -> Result<Arc<EventId>> {
self.db.get_eventid_from_short(shorteventid)
}
pub fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(StateEventType, String)> {
pub(crate) fn get_statekey_from_short(&self, shortstatekey: u64) -> Result<(StateEventType, String)> {
self.db.get_statekey_from_short(shortstatekey)
}
/// Returns (shortstatehash, already_existed)
pub fn get_or_create_shortstatehash(&self, state_hash: &[u8]) -> Result<(u64, bool)> {
pub(crate) fn get_or_create_shortstatehash(&self, state_hash: &[u8]) -> Result<(u64, bool)> {
self.db.get_or_create_shortstatehash(state_hash)
}
pub fn get_shortroomid(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.get_shortroomid(room_id) }
pub(crate) fn get_shortroomid(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.get_shortroomid(room_id) }
pub fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result<u64> {
pub(crate) fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result<u64> {
self.db.get_or_create_shortroomid(room_id)
}
}

View file

@ -34,22 +34,22 @@ use tracing::{debug, error, warn};
use crate::{debug_info, services, Error, Result};
pub struct CachedSpaceHierarchySummary {
pub(crate) struct CachedSpaceHierarchySummary {
summary: SpaceHierarchyParentSummary,
}
pub enum SummaryAccessibility {
enum SummaryAccessibility {
Accessible(Box<SpaceHierarchyParentSummary>),
Inaccessible,
}
pub struct Arena {
struct Arena {
nodes: Vec<Node>,
max_depth: usize,
first_untraversed: Option<NodeId>,
}
pub struct Node {
struct Node {
parent: Option<NodeId>,
// Next meaning:
// -->
@ -60,13 +60,13 @@ pub struct Node {
// v
// o o o o
first_child: Option<NodeId>,
pub room_id: OwnedRoomId,
pub via: Vec<OwnedServerName>,
room_id: OwnedRoomId,
via: Vec<OwnedServerName>,
traversed: bool,
}
#[derive(Clone, Copy, PartialEq, Debug, PartialOrd)]
pub struct NodeId {
struct NodeId {
index: usize,
}
@ -288,14 +288,14 @@ impl Display for PagnationToken {
/// Identifier used to check if rooms are accessible
///
/// None is used if you want to return the room, no matter if accessible or not
pub enum Identifier<'a> {
enum Identifier<'a> {
UserId(&'a UserId),
ServerName(&'a ServerName),
None,
}
pub struct Service {
pub roomid_spacehierarchy_cache: Mutex<LruCache<OwnedRoomId, Option<CachedSpaceHierarchySummary>>>,
pub(crate) struct Service {
pub(crate) 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 async fn get_federation_hierarchy(
pub(crate) async fn get_federation_hierarchy(
&self, room_id: &RoomId, server_name: &ServerName, suggested_only: bool,
) -> Result<federation::space::get_hierarchy::v1::Response> {
match self
@ -649,7 +649,7 @@ impl Service {
})
}
pub async fn get_client_hierarchy(
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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

@ -21,13 +21,13 @@ use tracing::warn;
use super::state_compressor::CompressedStateEvent;
use crate::{services, utils::calculate_hash, Error, PduEvent, Result};
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
/// Set the room to the given statehash and update caches.
pub async fn force_state(
pub(crate) 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 fn set_event_state(
pub(crate) 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 fn append_to_state(&self, new_pdu: &PduEvent) -> Result<u64> {
pub(crate) 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 fn calculate_invite_state(&self, invite_event: &PduEvent) -> Result<Vec<Raw<AnyStrippedStateEvent>>> {
pub(crate) 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 fn set_room_state(
pub(crate) 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 fn get_room_version(&self, room_id: &RoomId) -> Result<RoomVersionId> {
pub(crate) 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 fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result<Option<u64>> {
pub(crate) fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.db.get_room_shortstatehash(room_id)
}
pub fn get_forward_extremities(&self, room_id: &RoomId) -> Result<HashSet<Arc<EventId>>> {
pub(crate) fn get_forward_extremities(&self, room_id: &RoomId) -> Result<HashSet<Arc<EventId>>> {
self.db.get_forward_extremities(room_id)
}
pub fn set_forward_extremities(
pub(crate) 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 fn get_auth_events(
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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 use data::Data;
pub(crate) use data::Data;
use lru_cache::LruCache;
use ruma::{
events::{
@ -24,28 +24,30 @@ use tracing::{error, warn};
use crate::{service::pdu::PduBuilder, services, Error, PduEvent, Result};
pub struct Service {
pub db: &'static dyn Data,
pub server_visibility_cache: Mutex<LruCache<(OwnedServerName, u64), bool>>,
pub user_visibility_cache: Mutex<LruCache<(OwnedUserId, u64), bool>>,
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>>,
}
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 async fn state_full_ids(&self, shortstatehash: u64) -> Result<HashMap<u64, Arc<EventId>>> {
pub(crate) async fn state_full_ids(&self, shortstatehash: u64) -> Result<HashMap<u64, Arc<EventId>>> {
self.db.state_full_ids(shortstatehash).await
}
pub async fn state_full(&self, shortstatehash: u64) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
pub(crate) 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 fn state_get_id(
pub(crate) 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)
@ -53,7 +55,7 @@ impl Service {
/// Returns a single PDU from `room_id` with key (`event_type`,
/// `state_key`).
pub fn state_get(
pub(crate) 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)
@ -88,7 +90,9 @@ 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 fn server_can_see_event(&self, origin: &ServerName, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
pub(crate) 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);
};
@ -151,7 +155,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 fn user_can_see_event(&self, user_id: &UserId, room_id: &RoomId, event_id: &EventId) -> Result<bool> {
pub(crate) 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);
};
@ -210,7 +214,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 fn user_can_see_state_events(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
pub(crate) 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
@ -232,18 +236,22 @@ impl Service {
}
/// Returns the state hash for this pdu.
pub fn pdu_shortstatehash(&self, event_id: &EventId) -> Result<Option<u64>> { self.db.pdu_shortstatehash(event_id) }
pub(crate) 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 async fn room_state_full(&self, room_id: &RoomId) -> Result<HashMap<(StateEventType, String), Arc<PduEvent>>> {
pub(crate) 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 fn room_state_get_id(
pub(crate) 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)
@ -252,13 +260,13 @@ impl Service {
/// Returns a single PDU from `room_id` with key (`event_type`,
/// `state_key`).
#[tracing::instrument(skip(self))]
pub fn room_state_get(
pub(crate) 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 fn get_name(&self, room_id: &RoomId) -> Result<Option<String>> {
pub(crate) fn get_name(&self, room_id: &RoomId) -> Result<Option<String>> {
services()
.rooms
.state_accessor
@ -268,7 +276,7 @@ impl Service {
})
}
pub fn get_avatar(&self, room_id: &RoomId) -> Result<ruma::JsOption<RoomAvatarEventContent>> {
pub(crate) fn get_avatar(&self, room_id: &RoomId) -> Result<ruma::JsOption<RoomAvatarEventContent>> {
services()
.rooms
.state_accessor
@ -279,7 +287,7 @@ impl Service {
})
}
pub fn get_member(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<RoomMemberEventContent>> {
pub(crate) fn get_member(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<RoomMemberEventContent>> {
services()
.rooms
.state_accessor
@ -290,7 +298,7 @@ impl Service {
})
}
pub async fn user_can_invite(
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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 use data::Data;
pub(crate) use data::Data;
use itertools::Itertools;
use ruma::{
events::{
@ -23,15 +23,15 @@ use crate::{service::appservice::RegistrationInfo, services, Error, Result};
mod data;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
/// Update current membership data.
#[tracing::instrument(skip(self, last_state))]
#[allow(clippy::too_many_arguments)]
pub fn update_membership(
pub(crate) 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 fn update_joined_count(&self, room_id: &RoomId) -> Result<()> { self.db.update_joined_count(room_id) }
pub(crate) fn update_joined_count(&self, room_id: &RoomId) -> Result<()> { self.db.update_joined_count(room_id) }
#[tracing::instrument(skip(self, room_id))]
pub fn get_our_real_users(&self, room_id: &RoomId) -> Result<Arc<HashSet<OwnedUserId>>> {
pub(crate) 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 fn appservice_in_room(&self, room_id: &RoomId, appservice: &RegistrationInfo) -> Result<bool> {
pub(crate) 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 fn forget(&self, room_id: &RoomId, user_id: &UserId) -> Result<()> { self.db.forget(room_id, user_id) }
pub(crate) 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 fn room_servers<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedServerName>> + 'a {
pub(crate) 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 fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result<bool> {
pub(crate) 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 fn server_rooms<'a>(&'a self, server: &ServerName) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
pub(crate) 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 fn server_sees_user(&self, server: &ServerName, user_id: &UserId) -> Result<bool> {
pub(crate) 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 fn user_sees_user(&self, user_a: &UserId, user_b: &UserId) -> Result<bool> {
pub(crate) 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,88 +271,104 @@ impl Service {
/// Returns an iterator over all joined members of a room.
#[tracing::instrument(skip(self))]
pub fn room_members<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
pub(crate) 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 fn room_joined_count(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.room_joined_count(room_id) }
pub(crate) fn room_joined_count(&self, room_id: &RoomId) -> Result<Option<u64>> {
self.db.room_joined_count(room_id)
}
#[tracing::instrument(skip(self))]
pub fn room_invited_count(&self, room_id: &RoomId) -> Result<Option<u64>> { self.db.room_invited_count(room_id) }
pub(crate) 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 fn room_useroncejoined<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
pub(crate) 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 fn room_members_invited<'a>(&'a self, room_id: &RoomId) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
pub(crate) 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 fn get_invite_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
pub(crate) 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 fn get_left_count(&self, room_id: &RoomId, user_id: &UserId) -> Result<Option<u64>> {
pub(crate) 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 fn rooms_joined<'a>(&'a self, user_id: &UserId) -> impl Iterator<Item = Result<OwnedRoomId>> + 'a {
pub(crate) 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 fn rooms_invited<'a>(
pub(crate) 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 fn invite_state(&self, user_id: &UserId, room_id: &RoomId) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
pub(crate) 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 fn left_state(&self, user_id: &UserId, room_id: &RoomId) -> Result<Option<Vec<Raw<AnyStrippedStateEvent>>>> {
pub(crate) 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 fn rooms_left<'a>(
pub(crate) 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 fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
pub(crate) 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 fn is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { self.db.is_joined(user_id, room_id) }
pub(crate) 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 fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
pub(crate) 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 fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> { self.db.is_left(user_id, room_id) }
pub(crate) 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 fn servers_invite_via(&self, room_id: &RoomId) -> Result<Option<Vec<OwnedServerName>>> {
pub(crate) fn servers_invite_via(&self, room_id: &RoomId) -> Result<Option<Vec<OwnedServerName>>> {
self.db.servers_invite_via(room_id)
}
@ -361,7 +377,7 @@ impl Service {
///
/// See <https://spec.matrix.org/v1.10/appendices/#routing>
#[tracing::instrument(skip(self))]
pub fn servers_route_via(&self, room_id: &RoomId) -> Result<Vec<OwnedServerName>> {
pub(crate) 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 struct StateDiff {
pub parent: Option<u64>,
pub added: Arc<HashSet<CompressedStateEvent>>,
pub removed: Arc<HashSet<CompressedStateEvent>>,
pub(crate) struct StateDiff {
pub(crate) parent: Option<u64>,
pub(crate) added: Arc<HashSet<CompressedStateEvent>>,
pub(crate) removed: Arc<HashSet<CompressedStateEvent>>,
}
pub trait Data: Send + Sync {
pub(crate) 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 mod data;
pub(crate) mod data;
use std::{
collections::HashSet,
mem::size_of,
sync::{Arc, Mutex},
};
pub use data::Data;
pub(crate) 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 struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub stateinfo_cache: StateInfoLruCache,
pub(crate) stateinfo_cache: StateInfoLruCache,
}
pub type CompressedStateEvent = [u8; 2 * size_of::<u64>()];
pub(crate) 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 fn load_shortstatehash_info(&self, shortstatehash: u64) -> ShortStateInfoResult {
pub(crate) fn load_shortstatehash_info(&self, shortstatehash: u64) -> ShortStateInfoResult {
if let Some(r) = self
.stateinfo_cache
.lock()
@ -97,7 +97,7 @@ impl Service {
}
}
pub fn compress_state_event(&self, shortstatekey: u64, event_id: &EventId) -> Result<CompressedStateEvent> {
pub(crate) 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,7 +110,9 @@ impl Service {
}
/// Returns shortstatekey, event id
pub fn parse_compressed_state_event(&self, compressed_event: &CompressedStateEvent) -> Result<(u64, Arc<EventId>)> {
pub(crate) 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(
@ -138,7 +140,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 fn save_state_from_diff(
pub(crate) fn save_state_from_diff(
&self, shortstatehash: u64, statediffnew: Arc<HashSet<CompressedStateEvent>>,
statediffremoved: Arc<HashSet<CompressedStateEvent>>, diff_to_sibling: usize,
mut parent_states: ParentStatesVec,
@ -250,7 +252,7 @@ impl Service {
/// Returns the new shortstatehash, and the state diff from the previous
/// room state
pub fn save_state(
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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

@ -2,7 +2,7 @@ mod data;
use std::collections::BTreeMap;
pub use data::Data;
pub(crate) 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 struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
pub fn threads_until<'a>(
pub(crate) 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 fn add_to_thread(&self, root_event_id: &EventId, pdu: &PduEvent) -> Result<()> {
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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

@ -6,7 +6,7 @@ use std::{
sync::Arc,
};
pub use data::Data;
pub(crate) use data::Data;
use rand::prelude::SliceRandom;
use ruma::{
api::{client::error::ErrorKind, federation},
@ -45,17 +45,17 @@ use crate::{
};
#[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)]
pub enum PduCount {
pub(crate) enum PduCount {
Backfilled(u64),
Normal(u64),
}
impl PduCount {
pub fn min() -> Self { Self::Backfilled(u64::MAX) }
pub(crate) fn min() -> Self { Self::Backfilled(u64::MAX) }
pub fn max() -> Self { Self::Normal(u64::MAX) }
pub(crate) fn max() -> Self { Self::Normal(u64::MAX) }
pub fn try_from_string(token: &str) -> Result<Self> {
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 {
@ -64,7 +64,7 @@ impl PduCount {
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid pagination token."))
}
pub fn stringify(&self) -> String {
pub(crate) fn stringify(&self) -> String {
match self {
PduCount::Backfilled(x) => format!("-{x}"),
PduCount::Normal(x) => x.to_string(),
@ -104,15 +104,15 @@ struct ExtractRelatesToEventId {
relates_to: ExtractEventId,
}
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub lasttimelinecount_cache: Mutex<HashMap<OwnedRoomId, PduCount>>,
pub(crate) lasttimelinecount_cache: Mutex<HashMap<OwnedRoomId, PduCount>>,
}
impl Service {
#[tracing::instrument(skip(self))]
pub fn first_pdu_in_room(&self, room_id: &RoomId) -> Result<Option<Arc<PduEvent>>> {
pub(crate) 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)))
@ -120,17 +120,19 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount> {
pub(crate) 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 fn get_pdu_count(&self, event_id: &EventId) -> Result<Option<PduCount>> { self.db.get_pdu_count(event_id) }
pub(crate) 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 fn latest_pdu_count(&self, room_id: &RoomId) -> Result<u64> {
pub(crate) fn latest_pdu_count(&self, room_id: &RoomId) -> Result<u64> {
let prefix = self
.get_shortroomid(room_id)?
.expect("room exists")
@ -151,7 +153,7 @@ impl Service {
*/
/// Returns the version of a room, if known
pub fn get_room_version(&self, room_id: &RoomId) -> Result<Option<RoomVersionId>> {
pub(crate) fn get_room_version(&self, room_id: &RoomId) -> Result<Option<RoomVersionId>> {
let create_event = services()
.rooms
.state_accessor
@ -171,43 +173,43 @@ impl Service {
}
/// Returns the json of a pdu.
pub fn get_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
pub(crate) 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 fn get_non_outlier_pdu_json(&self, event_id: &EventId) -> Result<Option<CanonicalJsonObject>> {
pub(crate) 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 fn get_pdu_id(&self, event_id: &EventId) -> Result<Option<Vec<u8>>> { self.db.get_pdu_id(event_id) }
pub(crate) fn get_pdu_id(&self, event_id: &EventId) -> Result<Option<Vec<u8>>> { self.db.get_pdu_id(event_id) }
/// Returns the pdu.
///
/// Checks the `eventid_outlierpdu` Tree if not found in the timeline.
pub fn get_non_outlier_pdu(&self, event_id: &EventId) -> Result<Option<PduEvent>> {
pub(crate) 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 fn get_pdu(&self, event_id: &EventId) -> Result<Option<Arc<PduEvent>>> { self.db.get_pdu(event_id) }
pub(crate) 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 fn get_pdu_from_id(&self, pdu_id: &[u8]) -> Result<Option<PduEvent>> { self.db.get_pdu_from_id(pdu_id) }
pub(crate) 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 fn get_pdu_json_from_id(&self, pdu_id: &[u8]) -> Result<Option<CanonicalJsonObject>> {
pub(crate) 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 fn replace_pdu(&self, pdu_id: &[u8], pdu_json: &CanonicalJsonObject, pdu: &PduEvent) -> Result<()> {
pub(crate) fn replace_pdu(&self, pdu_id: &[u8], pdu_json: &CanonicalJsonObject, pdu: &PduEvent) -> Result<()> {
self.db.replace_pdu(pdu_id, pdu_json, pdu)
}
@ -218,7 +220,7 @@ impl Service {
///
/// Returns pdu id
#[tracing::instrument(skip(self, pdu, pdu_json, leaves))]
pub async fn append_pdu(
pub(crate) async fn append_pdu(
&self,
pdu: &PduEvent,
mut pdu_json: CanonicalJsonObject,
@ -615,7 +617,7 @@ impl Service {
Ok(pdu_id)
}
pub fn create_hash_and_sign_event(
pub(crate) fn create_hash_and_sign_event(
&self,
pdu_builder: PduBuilder,
sender: &UserId,
@ -798,7 +800,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 async fn build_and_append_pdu(
pub(crate) async fn build_and_append_pdu(
&self,
pdu_builder: PduBuilder,
sender: &UserId,
@ -940,7 +942,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 async fn append_incoming_pdu(
pub(crate) async fn append_incoming_pdu(
&self,
pdu: &PduEvent,
pdu_json: CanonicalJsonObject,
@ -979,7 +981,7 @@ impl Service {
}
/// Returns an iterator over all PDUs in a room.
pub fn all_pdus<'a>(
pub(crate) 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())
@ -989,7 +991,7 @@ impl Service {
/// happened before the event with id `until` in reverse-chronological
/// order.
#[tracing::instrument(skip(self))]
pub fn pdus_until<'a>(
pub(crate) 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)
@ -998,7 +1000,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 fn pdus_after<'a>(
pub(crate) 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)
@ -1006,7 +1008,7 @@ impl Service {
/// Replace a PDU with the redacted form.
#[tracing::instrument(skip(self, reason))]
pub fn redact_pdu(&self, event_id: &EventId, reason: &PduEvent) -> Result<()> {
pub(crate) 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
@ -1028,7 +1030,7 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id))]
pub async fn backfill_if_required(&self, room_id: &RoomId, from: PduCount) -> Result<()> {
pub(crate) 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()
@ -1142,7 +1144,7 @@ impl Service {
}
#[tracing::instrument(skip(self, pdu, pub_key_map))]
pub async fn backfill_pdu(
pub(crate) async fn backfill_pdu(
&self, origin: &ServerName, pdu: Box<RawJsonValue>,
pub_key_map: &RwLock<BTreeMap<String, BTreeMap<String, Base64>>>,
) -> Result<()> {

View file

@ -10,17 +10,18 @@ use tracing::debug;
use crate::{services, utils, Result};
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>,
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>,
}
impl Service {
/// Sets a user as typing until the timeout timestamp is reached or
/// roomtyping_remove is called.
pub async fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> {
pub(crate) async fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> {
debug!("typing add {:?} in {:?} timeout:{:?}", user_id, room_id, timeout);
// update clients
self.typing
@ -44,7 +45,7 @@ impl Service {
}
/// Removes a user from typing before the timeout is reached.
pub async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
pub(crate) async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
debug!("typing remove {:?} in {:?}", user_id, room_id);
// update clients
self.typing
@ -67,7 +68,7 @@ impl Service {
Ok(())
}
pub async fn wait_for_update(&self, room_id: &RoomId) -> Result<()> {
pub(crate) 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 {
@ -124,7 +125,7 @@ impl Service {
}
/// Returns the count of the last typing update in this room.
pub async fn last_typing_update(&self, room_id: &RoomId) -> Result<u64> {
pub(crate) async fn last_typing_update(&self, room_id: &RoomId) -> Result<u64> {
self.typings_maintain(room_id).await?;
Ok(self
.last_typing_update
@ -136,7 +137,7 @@ impl Service {
}
/// Returns a new typing EDU.
pub async fn typings_all(
pub(crate) 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 trait Data: Send + Sync {
pub(crate) 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,41 +1,45 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{OwnedRoomId, OwnedUserId, RoomId, UserId};
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
pub fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
pub(crate) fn reset_notification_counts(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
self.db.reset_notification_counts(user_id, room_id)
}
pub fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub(crate) fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
self.db.notification_count(user_id, room_id)
}
pub fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub(crate) fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
self.db.highlight_count(user_id, room_id)
}
pub fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
pub(crate) fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result<u64> {
self.db.last_notification_read(user_id, room_id)
}
pub fn associate_token_shortstatehash(&self, room_id: &RoomId, token: u64, shortstatehash: u64) -> Result<()> {
pub(crate) fn associate_token_shortstatehash(
&self, room_id: &RoomId, token: u64, shortstatehash: u64,
) -> Result<()> {
self.db
.associate_token_shortstatehash(room_id, token, shortstatehash)
}
pub fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result<Option<u64>> {
pub(crate) fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result<Option<u64>> {
self.db.get_token_shortstatehash(room_id, token)
}
pub fn get_shared_rooms(&self, users: Vec<OwnedUserId>) -> Result<impl Iterator<Item = Result<OwnedRoomId>>> {
pub(crate) fn get_shared_rooms(
&self, users: Vec<OwnedUserId>,
) -> Result<impl Iterator<Item = Result<OwnedRoomId>>> {
self.db.get_shared_rooms(users)
}
}

View file

@ -6,7 +6,7 @@ use crate::Result;
type OutgoingSendingIter<'a> = Box<dyn Iterator<Item = Result<(Vec<u8>, Destination, SendingEventType)>> + 'a>;
type SendingEventTypeIter<'a> = Box<dyn Iterator<Item = Result<(Vec<u8>, SendingEventType)>> + 'a>;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
fn active_requests(&self) -> OutgoingSendingIter<'_>;
fn active_requests_for(&self, destination: &Destination) -> SendingEventTypeIter<'_>;
fn delete_active_request(&self, key: Vec<u8>) -> Result<()>;

View file

@ -7,7 +7,7 @@ use std::{
};
use base64::{engine::general_purpose, Engine as _};
pub use data::Data;
pub(crate) use data::Data;
use federation::transactions::send_transaction_message;
use futures_util::{stream::FuturesUnordered, StreamExt};
use ruma::{
@ -30,19 +30,19 @@ use tracing::{error, warn};
use crate::{service::presence::Presence, services, utils::calculate_hash, Config, Error, PduEvent, Result};
pub mod appservice;
pub mod data;
pub mod send;
pub use send::FedDest;
mod appservice;
mod data;
mod send;
pub(crate) use send::FedDest;
const SELECT_EDU_LIMIT: usize = 16;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
/// The state for a given state hash.
pub(super) maximum_requests: Arc<Semaphore>,
pub sender: loole::Sender<(Destination, SendingEventType, Vec<u8>)>,
pub(crate) maximum_requests: Arc<Semaphore>,
pub(crate) sender: loole::Sender<(Destination, SendingEventType, Vec<u8>)>,
receiver: Mutex<loole::Receiver<(Destination, SendingEventType, Vec<u8>)>>,
startup_netburst: bool,
startup_netburst_keep: i64,
@ -50,7 +50,7 @@ pub struct Service {
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Destination {
pub(crate) enum Destination {
Appservice(String),
Push(OwnedUserId, String), // user and pushkey
Normal(OwnedServerName),
@ -58,7 +58,7 @@ pub enum Destination {
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[allow(clippy::module_name_repetitions)]
pub enum SendingEventType {
pub(crate) enum SendingEventType {
Pdu(Vec<u8>), // pduid
Edu(Vec<u8>), // pdu json
Flush, // none
@ -71,7 +71,7 @@ enum TransactionStatus {
}
impl Service {
pub fn build(db: &'static dyn Data, config: &Config) -> Arc<Self> {
pub(crate) fn build(db: &'static dyn Data, config: &Config) -> Arc<Self> {
let (sender, receiver) = loole::unbounded();
Arc::new(Self {
db,
@ -85,7 +85,7 @@ impl Service {
}
#[tracing::instrument(skip(self, pdu_id, user, pushkey))]
pub fn send_pdu_push(&self, pdu_id: &[u8], user: &UserId, pushkey: String) -> Result<()> {
pub(crate) fn send_pdu_push(&self, pdu_id: &[u8], user: &UserId, pushkey: String) -> Result<()> {
let destination = Destination::Push(user.to_owned(), pushkey);
let event = SendingEventType::Pdu(pdu_id.to_owned());
let _cork = services().globals.db.cork()?;
@ -98,7 +98,7 @@ impl Service {
}
#[tracing::instrument(skip(self))]
pub fn send_pdu_appservice(&self, appservice_id: String, pdu_id: Vec<u8>) -> Result<()> {
pub(crate) fn send_pdu_appservice(&self, appservice_id: String, pdu_id: Vec<u8>) -> Result<()> {
let destination = Destination::Appservice(appservice_id);
let event = SendingEventType::Pdu(pdu_id);
let _cork = services().globals.db.cork()?;
@ -111,7 +111,7 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id, pdu_id))]
pub fn send_pdu_room(&self, room_id: &RoomId, pdu_id: &[u8]) -> Result<()> {
pub(crate) fn send_pdu_room(&self, room_id: &RoomId, pdu_id: &[u8]) -> Result<()> {
let servers = services()
.rooms
.state_cache
@ -123,7 +123,9 @@ impl Service {
}
#[tracing::instrument(skip(self, servers, pdu_id))]
pub fn send_pdu_servers<I: Iterator<Item = OwnedServerName>>(&self, servers: I, pdu_id: &[u8]) -> Result<()> {
pub(crate) fn send_pdu_servers<I: Iterator<Item = OwnedServerName>>(
&self, servers: I, pdu_id: &[u8],
) -> Result<()> {
let requests = servers
.into_iter()
.map(|server| (Destination::Normal(server), SendingEventType::Pdu(pdu_id.to_owned())))
@ -143,7 +145,7 @@ impl Service {
}
#[tracing::instrument(skip(self, server, serialized))]
pub fn send_edu_server(&self, server: &ServerName, serialized: Vec<u8>) -> Result<()> {
pub(crate) fn send_edu_server(&self, server: &ServerName, serialized: Vec<u8>) -> Result<()> {
let destination = Destination::Normal(server.to_owned());
let event = SendingEventType::Edu(serialized);
let _cork = services().globals.db.cork()?;
@ -156,7 +158,7 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id, serialized))]
pub fn send_edu_room(&self, room_id: &RoomId, serialized: Vec<u8>) -> Result<()> {
pub(crate) fn send_edu_room(&self, room_id: &RoomId, serialized: Vec<u8>) -> Result<()> {
let servers = services()
.rooms
.state_cache
@ -168,7 +170,9 @@ impl Service {
}
#[tracing::instrument(skip(self, servers, serialized))]
pub fn send_edu_servers<I: Iterator<Item = OwnedServerName>>(&self, servers: I, serialized: Vec<u8>) -> Result<()> {
pub(crate) fn send_edu_servers<I: Iterator<Item = OwnedServerName>>(
&self, servers: I, serialized: Vec<u8>,
) -> Result<()> {
let requests = servers
.into_iter()
.map(|server| (Destination::Normal(server), SendingEventType::Edu(serialized.clone())))
@ -188,7 +192,7 @@ impl Service {
}
#[tracing::instrument(skip(self, room_id))]
pub fn flush_room(&self, room_id: &RoomId) -> Result<()> {
pub(crate) fn flush_room(&self, room_id: &RoomId) -> Result<()> {
let servers = services()
.rooms
.state_cache
@ -200,7 +204,7 @@ impl Service {
}
#[tracing::instrument(skip(self, servers))]
pub fn flush_servers<I: Iterator<Item = OwnedServerName>>(&self, servers: I) -> Result<()> {
pub(crate) fn flush_servers<I: Iterator<Item = OwnedServerName>>(&self, servers: I) -> Result<()> {
let requests = servers.into_iter().map(Destination::Normal);
for destination in requests {
@ -215,7 +219,7 @@ impl Service {
/// Cleanup event data
/// Used for instance after we remove an appservice registration
#[tracing::instrument(skip(self))]
pub fn cleanup_events(&self, appservice_id: String) -> Result<()> {
pub(crate) fn cleanup_events(&self, appservice_id: String) -> Result<()> {
self.db
.delete_all_requests_for(&Destination::Appservice(appservice_id))?;
@ -223,7 +227,7 @@ impl Service {
}
#[tracing::instrument(skip(self, request), name = "request")]
pub async fn send_federation_request<T>(&self, dest: &ServerName, request: T) -> Result<T::IncomingResponse>
pub(crate) async fn send_federation_request<T>(&self, dest: &ServerName, request: T) -> Result<T::IncomingResponse>
where
T: OutgoingRequest + Debug,
{
@ -245,7 +249,7 @@ impl Service {
///
/// Only returns None if there is no url specified in the appservice
/// registration file
pub async fn send_appservice_request<T>(
pub(crate) async fn send_appservice_request<T>(
&self, registration: Registration, request: T,
) -> Result<Option<T::IncomingResponse>>
where
@ -258,7 +262,7 @@ impl Service {
response
}
pub fn start_handler(self: &Arc<Self>) {
pub(crate) fn start_handler(self: &Arc<Self>) {
let self2 = Arc::clone(self);
tokio::spawn(async move {
self2
@ -430,7 +434,7 @@ impl Service {
}
#[tracing::instrument(skip(self, server_name))]
pub fn select_edus(&self, server_name: &ServerName) -> Result<(Vec<Vec<u8>>, u64)> {
pub(crate) fn select_edus(&self, server_name: &ServerName) -> Result<(Vec<Vec<u8>>, u64)> {
// u64: count of last edu
let since = self.db.get_latest_educount(server_name)?;
let mut events = Vec::new();
@ -481,7 +485,7 @@ impl Service {
/// Look for presence
#[tracing::instrument(skip(server_name, since, max_edu_count, events))]
pub fn select_edus_presence(
pub(crate) fn select_edus_presence(
server_name: &ServerName, since: u64, max_edu_count: &mut u64, events: &mut Vec<Vec<u8>>,
) -> Result<bool> {
// Look for presence updates for this server
@ -526,7 +530,7 @@ pub fn select_edus_presence(
/// Look for read receipts in this room
#[tracing::instrument(skip(room_id, since, max_edu_count, events))]
pub fn select_edus_receipts(
pub(crate) fn select_edus_receipts(
room_id: &RoomId, since: u64, max_edu_count: &mut u64, events: &mut Vec<Vec<u8>>,
) -> Result<bool> {
for r in services()
@ -828,7 +832,7 @@ async fn handle_events_destination_normal(
impl Destination {
#[tracing::instrument(skip(self))]
pub fn get_prefix(&self) -> Vec<u8> {
pub(crate) fn get_prefix(&self) -> Vec<u8> {
let mut prefix = match self {
Destination::Appservice(server) => {
let mut p = b"+".to_vec();

View file

@ -38,7 +38,7 @@ use crate::{debug_error, debug_info, debug_warn, services, Error, Result};
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FedDest {
pub(crate) enum FedDest {
Literal(SocketAddr),
Named(String, String),
}

View file

@ -2,7 +2,7 @@ use ruma::{DeviceId, TransactionId, UserId};
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
fn add_txnid(
&self, user_id: &UserId, device_id: Option<&DeviceId>, txn_id: &TransactionId, data: &[u8],
) -> Result<()>;

View file

@ -1,22 +1,22 @@
mod data;
pub use data::Data;
pub(crate) use data::Data;
use ruma::{DeviceId, TransactionId, UserId};
use crate::Result;
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
pub fn add_txnid(
pub(crate) fn add_txnid(
&self, user_id: &UserId, device_id: Option<&DeviceId>, txn_id: &TransactionId, data: &[u8],
) -> Result<()> {
self.db.add_txnid(user_id, device_id, txn_id, data)
}
pub fn existing_txnid(
pub(crate) fn existing_txnid(
&self, user_id: &UserId, device_id: Option<&DeviceId>, txn_id: &TransactionId,
) -> Result<Option<Vec<u8>>> {
self.db.existing_txnid(user_id, device_id, txn_id)

View file

@ -2,7 +2,7 @@ use ruma::{api::client::uiaa::UiaaInfo, CanonicalJsonValue, DeviceId, UserId};
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
fn set_uiaa_request(
&self, user_id: &UserId, device_id: &DeviceId, session: &str, request: &CanonicalJsonValue,
) -> Result<()>;

View file

@ -1,7 +1,7 @@
mod data;
use argon2::{PasswordHash, PasswordVerifier};
pub use data::Data;
pub(crate) use data::Data;
use ruma::{
api::client::{
error::ErrorKind,
@ -13,13 +13,13 @@ use tracing::error;
use crate::{api::client_server::SESSION_ID_LENGTH, services, utils, Error, Result};
pub struct Service {
pub db: &'static dyn Data,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
}
impl Service {
/// Creates a new Uiaa session. Make sure the session token is unique.
pub fn create(
pub(crate) fn create(
&self, user_id: &UserId, device_id: &DeviceId, uiaainfo: &UiaaInfo, json_body: &CanonicalJsonValue,
) -> Result<()> {
self.db.set_uiaa_request(
@ -37,7 +37,7 @@ impl Service {
)
}
pub fn try_auth(
pub(crate) fn try_auth(
&self, user_id: &UserId, device_id: &DeviceId, auth: &AuthData, uiaainfo: &UiaaInfo,
) -> Result<(bool, UiaaInfo)> {
let mut uiaainfo = auth.session().map_or_else(
@ -135,7 +135,7 @@ impl Service {
Ok((true, uiaainfo))
}
pub fn get_uiaa_request(
pub(crate) fn get_uiaa_request(
&self, user_id: &UserId, device_id: &DeviceId, session: &str,
) -> Option<CanonicalJsonValue> {
self.db.get_uiaa_request(user_id, device_id, session)

View file

@ -10,7 +10,7 @@ use ruma::{
use crate::Result;
pub trait Data: Send + Sync {
pub(crate) trait Data: Send + Sync {
/// Check if a user has an account on this homeserver.
fn exists(&self, user_id: &UserId) -> Result<bool>;

View file

@ -5,7 +5,7 @@ use std::{
sync::{Arc, Mutex},
};
pub use data::Data;
pub(crate) use data::Data;
use ruma::{
api::client::{
device::Device,
@ -25,7 +25,7 @@ use ruma::{
use crate::{services, Error, Result};
pub struct SlidingSyncCache {
pub(crate) struct SlidingSyncCache {
lists: BTreeMap<String, SyncRequestList>,
subscriptions: BTreeMap<OwnedRoomId, sync_events::v4::RoomSubscription>,
known_rooms: BTreeMap<String, BTreeMap<OwnedRoomId, u64>>, // For every room, the roomsince number
@ -34,23 +34,25 @@ pub struct SlidingSyncCache {
type DbConnections = Mutex<BTreeMap<(OwnedUserId, OwnedDeviceId, String), Arc<Mutex<SlidingSyncCache>>>>;
pub struct Service {
pub db: &'static dyn Data,
pub connections: DbConnections,
pub(crate) struct Service {
pub(crate) db: &'static dyn Data,
pub(crate) connections: DbConnections,
}
impl Service {
/// Check if a user has an account on this homeserver.
pub fn exists(&self, user_id: &UserId) -> Result<bool> { self.db.exists(user_id) }
pub(crate) fn exists(&self, user_id: &UserId) -> Result<bool> { self.db.exists(user_id) }
pub fn forget_sync_request_connection(&self, user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: String) {
pub(crate) fn forget_sync_request_connection(
&self, user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: String,
) {
self.connections
.lock()
.unwrap()
.remove(&(user_id, device_id, conn_id));
}
pub fn update_sync_request_with_cache(
pub(crate) fn update_sync_request_with_cache(
&self, user_id: OwnedUserId, device_id: OwnedDeviceId, request: &mut sync_events::v4::Request,
) -> BTreeMap<String, BTreeMap<OwnedRoomId, u64>> {
let Some(conn_id) = request.conn_id.clone() else {
@ -170,7 +172,7 @@ impl Service {
cached.known_rooms.clone()
}
pub fn update_sync_subscriptions(
pub(crate) fn update_sync_subscriptions(
&self, user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: String,
subscriptions: BTreeMap<OwnedRoomId, sync_events::v4::RoomSubscription>,
) {
@ -193,7 +195,7 @@ impl Service {
cached.subscriptions = subscriptions;
}
pub fn update_sync_known_rooms(
pub(crate) fn update_sync_known_rooms(
&self, user_id: OwnedUserId, device_id: OwnedDeviceId, conn_id: String, list_id: String,
new_cached_rooms: BTreeSet<OwnedRoomId>, globalsince: u64,
) {
@ -230,10 +232,10 @@ impl Service {
}
/// Check if account is deactivated
pub fn is_deactivated(&self, user_id: &UserId) -> Result<bool> { self.db.is_deactivated(user_id) }
pub(crate) fn is_deactivated(&self, user_id: &UserId) -> Result<bool> { self.db.is_deactivated(user_id) }
/// Check if a user is an admin
pub fn is_admin(&self, user_id: &UserId) -> Result<bool> {
pub(crate) fn is_admin(&self, user_id: &UserId) -> Result<bool> {
let admin_room_alias_id = RoomAliasId::parse(format!("#admins:{}", services().globals.server_name()))
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid alias."))?;
let admin_room_id = services()
@ -249,63 +251,63 @@ impl Service {
}
/// Create a new user account on this homeserver.
pub fn create(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
pub(crate) fn create(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
self.db.set_password(user_id, password)?;
Ok(())
}
/// Returns the number of users registered on this server.
pub fn count(&self) -> Result<usize> { self.db.count() }
pub(crate) fn count(&self) -> Result<usize> { self.db.count() }
/// Find out which user an access token belongs to.
pub fn find_from_token(&self, token: &str) -> Result<Option<(OwnedUserId, String)>> {
pub(crate) fn find_from_token(&self, token: &str) -> Result<Option<(OwnedUserId, String)>> {
self.db.find_from_token(token)
}
/// Returns an iterator over all users on this homeserver.
pub fn iter(&self) -> impl Iterator<Item = Result<OwnedUserId>> + '_ { self.db.iter() }
pub(crate) fn iter(&self) -> impl Iterator<Item = Result<OwnedUserId>> + '_ { self.db.iter() }
/// Returns a list of local users as list of usernames.
///
/// A user account is considered `local` if the length of it's password is
/// greater then zero.
pub fn list_local_users(&self) -> Result<Vec<String>> { self.db.list_local_users() }
pub(crate) fn list_local_users(&self) -> Result<Vec<String>> { self.db.list_local_users() }
/// Returns the password hash for the given user.
pub fn password_hash(&self, user_id: &UserId) -> Result<Option<String>> { self.db.password_hash(user_id) }
pub(crate) fn password_hash(&self, user_id: &UserId) -> Result<Option<String>> { self.db.password_hash(user_id) }
/// Hash and set the user's password to the Argon2 hash
pub fn set_password(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
pub(crate) fn set_password(&self, user_id: &UserId, password: Option<&str>) -> Result<()> {
self.db.set_password(user_id, password)
}
/// Returns the displayname of a user on this homeserver.
pub fn displayname(&self, user_id: &UserId) -> Result<Option<String>> { self.db.displayname(user_id) }
pub(crate) fn displayname(&self, user_id: &UserId) -> Result<Option<String>> { self.db.displayname(user_id) }
/// Sets a new displayname or removes it if displayname is None. You still
/// need to nofify all rooms of this change.
pub async fn set_displayname(&self, user_id: &UserId, displayname: Option<String>) -> Result<()> {
pub(crate) async fn set_displayname(&self, user_id: &UserId, displayname: Option<String>) -> Result<()> {
self.db.set_displayname(user_id, displayname)
}
/// Get the avatar_url of a user.
pub fn avatar_url(&self, user_id: &UserId) -> Result<Option<OwnedMxcUri>> { self.db.avatar_url(user_id) }
pub(crate) fn avatar_url(&self, user_id: &UserId) -> Result<Option<OwnedMxcUri>> { self.db.avatar_url(user_id) }
/// Sets a new avatar_url or removes it if avatar_url is None.
pub async fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<OwnedMxcUri>) -> Result<()> {
pub(crate) async fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option<OwnedMxcUri>) -> Result<()> {
self.db.set_avatar_url(user_id, avatar_url)
}
/// Get the blurhash of a user.
pub fn blurhash(&self, user_id: &UserId) -> Result<Option<String>> { self.db.blurhash(user_id) }
pub(crate) fn blurhash(&self, user_id: &UserId) -> Result<Option<String>> { self.db.blurhash(user_id) }
/// Sets a new avatar_url or removes it if avatar_url is None.
pub async fn set_blurhash(&self, user_id: &UserId, blurhash: Option<String>) -> Result<()> {
pub(crate) async fn set_blurhash(&self, user_id: &UserId, blurhash: Option<String>) -> Result<()> {
self.db.set_blurhash(user_id, blurhash)
}
/// Adds a new device to a user.
pub fn create_device(
pub(crate) fn create_device(
&self, user_id: &UserId, device_id: &DeviceId, token: &str, initial_device_display_name: Option<String>,
) -> Result<()> {
self.db
@ -313,21 +315,21 @@ impl Service {
}
/// Removes a device from a user.
pub fn remove_device(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
pub(crate) fn remove_device(&self, user_id: &UserId, device_id: &DeviceId) -> Result<()> {
self.db.remove_device(user_id, device_id)
}
/// Returns an iterator over all device ids of this user.
pub fn all_device_ids<'a>(&'a self, user_id: &UserId) -> impl Iterator<Item = Result<OwnedDeviceId>> + 'a {
pub(crate) fn all_device_ids<'a>(&'a self, user_id: &UserId) -> impl Iterator<Item = Result<OwnedDeviceId>> + 'a {
self.db.all_device_ids(user_id)
}
/// Replaces the access token of one device.
pub fn set_token(&self, user_id: &UserId, device_id: &DeviceId, token: &str) -> Result<()> {
pub(crate) fn set_token(&self, user_id: &UserId, device_id: &DeviceId, token: &str) -> Result<()> {
self.db.set_token(user_id, device_id, token)
}
pub fn add_one_time_key(
pub(crate) fn add_one_time_key(
&self, user_id: &UserId, device_id: &DeviceId, one_time_key_key: &DeviceKeyId,
one_time_key_value: &Raw<OneTimeKey>,
) -> Result<()> {
@ -335,27 +337,29 @@ impl Service {
.add_one_time_key(user_id, device_id, one_time_key_key, one_time_key_value)
}
pub fn last_one_time_keys_update(&self, user_id: &UserId) -> Result<u64> {
pub(crate) fn last_one_time_keys_update(&self, user_id: &UserId) -> Result<u64> {
self.db.last_one_time_keys_update(user_id)
}
pub fn take_one_time_key(
pub(crate) fn take_one_time_key(
&self, user_id: &UserId, device_id: &DeviceId, key_algorithm: &DeviceKeyAlgorithm,
) -> Result<Option<(OwnedDeviceKeyId, Raw<OneTimeKey>)>> {
self.db.take_one_time_key(user_id, device_id, key_algorithm)
}
pub fn count_one_time_keys(
pub(crate) fn count_one_time_keys(
&self, user_id: &UserId, device_id: &DeviceId,
) -> Result<BTreeMap<DeviceKeyAlgorithm, UInt>> {
self.db.count_one_time_keys(user_id, device_id)
}
pub fn add_device_keys(&self, user_id: &UserId, device_id: &DeviceId, device_keys: &Raw<DeviceKeys>) -> Result<()> {
pub(crate) fn add_device_keys(
&self, user_id: &UserId, device_id: &DeviceId, device_keys: &Raw<DeviceKeys>,
) -> Result<()> {
self.db.add_device_keys(user_id, device_id, device_keys)
}
pub fn add_cross_signing_keys(
pub(crate) fn add_cross_signing_keys(
&self, user_id: &UserId, master_key: &Raw<CrossSigningKey>, self_signing_key: &Option<Raw<CrossSigningKey>>,
user_signing_key: &Option<Raw<CrossSigningKey>>, notify: bool,
) -> Result<()> {
@ -363,56 +367,58 @@ impl Service {
.add_cross_signing_keys(user_id, master_key, self_signing_key, user_signing_key, notify)
}
pub fn sign_key(
pub(crate) fn sign_key(
&self, target_id: &UserId, key_id: &str, signature: (String, String), sender_id: &UserId,
) -> Result<()> {
self.db.sign_key(target_id, key_id, signature, sender_id)
}
pub fn keys_changed<'a>(
pub(crate) fn keys_changed<'a>(
&'a self, user_or_room_id: &str, from: u64, to: Option<u64>,
) -> impl Iterator<Item = Result<OwnedUserId>> + 'a {
self.db.keys_changed(user_or_room_id, from, to)
}
pub fn mark_device_key_update(&self, user_id: &UserId) -> Result<()> { self.db.mark_device_key_update(user_id) }
pub(crate) fn mark_device_key_update(&self, user_id: &UserId) -> Result<()> {
self.db.mark_device_key_update(user_id)
}
pub fn get_device_keys(&self, user_id: &UserId, device_id: &DeviceId) -> Result<Option<Raw<DeviceKeys>>> {
pub(crate) fn get_device_keys(&self, user_id: &UserId, device_id: &DeviceId) -> Result<Option<Raw<DeviceKeys>>> {
self.db.get_device_keys(user_id, device_id)
}
pub fn parse_master_key(
pub(crate) fn parse_master_key(
&self, user_id: &UserId, master_key: &Raw<CrossSigningKey>,
) -> Result<(Vec<u8>, CrossSigningKey)> {
self.db.parse_master_key(user_id, master_key)
}
pub fn get_key(
pub(crate) fn get_key(
&self, key: &[u8], sender_user: Option<&UserId>, user_id: &UserId, allowed_signatures: &dyn Fn(&UserId) -> bool,
) -> Result<Option<Raw<CrossSigningKey>>> {
self.db
.get_key(key, sender_user, user_id, allowed_signatures)
}
pub fn get_master_key(
pub(crate) fn get_master_key(
&self, sender_user: Option<&UserId>, user_id: &UserId, allowed_signatures: &dyn Fn(&UserId) -> bool,
) -> Result<Option<Raw<CrossSigningKey>>> {
self.db
.get_master_key(sender_user, user_id, allowed_signatures)
}
pub fn get_self_signing_key(
pub(crate) fn get_self_signing_key(
&self, sender_user: Option<&UserId>, user_id: &UserId, allowed_signatures: &dyn Fn(&UserId) -> bool,
) -> Result<Option<Raw<CrossSigningKey>>> {
self.db
.get_self_signing_key(sender_user, user_id, allowed_signatures)
}
pub fn get_user_signing_key(&self, user_id: &UserId) -> Result<Option<Raw<CrossSigningKey>>> {
pub(crate) fn get_user_signing_key(&self, user_id: &UserId) -> Result<Option<Raw<CrossSigningKey>>> {
self.db.get_user_signing_key(user_id)
}
pub fn add_to_device_event(
pub(crate) fn add_to_device_event(
&self, sender: &UserId, target_user_id: &UserId, target_device_id: &DeviceId, event_type: &str,
content: serde_json::Value,
) -> Result<()> {
@ -420,33 +426,35 @@ impl Service {
.add_to_device_event(sender, target_user_id, target_device_id, event_type, content)
}
pub fn get_to_device_events(&self, user_id: &UserId, device_id: &DeviceId) -> Result<Vec<Raw<AnyToDeviceEvent>>> {
pub(crate) fn get_to_device_events(
&self, user_id: &UserId, device_id: &DeviceId,
) -> Result<Vec<Raw<AnyToDeviceEvent>>> {
self.db.get_to_device_events(user_id, device_id)
}
pub fn remove_to_device_events(&self, user_id: &UserId, device_id: &DeviceId, until: u64) -> Result<()> {
pub(crate) fn remove_to_device_events(&self, user_id: &UserId, device_id: &DeviceId, until: u64) -> Result<()> {
self.db.remove_to_device_events(user_id, device_id, until)
}
pub fn update_device_metadata(&self, user_id: &UserId, device_id: &DeviceId, device: &Device) -> Result<()> {
pub(crate) fn update_device_metadata(&self, user_id: &UserId, device_id: &DeviceId, device: &Device) -> Result<()> {
self.db.update_device_metadata(user_id, device_id, device)
}
/// Get device metadata.
pub fn get_device_metadata(&self, user_id: &UserId, device_id: &DeviceId) -> Result<Option<Device>> {
pub(crate) fn get_device_metadata(&self, user_id: &UserId, device_id: &DeviceId) -> Result<Option<Device>> {
self.db.get_device_metadata(user_id, device_id)
}
pub fn get_devicelist_version(&self, user_id: &UserId) -> Result<Option<u64>> {
pub(crate) fn get_devicelist_version(&self, user_id: &UserId) -> Result<Option<u64>> {
self.db.get_devicelist_version(user_id)
}
pub fn all_devices_metadata<'a>(&'a self, user_id: &UserId) -> impl Iterator<Item = Result<Device>> + 'a {
pub(crate) fn all_devices_metadata<'a>(&'a self, user_id: &UserId) -> impl Iterator<Item = Result<Device>> + 'a {
self.db.all_devices_metadata(user_id)
}
/// Deactivate account
pub fn deactivate_account(&self, user_id: &UserId) -> Result<()> {
pub(crate) fn deactivate_account(&self, user_id: &UserId) -> Result<()> {
// Remove all associated devices
for device_id in self.all_device_ids(user_id) {
self.remove_device(user_id, &device_id?)?;
@ -463,11 +471,11 @@ impl Service {
}
/// Creates a new sync filter. Returns the filter id.
pub fn create_filter(&self, user_id: &UserId, filter: &FilterDefinition) -> Result<String> {
pub(crate) fn create_filter(&self, user_id: &UserId, filter: &FilterDefinition) -> Result<String> {
self.db.create_filter(user_id, filter)
}
pub fn get_filter(&self, user_id: &UserId, filter_id: &str) -> Result<Option<FilterDefinition>> {
pub(crate) fn get_filter(&self, user_id: &UserId, filter_id: &str) -> Result<Option<FilterDefinition>> {
self.db.get_filter(user_id, filter_id)
}
}