From 66bb88a03a204b02ecbb63bcaf5915df24316b88 Mon Sep 17 00:00:00 2001 From: strawberry Date: Mon, 22 Apr 2024 23:48:57 -0400 Subject: [PATCH] make everything pub(crate) instead of pub conduwuit is not a library Signed-off-by: strawberry --- Cargo.toml | 2 +- src/api/client_server/account.rs | 18 +- src/api/client_server/alias.rs | 6 +- src/api/client_server/backup.rs | 34 +- src/api/client_server/capabilities.rs | 2 +- src/api/client_server/config.rs | 8 +- src/api/client_server/context.rs | 2 +- src/api/client_server/device.rs | 12 +- src/api/client_server/directory.rs | 8 +- src/api/client_server/filter.rs | 4 +- src/api/client_server/keys.rs | 14 +- src/api/client_server/media.rs | 28 +- src/api/client_server/membership.rs | 30 +- src/api/client_server/message.rs | 4 +- src/api/client_server/mod.rs | 78 ++--- src/api/client_server/presence.rs | 4 +- src/api/client_server/profile.rs | 14 +- src/api/client_server/push.rs | 22 +- src/api/client_server/read_marker.rs | 8 +- src/api/client_server/redact.rs | 2 +- src/api/client_server/relations.rs | 6 +- src/api/client_server/report.rs | 4 +- src/api/client_server/room.rs | 10 +- src/api/client_server/search.rs | 2 +- src/api/client_server/session.rs | 10 +- src/api/client_server/space.rs | 2 +- src/api/client_server/state.rs | 10 +- src/api/client_server/sync.rs | 4 +- src/api/client_server/tag.rs | 6 +- src/api/client_server/thirdparty.rs | 4 +- src/api/client_server/threads.rs | 2 +- src/api/client_server/to_device.rs | 2 +- src/api/client_server/typing.rs | 2 +- src/api/client_server/unstable.rs | 2 +- src/api/client_server/unversioned.rs | 12 +- src/api/client_server/user_directory.rs | 2 +- src/api/client_server/voip.rs | 2 +- src/api/mod.rs | 6 +- src/api/ruma_wrapper/mod.rs | 17 +- src/api/server_server.rs | 58 ++-- src/clap.rs | 6 +- src/config/check.rs | 2 +- src/config/mod.rs | 304 +++++++++--------- src/config/proxy.rs | 8 +- src/database/cork.rs | 2 +- src/database/mod.rs | 212 ++++++------ src/database/rocksdb/kvtree.rs | 8 +- src/database/sqlite/mod.rs | 10 +- src/database/watchers.rs | 6 +- src/main.rs | 4 +- src/routes.rs | 4 +- src/service/account_data/data.rs | 2 +- src/service/account_data/mod.rs | 10 +- .../admin/appservice/appservice_command.rs | 8 +- src/service/admin/debug/debug_commands.rs | 22 +- .../admin/federation/federation_commands.rs | 8 +- src/service/admin/fsck/fsck_commands.rs | 2 +- src/service/admin/media/media_commands.rs | 6 +- src/service/admin/mod.rs | 14 +- src/service/admin/query/account_data.rs | 2 +- src/service/admin/query/appservice.rs | 2 +- src/service/admin/query/globals.rs | 2 +- src/service/admin/query/presence.rs | 2 +- src/service/admin/query/room_alias.rs | 2 +- src/service/admin/query/sending.rs | 2 +- src/service/admin/query/users.rs | 2 +- src/service/admin/room/room_commands.rs | 2 +- src/service/admin/server/server_commands.rs | 14 +- src/service/admin/user/user_commands.rs | 12 +- src/service/appservice/data.rs | 2 +- src/service/appservice/mod.rs | 50 +-- src/service/globals/client.rs | 18 +- src/service/globals/data.rs | 2 +- src/service/globals/mod.rs | 236 +++++++------- src/service/globals/resolver.rs | 20 +- src/service/key_backups/data.rs | 2 +- src/service/key_backups/mod.rs | 40 ++- src/service/media/data.rs | 2 +- src/service/media/mod.rs | 48 +-- src/service/mod.rs | 30 +- src/service/pdu.rs | 79 ++--- src/service/presence/data.rs | 2 +- src/service/presence/mod.rs | 47 +-- src/service/pusher/data.rs | 2 +- src/service/pusher/mod.rs | 20 +- src/service/rooms/alias/data.rs | 2 +- src/service/rooms/alias/mod.rs | 18 +- src/service/rooms/auth_chain/data.rs | 2 +- src/service/rooms/auth_chain/mod.rs | 16 +- src/service/rooms/directory/data.rs | 2 +- src/service/rooms/directory/mod.rs | 14 +- src/service/rooms/event_handler/mod.rs | 12 +- .../rooms/event_handler/signing_keys.rs | 2 +- src/service/rooms/lazy_loading/data.rs | 2 +- src/service/rooms/lazy_loading/mod.rs | 17 +- src/service/rooms/metadata/data.rs | 2 +- src/service/rooms/metadata/mod.rs | 20 +- src/service/rooms/mod.rs | 84 ++--- src/service/rooms/outlier/data.rs | 2 +- src/service/rooms/outlier/mod.rs | 14 +- src/service/rooms/pdu_metadata/data.rs | 2 +- src/service/rooms/pdu_metadata/mod.rs | 24 +- src/service/rooms/read_receipt/data.rs | 2 +- src/service/rooms/read_receipt/mod.rs | 16 +- src/service/rooms/search/data.rs | 2 +- src/service/rooms/search/mod.rs | 10 +- src/service/rooms/short/data.rs | 2 +- src/service/rooms/short/mod.rs | 24 +- src/service/rooms/spaces/mod.rs | 24 +- src/service/rooms/state/data.rs | 2 +- src/service/rooms/state/mod.rs | 24 +- src/service/rooms/state_accessor/data.rs | 2 +- src/service/rooms/state_accessor/mod.rs | 48 +-- src/service/rooms/state_cache/data.rs | 2 +- src/service/rooms/state_cache/mod.rs | 78 +++-- src/service/rooms/state_compressor/data.rs | 10 +- src/service/rooms/state_compressor/mod.rs | 24 +- src/service/rooms/threads/data.rs | 2 +- src/service/rooms/threads/mod.rs | 10 +- src/service/rooms/timeline/data.rs | 2 +- src/service/rooms/timeline/mod.rs | 66 ++-- src/service/rooms/typing/mod.rs | 21 +- src/service/rooms/user/data.rs | 2 +- src/service/rooms/user/mod.rs | 24 +- src/service/sending/data.rs | 2 +- src/service/sending/mod.rs | 62 ++-- src/service/sending/send.rs | 2 +- src/service/transaction_ids/data.rs | 2 +- src/service/transaction_ids/mod.rs | 10 +- src/service/uiaa/data.rs | 2 +- src/service/uiaa/mod.rs | 12 +- src/service/users/data.rs | 2 +- src/service/users/mod.rs | 116 +++---- src/utils/error.rs | 14 +- src/utils/mod.rs | 14 +- 135 files changed, 1366 insertions(+), 1247 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fe565bdb..c87ce215 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -487,6 +487,7 @@ elided_lifetimes_in_paths = "warn" macro_use_extern_crate = "warn" single_use_lifetimes = "warn" unsafe_op_in_unsafe_fn = "warn" +unreachable_pub = "warn" # not in rust 1.75.0 (doesn't break CI but won't check for it) unit_bindings = "warn" @@ -495,7 +496,6 @@ unit_bindings = "warn" unused_braces = "allow" # some sadness -unreachable_pub = "allow" missing_docs = "allow" diff --git a/src/api/client_server/account.rs b/src/api/client_server/account.rs index f74cdaa7..1187ec7b 100644 --- a/src/api/client_server/account.rs +++ b/src/api/client_server/account.rs @@ -34,7 +34,7 @@ const RANDOM_USER_ID_LENGTH: usize = 10; /// /// Note: This will not reserve the username, so the username might become /// invalid when trying to register -pub async fn get_register_available_route( +pub(crate) async fn get_register_available_route( body: Ruma, ) -> Result { // Validate user id @@ -82,7 +82,7 @@ pub async fn get_register_available_route( /// - If `inhibit_login` is false: Creates a device and returns device id and /// access_token #[allow(clippy::doc_markdown)] -pub async fn register_route(body: Ruma) -> Result { +pub(crate) async fn register_route(body: Ruma) -> Result { if !services().globals.allow_registration() && body.appservice_info.is_none() { info!( "Registration disabled and request not from known appservice, rejecting registration attempt for username \ @@ -406,7 +406,9 @@ pub async fn register_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn change_password_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); @@ -469,7 +471,7 @@ pub async fn change_password_route(body: Ruma) -> /// Get `user_id` of the sender user. /// /// Note: Also works for Application Services -pub async fn whoami_route(body: Ruma) -> Result { +pub(crate) async fn whoami_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let device_id = body.sender_device.clone(); @@ -491,7 +493,7 @@ pub async fn whoami_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn deactivate_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); @@ -546,7 +548,7 @@ pub async fn deactivate_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn third_party_route(body: Ruma) -> Result { let _sender_user = body.sender_user.as_ref().expect("user is authenticated"); Ok(get_3pids::v3::Response::new(Vec::new())) @@ -559,7 +561,7 @@ pub async fn third_party_route(body: Ruma) -> Result, ) -> Result { Err(Error::BadRequest( @@ -575,7 +577,7 @@ pub async fn request_3pid_management_token_via_email_route( /// /// - 403 signals that The homeserver does not allow the third party identifier /// as a contact option. -pub async fn request_3pid_management_token_via_msisdn_route( +pub(crate) async fn request_3pid_management_token_via_msisdn_route( _body: Ruma, ) -> Result { Err(Error::BadRequest( diff --git a/src/api/client_server/alias.rs b/src/api/client_server/alias.rs index 045d1174..1fb78792 100644 --- a/src/api/client_server/alias.rs +++ b/src/api/client_server/alias.rs @@ -17,7 +17,7 @@ use crate::{debug_info, debug_warn, services, Error, Result, Ruma}; /// # `PUT /_matrix/client/v3/directory/room/{roomAlias}` /// /// Creates a new room alias on this server. -pub async fn create_alias_route(body: Ruma) -> Result { +pub(crate) async fn create_alias_route(body: Ruma) -> Result { if body.room_alias.server_name() != services().globals.server_name() { return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server.")); } @@ -72,7 +72,7 @@ pub async fn create_alias_route(body: Ruma) -> Result /// /// - TODO: additional access control checks /// - TODO: Update canonical alias event -pub async fn delete_alias_route(body: Ruma) -> Result { +pub(crate) async fn delete_alias_route(body: Ruma) -> Result { if body.room_alias.server_name() != services().globals.server_name() { return Err(Error::BadRequest(ErrorKind::InvalidParam, "Alias is from another server.")); } @@ -118,7 +118,7 @@ pub async fn delete_alias_route(body: Ruma) -> Result /// # `GET /_matrix/client/v3/directory/room/{roomAlias}` /// /// Resolve an alias locally or over federation. -pub async fn get_alias_route(body: Ruma) -> Result { +pub(crate) async fn get_alias_route(body: Ruma) -> Result { get_alias_helper(body.body.room_alias, None).await } diff --git a/src/api/client_server/backup.rs b/src/api/client_server/backup.rs index 517a2f60..dffcd011 100644 --- a/src/api/client_server/backup.rs +++ b/src/api/client_server/backup.rs @@ -13,7 +13,7 @@ use crate::{services, Error, Result, Ruma}; /// # `POST /_matrix/client/r0/room_keys/version` /// /// Creates a new backup. -pub async fn create_backup_version_route( +pub(crate) async fn create_backup_version_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -30,7 +30,7 @@ pub async fn create_backup_version_route( /// /// Update information about an existing backup. Only `auth_data` can be /// modified. -pub async fn update_backup_version_route( +pub(crate) async fn update_backup_version_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -44,7 +44,7 @@ pub async fn update_backup_version_route( /// # `GET /_matrix/client/r0/room_keys/version` /// /// Get information about the latest backup version. -pub async fn get_latest_backup_info_route( +pub(crate) async fn get_latest_backup_info_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -65,7 +65,9 @@ pub async fn get_latest_backup_info_route( /// # `GET /_matrix/client/r0/room_keys/version` /// /// Get information about an existing backup. -pub async fn get_backup_info_route(body: Ruma) -> Result { +pub(crate) async fn get_backup_info_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let algorithm = services() .key_backups @@ -91,7 +93,7 @@ pub async fn get_backup_info_route(body: Ruma) -> /// /// - Deletes both information about the backup, as well as all key data related /// to the backup -pub async fn delete_backup_version_route( +pub(crate) async fn delete_backup_version_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -111,7 +113,9 @@ pub async fn delete_backup_version_route( /// allowed /// - Adds the keys to the backup /// - Returns the new number of keys in this backup and the etag -pub async fn add_backup_keys_route(body: Ruma) -> Result { +pub(crate) async fn add_backup_keys_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if Some(&body.version) @@ -153,7 +157,7 @@ pub async fn add_backup_keys_route(body: Ruma) -> /// allowed /// - Adds the keys to the backup /// - Returns the new number of keys in this backup and the etag -pub async fn add_backup_keys_for_room_route( +pub(crate) async fn add_backup_keys_for_room_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -195,7 +199,7 @@ pub async fn add_backup_keys_for_room_route( /// allowed /// - Adds the keys to the backup /// - Returns the new number of keys in this backup and the etag -pub async fn add_backup_keys_for_session_route( +pub(crate) async fn add_backup_keys_for_session_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -230,7 +234,9 @@ pub async fn add_backup_keys_for_session_route( /// # `GET /_matrix/client/r0/room_keys/keys` /// /// Retrieves all keys from the backup. -pub async fn get_backup_keys_route(body: Ruma) -> Result { +pub(crate) async fn get_backup_keys_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let rooms = services().key_backups.get_all(sender_user, &body.version)?; @@ -243,7 +249,7 @@ pub async fn get_backup_keys_route(body: Ruma) -> /// # `GET /_matrix/client/r0/room_keys/keys/{roomId}` /// /// Retrieves all keys from the backup for a given room. -pub async fn get_backup_keys_for_room_route( +pub(crate) async fn get_backup_keys_for_room_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -260,7 +266,7 @@ pub async fn get_backup_keys_for_room_route( /// # `GET /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}` /// /// Retrieves a key from the backup. -pub async fn get_backup_keys_for_session_route( +pub(crate) async fn get_backup_keys_for_session_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -281,7 +287,7 @@ pub async fn get_backup_keys_for_session_route( /// # `DELETE /_matrix/client/r0/room_keys/keys` /// /// Delete the keys from the backup. -pub async fn delete_backup_keys_route( +pub(crate) async fn delete_backup_keys_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -304,7 +310,7 @@ pub async fn delete_backup_keys_route( /// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}` /// /// Delete the keys from the backup for a given room. -pub async fn delete_backup_keys_for_room_route( +pub(crate) async fn delete_backup_keys_for_room_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -327,7 +333,7 @@ pub async fn delete_backup_keys_for_room_route( /// # `DELETE /_matrix/client/r0/room_keys/keys/{roomId}/{sessionId}` /// /// Delete a key from the backup. -pub async fn delete_backup_keys_for_session_route( +pub(crate) async fn delete_backup_keys_for_session_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/capabilities.rs b/src/api/client_server/capabilities.rs index 7aae8465..213430e1 100644 --- a/src/api/client_server/capabilities.rs +++ b/src/api/client_server/capabilities.rs @@ -11,7 +11,7 @@ use crate::{services, Result, Ruma}; /// /// Get information on the supported feature set and other relevent capabilities /// of this server. -pub async fn get_capabilities_route( +pub(crate) async fn get_capabilities_route( _body: Ruma, ) -> Result { let mut available = BTreeMap::new(); diff --git a/src/api/client_server/config.rs b/src/api/client_server/config.rs index 247b4ef8..c67c9311 100644 --- a/src/api/client_server/config.rs +++ b/src/api/client_server/config.rs @@ -14,7 +14,7 @@ use crate::{services, Error, Result, Ruma}; /// # `PUT /_matrix/client/r0/user/{userId}/account_data/{type}` /// /// Sets some account data for the sender user. -pub async fn set_global_account_data_route( +pub(crate) async fn set_global_account_data_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -40,7 +40,7 @@ pub async fn set_global_account_data_route( /// # `PUT /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}` /// /// Sets some room account data for the sender user. -pub async fn set_room_account_data_route( +pub(crate) async fn set_room_account_data_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -66,7 +66,7 @@ pub async fn set_room_account_data_route( /// # `GET /_matrix/client/r0/user/{userId}/account_data/{type}` /// /// Gets some account data for the sender user. -pub async fn get_global_account_data_route( +pub(crate) async fn get_global_account_data_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -88,7 +88,7 @@ pub async fn get_global_account_data_route( /// # `GET /_matrix/client/r0/user/{userId}/rooms/{roomId}/account_data/{type}` /// /// Gets some room account data for the sender user. -pub async fn get_room_account_data_route( +pub(crate) async fn get_room_account_data_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/context.rs b/src/api/client_server/context.rs index 0b012219..260698cc 100644 --- a/src/api/client_server/context.rs +++ b/src/api/client_server/context.rs @@ -15,7 +15,7 @@ use crate::{services, Error, Result, Ruma}; /// - Only works if the user is joined (TODO: always allow, but only show events /// if the user was /// joined, depending on history_visibility) -pub async fn get_context_route(body: Ruma) -> Result { +pub(crate) async fn get_context_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/device.rs b/src/api/client_server/device.rs index 10a38a73..c917ba77 100644 --- a/src/api/client_server/device.rs +++ b/src/api/client_server/device.rs @@ -10,7 +10,7 @@ use crate::{services, utils, Error, Result, Ruma}; /// # `GET /_matrix/client/r0/devices` /// /// Get metadata on all devices of the sender user. -pub async fn get_devices_route(body: Ruma) -> Result { +pub(crate) async fn get_devices_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let devices: Vec = services() @@ -27,7 +27,7 @@ pub async fn get_devices_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn get_device_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let device = services() @@ -43,7 +43,7 @@ pub async fn get_device_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn update_device_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let mut device = services() @@ -70,7 +70,7 @@ pub async fn update_device_route(body: Ruma) -> Resu /// last seen ts) /// - Forgets to-device events /// - Triggers device list updates -pub async fn delete_device_route(body: Ruma) -> Result { +pub(crate) async fn delete_device_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); @@ -122,7 +122,9 @@ pub async fn delete_device_route(body: Ruma) -> Resu /// last seen ts) /// - Forgets to-device events /// - Triggers device list updates -pub async fn delete_devices_route(body: Ruma) -> Result { +pub(crate) async fn delete_devices_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/directory.rs b/src/api/client_server/directory.rs index f1d70e9a..563f7e08 100644 --- a/src/api/client_server/directory.rs +++ b/src/api/client_server/directory.rs @@ -31,7 +31,7 @@ use crate::{services, Error, Result, Ruma}; /// Lists the public rooms on this server. /// /// - Rooms are ordered by the number of joined members -pub async fn get_public_rooms_filtered_route( +pub(crate) async fn get_public_rooms_filtered_route( body: Ruma, ) -> Result { if let Some(server) = &body.server { @@ -68,7 +68,7 @@ pub async fn get_public_rooms_filtered_route( /// Lists the public rooms on this server. /// /// - Rooms are ordered by the number of joined members -pub async fn get_public_rooms_route( +pub(crate) async fn get_public_rooms_route( body: Ruma, ) -> Result { if let Some(server) = &body.server { @@ -110,7 +110,7 @@ pub async fn get_public_rooms_route( /// Sets the visibility of a given room in the room directory. /// /// - TODO: Access control checks -pub async fn set_room_visibility_route( +pub(crate) async fn set_room_visibility_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -153,7 +153,7 @@ pub async fn set_room_visibility_route( /// # `GET /_matrix/client/r0/directory/list/room/{roomId}` /// /// Gets the visibility of a given room in the room directory. -pub async fn get_room_visibility_route( +pub(crate) async fn get_room_visibility_route( body: Ruma, ) -> Result { if !services().rooms.metadata.exists(&body.room_id)? { diff --git a/src/api/client_server/filter.rs b/src/api/client_server/filter.rs index f0e0f38c..5a161400 100644 --- a/src/api/client_server/filter.rs +++ b/src/api/client_server/filter.rs @@ -10,7 +10,7 @@ use crate::{services, Error, Result, Ruma}; /// Loads a filter that was previously created. /// /// - A user can only access their own filters -pub async fn get_filter_route(body: Ruma) -> Result { +pub(crate) async fn get_filter_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let Some(filter) = services().users.get_filter(sender_user, &body.filter_id)? else { return Err(Error::BadRequest(ErrorKind::NotFound, "Filter not found.")); @@ -22,7 +22,7 @@ pub async fn get_filter_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn create_filter_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); Ok(create_filter::v3::Response::new( services().users.create_filter(sender_user, &body.filter)?, diff --git a/src/api/client_server/keys.rs b/src/api/client_server/keys.rs index 0e717406..f58ea248 100644 --- a/src/api/client_server/keys.rs +++ b/src/api/client_server/keys.rs @@ -29,7 +29,7 @@ use crate::{services, utils, Error, Result, Ruma}; /// - Adds one time keys /// - If there are no device keys yet: Adds device keys (TODO: merge with /// existing keys?) -pub async fn upload_keys_route(body: Ruma) -> Result { +pub(crate) async fn upload_keys_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); @@ -68,7 +68,7 @@ pub async fn upload_keys_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn get_keys_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let response = get_keys_helper( @@ -85,7 +85,7 @@ pub async fn get_keys_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn claim_keys_route(body: Ruma) -> Result { let response = claim_keys_helper(&body.one_time_keys).await?; Ok(response) @@ -96,7 +96,7 @@ pub async fn claim_keys_route(body: Ruma) -> Result, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -147,7 +147,7 @@ pub async fn upload_signing_keys_route( /// # `POST /_matrix/client/r0/keys/signatures/upload` /// /// Uploads end-to-end key signatures from the sender user. -pub async fn upload_signatures_route( +pub(crate) async fn upload_signatures_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -193,7 +193,9 @@ pub async fn upload_signatures_route( /// previous sync token. /// /// - TODO: left users -pub async fn get_key_changes_route(body: Ruma) -> Result { +pub(crate) async fn get_key_changes_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let mut device_list_updates = HashSet::new(); diff --git a/src/api/client_server/media.rs b/src/api/client_server/media.rs index 0e544aa6..4021d8cc 100644 --- a/src/api/client_server/media.rs +++ b/src/api/client_server/media.rs @@ -24,7 +24,7 @@ const MXC_LENGTH: usize = 32; /// # `GET /_matrix/media/v3/config` /// /// Returns max upload size. -pub async fn get_media_config_route( +pub(crate) async fn get_media_config_route( _body: Ruma, ) -> Result { Ok(get_media_config::v3::Response { @@ -39,7 +39,7 @@ pub async fn get_media_config_route( /// See /// /// Returns max upload size. -pub async fn get_media_config_v1_route( +pub(crate) async fn get_media_config_v1_route( _body: Ruma, ) -> Result> { Ok(get_media_config::v3::Response { @@ -51,7 +51,7 @@ pub async fn get_media_config_v1_route( /// # `GET /_matrix/media/v3/preview_url` /// /// Returns URL preview. -pub async fn get_media_preview_route( +pub(crate) async fn get_media_preview_route( body: Ruma, ) -> Result { let url = &body.url; @@ -95,7 +95,7 @@ pub async fn get_media_preview_route( /// See /// /// Returns URL preview. -pub async fn get_media_preview_v1_route( +pub(crate) async fn get_media_preview_v1_route( body: Ruma, ) -> Result> { let url = &body.url; @@ -138,7 +138,9 @@ pub async fn get_media_preview_v1_route( /// /// - Some metadata will be saved in the database /// - Media will be saved in the media/ directory -pub async fn create_content_route(body: Ruma) -> Result { +pub(crate) async fn create_content_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let mxc = format!( @@ -179,7 +181,7 @@ pub async fn create_content_route(body: Ruma) -> Re /// /// - Some metadata will be saved in the database /// - Media will be saved in the media/ directory -pub async fn create_content_v1_route( +pub(crate) async fn create_content_v1_route( body: Ruma, ) -> Result> { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -214,7 +216,7 @@ pub async fn create_content_v1_route( } /// helper method to fetch remote media from other servers over federation -pub async fn get_remote_content( +pub(crate) async fn get_remote_content( mxc: &str, server_name: &ruma::ServerName, media_id: String, allow_redirect: bool, timeout_ms: Duration, ) -> Result { // we'll lie to the client and say the blocked server's media was not found and @@ -267,7 +269,7 @@ pub async fn get_remote_content( /// - Only redirects if `allow_redirect` is true /// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// seconds -pub async fn get_content_route(body: Ruma) -> Result { +pub(crate) async fn get_content_route(body: Ruma) -> Result { let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); if let Some(FileMeta { @@ -310,7 +312,7 @@ pub async fn get_content_route(body: Ruma) -> Result, ) -> Result> { let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); @@ -352,7 +354,7 @@ pub async fn get_content_v1_route( /// - Only redirects if `allow_redirect` is true /// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// seconds -pub async fn get_content_as_filename_route( +pub(crate) async fn get_content_as_filename_route( body: Ruma, ) -> Result { let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); @@ -404,7 +406,7 @@ pub async fn get_content_as_filename_route( /// - Only redirects if `allow_redirect` is true /// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// seconds -pub async fn get_content_as_filename_v1_route( +pub(crate) async fn get_content_as_filename_v1_route( body: Ruma, ) -> Result> { let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); @@ -454,7 +456,7 @@ pub async fn get_content_as_filename_v1_route( /// - Only redirects if `allow_redirect` is true /// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// seconds -pub async fn get_content_thumbnail_route( +pub(crate) async fn get_content_thumbnail_route( body: Ruma, ) -> Result { let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); @@ -545,7 +547,7 @@ pub async fn get_content_thumbnail_route( /// - Only redirects if `allow_redirect` is true /// - Uses client-provided `timeout_ms` if available, else defaults to 20 /// seconds -pub async fn get_content_thumbnail_v1_route( +pub(crate) async fn get_content_thumbnail_v1_route( body: Ruma, ) -> Result> { let mxc = format!("mxc://{}/{}", body.server_name, body.media_id); diff --git a/src/api/client_server/membership.rs b/src/api/client_server/membership.rs index 0c5744c3..afbe5ab4 100644 --- a/src/api/client_server/membership.rs +++ b/src/api/client_server/membership.rs @@ -45,7 +45,9 @@ use crate::{ /// rules locally /// - If the server does not know about the room: asks other servers over /// federation -pub async fn join_room_by_id_route(body: Ruma) -> Result { +pub(crate) async fn join_room_by_id_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if services().rooms.metadata.is_banned(&body.room_id)? && !services().users.is_admin(sender_user)? { @@ -118,7 +120,7 @@ pub async fn join_room_by_id_route(body: Ruma) -> /// - If the server does not know about the room: use the server name query /// param if specified. if not specified, asks other servers over federation /// via room alias server name and room ID server name -pub async fn join_room_by_id_or_alias_route( +pub(crate) async fn join_room_by_id_or_alias_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_deref().expect("user is authenticated"); @@ -291,7 +293,7 @@ pub async fn join_room_by_id_or_alias_route( /// Tries to leave the sender user from a room. /// /// - This should always work if the user is currently joined. -pub async fn leave_room_route(body: Ruma) -> Result { +pub(crate) async fn leave_room_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); leave_room(sender_user, &body.room_id, body.reason.clone()).await?; @@ -302,7 +304,7 @@ pub async fn leave_room_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn invite_user_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if !services().users.is_admin(sender_user)? && services().globals.block_non_admin_invites() { @@ -355,7 +357,7 @@ pub async fn invite_user_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn kick_user_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if let Ok(true) = services() @@ -420,7 +422,7 @@ pub async fn kick_user_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn ban_user_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if let Ok(Some(membership_event)) = services() @@ -506,7 +508,7 @@ pub async fn ban_user_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn unban_user_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if let Ok(Some(membership_event)) = services() @@ -577,7 +579,7 @@ pub async fn unban_user_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn forget_room_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); services() @@ -591,7 +593,7 @@ pub async fn forget_room_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn joined_rooms_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); Ok(joined_rooms::v3::Response { @@ -610,7 +612,7 @@ pub async fn joined_rooms_route(body: Ruma) -> Result /// specific membership). /// /// - Only works if the user is currently joined -pub async fn get_member_events_route( +pub(crate) async fn get_member_events_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -645,7 +647,9 @@ pub async fn get_member_events_route( /// /// - The sender user must be in the room /// - TODO: An appservice just needs a puppet joined -pub async fn joined_members_route(body: Ruma) -> Result { +pub(crate) async fn joined_members_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if !services() @@ -1600,7 +1604,7 @@ pub(crate) async fn invite_helper( } // Make a user leave all their joined rooms -pub async fn leave_all_rooms(user_id: &UserId) -> Result<()> { +pub(crate) async fn leave_all_rooms(user_id: &UserId) -> Result<()> { let all_rooms = services() .rooms .state_cache @@ -1626,7 +1630,7 @@ pub async fn leave_all_rooms(user_id: &UserId) -> Result<()> { Ok(()) } -pub async fn leave_room(user_id: &UserId, room_id: &RoomId, reason: Option) -> Result<()> { +pub(crate) async fn leave_room(user_id: &UserId, room_id: &RoomId, reason: Option) -> Result<()> { // Ask a remote server if we don't have this room if !services() .rooms diff --git a/src/api/client_server/message.rs b/src/api/client_server/message.rs index 765dd595..3a30ed15 100644 --- a/src/api/client_server/message.rs +++ b/src/api/client_server/message.rs @@ -28,7 +28,7 @@ use crate::{ /// - The only requirement for the content is that it has to be valid json /// - Tries to send the event into the room, auth rules will determine if it is /// allowed -pub async fn send_message_event_route( +pub(crate) async fn send_message_event_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -119,7 +119,7 @@ pub async fn send_message_event_route( /// - Only works if the user is joined (TODO: always allow, but only show events /// where the user was /// joined, depending on `history_visibility`) -pub async fn get_message_events_route( +pub(crate) async fn get_message_events_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/mod.rs b/src/api/client_server/mod.rs index 1aac4aaa..59d851bf 100644 --- a/src/api/client_server/mod.rs +++ b/src/api/client_server/mod.rs @@ -34,50 +34,50 @@ mod unversioned; mod user_directory; mod voip; -pub use account::*; -pub use alias::*; -pub use backup::*; -pub use capabilities::*; -pub use config::*; -pub use context::*; -pub use device::*; -pub use directory::*; -pub use filter::*; -pub use keys::*; -pub use media::*; -pub use membership::*; -pub use message::*; -pub use presence::*; -pub use profile::*; -pub use push::*; -pub use read_marker::*; -pub use redact::*; -pub use relations::*; -pub use report::*; -pub use room::*; -pub use search::*; -pub use session::*; -pub use space::*; -pub use state::*; -pub use sync::*; -pub use tag::*; -pub use thirdparty::*; -pub use threads::*; -pub use to_device::*; -pub use typing::*; -pub use unstable::*; -pub use unversioned::*; -pub use user_directory::*; -pub use voip::*; +pub(crate) use account::*; +pub(crate) use alias::*; +pub(crate) use backup::*; +pub(crate) use capabilities::*; +pub(crate) use config::*; +pub(crate) use context::*; +pub(crate) use device::*; +pub(crate) use directory::*; +pub(crate) use filter::*; +pub(crate) use keys::*; +pub(crate) use media::*; +pub(crate) use membership::*; +pub(crate) use message::*; +pub(crate) use presence::*; +pub(crate) use profile::*; +pub(crate) use push::*; +pub(crate) use read_marker::*; +pub(crate) use redact::*; +pub(crate) use relations::*; +pub(crate) use report::*; +pub(crate) use room::*; +pub(crate) use search::*; +pub(crate) use session::*; +pub(crate) use space::*; +pub(crate) use state::*; +pub(crate) use sync::*; +pub(crate) use tag::*; +pub(crate) use thirdparty::*; +pub(crate) use threads::*; +pub(crate) use to_device::*; +pub(crate) use typing::*; +pub(crate) use unstable::*; +pub(crate) use unversioned::*; +pub(crate) use user_directory::*; +pub(crate) use voip::*; /// generated device ID length -pub const DEVICE_ID_LENGTH: usize = 10; +const DEVICE_ID_LENGTH: usize = 10; /// generated user access token length -pub const TOKEN_LENGTH: usize = 32; +const TOKEN_LENGTH: usize = 32; /// generated user session ID length -pub const SESSION_ID_LENGTH: usize = 32; +pub(crate) const SESSION_ID_LENGTH: usize = 32; /// auto-generated password length -pub const AUTO_GEN_PASSWORD_LENGTH: usize = 25; +pub(crate) const AUTO_GEN_PASSWORD_LENGTH: usize = 25; diff --git a/src/api/client_server/presence.rs b/src/api/client_server/presence.rs index 424fe105..29310b42 100644 --- a/src/api/client_server/presence.rs +++ b/src/api/client_server/presence.rs @@ -10,7 +10,7 @@ use crate::{services, Error, Result, Ruma}; /// # `PUT /_matrix/client/r0/presence/{userId}/status` /// /// Sets the presence state of the sender user. -pub async fn set_presence_route(body: Ruma) -> Result { +pub(crate) async fn set_presence_route(body: Ruma) -> Result { if !services().globals.allow_local_presence() { return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server")); } @@ -28,7 +28,7 @@ pub async fn set_presence_route(body: Ruma) -> Result /// Gets the presence state of the given user. /// /// - Only works if you share a room with the user -pub async fn get_presence_route(body: Ruma) -> Result { +pub(crate) async fn get_presence_route(body: Ruma) -> Result { if !services().globals.allow_local_presence() { return Err(Error::BadRequest(ErrorKind::forbidden(), "Presence is disabled on this server")); } diff --git a/src/api/client_server/profile.rs b/src/api/client_server/profile.rs index 083a3073..68a12db0 100644 --- a/src/api/client_server/profile.rs +++ b/src/api/client_server/profile.rs @@ -20,7 +20,7 @@ use crate::{service::pdu::PduBuilder, services, Error, Result, Ruma}; /// Updates the displayname. /// /// - Also makes sure other users receive the update using presence EDUs -pub async fn set_displayname_route( +pub(crate) async fn set_displayname_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -102,7 +102,7 @@ pub async fn set_displayname_route( /// /// - If user is on another server and we do not have a local copy already /// fetch displayname over federation -pub async fn get_displayname_route( +pub(crate) async fn get_displayname_route( body: Ruma, ) -> Result { if body.user_id.server_name() != services().globals.server_name() { @@ -157,7 +157,9 @@ pub async fn get_displayname_route( /// Updates the `avatar_url` and `blurhash`. /// /// - Also makes sure other users receive the update using presence EDUs -pub async fn set_avatar_url_route(body: Ruma) -> Result { +pub(crate) async fn set_avatar_url_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); services() @@ -242,7 +244,9 @@ pub async fn set_avatar_url_route(body: Ruma) -> Re /// /// - If user is on another server and we do not have a local copy already /// fetch `avatar_url` and blurhash over federation -pub async fn get_avatar_url_route(body: Ruma) -> Result { +pub(crate) async fn get_avatar_url_route( + body: Ruma, +) -> Result { if body.user_id.server_name() != services().globals.server_name() { // Create and update our local copy of the user if let Ok(response) = services() @@ -298,7 +302,7 @@ pub async fn get_avatar_url_route(body: Ruma) -> Re /// /// - If user is on another server and we do not have a local copy already, /// fetch profile over federation. -pub async fn get_profile_route(body: Ruma) -> Result { +pub(crate) async fn get_profile_route(body: Ruma) -> Result { if body.user_id.server_name() != services().globals.server_name() { // Create and update our local copy of the user if let Ok(response) = services() diff --git a/src/api/client_server/push.rs b/src/api/client_server/push.rs index 71d937a6..a928f9d9 100644 --- a/src/api/client_server/push.rs +++ b/src/api/client_server/push.rs @@ -15,7 +15,7 @@ use crate::{services, Error, Result, Ruma}; /// # `GET /_matrix/client/r0/pushrules/` /// /// Retrieves the push rules event for this user. -pub async fn get_pushrules_all_route( +pub(crate) async fn get_pushrules_all_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -55,7 +55,7 @@ pub async fn get_pushrules_all_route( /// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// /// Retrieves a single specified push rule for this user. -pub async fn get_pushrule_route(body: Ruma) -> Result { +pub(crate) async fn get_pushrule_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let event = services() @@ -84,7 +84,7 @@ pub async fn get_pushrule_route(body: Ruma) -> Result /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// /// Creates a single specified push rule for this user. -pub async fn set_pushrule_route(body: Ruma) -> Result { +pub(crate) async fn set_pushrule_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let body = body.body; @@ -147,7 +147,7 @@ pub async fn set_pushrule_route(body: Ruma) -> Result /// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions` /// /// Gets the actions of a single specified push rule for this user. -pub async fn get_pushrule_actions_route( +pub(crate) async fn get_pushrule_actions_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -182,7 +182,7 @@ pub async fn get_pushrule_actions_route( /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/actions` /// /// Sets the actions of a single specified push rule for this user. -pub async fn set_pushrule_actions_route( +pub(crate) async fn set_pushrule_actions_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -224,7 +224,7 @@ pub async fn set_pushrule_actions_route( /// # `GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled` /// /// Gets the enabled status of a single specified push rule for this user. -pub async fn get_pushrule_enabled_route( +pub(crate) async fn get_pushrule_enabled_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -258,7 +258,7 @@ pub async fn get_pushrule_enabled_route( /// # `PUT /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled` /// /// Sets the enabled status of a single specified push rule for this user. -pub async fn set_pushrule_enabled_route( +pub(crate) async fn set_pushrule_enabled_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -300,7 +300,9 @@ pub async fn set_pushrule_enabled_route( /// # `DELETE /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}` /// /// Deletes a single specified push rule for this user. -pub async fn delete_pushrule_route(body: Ruma) -> Result { +pub(crate) async fn delete_pushrule_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if body.scope != RuleScope::Global { @@ -347,7 +349,7 @@ pub async fn delete_pushrule_route(body: Ruma) -> /// # `GET /_matrix/client/r0/pushers` /// /// Gets all currently active pushers for the sender user. -pub async fn get_pushers_route(body: Ruma) -> Result { +pub(crate) async fn get_pushers_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); Ok(get_pushers::v3::Response { @@ -360,7 +362,7 @@ pub async fn get_pushers_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn set_pushers_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); services() diff --git a/src/api/client_server/read_marker.rs b/src/api/client_server/read_marker.rs index 607b5aba..f3d6c362 100644 --- a/src/api/client_server/read_marker.rs +++ b/src/api/client_server/read_marker.rs @@ -18,7 +18,9 @@ use crate::{service::rooms::timeline::PduCount, services, Error, Result, Ruma}; /// - Updates fully-read account data event to `fully_read` /// - If `read_receipt` is set: Update private marker and public read receipt /// EDU -pub async fn set_read_marker_route(body: Ruma) -> Result { +pub(crate) async fn set_read_marker_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if let Some(fully_read) = &body.fully_read { @@ -95,7 +97,9 @@ pub async fn set_read_marker_route(body: Ruma) -> /// # `POST /_matrix/client/r0/rooms/{roomId}/receipt/{receiptType}/{eventId}` /// /// Sets private read marker and public read receipt EDU. -pub async fn create_receipt_route(body: Ruma) -> Result { +pub(crate) async fn create_receipt_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if matches!( diff --git a/src/api/client_server/redact.rs b/src/api/client_server/redact.rs index 8e71bd3b..d92ef002 100644 --- a/src/api/client_server/redact.rs +++ b/src/api/client_server/redact.rs @@ -13,7 +13,7 @@ use crate::{service::pdu::PduBuilder, services, Result, Ruma}; /// Tries to send a redaction event into the room. /// /// - TODO: Handle txn id -pub async fn redact_event_route(body: Ruma) -> Result { +pub(crate) async fn redact_event_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let body = body.body; diff --git a/src/api/client_server/relations.rs b/src/api/client_server/relations.rs index f2ddfecb..fb366bdc 100644 --- a/src/api/client_server/relations.rs +++ b/src/api/client_server/relations.rs @@ -5,7 +5,7 @@ use ruma::api::client::relations::{ use crate::{services, Result, Ruma}; /// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}/{eventType}` -pub async fn get_relating_events_with_rel_type_and_event_type_route( +pub(crate) async fn get_relating_events_with_rel_type_and_event_type_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -35,7 +35,7 @@ pub async fn get_relating_events_with_rel_type_and_event_type_route( } /// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}/{relType}` -pub async fn get_relating_events_with_rel_type_route( +pub(crate) async fn get_relating_events_with_rel_type_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -65,7 +65,7 @@ pub async fn get_relating_events_with_rel_type_route( } /// # `GET /_matrix/client/r0/rooms/{roomId}/relations/{eventId}` -pub async fn get_relating_events_route( +pub(crate) async fn get_relating_events_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/report.rs b/src/api/client_server/report.rs index 86ba91f8..ee8f2e75 100644 --- a/src/api/client_server/report.rs +++ b/src/api/client_server/report.rs @@ -14,7 +14,9 @@ use crate::{services, utils::HtmlEscape, Error, Result, Ruma}; /// # `POST /_matrix/client/v3/rooms/{roomId}/report/{eventId}` /// /// Reports an inappropriate event to homeserver admins -pub async fn report_event_route(body: Ruma) -> Result { +pub(crate) async fn report_event_route( + body: Ruma, +) -> Result { // user authentication let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/room.rs b/src/api/client_server/room.rs index 78ba5142..8f629414 100644 --- a/src/api/client_server/room.rs +++ b/src/api/client_server/room.rs @@ -45,7 +45,7 @@ use crate::{api::client_server::invite_helper, service::pdu::PduBuilder, service /// - Send events listed in initial state /// - Send events implied by `name` and `topic` /// - Send invite events -pub async fn create_room_route(body: Ruma) -> Result { +pub(crate) async fn create_room_route(body: Ruma) -> Result { use create_room::v3::RoomPreset; let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -603,7 +603,9 @@ pub async fn create_room_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn get_room_event_route( + body: Ruma, +) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let event = services() @@ -640,7 +642,7 @@ pub async fn get_room_event_route(body: Ruma) -> Re /// /// - Only users joined to the room are allowed to call this, or if /// `history_visibility` is world readable in the room -pub async fn get_room_aliases_route(body: Ruma) -> Result { +pub(crate) async fn get_room_aliases_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if !services() @@ -674,7 +676,7 @@ pub async fn get_room_aliases_route(body: Ruma) -> Result< /// - Transfers some state events /// - Moves local aliases /// - Modifies old room power levels to prevent users from speaking -pub async fn upgrade_room_route(body: Ruma) -> Result { +pub(crate) async fn upgrade_room_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); if !services() diff --git a/src/api/client_server/search.rs b/src/api/client_server/search.rs index d2a305d7..23072355 100644 --- a/src/api/client_server/search.rs +++ b/src/api/client_server/search.rs @@ -22,7 +22,7 @@ use crate::{services, Error, Result, Ruma}; /// /// - Only works if the user is currently joined to the room (TODO: Respect /// history visibility) -pub async fn search_events_route(body: Ruma) -> Result { +pub(crate) async fn search_events_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let search_criteria = body.search_categories.room_events.as_ref().unwrap(); diff --git a/src/api/client_server/session.rs b/src/api/client_server/session.rs index 21543637..554af631 100644 --- a/src/api/client_server/session.rs +++ b/src/api/client_server/session.rs @@ -33,7 +33,9 @@ struct Claims { /// /// Get the supported login types of this server. One of these should be used as /// the `type` field when logging in. -pub async fn get_login_types_route(_body: Ruma) -> Result { +pub(crate) async fn get_login_types_route( + _body: Ruma, +) -> Result { Ok(get_login_types::v3::Response::new(vec![ get_login_types::v3::LoginType::Password(PasswordLoginType::default()), get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()), @@ -54,7 +56,7 @@ pub async fn get_login_types_route(_body: Ruma) -> /// Note: You can use [`GET /// /_matrix/client/r0/login`](fn.get_supported_versions_route.html) to see /// supported login types. -pub async fn login_route(body: Ruma) -> Result { +pub(crate) async fn login_route(body: Ruma) -> Result { // Validate login method // TODO: Other login methods let user_id = match &body.login_info { @@ -235,7 +237,7 @@ pub async fn login_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn logout_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_device = body.sender_device.as_ref().expect("user is authenticated"); @@ -260,7 +262,7 @@ pub async fn logout_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn logout_all_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); for device_id in services().users.all_device_ids(sender_user).flatten() { diff --git a/src/api/client_server/space.rs b/src/api/client_server/space.rs index acce261e..69ccbc70 100644 --- a/src/api/client_server/space.rs +++ b/src/api/client_server/space.rs @@ -11,7 +11,7 @@ use crate::{service::rooms::spaces::PagnationToken, services, Error, Result, Rum /// /// Paginates over the space tree in a depth-first manner to locate child rooms /// of a given space. -pub async fn get_hierarchy_route(body: Ruma) -> Result { +pub(crate) async fn get_hierarchy_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let limit = body diff --git a/src/api/client_server/state.rs b/src/api/client_server/state.rs index 1476b892..b895b949 100644 --- a/src/api/client_server/state.rs +++ b/src/api/client_server/state.rs @@ -31,7 +31,7 @@ use crate::{ /// - Tries to send the event into the room, auth rules will determine if it is /// allowed /// - If event is new `canonical_alias`: Rejects if alias is incorrect -pub async fn send_state_event_for_key_route( +pub(crate) async fn send_state_event_for_key_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -59,7 +59,7 @@ pub async fn send_state_event_for_key_route( /// - Tries to send the event into the room, auth rules will determine if it is /// allowed /// - If event is new `canonical_alias`: Rejects if alias is incorrect -pub async fn send_state_event_for_empty_key_route( +pub(crate) async fn send_state_event_for_empty_key_route( body: Ruma, ) -> Result> { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -86,7 +86,7 @@ pub async fn send_state_event_for_empty_key_route( /// /// - If not joined: Only works if current room history visibility is world /// readable -pub async fn get_state_events_route( +pub(crate) async fn get_state_events_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -122,7 +122,7 @@ pub async fn get_state_events_route( /// /// - If not joined: Only works if current room history visibility is world /// readable -pub async fn get_state_events_for_key_route( +pub(crate) async fn get_state_events_for_key_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); @@ -177,7 +177,7 @@ pub async fn get_state_events_for_key_route( /// /// - If not joined: Only works if current room history visibility is world /// readable -pub async fn get_state_events_for_empty_key_route( +pub(crate) async fn get_state_events_for_empty_key_route( body: Ruma, ) -> Result> { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/sync.rs b/src/api/client_server/sync.rs index ef891621..d3079d61 100644 --- a/src/api/client_server/sync.rs +++ b/src/api/client_server/sync.rs @@ -77,7 +77,7 @@ use crate::{ /// - Sync is handled in an async task, multiple requests from the same device /// with the same /// `since` will be cached -pub async fn sync_events_route( +pub(crate) async fn sync_events_route( body: Ruma, ) -> Result> { let sender_user = body.sender_user.expect("user is authenticated"); @@ -1172,7 +1172,7 @@ fn share_encrypted_room(sender_user: &UserId, user_id: &UserId, ignore_room: &Ro /// POST `/_matrix/client/unstable/org.matrix.msc3575/sync` /// /// Sliding Sync endpoint (future endpoint: `/_matrix/client/v4/sync`) -pub async fn sync_events_v4_route( +pub(crate) async fn sync_events_v4_route( body: Ruma, ) -> Result> { let sender_user = body.sender_user.expect("user is authenticated"); diff --git a/src/api/client_server/tag.rs b/src/api/client_server/tag.rs index eb00e9fd..9fb60bc6 100644 --- a/src/api/client_server/tag.rs +++ b/src/api/client_server/tag.rs @@ -15,7 +15,7 @@ use crate::{services, Error, Result, Ruma}; /// Adds a tag to the room. /// /// - Inserts the tag into the tag event of the room account data. -pub async fn update_tag_route(body: Ruma) -> Result { +pub(crate) async fn update_tag_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let event = services() @@ -53,7 +53,7 @@ pub async fn update_tag_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn delete_tag_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let event = services() @@ -88,7 +88,7 @@ pub async fn delete_tag_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn get_tags_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let event = services() diff --git a/src/api/client_server/thirdparty.rs b/src/api/client_server/thirdparty.rs index f5de4c61..de24c0ec 100644 --- a/src/api/client_server/thirdparty.rs +++ b/src/api/client_server/thirdparty.rs @@ -7,7 +7,9 @@ use crate::{Result, Ruma}; /// # `GET /_matrix/client/r0/thirdparty/protocols` /// /// TODO: Fetches all metadata about protocols supported by the homeserver. -pub async fn get_protocols_route(_body: Ruma) -> Result { +pub(crate) async fn get_protocols_route( + _body: Ruma, +) -> Result { // TODO Ok(get_protocols::v3::Response { protocols: BTreeMap::new(), diff --git a/src/api/client_server/threads.rs b/src/api/client_server/threads.rs index c752d782..6b09f03c 100644 --- a/src/api/client_server/threads.rs +++ b/src/api/client_server/threads.rs @@ -3,7 +3,7 @@ use ruma::api::client::{error::ErrorKind, threads::get_threads}; use crate::{services, Error, Result, Ruma}; /// # `GET /_matrix/client/r0/rooms/{roomId}/threads` -pub async fn get_threads_route(body: Ruma) -> Result { +pub(crate) async fn get_threads_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); // Use limit or else 10, with maximum 100 diff --git a/src/api/client_server/to_device.rs b/src/api/client_server/to_device.rs index 128d3cda..15521aa8 100644 --- a/src/api/client_server/to_device.rs +++ b/src/api/client_server/to_device.rs @@ -13,7 +13,7 @@ use crate::{services, Error, Result, Ruma}; /// # `PUT /_matrix/client/r0/sendToDevice/{eventType}/{txnId}` /// /// Send a to-device event to a set of client devices. -pub async fn send_event_to_device_route( +pub(crate) async fn send_event_to_device_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/typing.rs b/src/api/client_server/typing.rs index 6dfdd97c..677906c0 100644 --- a/src/api/client_server/typing.rs +++ b/src/api/client_server/typing.rs @@ -5,7 +5,7 @@ use crate::{services, utils, Error, Result, Ruma}; /// # `PUT /_matrix/client/r0/rooms/{roomId}/typing/{userId}` /// /// Sets the typing state of the sender user. -pub async fn create_typing_event_route( +pub(crate) async fn create_typing_event_route( body: Ruma, ) -> Result { use create_typing_event::v3::Typing; diff --git a/src/api/client_server/unstable.rs b/src/api/client_server/unstable.rs index eb9fa0af..5fecfb71 100644 --- a/src/api/client_server/unstable.rs +++ b/src/api/client_server/unstable.rs @@ -12,7 +12,7 @@ use crate::{services, Error, Result, Ruma}; /// TODO: Implement pagination, currently this just returns everything /// /// An implementation of [MSC2666](https://github.com/matrix-org/matrix-spec-proposals/pull/2666) -pub async fn get_mutual_rooms_route( +pub(crate) async fn get_mutual_rooms_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/client_server/unversioned.rs b/src/api/client_server/unversioned.rs index 163837b0..c9dd1a4b 100644 --- a/src/api/client_server/unversioned.rs +++ b/src/api/client_server/unversioned.rs @@ -24,7 +24,7 @@ use crate::{services, Error, Result, Ruma}; /// /// Note: Unstable features are used while developing new features. Clients /// should avoid using unstable features in their stable releases -pub async fn get_supported_versions_route( +pub(crate) async fn get_supported_versions_route( _body: Ruma, ) -> Result { let resp = get_supported_versions::Response { @@ -60,7 +60,9 @@ pub async fn get_supported_versions_route( /// # `GET /.well-known/matrix/client` /// /// Returns the .well-known URL if it is configured, otherwise returns 404. -pub async fn well_known_client(_body: Ruma) -> Result { +pub(crate) async fn well_known_client( + _body: Ruma, +) -> Result { let client_url = match services().globals.well_known_client() { Some(url) => url.to_string(), None => return Err(Error::BadRequest(ErrorKind::NotFound, "Not found.")), @@ -81,7 +83,7 @@ pub async fn well_known_client(_body: Ruma) -> Res /// # `GET /.well-known/matrix/support` /// /// Server support contact and support page of a homeserver's domain. -pub async fn well_known_support(_body: Ruma) -> Result { +pub(crate) async fn well_known_support(_body: Ruma) -> Result { let support_page = services() .globals .well_known_support_page() @@ -131,7 +133,7 @@ pub async fn well_known_support(_body: Ruma) -> Resul /// /// Endpoint provided by sliding sync proxy used by some clients such as Element /// Web as a non-standard health check. -pub async fn syncv3_client_server_json() -> Result { +pub(crate) async fn syncv3_client_server_json() -> Result { let server_url = match services().globals.well_known_client() { Some(url) => url.to_string(), None => match services().globals.well_known_server() { @@ -155,7 +157,7 @@ pub async fn syncv3_client_server_json() -> Result { /// /// Conduwuit-specific API to get the server version, results akin to /// `/_matrix/federation/v1/version` -pub async fn conduwuit_server_version() -> Result { +pub(crate) async fn conduwuit_server_version() -> Result { let version = match option_env!("CONDUIT_VERSION_EXTRA") { Some(extra) => format!("{} ({})", env!("CARGO_PKG_VERSION"), extra), None => env!("CARGO_PKG_VERSION").to_owned(), diff --git a/src/api/client_server/user_directory.rs b/src/api/client_server/user_directory.rs index 418ad50c..c57f569e 100644 --- a/src/api/client_server/user_directory.rs +++ b/src/api/client_server/user_directory.rs @@ -15,7 +15,7 @@ use crate::{services, Result, Ruma}; /// - Hides any local users that aren't in any public rooms (i.e. those that /// have the join rule set to public) /// and don't share a room with the sender -pub async fn search_users_route(body: Ruma) -> Result { +pub(crate) async fn search_users_route(body: Ruma) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let limit = u64::from(body.limit) as usize; diff --git a/src/api/client_server/voip.rs b/src/api/client_server/voip.rs index 5bd10ea3..a3868824 100644 --- a/src/api/client_server/voip.rs +++ b/src/api/client_server/voip.rs @@ -12,7 +12,7 @@ type HmacSha1 = Hmac; /// # `GET /_matrix/client/r0/voip/turnServer` /// /// TODO: Returns information about the recommended turn server. -pub async fn turn_server_route( +pub(crate) async fn turn_server_route( body: Ruma, ) -> Result { let sender_user = body.sender_user.as_ref().expect("user is authenticated"); diff --git a/src/api/mod.rs b/src/api/mod.rs index 5c284757..285b9f51 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,3 +1,3 @@ -pub mod client_server; -pub mod ruma_wrapper; -pub mod server_server; +pub(crate) mod client_server; +pub(crate) mod ruma_wrapper; +pub(crate) mod server_server; diff --git a/src/api/ruma_wrapper/mod.rs b/src/api/ruma_wrapper/mod.rs index 0dd3a617..93474816 100644 --- a/src/api/ruma_wrapper/mod.rs +++ b/src/api/ruma_wrapper/mod.rs @@ -7,14 +7,13 @@ use crate::{service::appservice::RegistrationInfo, Error}; mod axum; /// Extractor for Ruma request structs -pub struct Ruma { - pub body: T, - pub sender_user: Option, - pub sender_device: Option, - pub sender_servername: Option, - // This is None when body is not a valid string - pub json_body: Option, - pub appservice_info: Option, +pub(crate) struct Ruma { + pub(crate) body: T, + pub(crate) sender_user: Option, + pub(crate) sender_device: Option, + pub(crate) sender_servername: Option, + pub(crate) json_body: Option, // This is None when body is not a valid string + pub(crate) appservice_info: Option, } impl Deref for Ruma { @@ -24,7 +23,7 @@ impl Deref for Ruma { } #[derive(Clone)] -pub struct RumaResponse(pub T); +pub(crate) struct RumaResponse(pub(crate) T); impl From for RumaResponse { fn from(t: T) -> Self { Self(t) } diff --git a/src/api/server_server.rs b/src/api/server_server.rs index 5dda87d3..1f4b983e 100644 --- a/src/api/server_server.rs +++ b/src/api/server_server.rs @@ -60,7 +60,7 @@ use crate::{ /// # `GET /_matrix/federation/v1/version` /// /// Get version information on this server. -pub async fn get_server_version_route( +pub(crate) async fn get_server_version_route( _body: Ruma, ) -> Result { let version = match option_env!("CONDUIT_VERSION_EXTRA") { @@ -85,7 +85,7 @@ pub async fn get_server_version_route( /// forever. // Response type for this endpoint is Json because we need to calculate a // signature for the response -pub async fn get_server_keys_route() -> Result { +pub(crate) async fn get_server_keys_route() -> Result { let mut verify_keys: BTreeMap = BTreeMap::new(); verify_keys.insert( format!("ed25519:{}", services().globals.keypair().version()) @@ -132,12 +132,12 @@ pub async fn get_server_keys_route() -> Result { /// - Matrix does not support invalidating public keys, so the key returned by /// this will be valid /// forever. -pub async fn get_server_keys_deprecated_route() -> impl IntoResponse { get_server_keys_route().await } +pub(crate) async fn get_server_keys_deprecated_route() -> impl IntoResponse { get_server_keys_route().await } /// # `POST /_matrix/federation/v1/publicRooms` /// /// Lists the public rooms on this server. -pub async fn get_public_rooms_filtered_route( +pub(crate) async fn get_public_rooms_filtered_route( body: Ruma, ) -> Result { if !services() @@ -171,7 +171,7 @@ pub async fn get_public_rooms_filtered_route( /// # `GET /_matrix/federation/v1/publicRooms` /// /// Lists the public rooms on this server. -pub async fn get_public_rooms_route( +pub(crate) async fn get_public_rooms_route( body: Ruma, ) -> Result { if !services() @@ -202,7 +202,7 @@ pub async fn get_public_rooms_route( }) } -pub fn parse_incoming_pdu(pdu: &RawJsonValue) -> Result<(OwnedEventId, CanonicalJsonObject, OwnedRoomId)> { +pub(crate) fn parse_incoming_pdu(pdu: &RawJsonValue) -> Result<(OwnedEventId, CanonicalJsonObject, OwnedRoomId)> { let value: CanonicalJsonObject = serde_json::from_str(pdu.get()).map_err(|e| { warn!("Error parsing incoming event {:?}: {:?}", pdu, e); Error::BadServerResponse("Invalid PDU in server response") @@ -231,7 +231,7 @@ pub fn parse_incoming_pdu(pdu: &RawJsonValue) -> Result<(OwnedEventId, Canonical /// # `PUT /_matrix/federation/v1/send/{txnId}` /// /// Push EDUs and PDUs to this server. -pub async fn send_transaction_message_route( +pub(crate) async fn send_transaction_message_route( body: Ruma, ) -> Result { let sender_servername = body @@ -522,7 +522,7 @@ pub async fn send_transaction_message_route( /// /// - Only works if a user of this server is currently invited or joined the /// room -pub async fn get_event_route(body: Ruma) -> Result { +pub(crate) async fn get_event_route(body: Ruma) -> Result { let sender_servername = body .sender_servername .as_ref() @@ -572,7 +572,7 @@ pub async fn get_event_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn get_backfill_route(body: Ruma) -> Result { let sender_servername = body .sender_servername .as_ref() @@ -635,7 +635,7 @@ pub async fn get_backfill_route(body: Ruma) -> Result /// # `POST /_matrix/federation/v1/get_missing_events/{roomId}` /// /// Retrieves events that the sender is missing. -pub async fn get_missing_events_route( +pub(crate) async fn get_missing_events_route( body: Ruma, ) -> Result { let sender_servername = body @@ -718,7 +718,7 @@ pub async fn get_missing_events_route( /// Retrieves the auth chain for a given event. /// /// - This does not include the event itself -pub async fn get_event_authorization_route( +pub(crate) async fn get_event_authorization_route( body: Ruma, ) -> Result { let sender_servername = body @@ -773,7 +773,9 @@ pub async fn get_event_authorization_route( /// # `GET /_matrix/federation/v1/state/{roomId}` /// /// Retrieves the current state of the room. -pub async fn get_room_state_route(body: Ruma) -> Result { +pub(crate) async fn get_room_state_route( + body: Ruma, +) -> Result { let sender_servername = body .sender_servername .as_ref() @@ -840,7 +842,7 @@ pub async fn get_room_state_route(body: Ruma) -> Re /// # `GET /_matrix/federation/v1/state_ids/{roomId}` /// /// Retrieves the current state of the room. -pub async fn get_room_state_ids_route( +pub(crate) async fn get_room_state_ids_route( body: Ruma, ) -> Result { let sender_servername = body @@ -891,7 +893,7 @@ pub async fn get_room_state_ids_route( /// # `GET /_matrix/federation/v1/make_join/{roomId}/{userId}` /// /// Creates a join template. -pub async fn create_join_event_template_route( +pub(crate) async fn create_join_event_template_route( body: Ruma, ) -> Result { if !services().rooms.metadata.exists(&body.room_id)? { @@ -1224,7 +1226,7 @@ async fn create_join_event( /// # `PUT /_matrix/federation/v1/send_join/{roomId}/{eventId}` /// /// Submits a signed join event. -pub async fn create_join_event_v1_route( +pub(crate) async fn create_join_event_v1_route( body: Ruma, ) -> Result { let sender_servername = body @@ -1278,7 +1280,7 @@ pub async fn create_join_event_v1_route( /// # `PUT /_matrix/federation/v2/send_join/{roomId}/{eventId}` /// /// Submits a signed join event. -pub async fn create_join_event_v2_route( +pub(crate) async fn create_join_event_v2_route( body: Ruma, ) -> Result { let sender_servername = body @@ -1338,7 +1340,7 @@ pub async fn create_join_event_v2_route( /// # `PUT /_matrix/federation/v1/make_leave/{roomId}/{eventId}` /// /// Creates a leave template. -pub async fn create_leave_event_template_route( +pub(crate) async fn create_leave_event_template_route( body: Ruma, ) -> Result { let sender_servername = body @@ -1490,7 +1492,7 @@ async fn create_leave_event(sender_servername: &ServerName, room_id: &RoomId, pd /// # `PUT /_matrix/federation/v1/send_leave/{roomId}/{eventId}` /// /// Submits a signed leave event. -pub async fn create_leave_event_v1_route( +pub(crate) async fn create_leave_event_v1_route( body: Ruma, ) -> Result { let sender_servername = body @@ -1506,7 +1508,7 @@ pub async fn create_leave_event_v1_route( /// # `PUT /_matrix/federation/v2/send_leave/{roomId}/{eventId}` /// /// Submits a signed leave event. -pub async fn create_leave_event_v2_route( +pub(crate) async fn create_leave_event_v2_route( body: Ruma, ) -> Result { let sender_servername = body @@ -1522,7 +1524,7 @@ pub async fn create_leave_event_v2_route( /// # `PUT /_matrix/federation/v2/invite/{roomId}/{eventId}` /// /// Invites a remote user to a room. -pub async fn create_invite_route(body: Ruma) -> Result { +pub(crate) async fn create_invite_route(body: Ruma) -> Result { let sender_servername = body .sender_servername .as_ref() @@ -1692,7 +1694,7 @@ pub async fn create_invite_route(body: Ruma) -> Resu /// # `GET /_matrix/federation/v1/user/devices/{userId}` /// /// Gets information on all devices of the user. -pub async fn get_devices_route(body: Ruma) -> Result { +pub(crate) async fn get_devices_route(body: Ruma) -> Result { if body.user_id.server_name() != services().globals.server_name() { return Err(Error::BadRequest( ErrorKind::InvalidParam, @@ -1746,7 +1748,7 @@ pub async fn get_devices_route(body: Ruma) -> Result, ) -> Result { let room_id = services() @@ -1786,7 +1788,7 @@ pub async fn get_room_information_route( /// /// /// Gets information on a profile. -pub async fn get_profile_information_route( +pub(crate) async fn get_profile_information_route( body: Ruma, ) -> Result { if !services() @@ -1837,7 +1839,7 @@ pub async fn get_profile_information_route( /// # `POST /_matrix/federation/v1/user/keys/query` /// /// Gets devices and identity keys for the given users. -pub async fn get_keys_route(body: Ruma) -> Result { +pub(crate) async fn get_keys_route(body: Ruma) -> Result { if body .device_keys .iter() @@ -1867,7 +1869,7 @@ pub async fn get_keys_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn claim_keys_route(body: Ruma) -> Result { if body .one_time_keys .iter() @@ -1889,7 +1891,9 @@ pub async fn claim_keys_route(body: Ruma) -> Result) -> Result { +pub(crate) async fn well_known_server( + _body: Ruma, +) -> Result { Ok(discover_homeserver::Response { server: match services().globals.well_known_server() { Some(server_name) => server_name.to_owned(), @@ -1902,7 +1906,7 @@ pub async fn well_known_server(_body: Ruma) -> Res /// /// Gets the space tree in a depth-first manner to locate child rooms of a given /// space. -pub async fn get_hierarchy_route(body: Ruma) -> Result { +pub(crate) async fn get_hierarchy_route(body: Ruma) -> Result { let sender_servername = body .sender_servername .as_ref() diff --git a/src/clap.rs b/src/clap.rs index 9bfe475d..22ff6cab 100644 --- a/src/clap.rs +++ b/src/clap.rs @@ -22,12 +22,12 @@ fn version() -> String { /// Commandline arguments #[derive(Parser, Debug)] #[clap(version = version(), about, long_about = None)] -pub struct Args { +pub(crate) struct Args { #[arg(short, long)] /// Optional argument to the path of a conduwuit config TOML file - pub config: Option, + pub(crate) config: Option, } /// Parse commandline arguments into structured data #[must_use] -pub fn parse() -> Args { Args::parse() } +pub(crate) fn parse() -> Args { Args::parse() } diff --git a/src/config/check.rs b/src/config/check.rs index f289851f..14cdc21f 100644 --- a/src/config/check.rs +++ b/src/config/check.rs @@ -5,7 +5,7 @@ use tracing::{debug, error, info, warn}; use crate::{utils::error::Error, Config}; -pub(super) fn check(config: &Config) -> Result<(), Error> { +pub(crate) fn check(config: &Config) -> Result<(), Error> { config.warn_deprecated(); config.warn_unknown_key(); diff --git a/src/config/mod.rs b/src/config/mod.rs index d1034d96..16a37119 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -30,323 +30,323 @@ mod proxy; #[derive(Deserialize, Clone, Debug)] #[serde(transparent)] -pub struct ListeningPort { +struct ListeningPort { #[serde(with = "either::serde_untagged")] - pub ports: Either>, + ports: Either>, } /// all the config options for conduwuit #[derive(Clone, Debug, Deserialize)] #[allow(clippy::struct_excessive_bools)] -pub struct Config { +pub(crate) struct Config { /// [`IpAddr`] conduwuit will listen on (can be IPv4 or IPv6) #[serde(default = "default_address")] - pub address: IpAddr, + pub(crate) address: IpAddr, /// default TCP port(s) conduwuit will listen on #[serde(default = "default_port")] - pub port: ListeningPort, - pub tls: Option, - pub unix_socket_path: Option, + port: ListeningPort, + pub(crate) tls: Option, + pub(crate) unix_socket_path: Option, #[serde(default = "default_unix_socket_perms")] - pub unix_socket_perms: u32, - pub server_name: OwnedServerName, + pub(crate) unix_socket_perms: u32, + pub(crate) server_name: OwnedServerName, #[serde(default = "default_database_backend")] - pub database_backend: String, - pub database_path: PathBuf, - pub database_backup_path: Option, + pub(crate) database_backend: String, + pub(crate) database_path: PathBuf, + pub(crate) database_backup_path: Option, #[serde(default = "default_database_backups_to_keep")] - pub database_backups_to_keep: i16, + pub(crate) database_backups_to_keep: i16, #[serde(default = "default_db_cache_capacity_mb")] - pub db_cache_capacity_mb: f64, + pub(crate) db_cache_capacity_mb: f64, #[serde(default = "default_new_user_displayname_suffix")] - pub new_user_displayname_suffix: String, + pub(crate) new_user_displayname_suffix: String, #[serde(default)] - pub allow_check_for_updates: bool, + pub(crate) allow_check_for_updates: bool, #[serde(default = "default_pdu_cache_capacity")] - pub pdu_cache_capacity: u32, + pub(crate) pdu_cache_capacity: u32, #[serde(default = "default_conduit_cache_capacity_modifier")] - pub conduit_cache_capacity_modifier: f64, + pub(crate) conduit_cache_capacity_modifier: f64, #[serde(default = "default_auth_chain_cache_capacity")] - pub auth_chain_cache_capacity: u32, + pub(crate) auth_chain_cache_capacity: u32, #[serde(default = "default_shorteventid_cache_capacity")] - pub shorteventid_cache_capacity: u32, + pub(crate) shorteventid_cache_capacity: u32, #[serde(default = "default_eventidshort_cache_capacity")] - pub eventidshort_cache_capacity: u32, + pub(crate) eventidshort_cache_capacity: u32, #[serde(default = "default_shortstatekey_cache_capacity")] - pub shortstatekey_cache_capacity: u32, + pub(crate) shortstatekey_cache_capacity: u32, #[serde(default = "default_statekeyshort_cache_capacity")] - pub statekeyshort_cache_capacity: u32, + pub(crate) statekeyshort_cache_capacity: u32, #[serde(default = "default_server_visibility_cache_capacity")] - pub server_visibility_cache_capacity: u32, + pub(crate) server_visibility_cache_capacity: u32, #[serde(default = "default_user_visibility_cache_capacity")] - pub user_visibility_cache_capacity: u32, + pub(crate) user_visibility_cache_capacity: u32, #[serde(default = "default_stateinfo_cache_capacity")] - pub stateinfo_cache_capacity: u32, + pub(crate) stateinfo_cache_capacity: u32, #[serde(default = "default_roomid_spacehierarchy_cache_capacity")] - pub roomid_spacehierarchy_cache_capacity: u32, + pub(crate) roomid_spacehierarchy_cache_capacity: u32, #[serde(default = "default_cleanup_second_interval")] - pub cleanup_second_interval: u32, + pub(crate) cleanup_second_interval: u32, #[serde(default = "default_dns_cache_entries")] - pub dns_cache_entries: u32, + pub(crate) dns_cache_entries: u32, #[serde(default = "default_dns_min_ttl")] - pub dns_min_ttl: u64, + pub(crate) dns_min_ttl: u64, #[serde(default = "default_dns_min_ttl_nxdomain")] - pub dns_min_ttl_nxdomain: u64, + pub(crate) dns_min_ttl_nxdomain: u64, #[serde(default = "default_dns_attempts")] - pub dns_attempts: u16, + pub(crate) dns_attempts: u16, #[serde(default = "default_dns_timeout")] - pub dns_timeout: u64, + pub(crate) dns_timeout: u64, #[serde(default = "true_fn")] - pub dns_tcp_fallback: bool, + pub(crate) dns_tcp_fallback: bool, #[serde(default = "true_fn")] - pub query_all_nameservers: bool, + pub(crate) query_all_nameservers: bool, #[serde(default = "default_max_request_size")] - pub max_request_size: u32, + pub(crate) max_request_size: u32, #[serde(default = "default_max_concurrent_requests")] - pub max_concurrent_requests: u16, + pub(crate) max_concurrent_requests: u16, #[serde(default = "default_max_fetch_prev_events")] - pub max_fetch_prev_events: u16, + pub(crate) max_fetch_prev_events: u16, #[serde(default = "default_request_conn_timeout")] - pub request_conn_timeout: u64, + pub(crate) request_conn_timeout: u64, #[serde(default = "default_request_timeout")] - pub request_timeout: u64, + pub(crate) request_timeout: u64, #[serde(default = "default_request_total_timeout")] - pub request_total_timeout: u64, + pub(crate) request_total_timeout: u64, #[serde(default = "default_request_idle_timeout")] - pub request_idle_timeout: u64, + pub(crate) request_idle_timeout: u64, #[serde(default = "default_request_idle_per_host")] - pub request_idle_per_host: u16, + pub(crate) request_idle_per_host: u16, #[serde(default = "default_well_known_conn_timeout")] - pub well_known_conn_timeout: u64, + pub(crate) well_known_conn_timeout: u64, #[serde(default = "default_well_known_timeout")] - pub well_known_timeout: u64, + pub(crate) well_known_timeout: u64, #[serde(default = "default_federation_timeout")] - pub federation_timeout: u64, + pub(crate) federation_timeout: u64, #[serde(default = "default_federation_idle_timeout")] - pub federation_idle_timeout: u64, + pub(crate) federation_idle_timeout: u64, #[serde(default = "default_federation_idle_per_host")] - pub federation_idle_per_host: u16, + pub(crate) federation_idle_per_host: u16, #[serde(default = "default_sender_timeout")] - pub sender_timeout: u64, + pub(crate) sender_timeout: u64, #[serde(default = "default_sender_idle_timeout")] - pub sender_idle_timeout: u64, + pub(crate) sender_idle_timeout: u64, #[serde(default = "default_sender_retry_backoff_limit")] - pub sender_retry_backoff_limit: u64, + pub(crate) sender_retry_backoff_limit: u64, #[serde(default = "default_appservice_timeout")] - pub appservice_timeout: u64, + pub(crate) appservice_timeout: u64, #[serde(default = "default_appservice_idle_timeout")] - pub appservice_idle_timeout: u64, + pub(crate) appservice_idle_timeout: u64, #[serde(default = "default_pusher_idle_timeout")] - pub pusher_idle_timeout: u64, + pub(crate) pusher_idle_timeout: u64, #[serde(default)] - pub allow_registration: bool, + pub(crate) allow_registration: bool, #[serde(default)] - pub yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse: bool, - pub registration_token: Option, + pub(crate) yes_i_am_very_very_sure_i_want_an_open_registration_server_prone_to_abuse: bool, + pub(crate) registration_token: Option, #[serde(default = "true_fn")] - pub allow_encryption: bool, + pub(crate) allow_encryption: bool, #[serde(default = "true_fn")] - pub allow_federation: bool, + pub(crate) allow_federation: bool, #[serde(default)] - pub allow_public_room_directory_over_federation: bool, + pub(crate) allow_public_room_directory_over_federation: bool, #[serde(default)] - pub allow_public_room_directory_without_auth: bool, + pub(crate) allow_public_room_directory_without_auth: bool, #[serde(default)] - pub lockdown_public_room_directory: bool, + pub(crate) lockdown_public_room_directory: bool, #[serde(default)] - pub allow_device_name_federation: bool, + pub(crate) allow_device_name_federation: bool, #[serde(default = "true_fn")] - pub allow_profile_lookup_federation_requests: bool, + pub(crate) allow_profile_lookup_federation_requests: bool, #[serde(default = "true_fn")] - pub allow_room_creation: bool, + pub(crate) allow_room_creation: bool, #[serde(default = "true_fn")] - pub allow_unstable_room_versions: bool, + pub(crate) allow_unstable_room_versions: bool, #[serde(default = "default_default_room_version")] - pub default_room_version: RoomVersionId, + pub(crate) default_room_version: RoomVersionId, #[serde(default)] - pub well_known: WellKnownConfig, + pub(crate) well_known: WellKnownConfig, #[serde(default)] - pub allow_jaeger: bool, + pub(crate) allow_jaeger: bool, #[serde(default)] - pub tracing_flame: bool, + pub(crate) tracing_flame: bool, #[serde(default)] - pub proxy: ProxyConfig, - pub jwt_secret: Option, + pub(crate) proxy: ProxyConfig, + pub(crate) jwt_secret: Option, #[serde(default = "default_trusted_servers")] - pub trusted_servers: Vec, + pub(crate) trusted_servers: Vec, #[serde(default = "true_fn")] - pub query_trusted_key_servers_first: bool, + pub(crate) query_trusted_key_servers_first: bool, #[serde(default = "default_log")] - pub log: String, + pub(crate) log: String, #[serde(default)] - pub turn_username: String, + pub(crate) turn_username: String, #[serde(default)] - pub turn_password: String, + pub(crate) turn_password: String, #[serde(default = "Vec::new")] - pub turn_uris: Vec, + pub(crate) turn_uris: Vec, #[serde(default)] - pub turn_secret: String, + pub(crate) turn_secret: String, #[serde(default = "default_turn_ttl")] - pub turn_ttl: u64, + pub(crate) turn_ttl: u64, #[serde(default = "Vec::new")] - pub auto_join_rooms: Vec, + pub(crate) auto_join_rooms: Vec, #[serde(default = "default_rocksdb_log_level")] - pub rocksdb_log_level: String, + pub(crate) rocksdb_log_level: String, #[serde(default)] - pub rocksdb_log_stderr: bool, + pub(crate) rocksdb_log_stderr: bool, #[serde(default = "default_rocksdb_max_log_file_size")] - pub rocksdb_max_log_file_size: usize, + pub(crate) rocksdb_max_log_file_size: usize, #[serde(default = "default_rocksdb_log_time_to_roll")] - pub rocksdb_log_time_to_roll: usize, + pub(crate) rocksdb_log_time_to_roll: usize, #[serde(default)] - pub rocksdb_optimize_for_spinning_disks: bool, + pub(crate) rocksdb_optimize_for_spinning_disks: bool, #[serde(default = "default_rocksdb_parallelism_threads")] - pub rocksdb_parallelism_threads: usize, + pub(crate) rocksdb_parallelism_threads: usize, #[serde(default = "default_rocksdb_max_log_files")] - pub rocksdb_max_log_files: usize, + pub(crate) rocksdb_max_log_files: usize, #[serde(default = "default_rocksdb_compression_algo")] - pub rocksdb_compression_algo: String, + pub(crate) rocksdb_compression_algo: String, #[serde(default = "default_rocksdb_compression_level")] - pub rocksdb_compression_level: i32, + pub(crate) rocksdb_compression_level: i32, #[serde(default = "default_rocksdb_bottommost_compression_level")] - pub rocksdb_bottommost_compression_level: i32, + pub(crate) rocksdb_bottommost_compression_level: i32, #[serde(default)] - pub rocksdb_bottommost_compression: bool, + pub(crate) rocksdb_bottommost_compression: bool, #[serde(default = "default_rocksdb_recovery_mode")] - pub rocksdb_recovery_mode: u8, + pub(crate) rocksdb_recovery_mode: u8, #[serde(default)] - pub rocksdb_repair: bool, + pub(crate) rocksdb_repair: bool, #[serde(default)] - pub rocksdb_read_only: bool, + pub(crate) rocksdb_read_only: bool, #[serde(default)] - pub rocksdb_periodic_cleanup: bool, + pub(crate) rocksdb_periodic_cleanup: bool, - pub emergency_password: Option, + pub(crate) emergency_password: Option, #[serde(default = "default_notification_push_path")] - pub notification_push_path: String, + pub(crate) notification_push_path: String, #[serde(default = "true_fn")] - pub allow_local_presence: bool, + pub(crate) allow_local_presence: bool, #[serde(default = "true_fn")] - pub allow_incoming_presence: bool, + pub(crate) allow_incoming_presence: bool, #[serde(default = "true_fn")] - pub allow_outgoing_presence: bool, + pub(crate) allow_outgoing_presence: bool, #[serde(default = "default_presence_idle_timeout_s")] - pub presence_idle_timeout_s: u64, + pub(crate) presence_idle_timeout_s: u64, #[serde(default = "default_presence_offline_timeout_s")] - pub presence_offline_timeout_s: u64, + pub(crate) presence_offline_timeout_s: u64, #[serde(default = "true_fn")] - pub presence_timeout_remote_users: bool, + pub(crate) presence_timeout_remote_users: bool, #[serde(default = "true_fn")] - pub allow_incoming_read_receipts: bool, + pub(crate) allow_incoming_read_receipts: bool, #[serde(default = "true_fn")] - pub allow_outgoing_read_receipts: bool, + pub(crate) allow_outgoing_read_receipts: bool, #[serde(default = "true_fn")] - pub allow_outgoing_typing: bool, + pub(crate) allow_outgoing_typing: bool, #[serde(default = "true_fn")] - pub allow_incoming_typing: bool, + pub(crate) allow_incoming_typing: bool, #[serde(default = "default_typing_federation_timeout_s")] - pub typing_federation_timeout_s: u64, + pub(crate) typing_federation_timeout_s: u64, #[serde(default = "default_typing_client_timeout_min_s")] - pub typing_client_timeout_min_s: u64, + pub(crate) typing_client_timeout_min_s: u64, #[serde(default = "default_typing_client_timeout_max_s")] - pub typing_client_timeout_max_s: u64, + pub(crate) typing_client_timeout_max_s: u64, #[serde(default)] - pub zstd_compression: bool, + pub(crate) zstd_compression: bool, #[serde(default)] - pub gzip_compression: bool, + pub(crate) gzip_compression: bool, #[serde(default)] - pub brotli_compression: bool, + pub(crate) brotli_compression: bool, #[serde(default)] - pub allow_guest_registration: bool, + pub(crate) allow_guest_registration: bool, #[serde(default)] - pub log_guest_registrations: bool, + pub(crate) log_guest_registrations: bool, #[serde(default)] - pub allow_guests_auto_join_rooms: bool, + pub(crate) allow_guests_auto_join_rooms: bool, #[serde(default = "Vec::new")] - pub prevent_media_downloads_from: Vec, + pub(crate) prevent_media_downloads_from: Vec, #[serde(default = "Vec::new")] - pub forbidden_remote_server_names: Vec, + pub(crate) forbidden_remote_server_names: Vec, #[serde(default = "Vec::new")] - pub forbidden_remote_room_directory_server_names: Vec, + pub(crate) forbidden_remote_room_directory_server_names: Vec, #[serde(default = "default_ip_range_denylist")] - pub ip_range_denylist: Vec, + pub(crate) ip_range_denylist: Vec, #[serde(default = "Vec::new")] - pub url_preview_domain_contains_allowlist: Vec, + pub(crate) url_preview_domain_contains_allowlist: Vec, #[serde(default = "Vec::new")] - pub url_preview_domain_explicit_allowlist: Vec, + pub(crate) url_preview_domain_explicit_allowlist: Vec, #[serde(default = "Vec::new")] - pub url_preview_domain_explicit_denylist: Vec, + pub(crate) url_preview_domain_explicit_denylist: Vec, #[serde(default = "Vec::new")] - pub url_preview_url_contains_allowlist: Vec, + pub(crate) url_preview_url_contains_allowlist: Vec, #[serde(default = "default_url_preview_max_spider_size")] - pub url_preview_max_spider_size: usize, + pub(crate) url_preview_max_spider_size: usize, #[serde(default)] - pub url_preview_check_root_domain: bool, + pub(crate) url_preview_check_root_domain: bool, #[serde(default = "RegexSet::empty")] #[serde(with = "serde_regex")] - pub forbidden_alias_names: RegexSet, + pub(crate) forbidden_alias_names: RegexSet, #[serde(default = "RegexSet::empty")] #[serde(with = "serde_regex")] - pub forbidden_usernames: RegexSet, + pub(crate) forbidden_usernames: RegexSet, #[serde(default = "true_fn")] - pub startup_netburst: bool, + pub(crate) startup_netburst: bool, #[serde(default = "default_startup_netburst_keep")] - pub startup_netburst_keep: i64, + pub(crate) startup_netburst_keep: i64, #[serde(default)] - pub block_non_admin_invites: bool, + pub(crate) block_non_admin_invites: bool, #[serde(default)] - pub sentry: bool, + pub(crate) sentry: bool, #[serde(default)] - pub sentry_send_server_name: bool, + pub(crate) sentry_send_server_name: bool, #[serde(default = "default_sentry_traces_sample_rate")] - pub sentry_traces_sample_rate: f32, + pub(crate) sentry_traces_sample_rate: f32, #[serde(flatten)] #[allow(clippy::zero_sized_map_values)] // this is a catchall, the map shouldn't be zero at runtime - pub catchall: BTreeMap, + catchall: BTreeMap, } #[derive(Clone, Debug, Deserialize)] -pub struct TlsConfig { - pub certs: String, - pub key: String, +pub(crate) struct TlsConfig { + pub(crate) certs: String, + pub(crate) key: String, #[serde(default)] /// Whether to listen and allow for HTTP and HTTPS connections (insecure!) /// Only works / does something if the `axum_dual_protocol` feature flag was /// built - pub dual_protocol: bool, + pub(crate) dual_protocol: bool, } #[derive(Clone, Debug, Deserialize, Default)] -pub struct WellKnownConfig { - pub client: Option, - pub server: Option, - pub support_page: Option, - pub support_role: Option, - pub support_email: Option, - pub support_mxid: Option, +pub(crate) struct WellKnownConfig { + pub(crate) client: Option, + pub(crate) server: Option, + pub(crate) support_page: Option, + pub(crate) support_role: Option, + pub(crate) support_email: Option, + pub(crate) support_mxid: Option, } const DEPRECATED_KEYS: &[&str] = &[ @@ -361,7 +361,7 @@ const DEPRECATED_KEYS: &[&str] = &[ impl Config { /// Initialize config - pub fn new(path: Option) -> Result { + pub(crate) fn new(path: Option) -> Result { let raw_config = if let Some(config_file_env) = Env::var("CONDUIT_CONFIG") { Figment::new() .merge(Toml::file(config_file_env).nested()) @@ -389,7 +389,7 @@ impl Config { /// Iterates over all the keys in the config file and warns if there is a /// deprecated key specified - pub fn warn_deprecated(&self) { + pub(crate) fn warn_deprecated(&self) { debug!("Checking for deprecated config keys"); let mut was_deprecated = false; for key in self @@ -411,7 +411,7 @@ impl Config { /// iterates over all the catchall keys (unknown config options) and warns /// if there are any. - pub fn warn_unknown_key(&self) { + pub(crate) fn warn_unknown_key(&self) { debug!("Checking for unknown config keys"); for key in self .catchall @@ -439,7 +439,7 @@ impl Config { } #[must_use] - pub fn get_bind_addrs(&self) -> Vec { + pub(crate) fn get_bind_addrs(&self) -> Vec { match &self.port.ports { Left(port) => { // Left is only 1 value, so make a vec with 1 value only @@ -459,7 +459,7 @@ impl Config { } } - pub fn check(&self) -> Result<(), Error> { check(self) } + pub(crate) fn check(&self) -> Result<(), Error> { check(self) } } impl fmt::Display for Config { diff --git a/src/config/proxy.rs b/src/config/proxy.rs index bf9a672d..691c3394 100644 --- a/src/config/proxy.rs +++ b/src/config/proxy.rs @@ -30,7 +30,7 @@ use crate::Result; /// `ordinary.onion`, `matrix.myspecial.onion`, but not `hello.myspecial.onion`. #[derive(Clone, Default, Debug, Deserialize)] #[serde(rename_all = "snake_case")] -pub enum ProxyConfig { +pub(crate) enum ProxyConfig { #[default] None, Global { @@ -40,7 +40,7 @@ pub enum ProxyConfig { ByDomain(Vec), } impl ProxyConfig { - pub fn to_proxy(&self) -> Result> { + pub(crate) fn to_proxy(&self) -> Result> { Ok(match self.clone() { ProxyConfig::None => None, ProxyConfig::Global { @@ -55,7 +55,7 @@ impl ProxyConfig { } #[derive(Clone, Debug, Deserialize)] -pub struct PartialProxyConfig { +pub(crate) struct PartialProxyConfig { #[serde(deserialize_with = "crate::utils::deserialize_from_str")] url: Url, #[serde(default)] @@ -64,7 +64,7 @@ pub struct PartialProxyConfig { exclude: Vec, } impl PartialProxyConfig { - pub fn for_url(&self, url: &Url) -> Option<&Url> { + pub(crate) fn for_url(&self, url: &Url) -> Option<&Url> { let domain = url.domain()?; let mut included_because = None; // most specific reason it was included let mut excluded_because = None; // most specific reason it was excluded diff --git a/src/database/cork.rs b/src/database/cork.rs index 27b59d17..db7dfac2 100644 --- a/src/database/cork.rs +++ b/src/database/cork.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use super::KeyValueDatabaseEngine; -pub struct Cork { +pub(crate) struct Cork { db: Arc, flush: bool, sync: bool, diff --git a/src/database/mod.rs b/src/database/mod.rs index 8609bbc5..c8e1a17b 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -1,14 +1,14 @@ -pub(crate) mod cork; -pub(crate) mod key_value; -pub(crate) mod kvengine; -pub(crate) mod kvtree; +mod cork; +mod key_value; +mod kvengine; +mod kvtree; mod migrations; #[cfg(feature = "rocksdb")] -pub(crate) mod rocksdb; +mod rocksdb; #[cfg(feature = "sqlite")] -pub mod sqlite; +mod sqlite; #[cfg(any(feature = "sqlite", feature = "rocksdb"))] pub(crate) mod watchers; @@ -44,149 +44,149 @@ use crate::{ SERVICES, }; -pub struct KeyValueDatabase { +pub(crate) struct KeyValueDatabase { db: Arc, - //pub globals: globals::Globals, - pub(super) global: Arc, - pub(super) server_signingkeys: Arc, + //pub(crate) globals: globals::Globals, + pub(crate) global: Arc, + pub(crate) server_signingkeys: Arc, - pub(super) roomid_inviteviaservers: Arc, + pub(crate) roomid_inviteviaservers: Arc, - //pub users: users::Users, - pub(super) userid_password: Arc, - pub(super) userid_displayname: Arc, - pub(super) userid_avatarurl: Arc, - pub(super) userid_blurhash: Arc, - pub(super) userdeviceid_token: Arc, - pub(super) userdeviceid_metadata: Arc, // This is also used to check if a device exists - pub(super) userid_devicelistversion: Arc, // DevicelistVersion = u64 - pub(super) token_userdeviceid: Arc, + //pub(crate) users: users::Users, + pub(crate) userid_password: Arc, + pub(crate) userid_displayname: Arc, + pub(crate) userid_avatarurl: Arc, + pub(crate) userid_blurhash: Arc, + pub(crate) userdeviceid_token: Arc, + pub(crate) userdeviceid_metadata: Arc, // This is also used to check if a device exists + pub(crate) userid_devicelistversion: Arc, // DevicelistVersion = u64 + pub(crate) token_userdeviceid: Arc, - pub(super) onetimekeyid_onetimekeys: Arc, // OneTimeKeyId = UserId + DeviceKeyId - pub(super) userid_lastonetimekeyupdate: Arc, // LastOneTimeKeyUpdate = Count - pub(super) keychangeid_userid: Arc, // KeyChangeId = UserId/RoomId + Count - pub(super) keyid_key: Arc, // KeyId = UserId + KeyId (depends on key type) - pub(super) userid_masterkeyid: Arc, - pub(super) userid_selfsigningkeyid: Arc, - pub(super) userid_usersigningkeyid: Arc, + pub(crate) onetimekeyid_onetimekeys: Arc, // OneTimeKeyId = UserId + DeviceKeyId + pub(crate) userid_lastonetimekeyupdate: Arc, // LastOneTimeKeyUpdate = Count + pub(crate) keychangeid_userid: Arc, // KeyChangeId = UserId/RoomId + Count + pub(crate) keyid_key: Arc, // KeyId = UserId + KeyId (depends on key type) + pub(crate) userid_masterkeyid: Arc, + pub(crate) userid_selfsigningkeyid: Arc, + pub(crate) userid_usersigningkeyid: Arc, - pub(super) userfilterid_filter: Arc, // UserFilterId = UserId + FilterId - pub(super) todeviceid_events: Arc, // ToDeviceId = UserId + DeviceId + Count - pub(super) userid_presenceid: Arc, // UserId => Count - pub(super) presenceid_presence: Arc, // Count + UserId => Presence + pub(crate) userfilterid_filter: Arc, // UserFilterId = UserId + FilterId + pub(crate) todeviceid_events: Arc, // ToDeviceId = UserId + DeviceId + Count + pub(crate) userid_presenceid: Arc, // UserId => Count + pub(crate) presenceid_presence: Arc, // Count + UserId => Presence - //pub uiaa: uiaa::Uiaa, - pub(super) userdevicesessionid_uiaainfo: Arc, // User-interactive authentication - pub(super) userdevicesessionid_uiaarequest: + //pub(crate) uiaa: uiaa::Uiaa, + pub(crate) userdevicesessionid_uiaainfo: Arc, // User-interactive authentication + pub(crate) userdevicesessionid_uiaarequest: RwLock>, - //pub edus: RoomEdus, - pub(super) readreceiptid_readreceipt: Arc, // ReadReceiptId = RoomId + Count + UserId - pub(super) roomuserid_privateread: Arc, // RoomUserId = Room + User, PrivateRead = Count - pub(super) roomuserid_lastprivatereadupdate: Arc, // LastPrivateReadUpdate = Count + //pub(crate) edus: RoomEdus, + pub(crate) readreceiptid_readreceipt: Arc, // ReadReceiptId = RoomId + Count + UserId + pub(crate) roomuserid_privateread: Arc, // RoomUserId = Room + User, PrivateRead = Count + pub(crate) roomuserid_lastprivatereadupdate: Arc, // LastPrivateReadUpdate = Count - //pub rooms: rooms::Rooms, - pub(super) pduid_pdu: Arc, // PduId = ShortRoomId + Count - pub(super) eventid_pduid: Arc, - pub(super) roomid_pduleaves: Arc, - pub(super) alias_roomid: Arc, - pub(super) aliasid_alias: Arc, // AliasId = RoomId + Count - pub(super) publicroomids: Arc, + //pub(crate) rooms: rooms::Rooms, + pub(crate) pduid_pdu: Arc, // PduId = ShortRoomId + Count + pub(crate) eventid_pduid: Arc, + pub(crate) roomid_pduleaves: Arc, + pub(crate) alias_roomid: Arc, + pub(crate) aliasid_alias: Arc, // AliasId = RoomId + Count + pub(crate) publicroomids: Arc, - pub(super) threadid_userids: Arc, // ThreadId = RoomId + Count + pub(crate) threadid_userids: Arc, // ThreadId = RoomId + Count - pub(super) tokenids: Arc, // TokenId = ShortRoomId + Token + PduIdCount + pub(crate) tokenids: Arc, // TokenId = ShortRoomId + Token + PduIdCount /// Participating servers in a room. - pub(super) roomserverids: Arc, // RoomServerId = RoomId + ServerName - pub(super) serverroomids: Arc, // ServerRoomId = ServerName + RoomId + pub(crate) roomserverids: Arc, // RoomServerId = RoomId + ServerName + pub(crate) serverroomids: Arc, // ServerRoomId = ServerName + RoomId - pub(super) userroomid_joined: Arc, - pub(super) roomuserid_joined: Arc, - pub(super) roomid_joinedcount: Arc, - pub(super) roomid_invitedcount: Arc, - pub(super) roomuseroncejoinedids: Arc, - pub(super) userroomid_invitestate: Arc, // InviteState = Vec> - pub(super) roomuserid_invitecount: Arc, // InviteCount = Count - pub(super) userroomid_leftstate: Arc, - pub(super) roomuserid_leftcount: Arc, + pub(crate) userroomid_joined: Arc, + pub(crate) roomuserid_joined: Arc, + pub(crate) roomid_joinedcount: Arc, + pub(crate) roomid_invitedcount: Arc, + pub(crate) roomuseroncejoinedids: Arc, + pub(crate) userroomid_invitestate: Arc, // InviteState = Vec> + pub(crate) roomuserid_invitecount: Arc, // InviteCount = Count + pub(crate) userroomid_leftstate: Arc, + pub(crate) roomuserid_leftcount: Arc, - pub(super) disabledroomids: Arc, // Rooms where incoming federation handling is disabled + pub(crate) disabledroomids: Arc, // Rooms where incoming federation handling is disabled - pub(super) bannedroomids: Arc, // Rooms where local users are not allowed to join + pub(crate) bannedroomids: Arc, // Rooms where local users are not allowed to join - pub(super) lazyloadedids: Arc, // LazyLoadedIds = UserId + DeviceId + RoomId + LazyLoadedUserId + pub(crate) lazyloadedids: Arc, // LazyLoadedIds = UserId + DeviceId + RoomId + LazyLoadedUserId - pub(super) userroomid_notificationcount: Arc, // NotifyCount = u64 - pub(super) userroomid_highlightcount: Arc, // HightlightCount = u64 - pub(super) roomuserid_lastnotificationread: Arc, // LastNotificationRead = u64 + pub(crate) userroomid_notificationcount: Arc, // NotifyCount = u64 + pub(crate) userroomid_highlightcount: Arc, // HightlightCount = u64 + pub(crate) roomuserid_lastnotificationread: Arc, // LastNotificationRead = u64 /// Remember the current state hash of a room. - pub(super) roomid_shortstatehash: Arc, - pub(super) roomsynctoken_shortstatehash: Arc, + pub(crate) roomid_shortstatehash: Arc, + pub(crate) roomsynctoken_shortstatehash: Arc, /// Remember the state hash at events in the past. - pub(super) shorteventid_shortstatehash: Arc, - pub(super) statekey_shortstatekey: Arc, /* StateKey = EventType + StateKey, ShortStateKey = + pub(crate) shorteventid_shortstatehash: Arc, + pub(crate) statekey_shortstatekey: Arc, /* StateKey = EventType + StateKey, ShortStateKey = * Count */ - pub(super) shortstatekey_statekey: Arc, + pub(crate) shortstatekey_statekey: Arc, - pub(super) roomid_shortroomid: Arc, + pub(crate) roomid_shortroomid: Arc, - pub(super) shorteventid_eventid: Arc, - pub(super) eventid_shorteventid: Arc, + pub(crate) shorteventid_eventid: Arc, + pub(crate) eventid_shorteventid: Arc, - pub(super) statehash_shortstatehash: Arc, - pub(super) shortstatehash_statediff: Arc, /* StateDiff = parent (or 0) + + pub(crate) statehash_shortstatehash: Arc, + pub(crate) shortstatehash_statediff: Arc, /* StateDiff = parent (or 0) + * (shortstatekey+shorteventid++) + 0_u64 + * (shortstatekey+shorteventid--) */ - pub(super) shorteventid_authchain: Arc, + pub(crate) shorteventid_authchain: Arc, /// RoomId + EventId -> outlier PDU. /// Any pdu that has passed the steps 1-8 in the incoming event /// /federation/send/txn. - pub(super) eventid_outlierpdu: Arc, - pub(super) softfailedeventids: Arc, + pub(crate) eventid_outlierpdu: Arc, + pub(crate) softfailedeventids: Arc, /// ShortEventId + ShortEventId -> (). - pub(super) tofrom_relation: Arc, + pub(crate) tofrom_relation: Arc, /// RoomId + EventId -> Parent PDU EventId. - pub(super) referencedevents: Arc, + pub(crate) referencedevents: Arc, - //pub account_data: account_data::AccountData, - pub(super) roomuserdataid_accountdata: Arc, // RoomUserDataId = Room + User + Count + Type - pub(super) roomusertype_roomuserdataid: Arc, // RoomUserType = Room + User + Type + //pub(crate) account_data: account_data::AccountData, + pub(crate) roomuserdataid_accountdata: Arc, // RoomUserDataId = Room + User + Count + Type + pub(crate) roomusertype_roomuserdataid: Arc, // RoomUserType = Room + User + Type - //pub media: media::Media, - pub(super) mediaid_file: Arc, // MediaId = MXC + WidthHeight + ContentDisposition + ContentType - pub(super) url_previews: Arc, - pub(super) mediaid_user: Arc, - //pub key_backups: key_backups::KeyBackups, - pub(super) backupid_algorithm: Arc, // BackupId = UserId + Version(Count) - pub(super) backupid_etag: Arc, // BackupId = UserId + Version(Count) - pub(super) backupkeyid_backup: Arc, // BackupKeyId = UserId + Version + RoomId + SessionId + //pub(crate) media: media::Media, + pub(crate) mediaid_file: Arc, // MediaId = MXC + WidthHeight + ContentDisposition + ContentType + pub(crate) url_previews: Arc, + pub(crate) mediaid_user: Arc, + //pub(crate) key_backups: key_backups::KeyBackups, + pub(crate) backupid_algorithm: Arc, // BackupId = UserId + Version(Count) + pub(crate) backupid_etag: Arc, // BackupId = UserId + Version(Count) + pub(crate) backupkeyid_backup: Arc, // BackupKeyId = UserId + Version + RoomId + SessionId - //pub transaction_ids: transaction_ids::TransactionIds, - pub(super) userdevicetxnid_response: Arc, /* Response can be empty (/sendToDevice) or the event id + //pub(crate) transaction_ids: transaction_ids::TransactionIds, + pub(crate) userdevicetxnid_response: Arc, /* Response can be empty (/sendToDevice) or the event id * (/send) */ - //pub sending: sending::Sending, - pub(super) servername_educount: Arc, // EduCount: Count of last EDU sync - pub(super) servernameevent_data: Arc, /* ServernameEvent = (+ / $)SenderKey / ServerName / UserId + + //pub(crate) sending: sending::Sending, + pub(crate) servername_educount: Arc, // EduCount: Count of last EDU sync + pub(crate) servernameevent_data: Arc, /* ServernameEvent = (+ / $)SenderKey / ServerName / UserId + * PduId / Id (for edus), Data = EDU content */ - pub(super) servercurrentevent_data: Arc, /* ServerCurrentEvents = (+ / $)ServerName / UserId + PduId + pub(crate) servercurrentevent_data: Arc, /* ServerCurrentEvents = (+ / $)ServerName / UserId + PduId * / Id (for edus), Data = EDU content */ - //pub appservice: appservice::Appservice, - pub(super) id_appserviceregistrations: Arc, + //pub(crate) appservice: appservice::Appservice, + pub(crate) id_appserviceregistrations: Arc, - //pub pusher: pusher::PushData, - pub(super) senderkey_pusher: Arc, + //pub(crate) pusher: pusher::PushData, + pub(crate) senderkey_pusher: Arc, - pub(super) auth_chain_cache: Mutex, Arc<[u64]>>>, - pub(super) our_real_users_cache: RwLock>>>, - pub(super) appservice_in_room_cache: RwLock>>, - pub(super) lasttimelinecount_cache: Mutex>, + pub(crate) auth_chain_cache: Mutex, Arc<[u64]>>>, + pub(crate) our_real_users_cache: RwLock>>>, + pub(crate) appservice_in_room_cache: RwLock>>, + pub(crate) lasttimelinecount_cache: Mutex>, } #[derive(Deserialize)] @@ -203,7 +203,7 @@ struct CheckForUpdatesResponse { impl KeyValueDatabase { /// Load an existing database or create a new one. #[allow(clippy::too_many_lines)] - pub async fn load_or_create( + pub(crate) async fn load_or_create( config: Config, tracing_reload_handler: tracing_subscriber::reload::Handle< tracing_subscriber::EnvFilter, @@ -545,7 +545,7 @@ impl KeyValueDatabase { } #[allow(dead_code)] - pub fn flush(&self) -> Result<()> { + fn flush(&self) -> Result<()> { let start = std::time::Instant::now(); let res = self.db.flush(); diff --git a/src/database/rocksdb/kvtree.rs b/src/database/rocksdb/kvtree.rs index 1d9adaa4..4761624b 100644 --- a/src/database/rocksdb/kvtree.rs +++ b/src/database/rocksdb/kvtree.rs @@ -5,10 +5,10 @@ use rust_rocksdb::WriteBatchWithTransaction; use super::{watchers::Watchers, Engine, KeyValueDatabaseEngine, KvTree}; use crate::{utils, Result}; -pub(super) struct RocksDbEngineTree<'a> { - pub db: Arc, - pub name: &'a str, - pub watchers: Watchers, +pub(crate) struct RocksDbEngineTree<'a> { + pub(crate) db: Arc, + pub(crate) name: &'a str, + pub(crate) watchers: Watchers, } impl RocksDbEngineTree<'_> { diff --git a/src/database/sqlite/mod.rs b/src/database/sqlite/mod.rs index 11c81e03..60014ab0 100644 --- a/src/database/sqlite/mod.rs +++ b/src/database/sqlite/mod.rs @@ -20,8 +20,8 @@ thread_local! { } struct PreparedStatementIterator<'a> { - pub iterator: Box + 'a>, - pub _statement_ref: NonAliasingBox>, + iterator: Box + 'a>, + _statement_ref: NonAliasingBox>, } impl Iterator for PreparedStatementIterator<'_> { @@ -77,7 +77,7 @@ impl Engine { .get_or(|| Self::prepare_conn(&self.path, self.cache_size_per_thread).unwrap()) } - pub fn flush_wal(self: &Arc) -> Result<()> { + fn flush_wal(self: &Arc) -> Result<()> { self.write_lock() .pragma_update(Some(Main), "wal_checkpoint", "RESTART")?; Ok(()) @@ -130,7 +130,7 @@ impl KeyValueDatabaseEngine for Arc { fn cleanup(&self) -> Result<()> { self.flush_wal() } } -pub struct SqliteTable { +struct SqliteTable { engine: Arc, name: String, watchers: Watchers, @@ -154,7 +154,7 @@ impl SqliteTable { Ok(()) } - pub fn iter_with_guard<'a>(&'a self, guard: &'a Connection) -> Box + 'a> { + fn iter_with_guard<'a>(&'a self, guard: &'a Connection) -> Box + 'a> { let statement = Box::leak(Box::new( guard .prepare(&format!("SELECT key, value FROM {} ORDER BY key ASC", &self.name)) diff --git a/src/database/watchers.rs b/src/database/watchers.rs index 9707e64b..a4152a09 100644 --- a/src/database/watchers.rs +++ b/src/database/watchers.rs @@ -10,12 +10,12 @@ use tokio::sync::watch; type Watcher = RwLock, (watch::Sender<()>, watch::Receiver<()>)>>; #[derive(Default)] -pub(super) struct Watchers { +pub(crate) struct Watchers { watchers: Watcher, } impl Watchers { - pub(super) fn watch<'a>(&'a self, prefix: &[u8]) -> Pin + Send + 'a>> { + pub(crate) fn watch<'a>(&'a self, prefix: &[u8]) -> Pin + Send + 'a>> { let mut rx = match self.watchers.write().unwrap().entry(prefix.to_vec()) { hash_map::Entry::Occupied(o) => o.get().1.clone(), hash_map::Entry::Vacant(v) => { @@ -31,7 +31,7 @@ impl Watchers { }) } - pub(super) fn wake(&self, key: &[u8]) { + pub(crate) fn wake(&self, key: &[u8]) { let watchers = self.watchers.read().unwrap(); let mut triggered = Vec::new(); diff --git a/src/main.rs b/src/main.rs index 89d4a341..90eb18b0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,10 +54,10 @@ mod routes; mod service; mod utils; -pub static SERVICES: RwLock>> = RwLock::new(None); +pub(crate) static SERVICES: RwLock>> = RwLock::new(None); #[must_use] -pub fn services() -> &'static Services<'static> { +pub(crate) fn services() -> &'static Services<'static> { SERVICES .read() .unwrap() diff --git a/src/routes.rs b/src/routes.rs index f4334da1..bd7f933d 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -15,7 +15,7 @@ use crate::{ Config, Error, Result, Ruma, RumaResponse, }; -pub fn routes(config: &Config) -> Router { +pub(crate) fn routes(config: &Config) -> Router { let router = Router::new() .ruma_route(client_server::get_supported_versions_route) .ruma_route(client_server::get_register_available_route) @@ -266,7 +266,7 @@ impl RouterExt for Router { } } -pub trait RumaHandler { +pub(crate) trait RumaHandler { // Can't transform to a handler without boxing or relying on the nightly-only // impl-trait-in-traits feature. Moving a small amount of extra logic into the // trait allows bypassing both. diff --git a/src/service/account_data/data.rs b/src/service/account_data/data.rs index 492c500c..b538ef76 100644 --- a/src/service/account_data/data.rs +++ b/src/service/account_data/data.rs @@ -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( diff --git a/src/service/account_data/mod.rs b/src/service/account_data/mod.rs index 6acfbef4..e8de80e6 100644 --- a/src/service/account_data/mod.rs +++ b/src/service/account_data/mod.rs @@ -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>> { 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>> { self.db.changes_since(room_id, user_id, since) diff --git a/src/service/admin/appservice/appservice_command.rs b/src/service/admin/appservice/appservice_command.rs index e2c47a50..3a5fdaf7 100644 --- a/src/service/admin/appservice/appservice_command.rs +++ b/src/service/admin/appservice/appservice_command.rs @@ -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 { +pub(crate) async fn register(body: Vec<&str>) -> Result { 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::(&appservice_config); @@ -26,7 +26,7 @@ pub(super) async fn register(body: Vec<&str>) -> Result } } -pub(super) async fn unregister(_body: Vec<&str>, appservice_identifier: String) -> Result { +pub(crate) async fn unregister(_body: Vec<&str>, appservice_identifier: String) -> Result { 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 { +pub(crate) async fn show(_body: Vec<&str>, appservice_identifier: String) -> Result { 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 { +pub(crate) async fn list(_body: Vec<&str>) -> Result { let appservices = services().appservice.iter_ids().await; let output = format!("Appservices ({}): {}", appservices.len(), appservices.join(", ")); Ok(RoomMessageEventContent::text_plain(output)) diff --git a/src/service/admin/debug/debug_commands.rs b/src/service/admin/debug/debug_commands.rs index aae4b948..7a70f8a8 100644 --- a/src/service/admin/debug/debug_commands.rs +++ b/src/service/admin/debug/debug_commands.rs @@ -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) -> Result { +pub(crate) async fn get_auth_chain(_body: Vec<&str>, event_id: Box) -> Result { let event_id = Arc::::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) -> } } -pub(super) async fn parse_pdu(body: Vec<&str>) -> Result { +pub(crate) async fn parse_pdu(body: Vec<&str>) -> Result { 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, event_id: Box) -> Result { +pub(crate) async fn get_pdu(_body: Vec<&str>, event_id: Box) -> Result { 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) -> Result< } } -pub(super) async fn get_remote_pdu_list( +pub(crate) async fn get_remote_pdu_list( body: Vec<&str>, server: Box, force: bool, ) -> Result { 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, server: Box, ) -> Result { 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) -> Result { +pub(crate) async fn get_room_state(_body: Vec<&str>, room_id: Box) -> Result { let room_state = services() .rooms .state_accessor @@ -261,7 +261,7 @@ pub(super) async fn get_room_state(_body: Vec<&str>, room_id: Box) -> Re )) } -pub(super) async fn ping(_body: Vec<&str>, server: Box) -> Result { +pub(crate) async fn ping(_body: Vec<&str>, server: Box) -> Result { 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) -> Result) -> Result { +pub(crate) async fn force_device_list_updates(_body: Vec<&str>) -> Result { // 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, filter: Option, reset: bool, ) -> Result { 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 { +pub(crate) async fn sign_json(body: Vec<&str>) -> Result { 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) -> Result { +pub(crate) async fn verify_json(body: Vec<&str>) -> Result { 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) { diff --git a/src/service/admin/federation/federation_commands.rs b/src/service/admin/federation/federation_commands.rs index 56c9f510..03a3edc7 100644 --- a/src/service/admin/federation/federation_commands.rs +++ b/src/service/admin/federation/federation_commands.rs @@ -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) -> Result { +pub(crate) async fn disable_room(_body: Vec<&str>, room_id: Box) -> Result { 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) -> Result { +pub(crate) async fn enable_room(_body: Vec<&str>, room_id: Box) -> Result { services().rooms.metadata.disable_room(&room_id, false)?; Ok(RoomMessageEventContent::text_plain("Room enabled.")) } -pub(super) async fn incoming_federeation(_body: Vec<&str>) -> Result { +pub(crate) async fn incoming_federeation(_body: Vec<&str>) -> Result { 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, server_name: Box, ) -> Result { let response = services() diff --git a/src/service/admin/fsck/fsck_commands.rs b/src/service/admin/fsck/fsck_commands.rs index 46a04c3c..dec407d8 100644 --- a/src/service/admin/fsck/fsck_commands.rs +++ b/src/service/admin/fsck/fsck_commands.rs @@ -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 { +pub(crate) async fn check_all_users(_body: Vec<&str>) -> Result { let timer = tokio::time::Instant::now(); let results = services().users.db.iter(); let query_time = timer.elapsed(); diff --git a/src/service/admin/media/media_commands.rs b/src/service/admin/media/media_commands.rs index d7745088..19e539dd 100644 --- a/src/service/admin/media/media_commands.rs +++ b/src/service/admin/media/media_commands.rs @@ -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>, event_id: Option>, ) -> Result { 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 { +pub(crate) async fn delete_list(body: Vec<&str>) -> Result { if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" { let mxc_list = body.clone().drain(1..body.len() - 1).collect::>(); @@ -159,7 +159,7 @@ pub(super) async fn delete_list(body: Vec<&str>) -> Result, duration: String) -> Result { +pub(crate) async fn delete_past_remote_media(_body: Vec<&str>, duration: String) -> Result { let deleted_count = services() .media .delete_all_remote_media_at_after_time(duration) diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs index f1a63652..50fb58c6 100644 --- a/src/service/admin/mod.rs +++ b/src/service/admin/mod.rs @@ -90,18 +90,18 @@ enum AdminCommand { } #[derive(Debug)] -pub enum AdminRoomEvent { +pub(crate) enum AdminRoomEvent { ProcessMessage(String, Arc), SendMessage(RoomMessageEventContent), } -pub struct Service { - pub sender: loole::Sender, +pub(crate) struct Service { + pub(crate) sender: loole::Sender, receiver: Mutex>, } impl Service { - pub fn build() -> Arc { + pub(crate) fn build() -> Arc { let (sender, receiver) = loole::unbounded(); Arc::new(Self { sender, @@ -109,7 +109,7 @@ impl Service { }) } - pub fn start_handler(self: &Arc) { + pub(crate) fn start_handler(self: &Arc) { 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) { + pub(crate) fn process_message(&self, room_message: String, event_id: Arc) { 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(); diff --git a/src/service/admin/query/account_data.rs b/src/service/admin/query/account_data.rs index 15d45633..44a5544f 100644 --- a/src/service/admin/query/account_data.rs +++ b/src/service/admin/query/account_data.rs @@ -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 { +pub(crate) async fn account_data(subcommand: AccountData) -> Result { match subcommand { AccountData::ChangesSince { user_id, diff --git a/src/service/admin/query/appservice.rs b/src/service/admin/query/appservice.rs index 8b97eec0..88c74d5e 100644 --- a/src/service/admin/query/appservice.rs +++ b/src/service/admin/query/appservice.rs @@ -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 { +pub(crate) async fn appservice(subcommand: Appservice) -> Result { match subcommand { Appservice::GetRegistration { appservice_id, diff --git a/src/service/admin/query/globals.rs b/src/service/admin/query/globals.rs index ff962cb5..37a549ad 100644 --- a/src/service/admin/query/globals.rs +++ b/src/service/admin/query/globals.rs @@ -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 { +pub(crate) async fn globals(subcommand: Globals) -> Result { match subcommand { Globals::DatabaseVersion => { let timer = tokio::time::Instant::now(); diff --git a/src/service/admin/query/presence.rs b/src/service/admin/query/presence.rs index 0e32bbd7..b77febfa 100644 --- a/src/service/admin/query/presence.rs +++ b/src/service/admin/query/presence.rs @@ -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 { +pub(crate) async fn presence(subcommand: Presence) -> Result { match subcommand { Presence::GetPresence { user_id, diff --git a/src/service/admin/query/room_alias.rs b/src/service/admin/query/room_alias.rs index e5238f38..eb2bac8a 100644 --- a/src/service/admin/query/room_alias.rs +++ b/src/service/admin/query/room_alias.rs @@ -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 { +pub(crate) async fn room_alias(subcommand: RoomAlias) -> Result { match subcommand { RoomAlias::ResolveLocalAlias { alias, diff --git a/src/service/admin/query/sending.rs b/src/service/admin/query/sending.rs index da96c8fe..19d73cf6 100644 --- a/src/service/admin/query/sending.rs +++ b/src/service/admin/query/sending.rs @@ -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 { +pub(crate) async fn sending(subcommand: Sending) -> Result { match subcommand { Sending::ActiveRequests => { let timer = tokio::time::Instant::now(); diff --git a/src/service/admin/query/users.rs b/src/service/admin/query/users.rs index 818ff6d6..2b624ed3 100644 --- a/src/service/admin/query/users.rs +++ b/src/service/admin/query/users.rs @@ -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 { +pub(crate) async fn users(subcommand: Users) -> Result { match subcommand { Users::Iter => { let timer = tokio::time::Instant::now(); diff --git a/src/service/admin/room/room_commands.rs b/src/service/admin/room/room_commands.rs index f4964adf..399f3c09 100644 --- a/src/service/admin/room/room_commands.rs +++ b/src/service/admin/room/room_commands.rs @@ -7,7 +7,7 @@ use crate::{ services, Result, }; -pub(super) async fn list(_body: Vec<&str>, page: Option) -> Result { +pub(crate) async fn list(_body: Vec<&str>, page: Option) -> Result { // 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() diff --git a/src/service/admin/server/server_commands.rs b/src/service/admin/server/server_commands.rs index f363d7ff..363f104b 100644 --- a/src/service/admin/server/server_commands.rs +++ b/src/service/admin/server/server_commands.rs @@ -2,12 +2,12 @@ use ruma::events::room::message::RoomMessageEventContent; use crate::{services, Result}; -pub(super) async fn show_config(_body: Vec<&str>) -> Result { +pub(crate) async fn show_config(_body: Vec<&str>) -> Result { // Construct and send the response Ok(RoomMessageEventContent::text_plain(format!("{}", services().globals.config))) } -pub(super) async fn memory_usage(_body: Vec<&str>) -> Result { +pub(crate) async fn memory_usage(_body: Vec<&str>) -> Result { 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, amount: u32) -> Result { +pub(crate) async fn clear_database_caches(_body: Vec<&str>, amount: u32) -> Result { services().globals.db.clear_caches(amount); Ok(RoomMessageEventContent::text_plain("Done.")) } -pub(super) async fn clear_service_caches(_body: Vec<&str>, amount: u32) -> Result { +pub(crate) async fn clear_service_caches(_body: Vec<&str>, amount: u32) -> Result { services().clear_caches(amount).await; Ok(RoomMessageEventContent::text_plain("Done.")) } -pub(super) async fn list_backups(_body: Vec<&str>) -> Result { +pub(crate) async fn list_backups(_body: Vec<&str>) -> Result { 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) -> Result { +pub(crate) async fn backup_database(_body: Vec<&str>) -> Result { 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) -> Result { +pub(crate) async fn list_database_files(_body: Vec<&str>) -> Result { if !cfg!(feature = "rocksdb") { return Ok(RoomMessageEventContent::text_plain( "Only RocksDB supports listing files in conduwuit.", diff --git a/src/service/admin/user/user_commands.rs b/src/service/admin/user/user_commands.rs index 52cc6792..4cb27636 100644 --- a/src/service/admin/user/user_commands.rs +++ b/src/service/admin/user/user_commands.rs @@ -10,7 +10,7 @@ use crate::{ services, utils, Result, }; -pub(super) async fn list(_body: Vec<&str>) -> Result { +pub(crate) async fn list(_body: Vec<&str>) -> Result { 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 { } } -pub(super) async fn create( +pub(crate) async fn create( _body: Vec<&str>, username: String, password: Option, ) -> Result { 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 { // Validate user id @@ -168,7 +168,7 @@ pub(super) async fn deactivate( } } -pub(super) async fn reset_password(_body: Vec<&str>, username: String) -> Result { +pub(crate) async fn reset_password(_body: Vec<&str>, username: String) -> Result { // 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 { +pub(crate) async fn deactivate_all(body: Vec<&str>, leave_rooms: bool, force: bool) -> Result { if body.len() > 2 && body[0].trim().starts_with("```") && body.last().unwrap().trim() == "```" { let usernames = body.clone().drain(1..body.len() - 1).collect::>(); @@ -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 { +pub(crate) async fn list_joined_rooms(_body: Vec<&str>, user_id: String) -> Result { // Validate user id let user_id = match UserId::parse_with_server_name(user_id.as_str().to_lowercase(), services().globals.server_name()) { diff --git a/src/service/appservice/data.rs b/src/service/appservice/data.rs index 52c8b34d..cb19ebb0 100644 --- a/src/service/appservice/data.rs +++ b/src/service/appservice/data.rs @@ -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; diff --git a/src/service/appservice/mod.rs b/src/service/appservice/mod.rs index ea387881..3f2241c6 100644 --- a/src/service/appservice/mod.rs +++ b/src/service/appservice/mod.rs @@ -15,14 +15,14 @@ use crate::{services, Result}; /// Compiled regular expressions for a namespace #[derive(Clone, Debug)] -pub struct NamespaceRegex { - pub exclusive: Option, - pub non_exclusive: Option, +pub(crate) struct NamespaceRegex { + pub(crate) exclusive: Option, + pub(crate) non_exclusive: Option, } 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> 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 for RegistrationInfo { @@ -108,13 +108,13 @@ impl TryFrom for RegistrationInfo { } } -pub struct Service { - pub db: &'static dyn Data, +pub(crate) struct Service { + pub(crate) db: &'static dyn Data, registration_info: RwLock>, } impl Service { - pub fn build(db: &'static dyn Data) -> Result { + pub(crate) fn build(db: &'static dyn Data) -> Result { 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 { + pub(crate) async fn register_appservice(&self, yaml: Registration) -> Result { //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 { + pub(crate) async fn get_registration(&self, id: &str) -> Option { self.registration_info .read() .await @@ -172,7 +172,7 @@ impl Service { .map(|info| info.registration) } - pub async fn iter_ids(&self) -> Vec { + pub(crate) async fn iter_ids(&self) -> Vec { self.registration_info .read() .await @@ -181,7 +181,7 @@ impl Service { .collect() } - pub async fn find_from_token(&self, token: &str) -> Option { + pub(crate) async fn find_from_token(&self, token: &str) -> Option { 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>> { + pub(crate) fn read( + &self, + ) -> impl Future>> { self.registration_info.read() } } diff --git a/src/service/globals/client.rs b/src/service/globals/client.rs index 138aa164..9b67c0b4 100644 --- a/src/service/globals/client.rs +++ b/src/service/globals/client.rs @@ -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) -> Client { + pub(crate) fn new(config: &Config, resolver: &Arc) -> Client { Client { default: Self::base(config) .unwrap() diff --git a/src/service/globals/data.rs b/src/service/globals/data.rs index 15c29094..c44500ab 100644 --- a/src/service/globals/data.rs +++ b/src/service/globals/data.rs @@ -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; fn current_count(&self) -> Result; fn last_check_for_updates_id(&self) -> Result; diff --git a/src/service/globals/mod.rs b/src/service/globals/mod.rs index 1aea4e32..dfdb40af 100644 --- a/src/service/globals/mod.rs +++ b/src/service/globals/mod.rs @@ -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>>, // 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, - pub config: Config, - pub cidr_range_denylist: Vec, + pub(crate) tracing_reload_handle: tracing_subscriber::reload::Handle, + pub(crate) config: Config, + pub(crate) cidr_range_denylist: Vec, keypair: Arc, jwt_decoding_key: Option, - pub resolver: Arc, - pub client: client::Client, - pub stable_room_versions: Vec, - pub unstable_room_versions: Vec, - pub bad_event_ratelimiter: Arc>>, - pub bad_signature_ratelimiter: Arc, RateLimitState>>>, - pub bad_query_ratelimiter: Arc>>, - pub servername_ratelimiter: Arc>>>, - pub sync_receivers: RwLock>, - pub roomid_mutex_insert: RwLock>>>, - pub roomid_mutex_state: RwLock>>>, - pub roomid_mutex_federation: RwLock>>>, // this lock will be held longer - pub roomid_federationhandletime: RwLock>, - pub stateres_mutex: Arc>, + pub(crate) resolver: Arc, + pub(crate) client: client::Client, + pub(crate) stable_room_versions: Vec, + pub(crate) unstable_room_versions: Vec, + pub(crate) bad_event_ratelimiter: Arc>>, + pub(crate) bad_signature_ratelimiter: Arc, RateLimitState>>>, + pub(crate) bad_query_ratelimiter: Arc>>, + pub(crate) servername_ratelimiter: Arc>>>, + pub(crate) sync_receivers: RwLock>, + pub(crate) roomid_mutex_insert: RwLock>>>, + pub(crate) roomid_mutex_state: RwLock>>>, + pub(crate) roomid_mutex_federation: RwLock>>>, // this lock will be held longer + pub(crate) roomid_federationhandletime: RwLock>, + pub(crate) stateres_mutex: Arc>, 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 { + pub(crate) fn watch(&self) -> impl Future { 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, ) -> Result { @@ -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 { self.db.next_count() } + pub(crate) fn next_count(&self) -> Result { self.db.next_count() } #[tracing::instrument(skip(self))] - pub fn current_count(&self) -> Result { self.db.current_count() } + pub(crate) fn current_count(&self) -> Result { self.db.current_count() } #[tracing::instrument(skip(self))] - pub fn last_check_for_updates_id(&self) -> Result { self.db.last_check_for_updates_id() } + pub(crate) fn last_check_for_updates_id(&self) -> Result { 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> { &self.resolver.destinations } + pub(crate) fn actual_destinations(&self) -> &Arc> { &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 { &self.config.emergency_password } + pub(crate) fn emergency_password(&self) -> &Option { &self.config.emergency_password } - pub fn url_preview_domain_contains_allowlist(&self) -> &Vec { + pub(crate) fn url_preview_domain_contains_allowlist(&self) -> &Vec { &self.config.url_preview_domain_contains_allowlist } - pub fn url_preview_domain_explicit_allowlist(&self) -> &Vec { + pub(crate) fn url_preview_domain_explicit_allowlist(&self) -> &Vec { &self.config.url_preview_domain_explicit_allowlist } - pub fn url_preview_domain_explicit_denylist(&self) -> &Vec { + pub(crate) fn url_preview_domain_explicit_denylist(&self) -> &Vec { &self.config.url_preview_domain_explicit_denylist } - pub fn url_preview_url_contains_allowlist(&self) -> &Vec { &self.config.url_preview_url_contains_allowlist } + pub(crate) fn url_preview_url_contains_allowlist(&self) -> &Vec { + &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 { &self.config.well_known.support_page } + pub(crate) fn well_known_support_page(&self) -> &Option { &self.config.well_known.support_page } - pub fn well_known_support_role(&self) -> &Option { &self.config.well_known.support_role } + pub(crate) fn well_known_support_role(&self) -> &Option { &self.config.well_known.support_role } - pub fn well_known_support_email(&self) -> &Option { &self.config.well_known.support_email } + pub(crate) fn well_known_support_email(&self) -> &Option { &self.config.well_known.support_email } - pub fn well_known_support_mxid(&self) -> &Option { &self.config.well_known.support_mxid } + pub(crate) fn well_known_support_mxid(&self) -> &Option { &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 { + pub(crate) fn supported_room_versions(&self) -> Vec { let mut room_versions: Vec = 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> { 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> { + pub(crate) fn signing_keys_for(&self, origin: &ServerName) -> Result> { 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 { self.db.database_version() } + pub(crate) fn database_version(&self) -> Result { 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 { &self.config.well_known.client } + pub(crate) fn well_known_client(&self) -> &Option { &self.config.well_known.client } - pub fn well_known_server(&self) -> &Option { &self.config.well_known.server } + pub(crate) fn well_known_server(&self) -> &Option { &self.config.well_known.server } - pub fn unix_socket_path(&self) -> &Option { &self.config.unix_socket_path } + pub(crate) fn unix_socket_path(&self) -> &Option { &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 diff --git a/src/service/globals/resolver.rs b/src/service/globals/resolver.rs index e0c7132f..35910f5d 100644 --- a/src/service/globals/resolver.rs +++ b/src/service/globals/resolver.rs @@ -14,19 +14,19 @@ use tracing::error; use crate::{service::sending::FedDest, Config, Error}; -pub type WellKnownMap = HashMap; -pub type TlsNameMap = HashMap, u16)>; +pub(crate) type WellKnownMap = HashMap; +type TlsNameMap = HashMap, u16)>; -pub struct Resolver { - pub destinations: Arc>, // actual_destination, host - pub overrides: Arc>, - pub resolver: Arc, - pub hooked: Arc, +pub(crate) struct Resolver { + pub(crate) destinations: Arc>, // actual_destination, host + pub(crate) overrides: Arc>, + pub(crate) resolver: Arc, + pub(crate) hooked: Arc, } -pub struct Hooked { - pub overrides: Arc>, - pub resolver: Arc, +pub(crate) struct Hooked { + pub(crate) overrides: Arc>, + pub(crate) resolver: Arc, } impl Resolver { diff --git a/src/service/key_backups/data.rs b/src/service/key_backups/data.rs index ac595a6b..5aefbd49 100644 --- a/src/service/key_backups/data.rs +++ b/src/service/key_backups/data.rs @@ -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) -> Result; fn delete_backup(&self, user_id: &UserId, version: &str) -> Result<()>; diff --git a/src/service/key_backups/mod.rs b/src/service/key_backups/mod.rs index f4bb5c3b..d071ccc4 100644 --- a/src/service/key_backups/mod.rs +++ b/src/service/key_backups/mod.rs @@ -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) -> Result { + pub(crate) fn create_backup(&self, user_id: &UserId, backup_metadata: &Raw) -> Result { 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, ) -> Result { self.db.update_backup(user_id, version, backup_metadata) } - pub fn get_latest_backup_version(&self, user_id: &UserId) -> Result> { + pub(crate) fn get_latest_backup_version(&self, user_id: &UserId) -> Result> { self.db.get_latest_backup_version(user_id) } - pub fn get_latest_backup(&self, user_id: &UserId) -> Result)>> { + pub(crate) fn get_latest_backup(&self, user_id: &UserId) -> Result)>> { self.db.get_latest_backup(user_id) } - pub fn get_backup(&self, user_id: &UserId, version: &str) -> Result>> { + pub(crate) fn get_backup(&self, user_id: &UserId, version: &str) -> Result>> { 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, ) -> 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 { self.db.count_keys(user_id, version) } + pub(crate) fn count_keys(&self, user_id: &UserId, version: &str) -> Result { + self.db.count_keys(user_id, version) + } - pub fn get_etag(&self, user_id: &UserId, version: &str) -> Result { self.db.get_etag(user_id, version) } + pub(crate) fn get_etag(&self, user_id: &UserId, version: &str) -> Result { + self.db.get_etag(user_id, version) + } - pub fn get_all(&self, user_id: &UserId, version: &str) -> Result> { + pub(crate) fn get_all(&self, user_id: &UserId, version: &str) -> Result> { 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>> { 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>> { 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) } diff --git a/src/service/media/data.rs b/src/service/media/data.rs index 7cbde755..2d15bea1 100644 --- a/src/service/media/data.rs +++ b/src/service/media/data.rs @@ -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>, diff --git a/src/service/media/mod.rs b/src/service/media/mod.rs index 6d3ef196..9e83e3c4 100644 --- a/src/service/media/mod.rs +++ b/src/service/media/mod.rs @@ -15,36 +15,36 @@ use tracing::{debug, error}; use crate::{services, utils, Error, Result}; #[derive(Debug)] -pub struct FileMeta { - pub content_disposition: Option, - pub content_type: Option, - pub file: Vec, +pub(crate) struct FileMeta { + pub(crate) content_disposition: Option, + pub(crate) content_type: Option, + pub(crate) file: Vec, } #[derive(Serialize, Default)] -pub struct UrlPreviewData { +pub(crate) struct UrlPreviewData { #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:title"))] - pub title: Option, + pub(crate) title: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:description"))] - pub description: Option, + pub(crate) description: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))] - pub image: Option, + pub(crate) image: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))] - pub image_size: Option, + pub(crate) image_size: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:width"))] - pub image_width: Option, + pub(crate) image_width: Option, #[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:height"))] - pub image_height: Option, + pub(crate) image_height: Option, } -pub struct Service { - pub db: &'static dyn Data, - pub url_preview_mutex: RwLock>>>, +pub(crate) struct Service { + pub(crate) db: &'static dyn Data, + pub(crate) url_preview_mutex: RwLock>>>, } impl Service { /// Uploads a file. - pub async fn create( + pub(crate) async fn create( &self, sender_user: Option, 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, 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> { + pub(crate) async fn get(&self, mxc: String) -> Result> { 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 { + pub(crate) async fn delete_all_remote_media_at_after_time(&self, time: String) -> Result { 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> { + pub(crate) async fn get_thumbnail(&self, mxc: String, width: u32, height: u32) -> Result> { 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 { self.db.get_url_preview(url) } + pub(crate) async fn get_url_preview(&self, url: &str) -> Option { 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"); diff --git a/src/service/mod.rs b/src/service/mod.rs index 4199b423..e530a2bb 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -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, - pub admin: Arc, - pub globals: globals::Service<'a>, - pub key_backups: key_backups::Service, - pub media: media::Service, - pub sending: Arc, +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, + pub(crate) admin: Arc, + pub(crate) globals: globals::Service<'a>, + pub(crate) key_backups: key_backups::Service, + pub(crate) media: media::Service, + pub(crate) sending: Arc, } impl Services<'_> { - pub fn build< + pub(crate) fn build< D: appservice::Data + pusher::Data + rooms::Data diff --git a/src/service/pdu.rs b/src/service/pdu.rs index b63e12a9..51f276d4 100644 --- a/src/service/pdu.rs +++ b/src/service/pdu.rs @@ -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, - pub room_id: OwnedRoomId, - pub sender: OwnedUserId, +pub(crate) struct PduEvent { + pub(crate) event_id: Arc, + pub(crate) room_id: OwnedRoomId, + pub(crate) sender: OwnedUserId, #[serde(skip_serializing_if = "Option::is_none")] - pub origin: Option, - pub origin_server_ts: UInt, + pub(crate) origin: Option, + pub(crate) origin_server_ts: UInt, #[serde(rename = "type")] - pub kind: TimelineEventType, - pub content: Box, + pub(crate) kind: TimelineEventType, + pub(crate) content: Box, #[serde(skip_serializing_if = "Option::is_none")] - pub state_key: Option, - pub prev_events: Vec>, - pub depth: UInt, - pub auth_events: Vec>, + pub(crate) state_key: Option, + pub(crate) prev_events: Vec>, + pub(crate) depth: UInt, + pub(crate) auth_events: Vec>, #[serde(skip_serializing_if = "Option::is_none")] - pub redacts: Option>, + pub(crate) redacts: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] - pub unsigned: Option>, - pub hashes: EventHash, + pub(crate) unsigned: Option>, + pub(crate) hashes: EventHash, #[serde(default, skip_serializing_if = "Option::is_none")] - pub signatures: Option>, // BTreeMap, BTreeMap> + pub(crate) signatures: Option>, /* BTreeMap, BTreeMap> */ } 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> = 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> = 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>, Box) { + pub(crate) fn copy_redacts(&self) -> (Option>, Box) { if self.kind == TimelineEventType::RoomRedaction { if let Ok(mut content) = serde_json::from_str::(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 { + pub(crate) fn to_sync_room_event(&self) -> Raw { 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 { + pub(crate) fn to_any_event(&self) -> Raw { 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 { + pub(crate) fn to_room_event(&self) -> Raw { 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 { + pub(crate) fn to_message_like_event(&self) -> Raw { 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 { + pub(crate) fn to_state_event(&self) -> Raw { 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 { + pub(crate) fn to_sync_state_event(&self) -> Raw { 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 { + pub(crate) fn to_stripped_state_event(&self) -> Raw { 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 { + pub(crate) fn to_stripped_spacechild_state_event(&self) -> Raw { 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> { + pub(crate) fn to_member_event(&self) -> Raw> { 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 { + pub(crate) fn convert_to_outgoing_federation_event(mut pdu_json: CanonicalJsonObject) -> Box { 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 { + pub(crate) fn from_id_val(event_id: &EventId, mut json: CanonicalJsonObject) -> Result { 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, - pub unsigned: Option>, - pub state_key: Option, - pub redacts: Option>, + pub(crate) event_type: TimelineEventType, + pub(crate) content: Box, + pub(crate) unsigned: Option>, + pub(crate) state_key: Option, + pub(crate) redacts: Option>, } diff --git a/src/service/presence/data.rs b/src/service/presence/data.rs index 6f0f58f8..6cd1e822 100644 --- a/src/service/presence/data.rs +++ b/src/service/presence/data.rs @@ -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>; diff --git a/src/service/presence/mod.rs b/src/service/presence/mod.rs index 2be8c981..4c71d013 100644 --- a/src/service/presence/mod.rs +++ b/src/service/presence/mod.rs @@ -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, +pub(crate) struct Presence { + state: PresenceState, + currently_active: bool, + last_active_ts: u64, + status_msg: Option, } impl Presence { - pub fn new(state: PresenceState, currently_active: bool, last_active_ts: u64, status_msg: Option) -> Self { + pub(crate) fn new( + state: PresenceState, currently_active: bool, last_active_ts: u64, status_msg: Option, + ) -> Self { Self { state, currently_active, @@ -35,21 +37,21 @@ impl Presence { } } - pub fn from_json_bytes_to_event(bytes: &[u8], user_id: &UserId) -> Result { + pub(crate) fn from_json_bytes_to_event(bytes: &[u8], user_id: &UserId) -> Result { let presence = Self::from_json_bytes(bytes)?; presence.to_presence_event(user_id) } - pub fn from_json_bytes(bytes: &[u8]) -> Result { + pub(crate) fn from_json_bytes(bytes: &[u8]) -> Result { serde_json::from_slice(bytes).map_err(|_| Error::bad_database("Invalid presence data in database")) } - pub fn to_json_bytes(&self) -> Result> { + pub(crate) fn to_json_bytes(&self) -> Result> { 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 { + pub(crate) fn to_presence_event(&self, user_id: &UserId) -> Result { 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>, timeout_remote_users: bool, } impl Service { - pub fn build(db: &'static dyn Data, config: &Config) -> Arc { + pub(crate) fn build(db: &'static dyn Data, config: &Config) -> Arc { let (timer_sender, timer_receiver) = loole::unbounded(); Arc::new(Self { @@ -90,7 +92,7 @@ impl Service { }) } - pub fn start_handler(self: &Arc) { + pub(crate) fn start_handler(self: &Arc) { 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> { + pub(crate) fn get_presence(&self, user_id: &UserId) -> Result> { 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, last_active_ago: Option, status_msg: Option, ) -> 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)>> { + pub(crate) fn presence_since(&self, since: u64) -> Box)>> { self.db.presence_since(since) } diff --git a/src/service/pusher/data.rs b/src/service/pusher/data.rs index b58cd3fc..0a5e2eb9 100644 --- a/src/service/pusher/data.rs +++ b/src/service/pusher/data.rs @@ -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>; diff --git a/src/service/pusher/mod.rs b/src/service/pusher/mod.rs index 287148db..e6f7c4be 100644 --- a/src/service/pusher/mod.rs +++ b/src/service/pusher/mod.rs @@ -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> { + pub(crate) fn get_pusher(&self, sender: &UserId, pushkey: &str) -> Result> { self.db.get_pusher(sender, pushkey) } - pub fn get_pushers(&self, sender: &UserId) -> Result> { self.db.get_pushers(sender) } + pub(crate) fn get_pushers(&self, sender: &UserId) -> Result> { self.db.get_pushers(sender) } - pub fn get_pushkeys(&self, sender: &UserId) -> Box>> { + pub(crate) fn get_pushkeys(&self, sender: &UserId) -> Box>> { self.db.get_pushkeys(sender) } #[tracing::instrument(skip(self, destination, request))] - pub async fn send_request(&self, destination: &str, request: T) -> Result + pub(crate) async fn send_request(&self, destination: &str, request: T) -> Result 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, room_id: &RoomId, ) -> Result<&'a [Action]> { diff --git a/src/service/rooms/alias/data.rs b/src/service/rooms/alias/data.rs index 095d6e66..acb2ecd6 100644 --- a/src/service/rooms/alias/data.rs +++ b/src/service/rooms/alias/data.rs @@ -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<()>; diff --git a/src/service/rooms/alias/mod.rs b/src/service/rooms/alias/mod.rs index a52faefe..0c95a8a9 100644 --- a/src/service/rooms/alias/mod.rs +++ b/src/service/rooms/alias/mod.rs @@ -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> { + pub(crate) fn resolve_local_alias(&self, alias: &RoomAliasId) -> Result> { 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> + 'a> { self.db.local_aliases_for_room(room_id) } #[tracing::instrument(skip(self))] - pub fn all_local_aliases<'a>(&'a self) -> Box> + 'a> { + pub(crate) fn all_local_aliases<'a>(&'a self) -> Box> + 'a> { self.db.all_local_aliases() } } diff --git a/src/service/rooms/auth_chain/data.rs b/src/service/rooms/auth_chain/data.rs index f77d2d90..baa63ebd 100644 --- a/src/service/rooms/auth_chain/data.rs +++ b/src/service/rooms/auth_chain/data.rs @@ -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>>; fn cache_auth_chain(&self, shorteventid: Vec, auth_chain: Arc<[u64]>) -> Result<()>; } diff --git a/src/service/rooms/auth_chain/mod.rs b/src/service/rooms/auth_chain/mod.rs index f3bf50f8..9a61e4ea 100644 --- a/src/service/rooms/auth_chain/mod.rs +++ b/src/service/rooms/auth_chain/mod.rs @@ -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>, ) -> Result> + '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> { + pub(crate) async fn get_auth_chain(&self, room_id: &RoomId, starting_events: &[&EventId]) -> Result> { 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>> { + pub(crate) fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result>> { self.db.get_cached_eventid_authchain(key) } #[tracing::instrument(skip(self))] - pub fn cache_auth_chain(&self, key: Vec, auth_chain: &HashSet) -> Result<()> { + pub(crate) fn cache_auth_chain(&self, key: Vec, auth_chain: &HashSet) -> Result<()> { self.db .cache_auth_chain(key, auth_chain.iter().copied().collect::>()) } #[tracing::instrument(skip(self))] - pub fn cache_auth_chain_vec(&self, key: Vec, auth_chain: &Vec) -> Result<()> { + pub(crate) fn cache_auth_chain_vec(&self, key: Vec, auth_chain: &Vec) -> Result<()> { self.db .cache_auth_chain(key, auth_chain.iter().copied().collect::>()) } diff --git a/src/service/rooms/directory/data.rs b/src/service/rooms/directory/data.rs index 691b8604..6efb1af4 100644 --- a/src/service/rooms/directory/data.rs +++ b/src/service/rooms/directory/data.rs @@ -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<()>; diff --git a/src/service/rooms/directory/mod.rs b/src/service/rooms/directory/mod.rs index 0efc365c..63a0abbf 100644 --- a/src/service/rooms/directory/mod.rs +++ b/src/service/rooms/directory/mod.rs @@ -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 { self.db.is_public_room(room_id) } + pub(crate) fn is_public_room(&self, room_id: &RoomId) -> Result { self.db.is_public_room(room_id) } #[tracing::instrument(skip(self))] - pub fn public_rooms(&self) -> impl Iterator> + '_ { self.db.public_rooms() } + pub(crate) fn public_rooms(&self) -> impl Iterator> + '_ { self.db.public_rooms() } } diff --git a/src/service/rooms/event_handler/mod.rs b/src/service/rooms/event_handler/mod.rs index 56b9260e..47b9295f 100644 --- a/src/service/rooms/event_handler/mod.rs +++ b/src/service/rooms/event_handler/mod.rs @@ -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, val: BTreeMap, create_event: &PduEvent, origin: &ServerName, room_id: &RoomId, pub_key_map: &RwLock>>, ) -> Result>> { @@ -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, ) -> Result>>> { 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, room_id: &RoomId, room_version_id: &RoomVersionId, ) -> Result>>> { 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 diff --git a/src/service/rooms/event_handler/signing_keys.rs b/src/service/rooms/event_handler/signing_keys.rs index a01082f5..5b2583f5 100644 --- a/src/service/rooms/event_handler/signing_keys.rs +++ b/src/service/rooms/event_handler/signing_keys.rs @@ -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, ) -> Result> { let contains_all_ids = |keys: &BTreeMap| signature_ids.iter().all(|id| keys.contains_key(id)); diff --git a/src/service/rooms/lazy_loading/data.rs b/src/service/rooms/lazy_loading/data.rs index 890a2f98..36db0ac8 100644 --- a/src/service/rooms/lazy_loading/data.rs +++ b/src/service/rooms/lazy_loading/data.rs @@ -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; diff --git a/src/service/rooms/lazy_loading/mod.rs b/src/service/rooms/lazy_loading/mod.rs index 13a45987..104da8fc 100644 --- a/src/service/rooms/lazy_loading/mod.rs +++ b/src/service/rooms/lazy_loading/mod.rs @@ -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>>, + pub(crate) lazy_load_waiting: + Mutex>>, } 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 { 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, 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) } } diff --git a/src/service/rooms/metadata/data.rs b/src/service/rooms/metadata/data.rs index d702b203..58d570d0 100644 --- a/src/service/rooms/metadata/data.rs +++ b/src/service/rooms/metadata/data.rs @@ -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; fn iter_ids<'a>(&'a self) -> Box> + 'a>; fn is_disabled(&self, room_id: &RoomId) -> Result; diff --git a/src/service/rooms/metadata/mod.rs b/src/service/rooms/metadata/mod.rs index 500ddcff..dd70745a 100644 --- a/src/service/rooms/metadata/mod.rs +++ b/src/service/rooms/metadata/mod.rs @@ -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 { self.db.exists(room_id) } + pub(crate) fn exists(&self, room_id: &RoomId) -> Result { self.db.exists(room_id) } - pub fn iter_ids<'a>(&'a self) -> Box> + 'a> { self.db.iter_ids() } + pub(crate) fn iter_ids<'a>(&'a self) -> Box> + 'a> { self.db.iter_ids() } - pub fn is_disabled(&self, room_id: &RoomId) -> Result { self.db.is_disabled(room_id) } + pub(crate) fn is_disabled(&self, room_id: &RoomId) -> Result { 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 { self.db.is_banned(room_id) } + pub(crate) fn is_banned(&self, room_id: &RoomId) -> Result { 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> + 'a> { + pub(crate) fn list_banned_rooms<'a>(&'a self) -> Box> + 'a> { self.db.list_banned_rooms() } } diff --git a/src/service/rooms/mod.rs b/src/service/rooms/mod.rs index baf3f7b5..1b78b1e2 100644 --- a/src/service/rooms/mod.rs +++ b/src/service/rooms/mod.rs @@ -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, } diff --git a/src/service/rooms/outlier/data.rs b/src/service/rooms/outlier/data.rs index 18eb3190..a5202a0f 100644 --- a/src/service/rooms/outlier/data.rs +++ b/src/service/rooms/outlier/data.rs @@ -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>; fn get_outlier_pdu(&self, event_id: &EventId) -> Result>; fn add_pdu_outlier(&self, event_id: &EventId, pdu: &CanonicalJsonObject) -> Result<()>; diff --git a/src/service/rooms/outlier/mod.rs b/src/service/rooms/outlier/mod.rs index 7a6a1d01..9865b4d8 100644 --- a/src/service/rooms/outlier/mod.rs +++ b/src/service/rooms/outlier/mod.rs @@ -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> { + pub(crate) fn get_outlier_pdu_json(&self, event_id: &EventId) -> Result> { 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> { self.db.get_outlier_pdu(event_id) } + pub(crate) fn get_pdu_outlier(&self, event_id: &EventId) -> Result> { + 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) } } diff --git a/src/service/rooms/pdu_metadata/data.rs b/src/service/rooms/pdu_metadata/data.rs index 8d9a2058..d4026f55 100644 --- a/src/service/rooms/pdu_metadata/data.rs +++ b/src/service/rooms/pdu_metadata/data.rs @@ -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>( diff --git a/src/service/rooms/pdu_metadata/mod.rs b/src/service/rooms/pdu_metadata/mod.rs index c2483475..d5afe247 100644 --- a/src/service/rooms/pdu_metadata/mod.rs +++ b/src/service/rooms/pdu_metadata/mod.rs @@ -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, filter_rel_type: &Option, from: &Option, to: &Option, limit: &Option, 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> { 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]) -> Result<()> { + pub(crate) fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Arc]) -> 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 { + pub(crate) fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result { 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 { self.db.is_event_soft_failed(event_id) } + pub(crate) fn is_event_soft_failed(&self, event_id: &EventId) -> Result { + self.db.is_event_soft_failed(event_id) + } } diff --git a/src/service/rooms/read_receipt/data.rs b/src/service/rooms/read_receipt/data.rs index dcb550f8..410067d5 100644 --- a/src/service/rooms/read_receipt/data.rs +++ b/src/service/rooms/read_receipt/data.rs @@ -9,7 +9,7 @@ use crate::Result; type AnySyncEphemeralRoomEventIter<'a> = Box)>> + '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<()>; diff --git a/src/service/rooms/read_receipt/mod.rs b/src/service/rooms/read_receipt/mod.rs index 85291182..006204ab 100644 --- a/src/service/rooms/read_receipt/mod.rs +++ b/src/service/rooms/read_receipt/mod.rs @@ -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)>> + '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> { + pub(crate) fn private_read_get(&self, room_id: &RoomId, user_id: &UserId) -> Result> { 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 { + pub(crate) fn last_privateread_update(&self, user_id: &UserId, room_id: &RoomId) -> Result { self.db.last_privateread_update(user_id, room_id) } } diff --git a/src/service/rooms/search/data.rs b/src/service/rooms/search/data.rs index 96439adf..48edc42b 100644 --- a/src/service/rooms/search/data.rs +++ b/src/service/rooms/search/data.rs @@ -4,7 +4,7 @@ use crate::Result; type SearchPdusResult<'a> = Result> + 'a>, Vec)>>; -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>; diff --git a/src/service/rooms/search/mod.rs b/src/service/rooms/search/mod.rs index e75f7d14..50843ae4 100644 --- a/src/service/rooms/search/mod.rs +++ b/src/service/rooms/search/mod.rs @@ -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> + 'a, Vec)>> { self.db.search_pdus(room_id, search_string) diff --git a/src/service/rooms/short/data.rs b/src/service/rooms/short/data.rs index d0e2085f..4bbed670 100644 --- a/src/service/rooms/short/data.rs +++ b/src/service/rooms/short/data.rs @@ -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; fn multi_get_or_create_shorteventid(&self, event_id: &[&EventId]) -> Result>; diff --git a/src/service/rooms/short/mod.rs b/src/service/rooms/short/mod.rs index 1490b38a..ed2eae97 100644 --- a/src/service/rooms/short/mod.rs +++ b/src/service/rooms/short/mod.rs @@ -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 { + pub(crate) fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result { self.db.get_or_create_shorteventid(event_id) } - pub fn multi_get_or_create_shorteventid(&self, event_ids: &[&EventId]) -> Result> { + pub(crate) fn multi_get_or_create_shorteventid(&self, event_ids: &[&EventId]) -> Result> { self.db.multi_get_or_create_shorteventid(event_ids) } - pub fn get_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result> { + pub(crate) fn get_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result> { self.db.get_shortstatekey(event_type, state_key) } - pub fn get_or_create_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result { + pub(crate) fn get_or_create_shortstatekey(&self, event_type: &StateEventType, state_key: &str) -> Result { self.db.get_or_create_shortstatekey(event_type, state_key) } - pub fn get_eventid_from_short(&self, shorteventid: u64) -> Result> { + pub(crate) fn get_eventid_from_short(&self, shorteventid: u64) -> Result> { 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> { self.db.get_shortroomid(room_id) } + pub(crate) fn get_shortroomid(&self, room_id: &RoomId) -> Result> { self.db.get_shortroomid(room_id) } - pub fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result { + pub(crate) fn get_or_create_shortroomid(&self, room_id: &RoomId) -> Result { self.db.get_or_create_shortroomid(room_id) } } diff --git a/src/service/rooms/spaces/mod.rs b/src/service/rooms/spaces/mod.rs index 25bf3c22..746a14f7 100644 --- a/src/service/rooms/spaces/mod.rs +++ b/src/service/rooms/spaces/mod.rs @@ -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), Inaccessible, } -pub struct Arena { +struct Arena { nodes: Vec, max_depth: usize, first_untraversed: Option, } -pub struct Node { +struct Node { parent: Option, // Next meaning: // --> @@ -60,13 +60,13 @@ pub struct Node { // v // o o o o first_child: Option, - pub room_id: OwnedRoomId, - pub via: Vec, + room_id: OwnedRoomId, + via: Vec, 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>>, +pub(crate) struct Service { + pub(crate) roomid_spacehierarchy_cache: Mutex>>, } // 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 { 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 { diff --git a/src/service/rooms/state/data.rs b/src/service/rooms/state/data.rs index f486f1f8..88d9fe92 100644 --- a/src/service/rooms/state/data.rs +++ b/src/service/rooms/state/data.rs @@ -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>; diff --git a/src/service/rooms/state/mod.rs b/src/service/rooms/state/mod.rs index 10ffda85..bbc561f2 100644 --- a/src/service/rooms/state/mod.rs +++ b/src/service/rooms/state/mod.rs @@ -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>, ) -> Result { 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 { + pub(crate) fn append_to_state(&self, new_pdu: &PduEvent) -> Result { 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>> { + pub(crate) fn calculate_invite_state(&self, invite_event: &PduEvent) -> Result>> { 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 { + pub(crate) fn get_room_version(&self, room_id: &RoomId) -> Result { 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> { + pub(crate) fn get_room_shortstatehash(&self, room_id: &RoomId) -> Result> { self.db.get_room_shortstatehash(room_id) } - pub fn get_forward_extremities(&self, room_id: &RoomId) -> Result>> { + pub(crate) fn get_forward_extremities(&self, room_id: &RoomId) -> Result>> { 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, @@ -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>> { diff --git a/src/service/rooms/state_accessor/data.rs b/src/service/rooms/state_accessor/data.rs index 5fd58864..9bc2667f 100644 --- a/src/service/rooms/state_accessor/data.rs +++ b/src/service/rooms/state_accessor/data.rs @@ -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 diff --git a/src/service/rooms/state_accessor/mod.rs b/src/service/rooms/state_accessor/mod.rs index e03e5464..43cbb3bd 100644 --- a/src/service/rooms/state_accessor/mod.rs +++ b/src/service/rooms/state_accessor/mod.rs @@ -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>, - pub user_visibility_cache: Mutex>, +pub(crate) struct Service { + pub(crate) db: &'static dyn Data, + pub(crate) server_visibility_cache: Mutex>, + pub(crate) user_visibility_cache: Mutex>, } 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>> { + pub(crate) async fn state_full_ids(&self, shortstatehash: u64) -> Result>> { self.db.state_full_ids(shortstatehash).await } - pub async fn state_full(&self, shortstatehash: u64) -> Result>> { + pub(crate) async fn state_full( + &self, shortstatehash: u64, + ) -> Result>> { 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>> { 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>> { 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 { + pub(crate) fn server_can_see_event( + &self, origin: &ServerName, room_id: &RoomId, event_id: &EventId, + ) -> Result { 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 { + pub(crate) fn user_can_see_event(&self, user_id: &UserId, room_id: &RoomId, event_id: &EventId) -> Result { 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 { + pub(crate) fn user_can_see_state_events(&self, user_id: &UserId, room_id: &RoomId) -> Result { 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> { self.db.pdu_shortstatehash(event_id) } + pub(crate) fn pdu_shortstatehash(&self, event_id: &EventId) -> Result> { + 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>> { + pub(crate) async fn room_state_full( + &self, room_id: &RoomId, + ) -> Result>> { 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>> { 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>> { self.db.room_state_get(room_id, event_type, state_key) } - pub fn get_name(&self, room_id: &RoomId) -> Result> { + pub(crate) fn get_name(&self, room_id: &RoomId) -> Result> { services() .rooms .state_accessor @@ -268,7 +276,7 @@ impl Service { }) } - pub fn get_avatar(&self, room_id: &RoomId) -> Result> { + pub(crate) fn get_avatar(&self, room_id: &RoomId) -> Result> { services() .rooms .state_accessor @@ -279,7 +287,7 @@ impl Service { }) } - pub fn get_member(&self, room_id: &RoomId, user_id: &UserId) -> Result> { + pub(crate) fn get_member(&self, room_id: &RoomId, user_id: &UserId) -> Result> { 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 { let content = to_raw_value(&RoomMemberEventContent::new(MembershipState::Invite)) diff --git a/src/service/rooms/state_cache/data.rs b/src/service/rooms/state_cache/data.rs index 4cd9c8fa..04a5753b 100644 --- a/src/service/rooms/state_cache/data.rs +++ b/src/service/rooms/state_cache/data.rs @@ -12,7 +12,7 @@ type StrippedStateEventIter<'a> = Box = Box>)>> + '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( diff --git a/src/service/rooms/state_cache/mod.rs b/src/service/rooms/state_cache/mod.rs index d6f1ff07..fa7914e8 100644 --- a/src/service/rooms/state_cache/mod.rs +++ b/src/service/rooms/state_cache/mod.rs @@ -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>>, invite_via: Option>, 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>> { + pub(crate) fn get_our_real_users(&self, room_id: &RoomId) -> Result>> { 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 { + pub(crate) fn appservice_in_room(&self, room_id: &RoomId, appservice: &RegistrationInfo) -> Result { 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> + 'a { + pub(crate) fn room_servers<'a>(&'a self, room_id: &RoomId) -> impl Iterator> + 'a { self.db.room_servers(room_id) } #[tracing::instrument(skip(self))] - pub fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result { + pub(crate) fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result { 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> + 'a { + pub(crate) fn server_rooms<'a>(&'a self, server: &ServerName) -> impl Iterator> + '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 { + pub(crate) fn server_sees_user(&self, server: &ServerName, user_id: &UserId) -> Result { 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 { + pub(crate) fn user_sees_user(&self, user_a: &UserId, user_b: &UserId) -> Result { // 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> + 'a { + pub(crate) fn room_members<'a>(&'a self, room_id: &RoomId) -> impl Iterator> + 'a { self.db.room_members(room_id) } #[tracing::instrument(skip(self))] - pub fn room_joined_count(&self, room_id: &RoomId) -> Result> { self.db.room_joined_count(room_id) } + pub(crate) fn room_joined_count(&self, room_id: &RoomId) -> Result> { + self.db.room_joined_count(room_id) + } #[tracing::instrument(skip(self))] - pub fn room_invited_count(&self, room_id: &RoomId) -> Result> { self.db.room_invited_count(room_id) } + pub(crate) fn room_invited_count(&self, room_id: &RoomId) -> Result> { + 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> + 'a { + pub(crate) fn room_useroncejoined<'a>( + &'a self, room_id: &RoomId, + ) -> impl Iterator> + '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> + 'a { + pub(crate) fn room_members_invited<'a>( + &'a self, room_id: &RoomId, + ) -> impl Iterator> + '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> { + pub(crate) fn get_invite_count(&self, room_id: &RoomId, user_id: &UserId) -> Result> { 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> { + pub(crate) fn get_left_count(&self, room_id: &RoomId, user_id: &UserId) -> Result> { 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> + 'a { + pub(crate) fn rooms_joined<'a>(&'a self, user_id: &UserId) -> impl Iterator> + '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>)>> + 'a { self.db.rooms_invited(user_id) } #[tracing::instrument(skip(self))] - pub fn invite_state(&self, user_id: &UserId, room_id: &RoomId) -> Result>>> { + pub(crate) fn invite_state( + &self, user_id: &UserId, room_id: &RoomId, + ) -> Result>>> { self.db.invite_state(user_id, room_id) } #[tracing::instrument(skip(self))] - pub fn left_state(&self, user_id: &UserId, room_id: &RoomId) -> Result>>> { + pub(crate) fn left_state( + &self, user_id: &UserId, room_id: &RoomId, + ) -> Result>>> { 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>)>> + 'a { self.db.rooms_left(user_id) } #[tracing::instrument(skip(self))] - pub fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result { + pub(crate) fn once_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result { self.db.once_joined(user_id, room_id) } #[tracing::instrument(skip(self))] - pub fn is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result { self.db.is_joined(user_id, room_id) } + pub(crate) fn is_joined(&self, user_id: &UserId, room_id: &RoomId) -> Result { + self.db.is_joined(user_id, room_id) + } #[tracing::instrument(skip(self))] - pub fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result { + pub(crate) fn is_invited(&self, user_id: &UserId, room_id: &RoomId) -> Result { self.db.is_invited(user_id, room_id) } #[tracing::instrument(skip(self))] - pub fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> Result { self.db.is_left(user_id, room_id) } + pub(crate) fn is_left(&self, user_id: &UserId, room_id: &RoomId) -> Result { + self.db.is_left(user_id, room_id) + } #[tracing::instrument(skip(self))] - pub fn servers_invite_via(&self, room_id: &RoomId) -> Result>> { + pub(crate) fn servers_invite_via(&self, room_id: &RoomId) -> Result>> { self.db.servers_invite_via(room_id) } @@ -361,7 +377,7 @@ impl Service { /// /// See #[tracing::instrument(skip(self))] - pub fn servers_route_via(&self, room_id: &RoomId) -> Result> { + pub(crate) fn servers_route_via(&self, room_id: &RoomId) -> Result> { let most_powerful_user_server = services() .rooms .state_accessor diff --git a/src/service/rooms/state_compressor/data.rs b/src/service/rooms/state_compressor/data.rs index eddc8716..32f902a2 100644 --- a/src/service/rooms/state_compressor/data.rs +++ b/src/service/rooms/state_compressor/data.rs @@ -3,13 +3,13 @@ use std::{collections::HashSet, sync::Arc}; use super::CompressedStateEvent; use crate::Result; -pub struct StateDiff { - pub parent: Option, - pub added: Arc>, - pub removed: Arc>, +pub(crate) struct StateDiff { + pub(crate) parent: Option, + pub(crate) added: Arc>, + pub(crate) removed: Arc>, } -pub trait Data: Send + Sync { +pub(crate) trait Data: Send + Sync { fn get_statediff(&self, shortstatehash: u64) -> Result; fn save_statediff(&self, shortstatehash: u64, diff: StateDiff) -> Result<()>; } diff --git a/src/service/rooms/state_compressor/mod.rs b/src/service/rooms/state_compressor/mod.rs index 36252897..8187d8cc 100644 --- a/src/service/rooms/state_compressor/mod.rs +++ b/src/service/rooms/state_compressor/mod.rs @@ -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>, Arc>)>; -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::()]; +pub(crate) type CompressedStateEvent = [u8; 2 * size_of::()]; 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 { + pub(crate) fn compress_state_event(&self, shortstatekey: u64, event_id: &EventId) -> Result { 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)> { + pub(crate) fn parse_compressed_state_event( + &self, compressed_event: &CompressedStateEvent, + ) -> Result<(u64, Arc)> { Ok(( utils::u64_from_bytes(&compressed_event[0..size_of::()]).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>, statediffremoved: Arc>, 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>, ) -> HashSetCompressStateEvent { let previous_shortstatehash = services().rooms.state.get_room_shortstatehash(room_id)?; diff --git a/src/service/rooms/threads/data.rs b/src/service/rooms/threads/data.rs index b18f4b79..41a4bdc1 100644 --- a/src/service/rooms/threads/data.rs +++ b/src/service/rooms/threads/data.rs @@ -4,7 +4,7 @@ use crate::{PduEvent, Result}; type PduEventIterResult<'a> = Result> + '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>; diff --git a/src/service/rooms/threads/mod.rs b/src/service/rooms/threads/mod.rs index e4f7b5dd..578b21d3 100644 --- a/src/service/rooms/threads/mod.rs +++ b/src/service/rooms/threads/mod.rs @@ -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> + '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 diff --git a/src/service/rooms/timeline/data.rs b/src/service/rooms/timeline/data.rs index a036b455..48b3088e 100644 --- a/src/service/rooms/timeline/data.rs +++ b/src/service/rooms/timeline/data.rs @@ -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; /// Returns the `count` of this pdu's id. diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 94b993f8..fdc6ba67 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -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 { + pub(crate) fn try_from_string(token: &str) -> Result { 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>, + pub(crate) lasttimelinecount_cache: Mutex>, } impl Service { #[tracing::instrument(skip(self))] - pub fn first_pdu_in_room(&self, room_id: &RoomId) -> Result>> { + pub(crate) fn first_pdu_in_room(&self, room_id: &RoomId) -> Result>> { 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 { + pub(crate) fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result { 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> { self.db.get_pdu_count(event_id) } + pub(crate) fn get_pdu_count(&self, event_id: &EventId) -> Result> { + 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 { + pub(crate) fn latest_pdu_count(&self, room_id: &RoomId) -> Result { 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> { + pub(crate) fn get_room_version(&self, room_id: &RoomId) -> Result> { 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> { + pub(crate) fn get_pdu_json(&self, event_id: &EventId) -> Result> { 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> { + pub(crate) fn get_non_outlier_pdu_json(&self, event_id: &EventId) -> Result> { self.db.get_non_outlier_pdu_json(event_id) } /// Returns the pdu's id. - pub fn get_pdu_id(&self, event_id: &EventId) -> Result>> { self.db.get_pdu_id(event_id) } + pub(crate) fn get_pdu_id(&self, event_id: &EventId) -> Result>> { 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> { + pub(crate) fn get_non_outlier_pdu(&self, event_id: &EventId) -> Result> { 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>> { self.db.get_pdu(event_id) } + pub(crate) fn get_pdu(&self, event_id: &EventId) -> Result>> { 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> { self.db.get_pdu_from_id(pdu_id) } + pub(crate) fn get_pdu_from_id(&self, pdu_id: &[u8]) -> Result> { self.db.get_pdu_from_id(pdu_id) } /// Returns the pdu as a `BTreeMap`. - pub fn get_pdu_json_from_id(&self, pdu_id: &[u8]) -> Result> { + pub(crate) fn get_pdu_json_from_id(&self, pdu_id: &[u8]) -> Result> { 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> + '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> + '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> + '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, pub_key_map: &RwLock>>, ) -> Result<()> { diff --git a/src/service/rooms/typing/mod.rs b/src/service/rooms/typing/mod.rs index 6d98937f..da087835 100644 --- a/src/service/rooms/typing/mod.rs +++ b/src/service/rooms/typing/mod.rs @@ -10,17 +10,18 @@ use tracing::debug; use crate::{services, utils, Result}; -pub struct Service { - pub typing: RwLock>>, // u64 is unix timestamp of timeout - pub last_typing_update: RwLock>, /* timestamp of the last change to typing - * users */ - pub typing_update_sender: broadcast::Sender, +pub(crate) struct Service { + pub(crate) typing: RwLock>>, // u64 is unix timestamp of timeout + pub(crate) last_typing_update: RwLock>, /* timestamp of the last change to + * typing + * users */ + pub(crate) typing_update_sender: broadcast::Sender, } 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 { + pub(crate) async fn last_typing_update(&self, room_id: &RoomId) -> Result { 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> { Ok(SyncEphemeralRoomEvent { diff --git a/src/service/rooms/user/data.rs b/src/service/rooms/user/data.rs index 2fd1c29e..d10eae21 100644 --- a/src/service/rooms/user/data.rs +++ b/src/service/rooms/user/data.rs @@ -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; diff --git a/src/service/rooms/user/mod.rs b/src/service/rooms/user/mod.rs index e1741782..58d6ea55 100644 --- a/src/service/rooms/user/mod.rs +++ b/src/service/rooms/user/mod.rs @@ -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 { + pub(crate) fn notification_count(&self, user_id: &UserId, room_id: &RoomId) -> Result { self.db.notification_count(user_id, room_id) } - pub fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result { + pub(crate) fn highlight_count(&self, user_id: &UserId, room_id: &RoomId) -> Result { self.db.highlight_count(user_id, room_id) } - pub fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result { + pub(crate) fn last_notification_read(&self, user_id: &UserId, room_id: &RoomId) -> Result { 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> { + pub(crate) fn get_token_shortstatehash(&self, room_id: &RoomId, token: u64) -> Result> { self.db.get_token_shortstatehash(room_id, token) } - pub fn get_shared_rooms(&self, users: Vec) -> Result>> { + pub(crate) fn get_shared_rooms( + &self, users: Vec, + ) -> Result>> { self.db.get_shared_rooms(users) } } diff --git a/src/service/sending/data.rs b/src/service/sending/data.rs index 33066a67..532a67d7 100644 --- a/src/service/sending/data.rs +++ b/src/service/sending/data.rs @@ -6,7 +6,7 @@ use crate::Result; type OutgoingSendingIter<'a> = Box, Destination, SendingEventType)>> + 'a>; type SendingEventTypeIter<'a> = Box, 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) -> Result<()>; diff --git a/src/service/sending/mod.rs b/src/service/sending/mod.rs index 4128e3c7..c330cfcc 100644 --- a/src/service/sending/mod.rs +++ b/src/service/sending/mod.rs @@ -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, - pub sender: loole::Sender<(Destination, SendingEventType, Vec)>, + pub(crate) maximum_requests: Arc, + pub(crate) sender: loole::Sender<(Destination, SendingEventType, Vec)>, receiver: Mutex)>>, 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), // pduid Edu(Vec), // pdu json Flush, // none @@ -71,7 +71,7 @@ enum TransactionStatus { } impl Service { - pub fn build(db: &'static dyn Data, config: &Config) -> Arc { + pub(crate) fn build(db: &'static dyn Data, config: &Config) -> Arc { 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) -> Result<()> { + pub(crate) fn send_pdu_appservice(&self, appservice_id: String, pdu_id: Vec) -> 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>(&self, servers: I, pdu_id: &[u8]) -> Result<()> { + pub(crate) fn send_pdu_servers>( + &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) -> Result<()> { + pub(crate) fn send_edu_server(&self, server: &ServerName, serialized: Vec) -> 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) -> Result<()> { + pub(crate) fn send_edu_room(&self, room_id: &RoomId, serialized: Vec) -> Result<()> { let servers = services() .rooms .state_cache @@ -168,7 +170,9 @@ impl Service { } #[tracing::instrument(skip(self, servers, serialized))] - pub fn send_edu_servers>(&self, servers: I, serialized: Vec) -> Result<()> { + pub(crate) fn send_edu_servers>( + &self, servers: I, serialized: Vec, + ) -> 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>(&self, servers: I) -> Result<()> { + pub(crate) fn flush_servers>(&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(&self, dest: &ServerName, request: T) -> Result + pub(crate) async fn send_federation_request(&self, dest: &ServerName, request: T) -> Result 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( + pub(crate) async fn send_appservice_request( &self, registration: Registration, request: T, ) -> Result> where @@ -258,7 +262,7 @@ impl Service { response } - pub fn start_handler(self: &Arc) { + pub(crate) fn start_handler(self: &Arc) { 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>, u64)> { + pub(crate) fn select_edus(&self, server_name: &ServerName) -> Result<(Vec>, 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>, ) -> Result { // 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>, ) -> Result { 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 { + pub(crate) fn get_prefix(&self) -> Vec { let mut prefix = match self { Destination::Appservice(server) => { let mut p = b"+".to_vec(); diff --git a/src/service/sending/send.rs b/src/service/sending/send.rs index 9c292a82..f08024e4 100644 --- a/src/service/sending/send.rs +++ b/src/service/sending/send.rs @@ -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), } diff --git a/src/service/transaction_ids/data.rs b/src/service/transaction_ids/data.rs index 2aed1981..1a0abb62 100644 --- a/src/service/transaction_ids/data.rs +++ b/src/service/transaction_ids/data.rs @@ -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<()>; diff --git a/src/service/transaction_ids/mod.rs b/src/service/transaction_ids/mod.rs index bc55861a..0bdaf925 100644 --- a/src/service/transaction_ids/mod.rs +++ b/src/service/transaction_ids/mod.rs @@ -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>> { self.db.existing_txnid(user_id, device_id, txn_id) diff --git a/src/service/uiaa/data.rs b/src/service/uiaa/data.rs index 3a157068..1b43ff8f 100644 --- a/src/service/uiaa/data.rs +++ b/src/service/uiaa/data.rs @@ -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<()>; diff --git a/src/service/uiaa/mod.rs b/src/service/uiaa/mod.rs index 695aa963..6e38bbcc 100644 --- a/src/service/uiaa/mod.rs +++ b/src/service/uiaa/mod.rs @@ -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 { self.db.get_uiaa_request(user_id, device_id, session) diff --git a/src/service/users/data.rs b/src/service/users/data.rs index 04074e85..9ce7ecdc 100644 --- a/src/service/users/data.rs +++ b/src/service/users/data.rs @@ -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; diff --git a/src/service/users/mod.rs b/src/service/users/mod.rs index b2fdeaf0..6889c57b 100644 --- a/src/service/users/mod.rs +++ b/src/service/users/mod.rs @@ -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, subscriptions: BTreeMap, known_rooms: BTreeMap>, // For every room, the roomsince number @@ -34,23 +34,25 @@ pub struct SlidingSyncCache { type DbConnections = Mutex>>>; -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 { self.db.exists(user_id) } + pub(crate) fn exists(&self, user_id: &UserId) -> Result { 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> { 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, ) { @@ -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, globalsince: u64, ) { @@ -230,10 +232,10 @@ impl Service { } /// Check if account is deactivated - pub fn is_deactivated(&self, user_id: &UserId) -> Result { self.db.is_deactivated(user_id) } + pub(crate) fn is_deactivated(&self, user_id: &UserId) -> Result { self.db.is_deactivated(user_id) } /// Check if a user is an admin - pub fn is_admin(&self, user_id: &UserId) -> Result { + pub(crate) fn is_admin(&self, user_id: &UserId) -> Result { 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 { self.db.count() } + pub(crate) fn count(&self) -> Result { self.db.count() } /// Find out which user an access token belongs to. - pub fn find_from_token(&self, token: &str) -> Result> { + pub(crate) fn find_from_token(&self, token: &str) -> Result> { self.db.find_from_token(token) } /// Returns an iterator over all users on this homeserver. - pub fn iter(&self) -> impl Iterator> + '_ { self.db.iter() } + pub(crate) fn iter(&self) -> impl Iterator> + '_ { 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> { self.db.list_local_users() } + pub(crate) fn list_local_users(&self) -> Result> { self.db.list_local_users() } /// Returns the password hash for the given user. - pub fn password_hash(&self, user_id: &UserId) -> Result> { self.db.password_hash(user_id) } + pub(crate) fn password_hash(&self, user_id: &UserId) -> Result> { 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> { self.db.displayname(user_id) } + pub(crate) fn displayname(&self, user_id: &UserId) -> Result> { 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) -> Result<()> { + pub(crate) async fn set_displayname(&self, user_id: &UserId, displayname: Option) -> Result<()> { self.db.set_displayname(user_id, displayname) } /// Get the avatar_url of a user. - pub fn avatar_url(&self, user_id: &UserId) -> Result> { self.db.avatar_url(user_id) } + pub(crate) fn avatar_url(&self, user_id: &UserId) -> Result> { 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) -> Result<()> { + pub(crate) async fn set_avatar_url(&self, user_id: &UserId, avatar_url: Option) -> Result<()> { self.db.set_avatar_url(user_id, avatar_url) } /// Get the blurhash of a user. - pub fn blurhash(&self, user_id: &UserId) -> Result> { self.db.blurhash(user_id) } + pub(crate) fn blurhash(&self, user_id: &UserId) -> Result> { 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) -> Result<()> { + pub(crate) async fn set_blurhash(&self, user_id: &UserId, blurhash: Option) -> 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, ) -> 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> + 'a { + pub(crate) fn all_device_ids<'a>(&'a self, user_id: &UserId) -> impl Iterator> + '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, ) -> 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 { + pub(crate) fn last_one_time_keys_update(&self, user_id: &UserId) -> Result { 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)>> { 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> { 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) -> Result<()> { + pub(crate) fn add_device_keys( + &self, user_id: &UserId, device_id: &DeviceId, device_keys: &Raw, + ) -> 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, self_signing_key: &Option>, user_signing_key: &Option>, 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, ) -> impl Iterator> + '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>> { + pub(crate) fn get_device_keys(&self, user_id: &UserId, device_id: &DeviceId) -> Result>> { 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, ) -> Result<(Vec, 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>> { 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>> { 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>> { self.db .get_self_signing_key(sender_user, user_id, allowed_signatures) } - pub fn get_user_signing_key(&self, user_id: &UserId) -> Result>> { + pub(crate) fn get_user_signing_key(&self, user_id: &UserId) -> Result>> { 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>> { + pub(crate) fn get_to_device_events( + &self, user_id: &UserId, device_id: &DeviceId, + ) -> Result>> { 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> { + pub(crate) fn get_device_metadata(&self, user_id: &UserId, device_id: &DeviceId) -> Result> { self.db.get_device_metadata(user_id, device_id) } - pub fn get_devicelist_version(&self, user_id: &UserId) -> Result> { + pub(crate) fn get_devicelist_version(&self, user_id: &UserId) -> Result> { self.db.get_devicelist_version(user_id) } - pub fn all_devices_metadata<'a>(&'a self, user_id: &UserId) -> impl Iterator> + 'a { + pub(crate) fn all_devices_metadata<'a>(&'a self, user_id: &UserId) -> impl Iterator> + '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 { + pub(crate) fn create_filter(&self, user_id: &UserId, filter: &FilterDefinition) -> Result { self.db.create_filter(user_id, filter) } - pub fn get_filter(&self, user_id: &UserId, filter_id: &str) -> Result> { + pub(crate) fn get_filter(&self, user_id: &UserId, filter_id: &str) -> Result> { self.db.get_filter(user_id, filter_id) } } diff --git a/src/utils/error.rs b/src/utils/error.rs index cd106035..47c6947e 100644 --- a/src/utils/error.rs +++ b/src/utils/error.rs @@ -17,10 +17,10 @@ use ErrorKind::{ use crate::RumaResponse; -pub type Result = std::result::Result; +pub(crate) type Result = std::result::Result; #[derive(Error)] -pub enum Error { +pub(crate) enum Error { #[cfg(feature = "sqlite")] #[error("There was a problem with the connection to the sqlite database: {source}")] Sqlite { @@ -83,19 +83,19 @@ pub enum Error { } impl Error { - pub fn bad_database(message: &'static str) -> Self { + pub(crate) fn bad_database(message: &'static str) -> Self { error!("BadDatabase: {}", message); Self::BadDatabase(message) } - pub fn bad_config(message: &str) -> Self { + pub(crate) fn bad_config(message: &str) -> Self { error!("BadConfig: {}", message); Self::BadConfig(message.to_owned()) } } impl Error { - pub fn to_response(&self) -> RumaResponse { + pub(crate) fn to_response(&self) -> RumaResponse { if let Self::Uiaa(uiaainfo) = self { return RumaResponse(UiaaResponse::AuthResponse(uiaainfo.clone())); } @@ -152,7 +152,7 @@ impl Error { } /// Returns the Matrix error code / error kind - pub fn error_code(&self) -> ErrorKind { + pub(crate) fn error_code(&self) -> ErrorKind { if let Self::Federation(_, error) = self { return error.error_kind().unwrap_or(&Unknown).clone(); } @@ -164,7 +164,7 @@ impl Error { } /// Sanitizes public-facing errors that can leak sensitive information. - pub fn sanitized_error(&self) -> String { + pub(crate) fn sanitized_error(&self) -> String { let db_error = String::from("Database or I/O error occurred."); match self { diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 248ff144..7ec47db5 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -37,7 +37,7 @@ pub(crate) fn increment(old: Option<&[u8]>) -> Vec { number.to_be_bytes().to_vec() } -pub fn generate_keypair() -> Vec { +pub(crate) fn generate_keypair() -> Vec { let mut value = random_string(8).as_bytes().to_vec(); value.push(0xFF); value.extend_from_slice( @@ -47,25 +47,25 @@ pub fn generate_keypair() -> Vec { } /// Parses the bytes into an u64. -pub fn u64_from_bytes(bytes: &[u8]) -> Result { +pub(crate) fn u64_from_bytes(bytes: &[u8]) -> Result { let array: [u8; 8] = bytes.try_into()?; Ok(u64::from_be_bytes(array)) } /// Parses the bytes into a string. -pub fn string_from_bytes(bytes: &[u8]) -> Result { +pub(crate) fn string_from_bytes(bytes: &[u8]) -> Result { String::from_utf8(bytes.to_vec()) } /// Parses a `OwnedUserId` from bytes. -pub fn user_id_from_bytes(bytes: &[u8]) -> Result { +pub(crate) fn user_id_from_bytes(bytes: &[u8]) -> Result { OwnedUserId::try_from( string_from_bytes(bytes).map_err(|_| Error::bad_database("Failed to parse string from bytes"))?, ) .map_err(|_| Error::bad_database("Failed to parse user id from bytes")) } -pub fn random_string(length: usize) -> String { +pub(crate) fn random_string(length: usize) -> String { thread_rng() .sample_iter(&rand::distributions::Alphanumeric) .take(length) @@ -74,7 +74,7 @@ pub fn random_string(length: usize) -> String { } /// Calculate a new hash for the given password -pub fn calculate_password_hash(password: &str) -> Result { +pub(crate) fn calculate_password_hash(password: &str) -> Result { let salt = SaltString::generate(thread_rng()); services() .globals @@ -84,7 +84,7 @@ pub fn calculate_password_hash(password: &str) -> Result Vec { +pub(crate) fn calculate_hash(keys: &[&[u8]]) -> Vec { // We only hash the pdu's event ids, not the whole pdu let bytes = keys.join(&0xFF); let hash = digest::digest(&digest::SHA256, &bytes);