Merge branch 'Nyaaori/code-cleanup' into 'next'

Code Cleanup

See merge request famedly/conduit!441
This commit is contained in:
Timo Kösters 2022-12-21 10:00:40 +00:00
commit 48bc0db723
15 changed files with 56 additions and 92 deletions

View file

@ -225,8 +225,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
services() services()
.admin .admin
.send_message(RoomMessageEventContent::notice_plain(format!( .send_message(RoomMessageEventContent::notice_plain(format!(
"New user {} registered on this server.", "New user {user_id} registered on this server."
user_id
))); )));
// If this is the first real user, grant them admin privileges // If this is the first real user, grant them admin privileges
@ -318,8 +317,7 @@ pub async fn change_password_route(
services() services()
.admin .admin
.send_message(RoomMessageEventContent::notice_plain(format!( .send_message(RoomMessageEventContent::notice_plain(format!(
"User {} changed their password.", "User {sender_user} changed their password."
sender_user
))); )));
Ok(change_password::v3::Response {}) Ok(change_password::v3::Response {})
@ -396,8 +394,7 @@ pub async fn deactivate_route(
services() services()
.admin .admin
.send_message(RoomMessageEventContent::notice_plain(format!( .send_message(RoomMessageEventContent::notice_plain(format!(
"User {} deactivated their account.", "User {sender_user} deactivated their account."
sender_user
))); )));
Ok(deactivate::v3::Response { Ok(deactivate::v3::Response {

View file

@ -361,7 +361,7 @@ pub(crate) async fn get_public_rooms_filtered_helper(
let prev_batch = if num_since == 0 { let prev_batch = if num_since == 0 {
None None
} else { } else {
Some(format!("p{}", num_since)) Some(format!("p{num_since}"))
}; };
let next_batch = if chunk.len() < limit as usize { let next_batch = if chunk.len() < limit as usize {

View file

@ -583,7 +583,7 @@ async fn join_room_by_id_helper(
if let Some(signed_raw) = &send_join_response.room_state.event { if let Some(signed_raw) = &send_join_response.room_state.event {
let (signed_event_id, signed_value) = let (signed_event_id, signed_value) =
match gen_event_id_canonical_json(&signed_raw, &room_version_id) { match gen_event_id_canonical_json(signed_raw, &room_version_id) {
Ok(t) => t, Ok(t) => t,
Err(_) => { Err(_) => {
// Event could not be converted to canonical json // Event could not be converted to canonical json
@ -594,7 +594,7 @@ async fn join_room_by_id_helper(
} }
}; };
if &signed_event_id != event_id { if signed_event_id != event_id {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Server sent event with wrong event id", "Server sent event with wrong event id",
@ -753,12 +753,12 @@ async fn join_room_by_id_helper(
.set_room_state(room_id, statehash_after_join, &state_lock)?; .set_room_state(room_id, statehash_after_join, &state_lock)?;
} else { } else {
let join_rules_event = services().rooms.state_accessor.room_state_get( let join_rules_event = services().rooms.state_accessor.room_state_get(
&room_id, room_id,
&StateEventType::RoomJoinRules, &StateEventType::RoomJoinRules,
"", "",
)?; )?;
let power_levels_event = services().rooms.state_accessor.room_state_get( let power_levels_event = services().rooms.state_accessor.room_state_get(
&room_id, room_id,
&StateEventType::RoomPowerLevels, &StateEventType::RoomPowerLevels,
"", "",
)?; )?;
@ -835,8 +835,7 @@ async fn join_room_by_id_helper(
.state_cache .state_cache
.room_members(restriction_room_id) .room_members(restriction_room_id)
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.filter(|uid| uid.server_name() == services().globals.server_name()) .find(|uid| uid.server_name() == services().globals.server_name())
.next()
}); });
Some(authorized_user) Some(authorized_user)
}) })
@ -982,7 +981,7 @@ async fn join_room_by_id_helper(
} }
}; };
if &signed_event_id != event_id { if signed_event_id != event_id {
return Err(Error::BadRequest( return Err(Error::BadRequest(
ErrorKind::InvalidParam, ErrorKind::InvalidParam,
"Server sent event with wrong event id", "Server sent event with wrong event id",
@ -1179,7 +1178,7 @@ pub(crate) async fn invite_helper<'a>(
user_id.server_name(), user_id.server_name(),
create_invite::v2::Request { create_invite::v2::Request {
room_id: room_id.to_owned(), room_id: room_id.to_owned(),
event_id: (&*pdu.event_id).to_owned(), event_id: (*pdu.event_id).to_owned(),
room_version: room_version_id.clone(), room_version: room_version_id.clone(),
event: PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()), event: PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()),
invite_room_state, invite_room_state,

View file

@ -308,8 +308,7 @@ impl Credentials for XMatrix {
fn decode(value: &http::HeaderValue) -> Option<Self> { fn decode(value: &http::HeaderValue) -> Option<Self> {
debug_assert!( debug_assert!(
value.as_bytes().starts_with(b"X-Matrix "), value.as_bytes().starts_with(b"X-Matrix "),
"HeaderValue to decode should start with \"X-Matrix ..\", received = {:?}", "HeaderValue to decode should start with \"X-Matrix ..\", received = {value:?}",
value,
); );
let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..]) let parameters = str::from_utf8(&value.as_bytes()["X-Matrix ".len()..])

View file

@ -84,8 +84,8 @@ pub enum FedDest {
impl FedDest { impl FedDest {
fn into_https_string(self) -> String { fn into_https_string(self) -> String {
match self { match self {
Self::Literal(addr) => format!("https://{}", addr), Self::Literal(addr) => format!("https://{addr}"),
Self::Named(host, port) => format!("https://{}{}", host, port), Self::Named(host, port) => format!("https://{host}{port}"),
} }
} }
@ -385,7 +385,7 @@ async fn find_actual_destination(destination: &'_ ServerName) -> (FedDest, FedDe
} }
if let Some(port) = force_port { if let Some(port) = force_port {
FedDest::Named(delegated_hostname, format!(":{}", port)) FedDest::Named(delegated_hostname, format!(":{port}"))
} else { } else {
add_port_to_hostname(&delegated_hostname) add_port_to_hostname(&delegated_hostname)
} }
@ -427,7 +427,7 @@ async fn find_actual_destination(destination: &'_ ServerName) -> (FedDest, FedDe
} }
if let Some(port) = force_port { if let Some(port) = force_port {
FedDest::Named(hostname.clone(), format!(":{}", port)) FedDest::Named(hostname.clone(), format!(":{port}"))
} else { } else {
add_port_to_hostname(&hostname) add_port_to_hostname(&hostname)
} }
@ -460,7 +460,7 @@ async fn query_srv_record(hostname: &'_ str) -> Option<FedDest> {
if let Ok(Some(host_port)) = services() if let Ok(Some(host_port)) = services()
.globals .globals
.dns_resolver() .dns_resolver()
.srv_lookup(format!("_matrix._tcp.{}", hostname)) .srv_lookup(format!("_matrix._tcp.{hostname}"))
.await .await
.map(|srv| { .map(|srv| {
srv.iter().next().map(|result| { srv.iter().next().map(|result| {
@ -482,10 +482,7 @@ async fn request_well_known(destination: &str) -> Option<String> {
&services() &services()
.globals .globals
.default_client() .default_client()
.get(&format!( .get(&format!("https://{destination}/.well-known/matrix/server"))
"https://{}/.well-known/matrix/server",
destination
))
.send() .send()
.await .await
.ok()? .ok()?

View file

@ -197,7 +197,7 @@ impl fmt::Display for Config {
msg += &format!("{}: {}\n", line.1 .0, line.1 .1); msg += &format!("{}: {}\n", line.1 .0, line.1 .1);
} }
write!(f, "{}", msg) write!(f, "{msg}")
} }
} }

View file

@ -106,7 +106,7 @@ impl KeyValueDatabaseEngine for Arc<Engine> {
} }
fn open_tree(&self, name: &str) -> Result<Arc<dyn KvTree>> { fn open_tree(&self, name: &str) -> Result<Arc<dyn KvTree>> {
self.write_lock().execute(&format!("CREATE TABLE IF NOT EXISTS {} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )", name), [])?; self.write_lock().execute(&format!("CREATE TABLE IF NOT EXISTS {name} ( \"key\" BLOB PRIMARY KEY, \"value\" BLOB NOT NULL )"), [])?;
Ok(Arc::new(SqliteTable { Ok(Arc::new(SqliteTable {
engine: Arc::clone(self), engine: Arc::clone(self),

View file

@ -827,7 +827,7 @@ impl KeyValueDatabase {
let rule = rules_list.content.get(content_rule_transformation[0]); let rule = rules_list.content.get(content_rule_transformation[0]);
if rule.is_some() { if rule.is_some() {
let mut rule = rule.unwrap().clone(); let mut rule = rule.unwrap().clone();
rule.rule_id = content_rule_transformation[1].to_string(); rule.rule_id = content_rule_transformation[1].to_owned();
rules_list.content.remove(content_rule_transformation[0]); rules_list.content.remove(content_rule_transformation[0]);
rules_list.content.insert(rule); rules_list.content.insert(rule);
} }
@ -850,7 +850,7 @@ impl KeyValueDatabase {
let rule = rules_list.underride.get(transformation[0]); let rule = rules_list.underride.get(transformation[0]);
if let Some(rule) = rule { if let Some(rule) = rule {
let mut rule = rule.clone(); let mut rule = rule.clone();
rule.rule_id = transformation[1].to_string(); rule.rule_id = transformation[1].to_owned();
rules_list.underride.remove(transformation[0]); rules_list.underride.remove(transformation[0]);
rules_list.underride.insert(rule); rules_list.underride.insert(rule);
} }

View file

@ -68,10 +68,7 @@ async fn main() {
let config = match raw_config.extract::<Config>() { let config = match raw_config.extract::<Config>() {
Ok(s) => s, Ok(s) => s,
Err(e) => { Err(e) => {
eprintln!( eprintln!("It looks like your config is invalid. The following error occurred: {e}");
"It looks like your config is invalid. The following error occurred: {}",
e
);
std::process::exit(1); std::process::exit(1);
} }
}; };
@ -91,8 +88,7 @@ async fn main() {
Ok(s) => s, Ok(s) => s,
Err(e) => { Err(e) => {
eprintln!( eprintln!(
"It looks like your log config is invalid. The following error occurred: {}", "It looks like your log config is invalid. The following error occurred: {e}"
e
); );
EnvFilter::try_new("warn").unwrap() EnvFilter::try_new("warn").unwrap()
} }
@ -118,7 +114,7 @@ async fn main() {
let filter_layer = match EnvFilter::try_new(&config.log) { let filter_layer = match EnvFilter::try_new(&config.log) {
Ok(s) => s, Ok(s) => s,
Err(e) => { Err(e) => {
eprintln!("It looks like your config is invalid. The following error occured while parsing it: {}", e); eprintln!("It looks like your config is invalid. The following error occured while parsing it: {e}");
EnvFilter::try_new("warn").unwrap() EnvFilter::try_new("warn").unwrap()
} }
}; };
@ -534,6 +530,6 @@ fn method_to_filter(method: Method) -> MethodFilter {
Method::POST => MethodFilter::POST, Method::POST => MethodFilter::POST,
Method::PUT => MethodFilter::PUT, Method::PUT => MethodFilter::PUT,
Method::TRACE => MethodFilter::TRACE, Method::TRACE => MethodFilter::TRACE,
m => panic!("Unsupported HTTP method: {:?}", m), m => panic!("Unsupported HTTP method: {m:?}"),
} }
} }

View file

@ -287,13 +287,11 @@ impl Service {
Err(error) => { Err(error) => {
let markdown_message = format!( let markdown_message = format!(
"Encountered an error while handling the command:\n\ "Encountered an error while handling the command:\n\
```\n{}\n```", ```\n{error}\n```",
error,
); );
let html_message = format!( let html_message = format!(
"Encountered an error while handling the command:\n\ "Encountered an error while handling the command:\n\
<pre>\n{}\n</pre>", <pre>\n{error}\n</pre>",
error,
); );
RoomMessageEventContent::text_html(markdown_message, html_message) RoomMessageEventContent::text_html(markdown_message, html_message)
@ -338,17 +336,14 @@ impl Service {
match parsed_config { match parsed_config {
Ok(yaml) => match services().appservice.register_appservice(yaml) { Ok(yaml) => match services().appservice.register_appservice(yaml) {
Ok(id) => RoomMessageEventContent::text_plain(format!( Ok(id) => RoomMessageEventContent::text_plain(format!(
"Appservice registered with ID: {}.", "Appservice registered with ID: {id}."
id
)), )),
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Failed to register appservice: {}", "Failed to register appservice: {e}"
e
)), )),
}, },
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Could not parse appservice config: {}", "Could not parse appservice config: {e}"
e
)), )),
} }
} else { } else {
@ -365,8 +360,7 @@ impl Service {
{ {
Ok(()) => RoomMessageEventContent::text_plain("Appservice unregistered."), Ok(()) => RoomMessageEventContent::text_plain("Appservice unregistered."),
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Failed to unregister appservice: {}", "Failed to unregister appservice: {e}"
e
)), )),
}, },
AdminCommand::ListAppservices => { AdminCommand::ListAppservices => {
@ -459,8 +453,7 @@ impl Service {
.count(); .count();
let elapsed = start.elapsed(); let elapsed = start.elapsed();
RoomMessageEventContent::text_plain(format!( RoomMessageEventContent::text_plain(format!(
"Loaded auth chain with length {} in {:?}", "Loaded auth chain with length {count} in {elapsed:?}"
count, elapsed
)) ))
} else { } else {
RoomMessageEventContent::text_plain("Event not found.") RoomMessageEventContent::text_plain("Event not found.")
@ -474,30 +467,26 @@ impl Service {
Ok(value) => { Ok(value) => {
match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) { match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
Ok(hash) => { Ok(hash) => {
let event_id = EventId::parse(format!("${}", hash)); let event_id = EventId::parse(format!("${hash}"));
match serde_json::from_value::<PduEvent>( match serde_json::from_value::<PduEvent>(
serde_json::to_value(value).expect("value is json"), serde_json::to_value(value).expect("value is json"),
) { ) {
Ok(pdu) => RoomMessageEventContent::text_plain(format!( Ok(pdu) => RoomMessageEventContent::text_plain(format!(
"EventId: {:?}\n{:#?}", "EventId: {event_id:?}\n{pdu:#?}"
event_id, pdu
)), )),
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"EventId: {:?}\nCould not parse event: {}", "EventId: {event_id:?}\nCould not parse event: {e}"
event_id, e
)), )),
} }
} }
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Could not parse PDU JSON: {:?}", "Could not parse PDU JSON: {e:?}"
e
)), )),
} }
} }
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Invalid json in command body: {}", "Invalid json in command body: {e}"
e
)), )),
} }
} else { } else {
@ -545,8 +534,7 @@ impl Service {
AdminCommand::DatabaseMemoryUsage => match services().globals.db.memory_usage() { AdminCommand::DatabaseMemoryUsage => match services().globals.db.memory_usage() {
Ok(response) => RoomMessageEventContent::text_plain(response), Ok(response) => RoomMessageEventContent::text_plain(response),
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Failed to get database memory usage: {}", "Failed to get database memory usage: {e}"
e
)), )),
}, },
AdminCommand::ShowConfig => { AdminCommand::ShowConfig => {
@ -561,8 +549,7 @@ impl Service {
Ok(id) => id, Ok(id) => id,
Err(e) => { Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!( return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {}", "The supplied username is not a valid username: {e}"
e
))) )))
} }
}; };
@ -589,12 +576,10 @@ impl Service {
.set_password(&user_id, Some(new_password.as_str())) .set_password(&user_id, Some(new_password.as_str()))
{ {
Ok(()) => RoomMessageEventContent::text_plain(format!( Ok(()) => RoomMessageEventContent::text_plain(format!(
"Successfully reset the password for user {}: {}", "Successfully reset the password for user {user_id}: {new_password}"
user_id, new_password
)), )),
Err(e) => RoomMessageEventContent::text_plain(format!( Err(e) => RoomMessageEventContent::text_plain(format!(
"Couldn't reset the password for user {}: {}", "Couldn't reset the password for user {user_id}: {e}"
user_id, e
)), )),
} }
} }
@ -609,8 +594,7 @@ impl Service {
Ok(id) => id, Ok(id) => id,
Err(e) => { Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!( return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {}", "The supplied username is not a valid username: {e}"
e
))) )))
} }
}; };
@ -676,8 +660,7 @@ impl Service {
let user_id = Arc::<UserId>::from(user_id); let user_id = Arc::<UserId>::from(user_id);
if services().users.exists(&user_id)? { if services().users.exists(&user_id)? {
RoomMessageEventContent::text_plain(format!( RoomMessageEventContent::text_plain(format!(
"Making {} leave all rooms before deactivation...", "Making {user_id} leave all rooms before deactivation..."
user_id
)); ));
services().users.deactivate_account(&user_id)?; services().users.deactivate_account(&user_id)?;
@ -687,13 +670,11 @@ impl Service {
} }
RoomMessageEventContent::text_plain(format!( RoomMessageEventContent::text_plain(format!(
"User {} has been deactivated", "User {user_id} has been deactivated"
user_id
)) ))
} else { } else {
RoomMessageEventContent::text_plain(format!( RoomMessageEventContent::text_plain(format!(
"User {} doesn't exist on this server", "User {user_id} doesn't exist on this server"
user_id
)) ))
} }
} }
@ -709,8 +690,7 @@ impl Service {
Ok(user_id) => user_ids.push(user_id), Ok(user_id) => user_ids.push(user_id),
Err(_) => { Err(_) => {
return Ok(RoomMessageEventContent::text_plain(format!( return Ok(RoomMessageEventContent::text_plain(format!(
"{} is not a valid username", "{username} is not a valid username"
username
))) )))
} }
} }
@ -746,8 +726,7 @@ impl Service {
if admins.is_empty() { if admins.is_empty() {
RoomMessageEventContent::text_plain(format!( RoomMessageEventContent::text_plain(format!(
"Deactivated {} accounts.", "Deactivated {deactivation_count} accounts."
deactivation_count
)) ))
} else { } else {
RoomMessageEventContent::text_plain(format!("Deactivated {} accounts.\nSkipped admin accounts: {:?}. Use --force to deactivate admin accounts", deactivation_count, admins.join(", "))) RoomMessageEventContent::text_plain(format!("Deactivated {} accounts.\nSkipped admin accounts: {:?}. Use --force to deactivate admin accounts", deactivation_count, admins.join(", ")))
@ -767,8 +746,8 @@ impl Service {
fn usage_to_html(&self, text: &str, server_name: &ServerName) -> String { fn usage_to_html(&self, text: &str, server_name: &ServerName) -> String {
// Replace `@conduit:servername:-subcmdname` with `@conduit:servername: subcmdname` // Replace `@conduit:servername:-subcmdname` with `@conduit:servername: subcmdname`
let text = text.replace( let text = text.replace(
&format!("@conduit:{}:-", server_name), &format!("@conduit:{server_name}:-"),
&format!("@conduit:{}: ", server_name), &format!("@conduit:{server_name}: "),
); );
// For the conduit admin room, subcommands become main commands // For the conduit admin room, subcommands become main commands

View file

@ -15,10 +15,7 @@ pub struct Service {
} }
impl Service { impl Service {
pub fn get_cached_eventid_authchain<'a>( pub fn get_cached_eventid_authchain(&self, key: &[u64]) -> Result<Option<Arc<HashSet<u64>>>> {
&'a self,
key: &[u64],
) -> Result<Option<Arc<HashSet<u64>>>> {
self.db.get_cached_eventid_authchain(key) self.db.get_cached_eventid_authchain(key)
} }

View file

@ -639,7 +639,7 @@ impl Service {
origin, origin,
get_room_state_ids::v1::Request { get_room_state_ids::v1::Request {
room_id: room_id.to_owned(), room_id: room_id.to_owned(),
event_id: (&*incoming_pdu.event_id).to_owned(), event_id: (*incoming_pdu.event_id).to_owned(),
}, },
) )
.await .await

View file

@ -37,7 +37,7 @@ pub trait Data: Send + Sync {
room_id: &RoomId, room_id: &RoomId,
) -> Box<dyn Iterator<Item = Result<OwnedServerName>> + 'a>; ) -> Box<dyn Iterator<Item = Result<OwnedServerName>> + 'a>;
fn server_in_room<'a>(&'a self, server: &ServerName, room_id: &RoomId) -> Result<bool>; fn server_in_room(&self, server: &ServerName, room_id: &RoomId) -> Result<bool>;
/// Returns an iterator of all rooms a server participates in (as far as we know). /// Returns an iterator of all rooms a server participates in (as far as we know).
fn server_rooms<'a>( fn server_rooms<'a>(

View file

@ -378,7 +378,7 @@ impl Service {
)?; )?;
let server_user = format!("@conduit:{}", services().globals.server_name()); let server_user = format!("@conduit:{}", services().globals.server_name());
let to_conduit = body.starts_with(&format!("{}: ", server_user)); let to_conduit = body.starts_with(&format!("{server_user}: "));
// This will evaluate to false if the emergency password is set up so that // This will evaluate to false if the emergency password is set up so that
// the administrator can execute commands as conduit // the administrator can execute commands as conduit

View file

@ -104,12 +104,12 @@ impl Error {
let mut error = error.clone(); let mut error = error.clone();
error.body = ErrorBody::Standard { error.body = ErrorBody::Standard {
kind: Unknown, kind: Unknown,
message: format!("Answer from {}: {}", origin, error), message: format!("Answer from {origin}: {error}"),
}; };
return RumaResponse(UiaaResponse::MatrixError(error)); return RumaResponse(UiaaResponse::MatrixError(error));
} }
let message = format!("{}", self); let message = format!("{self}");
use ErrorKind::*; use ErrorKind::*;
let (kind, status_code) = match self { let (kind, status_code) = match self {