fix some more pedantic clippy lints

Signed-off-by: strawberry <strawberry@puppygock.gay>
This commit is contained in:
strawberry 2024-03-23 14:38:15 -04:00 committed by June
parent a7e6fe8b60
commit 7bd56765ef
22 changed files with 136 additions and 126 deletions

View file

@ -396,11 +396,9 @@ workspace = true
[workspace.lints.rust] [workspace.lints.rust]
missing_abi = "warn" missing_abi = "warn"
# missing_docs = "warn"
noop_method_call = "warn" noop_method_call = "warn"
pointer_structural_match = "warn" pointer_structural_match = "warn"
explicit_outlives_requirements = "warn" explicit_outlives_requirements = "warn"
# unreachable_pub = "warn"
unused_extern_crates = "warn" unused_extern_crates = "warn"
unused_import_braces = "warn" unused_import_braces = "warn"
unused_lifetimes = "warn" unused_lifetimes = "warn"
@ -418,6 +416,11 @@ unit_bindings = "warn"
# this seems to suggest broken code and is not working correctly # this seems to suggest broken code and is not working correctly
unused_braces = "allow" unused_braces = "allow"
# some sadness
unreachable_pub = "allow"
missing_docs = "allow"
[workspace.lints.clippy] [workspace.lints.clippy]
# pedantic = "warn" # pedantic = "warn"
@ -435,51 +438,36 @@ char_lit_as_u8 = "warn"
dbg_macro = "warn" dbg_macro = "warn"
empty_structs_with_brackets = "warn" empty_structs_with_brackets = "warn"
get_unwrap = "warn" get_unwrap = "warn"
# if_then_some_else_none = "warn"
# let_underscore_must_use = "warn"
# map_err_ignore = "warn"
# missing_docs_in_private_items = "warn"
negative_feature_names = "warn" negative_feature_names = "warn"
pub_without_shorthand = "warn" pub_without_shorthand = "warn"
rc_buffer = "warn" rc_buffer = "warn"
rc_mutex = "warn" rc_mutex = "warn"
redundant_feature_names = "warn" redundant_feature_names = "warn"
redundant_type_annotations = "warn" redundant_type_annotations = "warn"
# ref_patterns = "warn"
rest_pat_in_fully_bound_structs = "warn" rest_pat_in_fully_bound_structs = "warn"
str_to_string = "warn" str_to_string = "warn"
# string_add = "warn"
# string_slice = "warn"
string_to_string = "warn" string_to_string = "warn"
tests_outside_test_module = "warn" tests_outside_test_module = "warn"
undocumented_unsafe_blocks = "warn" undocumented_unsafe_blocks = "warn"
unneeded_field_pattern = "warn" unneeded_field_pattern = "warn"
unseparated_literal_suffix = "warn" unseparated_literal_suffix = "warn"
# unwrap_used = "warn"
# expect_used = "warn"
wildcard_dependencies = "warn" wildcard_dependencies = "warn"
or_fun_call = "warn" or_fun_call = "warn"
unnecessary_lazy_evaluations = "warn" unnecessary_lazy_evaluations = "warn"
# as_conversions = "warn"
assertions_on_result_states = "warn" assertions_on_result_states = "warn"
default_union_representation = "warn" default_union_representation = "warn"
deref_by_slicing = "warn" deref_by_slicing = "warn"
empty_drop = "warn" empty_drop = "warn"
# error_impl_error = "warn"
exit = "warn" exit = "warn"
filetype_is_file = "warn" filetype_is_file = "warn"
float_cmp_const = "warn" float_cmp_const = "warn"
format_push_string = "warn" format_push_string = "warn"
impl_trait_in_params = "warn" impl_trait_in_params = "warn"
ref_to_mut = "warn" ref_to_mut = "warn"
# let_underscore_untyped = "warn"
lossy_float_literal = "warn" lossy_float_literal = "warn"
mem_forget = "warn" mem_forget = "warn"
missing_assert_message = "warn" missing_assert_message = "warn"
# mod_module_files = "warn"
# multiple_inherent_impl = "warn"
mutex_atomic = "warn" mutex_atomic = "warn"
# same_name_method = "warn"
semicolon_outside_block = "warn" semicolon_outside_block = "warn"
fn_to_numeric_cast = "warn" fn_to_numeric_cast = "warn"
fn_to_numeric_cast_with_truncation = "warn" fn_to_numeric_cast_with_truncation = "warn"
@ -490,9 +478,7 @@ unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn" unnecessary_safety_doc = "warn"
unnecessary_self_imports = "warn" unnecessary_self_imports = "warn"
verbose_file_reads = "warn" verbose_file_reads = "warn"
# cast_precision_loss = "warn"
cast_possible_wrap = "warn" cast_possible_wrap = "warn"
# cast_possible_truncation = "warn"
redundant_closure_for_method_calls = "warn" redundant_closure_for_method_calls = "warn"
large_futures = "warn" large_futures = "warn"
semicolon_if_nothing_returned = "warn" semicolon_if_nothing_returned = "warn"
@ -511,6 +497,32 @@ unnecessary_wraps = "warn"
match_same_arms = "warn" match_same_arms = "warn"
ignored_unit_patterns = "warn" ignored_unit_patterns = "warn"
redundant_else = "warn" redundant_else = "warn"
explicit_into_iter_loop = "warn"
used_underscore_binding = "warn"
needless_pass_by_value = "warn"
too_many_lines = "warn"
let_underscore_untyped = "warn"
# not in rust 1.75.0 (breaks CI) # some sadness
# infinite_loop = "warn" missing_errors_doc = "allow"
missing_panics_doc = "allow"
module_name_repetitions = "allow"
if_not_else = "allow"
doc_markdown = "allow"
cast_possible_truncation = "allow"
cast_precision_loss = "allow"
cast_sign_loss = "allow"
same_name_method = "allow"
mod_module_files = "allow"
unwrap_used = "allow"
expect_used = "allow"
if_then_some_else_none = "allow"
let_underscore_must_use = "allow"
map_err_ignore = "allow"
missing_docs_in_private_items = "allow"
multiple_inherent_impl = "allow"
error_impl_error = "allow"
as_conversions = "allow"
string_add = "allow"
string_slice = "allow"
ref_patterns = "allow"

1
clippy.toml Normal file
View file

@ -0,0 +1 @@
too-many-lines-threshold = 500

View file

@ -144,9 +144,8 @@ pub(crate) async fn get_alias_helper(room_alias: OwnedRoomAliasId) -> Result<get
}, },
}; };
let room_id = match room_id { let Some(room_id) = room_id else {
Some(room_id) => room_id, return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found."));
None => return Err(Error::BadRequest(ErrorKind::NotFound, "Room with alias not found.")),
}; };
let mut servers: Vec<OwnedServerName> = Vec::new(); let mut servers: Vec<OwnedServerName> = Vec::new();

View file

@ -143,22 +143,18 @@ pub async fn get_context_route(body: Ruma<get_context::v3::Request>) -> Result<g
let (event_type, state_key) = services().rooms.short.get_statekey_from_short(shortstatekey)?; let (event_type, state_key) = services().rooms.short.get_statekey_from_short(shortstatekey)?;
if event_type != StateEventType::RoomMember { if event_type != StateEventType::RoomMember {
let pdu = match services().rooms.timeline.get_pdu(&id)? { let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
Some(pdu) => pdu,
None => {
error!("Pdu in state not found: {}", id); error!("Pdu in state not found: {}", id);
continue; continue;
},
}; };
state.push(pdu.to_state_event()); state.push(pdu.to_state_event());
} else if !lazy_load_enabled || lazy_loaded.contains(&state_key) { } else if !lazy_load_enabled || lazy_loaded.contains(&state_key) {
let pdu = match services().rooms.timeline.get_pdu(&id)? { let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
Some(pdu) => pdu,
None => {
error!("Pdu in state not found: {}", id); error!("Pdu in state not found: {}", id);
continue; continue;
},
}; };
state.push(pdu.to_state_event()); state.push(pdu.to_state_event());
} }
} }

View file

@ -151,7 +151,6 @@ pub async fn upload_signatures_route(
.as_object() .as_object()
.ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature."))? .ok_or(Error::BadRequest(ErrorKind::InvalidParam, "Invalid signature."))?
.clone() .clone()
.into_iter()
{ {
// Signature validation? // Signature validation?
let signature = ( let signature = (

View file

@ -634,9 +634,8 @@ async fn download_html(client: &reqwest::Client, url: &str) -> Result<UrlPreview
} }
} }
let body = String::from_utf8_lossy(&bytes); let body = String::from_utf8_lossy(&bytes);
let html = match HTML::from_string(body.to_string(), Some(url.to_owned())) { let Ok(html) = HTML::from_string(body.to_string(), Some(url.to_owned())) else {
Ok(html) => html, return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to parse HTML"));
Err(_) => return Err(Error::BadRequest(ErrorKind::Unknown, "Failed to parse HTML")),
}; };
let mut data = match html.opengraph.images.first() { let mut data = match html.opengraph.images.first() {
@ -653,7 +652,7 @@ async fn download_html(client: &reqwest::Client, url: &str) -> Result<UrlPreview
Ok(data) Ok(data)
} }
fn url_request_allowed(addr: &IpAddr) -> bool { pub(crate) fn url_request_allowed(addr: &IpAddr) -> bool {
// TODO: make this check ip_range_denylist // TODO: make this check ip_range_denylist
// could be implemented with reqwest when it supports IP filtering: // could be implemented with reqwest when it supports IP filtering:

View file

@ -1264,12 +1264,12 @@ pub async fn leave_all_rooms(user_id: &UserId) -> Result<()> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for room_id in all_rooms { for room_id in all_rooms {
let room_id = match room_id { let Ok(room_id) = room_id else {
Ok(room_id) => room_id, continue;
Err(_) => continue,
}; };
let _ = leave_room(user_id, &room_id, None).await; // ignore errors
_ = leave_room(user_id, &room_id, None).await;
} }
Ok(()) Ok(())

View file

@ -68,7 +68,7 @@ pub async fn set_displayname_route(
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default()); Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default());
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await; _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await;
} }
if services().globals.allow_local_presence() { if services().globals.allow_local_presence() {
@ -179,7 +179,7 @@ pub async fn set_avatar_url_route(body: Ruma<set_avatar_url::v3::Request>) -> Re
Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default()); Arc::clone(services().globals.roomid_mutex_state.write().await.entry(room_id.clone()).or_default());
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
let _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await; _ = services().rooms.timeline.build_and_append_pdu(pdu_builder, sender_user, &room_id, &state_lock).await;
} }
if services().globals.allow_local_presence() { if services().globals.allow_local_presence() {

View file

@ -513,7 +513,7 @@ pub async fn create_room_route(body: Ruma<create_room::v3::Request>) -> Result<c
// 8. Events implied by invite (and TODO: invite_3pid) // 8. Events implied by invite (and TODO: invite_3pid)
drop(state_lock); drop(state_lock);
for user_id in &body.invite { for user_id in &body.invite {
let _ = invite_helper(sender_user, user_id, &room_id, None, body.is_direct).await; _ = invite_helper(sender_user, user_id, &room_id, None, body.is_direct).await;
} }
// Homeserver specific stuff // Homeserver specific stuff
@ -819,7 +819,7 @@ pub async fn upgrade_room_route(body: Ruma<upgrade_room::v3::Request>) -> Result
// Modify the power levels in the old room to prevent sending of events and // Modify the power levels in the old room to prevent sending of events and
// inviting new users // inviting new users
let _ = services() _ = services()
.rooms .rooms
.timeline .timeline
.build_and_append_pdu( .build_and_append_pdu(

View file

@ -146,7 +146,7 @@ async fn sync_helper_wrapper(
} }
} }
let _ = tx.send(Some(r.map(|(r, _)| r))); _ = tx.send(Some(r.map(|(r, _)| r)));
} }
async fn sync_helper( async fn sync_helper(
@ -300,12 +300,9 @@ async fn sync_helper(
// TODO: Delete the following line when this is resolved: https://github.com/vector-im/element-web/issues/22565 // TODO: Delete the following line when this is resolved: https://github.com/vector-im/element-web/issues/22565
|| *sender_user == state_key || *sender_user == state_key
{ {
let pdu = match services().rooms.timeline.get_pdu(&id)? { let Some(pdu) = services().rooms.timeline.get_pdu(&id)? else {
Some(pdu) => pdu,
None => {
error!("Pdu in state not found: {}", id); error!("Pdu in state not found: {}", id);
continue; continue;
},
}; };
left_state_events.push(pdu.to_sync_state_event()); left_state_events.push(pdu.to_sync_state_event());
@ -431,7 +428,7 @@ async fn sync_helper(
device_unused_fallback_key_types: None, device_unused_fallback_key_types: None,
}; };
// TODO: Retry the endpoint instead of returning (waiting for #118) // TODO: Retry the endpoint instead of returning
if !full_state if !full_state
&& response.rooms.is_empty() && response.rooms.is_empty()
&& response.presence.is_empty() && response.presence.is_empty()
@ -445,7 +442,7 @@ async fn sync_helper(
if duration.as_secs() > 30 { if duration.as_secs() > 30 {
duration = Duration::from_secs(30); duration = Duration::from_secs(30);
} }
let _ = tokio::time::timeout(duration, watcher).await; _ = tokio::time::timeout(duration, watcher).await;
Ok((response, false)) Ok((response, false))
} else { } else {
Ok((response, since != next_batch)) // Only cache if we made progress Ok((response, since != next_batch)) // Only cache if we made progress
@ -1382,7 +1379,7 @@ pub async fn sync_events_v4_route(
if duration.as_secs() > 30 { if duration.as_secs() > 30 {
duration = Duration::from_secs(30); duration = Duration::from_secs(30);
} }
let _ = tokio::time::timeout(duration, watcher).await; _ = tokio::time::timeout(duration, watcher).await;
} }
Ok(sync_events::v4::Response { Ok(sync_events::v4::Response {

View file

@ -174,7 +174,7 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
if !self.old_cfs.contains(&name.to_owned()) { if !self.old_cfs.contains(&name.to_owned()) {
// Create if it didn't exist // Create if it didn't exist
debug!("Creating new column family in database: {}", name); debug!("Creating new column family in database: {}", name);
let _ = self.rocks.create_cf(name, &self.opts); _ = self.rocks.create_cf(name, &self.opts);
} }
Ok(Arc::new(RocksDbEngineTree { Ok(Arc::new(RocksDbEngineTree {
@ -253,8 +253,8 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
match engine.create_new_backup_flush(&self.rocks, true) { match engine.create_new_backup_flush(&self.rocks, true) {
Err(e) => return Err(Box::new(e)), Err(e) => return Err(Box::new(e)),
Ok(()) => { Ok(()) => {
let _info = engine.get_backup_info(); let engine_info = engine.get_backup_info();
let info = &_info.last().unwrap(); let info = &engine_info.last().unwrap();
info!( info!(
"Created database backup #{} using {} bytes in {} files", "Created database backup #{} using {} bytes in {} files",
info.backup_id, info.size, info.num_files, info.backup_id, info.size, info.num_files,

View file

@ -38,7 +38,7 @@ impl<T> Drop for NonAliasingBox<T> {
// this was done. // this was done.
#[allow(clippy::undocumented_unsafe_blocks)] #[allow(clippy::undocumented_unsafe_blocks)]
unsafe { unsafe {
let _ = Box::from_raw(self.0); _ = Box::from_raw(self.0);
}; };
} }
} }

View file

@ -47,7 +47,7 @@ impl Watchers {
let mut watchers = self.watchers.write().unwrap(); let mut watchers = self.watchers.write().unwrap();
for prefix in triggered { for prefix in triggered {
if let Some(tx) = watchers.remove(prefix) { if let Some(tx) = watchers.remove(prefix) {
let _ = tx.0.send(()); _ = tx.0.send(());
} }
} }
}; };

View file

@ -237,6 +237,7 @@ impl KeyValueDatabase {
} }
/// Load an existing database or create a new one. /// Load an existing database or create a new one.
#[allow(clippy::too_many_lines)]
pub async fn load_or_create(config: Config) -> Result<()> { pub async fn load_or_create(config: Config) -> Result<()> {
Self::check_db_setup(&config)?; Self::check_db_setup(&config)?;
@ -397,7 +398,7 @@ impl KeyValueDatabase {
let db = Box::leak(db_raw); let db = Box::leak(db_raw);
let services_raw = Box::new(Services::build(db, config)?); let services_raw = Box::new(Services::build(db, &config)?);
// This is the first and only time we initialize the SERVICE static // This is the first and only time we initialize the SERVICE static
*SERVICES.write().unwrap() = Some(Box::leak(services_raw)); *SERVICES.write().unwrap() = Some(Box::leak(services_raw));
@ -1040,7 +1041,7 @@ impl KeyValueDatabase {
}, },
} }
let _ = Self::try_handle_updates().await; _ = Self::try_handle_updates().await;
} }
}); });
} }

View file

@ -435,6 +435,7 @@ async fn run_server() -> io::Result<()> {
tokio::fs::set_permissions(path, Permissions::from_mode(octal_perms)).await.unwrap(); tokio::fs::set_permissions(path, Permissions::from_mode(octal_perms)).await.unwrap();
let socket = SocketIncoming::from_listener(listener); let socket = SocketIncoming::from_listener(listener);
#[allow(clippy::let_underscore_untyped)] // error[E0658]: attributes on expressions are experimental
#[cfg(feature = "systemd")] #[cfg(feature = "systemd")]
let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]); let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]);
@ -486,6 +487,7 @@ async fn run_server() -> io::Result<()> {
} }
} }
#[allow(clippy::let_underscore_untyped)] // error[E0658]: attributes on expressions are experimental
#[cfg(feature = "systemd")] #[cfg(feature = "systemd")]
let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]); let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]);
@ -507,6 +509,7 @@ async fn run_server() -> io::Result<()> {
join_set.spawn(bind(*addr).handle(handle.clone()).serve(app.clone())); join_set.spawn(bind(*addr).handle(handle.clone()).serve(app.clone()));
} }
#[allow(clippy::let_underscore_untyped)] // error[E0658]: attributes on expressions are experimental
#[cfg(feature = "systemd")] #[cfg(feature = "systemd")]
let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]); let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]);
@ -785,6 +788,7 @@ async fn shutdown_signal(handle: ServerHandle, tx: Sender<()>) -> Result<()> {
services().globals.shutdown(); services().globals.shutdown();
#[allow(clippy::let_underscore_untyped)] // error[E0658]: attributes on expressions are experimental
#[cfg(feature = "systemd")] #[cfg(feature = "systemd")]
let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Stopping]); let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Stopping]);
@ -800,6 +804,7 @@ async fn shutdown_signal(handle: ServerHandle, tx: Sender<()>) -> Result<()> {
handle.connection_count() handle.connection_count()
); );
#[allow(clippy::let_underscore_untyped)] // error[E0658]: attributes on expressions are experimental
#[cfg(feature = "systemd")] #[cfg(feature = "systemd")]
let _ = sd_notify::notify(true, &[sd_notify::NotifyState::ExtendTimeoutUsec(120)]); let _ = sd_notify::notify(true, &[sd_notify::NotifyState::ExtendTimeoutUsec(120)]);
} }

View file

@ -589,6 +589,7 @@ impl Service {
AdminCommand::try_parse_from(argv).map_err(|error| error.to_string()) AdminCommand::try_parse_from(argv).map_err(|error| error.to_string())
} }
#[allow(clippy::too_many_lines)]
async fn process_admin_command(&self, command: AdminCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> { async fn process_admin_command(&self, command: AdminCommand, body: Vec<&str>) -> Result<RoomMessageEventContent> {
let reply_message_content = match command { let reply_message_content = match command {
AdminCommand::Appservices(command) => match command { AdminCommand::Appservices(command) => match command {
@ -787,8 +788,8 @@ impl Service {
} }
return Ok(RoomMessageEventContent::text_plain(format!( return Ok(RoomMessageEventContent::text_plain(format!(
"Deleted {} total MXCs from our database and the filesystem from event ID {event_id}.", "Deleted {mxc_deletion_count} total MXCs from our database and the filesystem from \
mxc_deletion_count event ID {event_id}."
))); )));
} }
@ -1050,7 +1051,7 @@ impl Service {
if leave_rooms { if leave_rooms {
for &user_id in &user_ids { for &user_id in &user_ids {
let _ = leave_all_rooms(user_id).await; _ = leave_all_rooms(user_id).await;
} }
} }
@ -1236,7 +1237,8 @@ impl Service {
evicting admins too)", evicting admins too)",
&local_user, &room_id &local_user, &room_id
); );
let _ = leave_room(&local_user, &room_id, None).await;
_ = leave_room(&local_user, &room_id, None).await;
} }
} else { } else {
for local_user in services() for local_user in services()
@ -1364,7 +1366,7 @@ impl Service {
errors, evicting admins too)", errors, evicting admins too)",
&local_user, room_id &local_user, room_id
); );
let _ = leave_room(&local_user, room_id, None).await; _ = leave_room(&local_user, room_id, None).await;
} }
} else { } else {
for local_user in services() for local_user in services()
@ -1632,11 +1634,11 @@ impl Service {
(_, Ok(None)) => match services().rooms.alias.set_alias(&room_alias, &room_id) { (_, Ok(None)) => match services().rooms.alias.set_alias(&room_alias, &room_id) {
Ok(()) => RoomMessageEventContent::text_plain("Successfully set alias"), Ok(()) => RoomMessageEventContent::text_plain("Successfully set alias"),
Err(err) => { Err(err) => {
RoomMessageEventContent::text_plain(format!("Failed to remove alias: {}", err)) RoomMessageEventContent::text_plain(format!("Failed to remove alias: {err}"))
}, },
}, },
(_, Err(err)) => { (_, Err(err)) => {
RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {}", err)) RoomMessageEventContent::text_plain(format!("Unable to lookup alias: {err}"))
}, },
}, },
RoomAliasCommand::Remove { RoomAliasCommand::Remove {
@ -1671,14 +1673,14 @@ impl Service {
}, },
RoomAliasCommand::List { RoomAliasCommand::List {
room_id, room_id,
} => match room_id { } => {
Some(room_id) => { if let Some(room_id) = room_id {
let aliases = let aliases =
services().rooms.alias.local_aliases_for_room(&room_id).collect::<Result<Vec<_>, _>>(); services().rooms.alias.local_aliases_for_room(&room_id).collect::<Result<Vec<_>, _>>();
match aliases { match aliases {
Ok(aliases) => { Ok(aliases) => {
let plain_list = aliases.iter().fold(String::new(), |mut output, alias| { let plain_list = aliases.iter().fold(String::new(), |mut output, alias| {
writeln!(output, "- {}", alias).unwrap(); writeln!(output, "- {alias}").unwrap();
output output
}); });
@ -1687,22 +1689,21 @@ impl Service {
output output
}); });
let plain = format!("Aliases for {}:\n{}", room_id, plain_list); let plain = format!("Aliases for {room_id}:\n{plain_list}");
let html = format!("Aliases for {}:\n<ul>{}</ul>", room_id, html_list); let html = format!("Aliases for {room_id}:\n<ul>{html_list}</ul>");
RoomMessageEventContent::text_html(plain, html) RoomMessageEventContent::text_html(plain, html)
}, },
Err(err) => { Err(err) => {
RoomMessageEventContent::text_plain(format!("Unable to list aliases: {}", err)) RoomMessageEventContent::text_plain(format!("Unable to list aliases: {}", err))
}, },
} }
}, } else {
None => {
let aliases = services().rooms.alias.all_local_aliases().collect::<Result<Vec<_>, _>>(); let aliases = services().rooms.alias.all_local_aliases().collect::<Result<Vec<_>, _>>();
match aliases { match aliases {
Ok(aliases) => { Ok(aliases) => {
let server_name = services().globals.server_name(); let server_name = services().globals.server_name();
let plain_list = aliases.iter().fold(String::new(), |mut output, (alias, id)| { let plain_list = aliases.iter().fold(String::new(), |mut output, (alias, id)| {
writeln!(output, "- `{}` -> #{}:{}", alias, id, server_name).unwrap(); writeln!(output, "- `{alias}` -> #{id}:{server_name}").unwrap();
output output
}); });
@ -1718,15 +1719,15 @@ impl Service {
output output
}); });
let plain = format!("Aliases:\n{}", plain_list); let plain = format!("Aliases:\n{plain_list}");
let html = format!("Aliases:\n<ul>{}</ul>", html_list); let html = format!("Aliases:\n<ul>{html_list}</ul>");
RoomMessageEventContent::text_html(plain, html) RoomMessageEventContent::text_html(plain, html)
}, },
Err(err) => { Err(e) => {
RoomMessageEventContent::text_plain(format!("Unable to list room aliases: {}", err)) RoomMessageEventContent::text_plain(format!("Unable to list room aliases: {e}"))
}, },
} }
}, }
}, },
}, },
RoomCommand::Directory(command) => match command { RoomCommand::Directory(command) => match command {

View file

@ -106,11 +106,11 @@ impl RotationHandler {
let mut r = self.0.subscribe(); let mut r = self.0.subscribe();
async move { async move {
let _ = r.recv().await; _ = r.recv().await;
} }
} }
pub fn fire(&self) { let _ = self.0.send(()); } pub fn fire(&self) { _ = self.0.send(()); }
} }
impl Default for RotationHandler { impl Default for RotationHandler {
@ -233,7 +233,7 @@ impl Client {
} }
impl Service<'_> { impl Service<'_> {
pub fn load(db: &'static dyn Data, config: Config) -> Result<Self> { pub fn load(db: &'static dyn Data, config: &Config) -> Result<Self> {
let keypair = db.load_keypair(); let keypair = db.load_keypair();
let keypair = match keypair { let keypair = match keypair {
@ -282,7 +282,7 @@ impl Service<'_> {
})?, })?,
actual_destination_cache: Arc::new(RwLock::new(WellKnownMap::new())), actual_destination_cache: Arc::new(RwLock::new(WellKnownMap::new())),
tls_name_override: tls_name_override.clone(), tls_name_override: tls_name_override.clone(),
client: Client::new(&config, &tls_name_override), client: Client::new(config, &tls_name_override),
jwt_decoding_key, jwt_decoding_key,
stable_room_versions, stable_room_versions,
unstable_room_versions, unstable_room_versions,

View file

@ -52,7 +52,7 @@ impl Services<'_> {
+ sending::Data + sending::Data
+ 'static, + 'static,
>( >(
db: &'static D, config: Config, db: &'static D, config: &Config,
) -> Result<Self> { ) -> Result<Self> {
Ok(Self { Ok(Self {
appservice: appservice::Service::build(db)?, appservice: appservice::Service::build(db)?,
@ -160,7 +160,7 @@ impl Services<'_> {
db, db,
url_preview_mutex: RwLock::new(HashMap::new()), url_preview_mutex: RwLock::new(HashMap::new()),
}, },
sending: sending::Service::build(db, &config), sending: sending::Service::build(db, config),
globals: globals::Service::load(db, config)?, globals: globals::Service::load(db, config)?,
}) })

View file

@ -18,7 +18,7 @@ impl Service {
pub async fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> { pub async fn typing_add(&self, user_id: &UserId, room_id: &RoomId, timeout: u64) -> Result<()> {
self.typing.write().await.entry(room_id.to_owned()).or_default().insert(user_id.to_owned(), timeout); self.typing.write().await.entry(room_id.to_owned()).or_default().insert(user_id.to_owned(), timeout);
self.last_typing_update.write().await.insert(room_id.to_owned(), services().globals.next_count()?); self.last_typing_update.write().await.insert(room_id.to_owned(), services().globals.next_count()?);
let _ = self.typing_update_sender.send(room_id.to_owned()); _ = self.typing_update_sender.send(room_id.to_owned());
Ok(()) Ok(())
} }
@ -26,7 +26,7 @@ impl Service {
pub async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> { pub async fn typing_remove(&self, user_id: &UserId, room_id: &RoomId) -> Result<()> {
self.typing.write().await.entry(room_id.to_owned()).or_default().remove(user_id); self.typing.write().await.entry(room_id.to_owned()).or_default().remove(user_id);
self.last_typing_update.write().await.insert(room_id.to_owned(), services().globals.next_count()?); self.last_typing_update.write().await.insert(room_id.to_owned(), services().globals.next_count()?);
let _ = self.typing_update_sender.send(room_id.to_owned()); _ = self.typing_update_sender.send(room_id.to_owned());
Ok(()) Ok(())
} }
@ -68,7 +68,7 @@ impl Service {
room.remove(&user); room.remove(&user);
} }
self.last_typing_update.write().await.insert(room_id.to_owned(), services().globals.next_count()?); self.last_typing_update.write().await.insert(room_id.to_owned(), services().globals.next_count()?);
let _ = self.typing_update_sender.send(room_id.to_owned()); _ = self.typing_update_sender.send(room_id.to_owned());
} }
Ok(()) Ok(())

View file

@ -1143,7 +1143,7 @@ impl Service {
{ {
let mut server_key_ids = HashMap::new(); let mut server_key_ids = HashMap::new();
for event in events.into_iter() { for event in events {
debug!("Fetching keys for event: {event:?}"); debug!("Fetching keys for event: {event:?}");
for (signature_server, signature) in event for (signature_server, signature) in event
.get("signatures") .get("signatures")
@ -1391,10 +1391,10 @@ impl Service {
// Try to fetch keys, failure is okay // Try to fetch keys, failure is okay
// Servers we couldn't find in the cache will be added to `servers` // Servers we couldn't find in the cache will be added to `servers`
for pdu in &event.room_state.state { for pdu in &event.room_state.state {
let _ = self.get_server_keys_from_cache(pdu, &mut servers, room_version, &mut pkm).await; _ = self.get_server_keys_from_cache(pdu, &mut servers, room_version, &mut pkm).await;
} }
for pdu in &event.room_state.auth_chain { for pdu in &event.room_state.auth_chain {
let _ = self.get_server_keys_from_cache(pdu, &mut servers, room_version, &mut pkm).await; _ = self.get_server_keys_from_cache(pdu, &mut servers, room_version, &mut pkm).await;
} }
drop(pkm); drop(pkm);

View file

@ -329,7 +329,7 @@ impl Service {
let mut children = Vec::new(); let mut children = Vec::new();
let mut inaccessible_children = Vec::new(); let mut inaccessible_children = Vec::new();
for child in get_parent_children(*room.clone(), suggested_only) { for child in get_parent_children(&room.clone(), suggested_only) {
match self match self
.get_summary_and_children(&child, suggested_only, Identifier::ServerName(server_name)) .get_summary_and_children(&child, suggested_only, Identifier::ServerName(server_name))
.await? .await?
@ -379,7 +379,7 @@ impl Service {
Ok( Ok(
if let Some(children_pdus) = get_stripped_space_child_events(current_room).await? { if let Some(children_pdus) = get_stripped_space_child_events(current_room).await? {
let summary = self.get_room_summary(current_room, children_pdus, identifier); let summary = self.get_room_summary(current_room, children_pdus, &identifier);
if let Ok(summary) = summary { if let Ok(summary) = summary {
self.roomid_spacehierarchy_cache.lock().await.insert( self.roomid_spacehierarchy_cache.lock().await.insert(
current_room.clone(), current_room.clone(),
@ -485,7 +485,7 @@ impl Service {
fn get_room_summary( fn get_room_summary(
&self, current_room: &OwnedRoomId, children_state: Vec<Raw<HierarchySpaceChildEvent>>, &self, current_room: &OwnedRoomId, children_state: Vec<Raw<HierarchySpaceChildEvent>>,
identifier: Identifier<'_>, identifier: &Identifier<'_>,
) -> Result<SpaceHierarchyParentSummary, Error> { ) -> Result<SpaceHierarchyParentSummary, Error> {
let room_id: &RoomId = current_room; let room_id: &RoomId = current_room;
@ -504,7 +504,7 @@ impl Service {
let allowed_room_ids = allowed_room_ids(join_rule.clone()); let allowed_room_ids = allowed_room_ids(join_rule.clone());
if !is_accessable_child(current_room, &join_rule.clone().into(), &identifier, &allowed_room_ids)? { if !is_accessable_child(current_room, &join_rule.clone().into(), identifier, &allowed_room_ids)? {
debug!("User is not allowed to see room {room_id}"); debug!("User is not allowed to see room {room_id}");
// This error will be caught later // This error will be caught later
return Err(Error::BadRequest(ErrorKind::Forbidden, "User is not allowed to see the room")); return Err(Error::BadRequest(ErrorKind::Forbidden, "User is not allowed to see the room"));
@ -590,7 +590,7 @@ impl Service {
let mut results = Vec::new(); let mut results = Vec::new();
let root = arena.first_untraversed().expect("The node just added is not traversed"); let root = arena.first_untraversed().expect("The node just added is not traversed");
arena.push(root, get_parent_children(*summary.clone(), suggested_only)); arena.push(root, get_parent_children(&summary.clone(), suggested_only));
results.push(summary_to_chunk(*summary.clone())); results.push(summary_to_chunk(*summary.clone()));
while let Some(current_room) = arena.first_untraversed() { while let Some(current_room) = arena.first_untraversed() {
@ -603,7 +603,7 @@ impl Service {
) )
.await? .await?
{ {
let children = get_parent_children(*summary.clone(), suggested_only); let children = get_parent_children(&summary.clone(), suggested_only);
arena.push(current_room, children); arena.push(current_room, children);
if left_to_skip > 0 { if left_to_skip > 0 {
@ -837,7 +837,7 @@ fn allowed_room_ids(join_rule: JoinRule) -> Vec<OwnedRoomId> {
/// Returns the children of a SpaceHierarchyParentSummary, making use of the /// Returns the children of a SpaceHierarchyParentSummary, making use of the
/// children_state field /// children_state field
fn get_parent_children(parent: SpaceHierarchyParentSummary, suggested_only: bool) -> Vec<OwnedRoomId> { fn get_parent_children(parent: &SpaceHierarchyParentSummary, suggested_only: bool) -> Vec<OwnedRoomId> {
parent parent
.children_state .children_state
.iter() .iter()
@ -861,10 +861,10 @@ mod tests {
use super::*; use super::*;
fn first(arena: &mut Arena, room_id: OwnedRoomId) { fn first(arena: &mut Arena, room_id: &OwnedRoomId) {
let first_untrav = arena.first_untraversed().unwrap(); let first_untrav = arena.first_untraversed().unwrap();
assert_eq!(arena.get(first_untrav).unwrap().room_id, room_id); assert_eq!(&arena.get(first_untrav).unwrap().room_id, room_id);
} }
#[test] #[test]
@ -896,16 +896,16 @@ mod tests {
vec![owned_room_id!("!room1:example.org"), owned_room_id!("!room2:example.org")], vec![owned_room_id!("!room1:example.org"), owned_room_id!("!room2:example.org")],
); );
first(&mut arena, owned_room_id!("!room1:example.org")); first(&mut arena, &owned_room_id!("!room1:example.org"));
first(&mut arena, owned_room_id!("!room2:example.org")); first(&mut arena, &owned_room_id!("!room2:example.org"));
arena.push( arena.push(
subspace2, subspace2,
vec![owned_room_id!("!room3:example.org"), owned_room_id!("!room4:example.org")], vec![owned_room_id!("!room3:example.org"), owned_room_id!("!room4:example.org")],
); );
first(&mut arena, owned_room_id!("!room3:example.org")); first(&mut arena, &owned_room_id!("!room3:example.org"));
first(&mut arena, owned_room_id!("!room4:example.org")); first(&mut arena, &owned_room_id!("!room4:example.org"));
let foo_node = NodeId { let foo_node = NodeId {
index: 1, index: 1,
@ -931,7 +931,7 @@ mod tests {
let room1 = arena.first_untraversed().unwrap(); let room1 = arena.first_untraversed().unwrap();
arena.push(room1, vec![]); arena.push(room1, vec![]);
first(&mut arena, owned_room_id!("!room2:example.org")); first(&mut arena, &owned_room_id!("!room2:example.org"));
assert!(arena.first_untraversed().is_none()); assert!(arena.first_untraversed().is_none());
} }
@ -973,9 +973,9 @@ mod tests {
], ],
); );
first(&mut arena, owned_room_id!("!room1:example.org")); first(&mut arena, &owned_room_id!("!room1:example.org"));
first(&mut arena, owned_room_id!("!room3:example.org")); first(&mut arena, &owned_room_id!("!room3:example.org"));
first(&mut arena, owned_room_id!("!room5:example.org")); first(&mut arena, &owned_room_id!("!room5:example.org"));
let subspace2 = arena.first_untraversed().unwrap(); let subspace2 = arena.first_untraversed().unwrap();
@ -986,9 +986,9 @@ mod tests {
vec![owned_room_id!("!room1:example.org"), owned_room_id!("!room2:example.org")], vec![owned_room_id!("!room1:example.org"), owned_room_id!("!room2:example.org")],
); );
first(&mut arena, owned_room_id!("!room1:example.org")); first(&mut arena, &owned_room_id!("!room1:example.org"));
first(&mut arena, owned_room_id!("!room2:example.org")); first(&mut arena, &owned_room_id!("!room2:example.org"));
first(&mut arena, owned_room_id!("!foo:example.org")); first(&mut arena, &owned_room_id!("!foo:example.org"));
assert_eq!(arena.first_untraversed(), None); assert_eq!(arena.first_untraversed(), None);
} }
@ -1052,14 +1052,14 @@ mod tests {
.into(); .into();
assert_eq!( assert_eq!(
get_parent_children(summary.clone(), false), get_parent_children(&summary, false),
vec![ vec![
owned_room_id!("!foo:example.org"), owned_room_id!("!foo:example.org"),
owned_room_id!("!bar:example.org"), owned_room_id!("!bar:example.org"),
owned_room_id!("!baz:example.org") owned_room_id!("!baz:example.org")
] ]
); );
assert_eq!(get_parent_children(summary, true), vec![owned_room_id!("!bar:example.org")]); assert_eq!(get_parent_children(&summary, true), vec![owned_room_id!("!bar:example.org")]);
} }
#[test] #[test]
@ -1191,10 +1191,10 @@ mod tests {
); );
assert_eq!(arena.nodes.len(), 7); assert_eq!(arena.nodes.len(), 7);
first(&mut arena, owned_room_id!("!room1:example.org")); first(&mut arena, &owned_room_id!("!room1:example.org"));
first(&mut arena, owned_room_id!("!room1:example.org")); first(&mut arena, &owned_room_id!("!room1:example.org"));
first(&mut arena, owned_room_id!("!room1:example.org")); first(&mut arena, &owned_room_id!("!room1:example.org"));
first(&mut arena, owned_room_id!("!subspace2:example.org")); first(&mut arena, &owned_room_id!("!subspace2:example.org"));
assert!(arena.first_untraversed().is_none()); assert!(arena.first_untraversed().is_none());
} }
} }

View file

@ -409,7 +409,7 @@ impl Service {
} }
#[tracing::instrument(skip(self, server, serialized))] #[tracing::instrument(skip(self, server, serialized))]
pub fn send_reliable_edu(&self, server: &ServerName, serialized: Vec<u8>, _id: u64) -> Result<()> { pub fn send_reliable_edu(&self, server: &ServerName, serialized: Vec<u8>, id: u64) -> Result<()> {
let outgoing_kind = OutgoingKind::Normal(server.to_owned()); let outgoing_kind = OutgoingKind::Normal(server.to_owned());
let event = SendingEventType::Edu(serialized); let event = SendingEventType::Edu(serialized);
let _cork = services().globals.db.cork()?; let _cork = services().globals.db.cork()?;
@ -446,7 +446,7 @@ impl Service {
.map(OutgoingKind::Normal) .map(OutgoingKind::Normal)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for outgoing_kind in requests.into_iter() { for outgoing_kind in requests {
self.sender.send((outgoing_kind, SendingEventType::Flush, Vec::<u8>::new())).unwrap(); self.sender.send((outgoing_kind, SendingEventType::Flush, Vec::<u8>::new())).unwrap();
} }