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()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"New user {} registered on this server.",
user_id
"New user {user_id} registered on this server."
)));
// If this is the first real user, grant them admin privileges
@ -318,8 +317,7 @@ pub async fn change_password_route(
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"User {} changed their password.",
sender_user
"User {sender_user} changed their password."
)));
Ok(change_password::v3::Response {})
@ -396,8 +394,7 @@ pub async fn deactivate_route(
services()
.admin
.send_message(RoomMessageEventContent::notice_plain(format!(
"User {} deactivated their account.",
sender_user
"User {sender_user} deactivated their account."
)));
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 {
None
} else {
Some(format!("p{}", num_since))
Some(format!("p{num_since}"))
};
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 {
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,
Err(_) => {
// 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(
ErrorKind::InvalidParam,
"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)?;
} else {
let join_rules_event = services().rooms.state_accessor.room_state_get(
&room_id,
room_id,
&StateEventType::RoomJoinRules,
"",
)?;
let power_levels_event = services().rooms.state_accessor.room_state_get(
&room_id,
room_id,
&StateEventType::RoomPowerLevels,
"",
)?;
@ -835,8 +835,7 @@ async fn join_room_by_id_helper(
.state_cache
.room_members(restriction_room_id)
.filter_map(|r| r.ok())
.filter(|uid| uid.server_name() == services().globals.server_name())
.next()
.find(|uid| uid.server_name() == services().globals.server_name())
});
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(
ErrorKind::InvalidParam,
"Server sent event with wrong event id",
@ -1179,7 +1178,7 @@ pub(crate) async fn invite_helper<'a>(
user_id.server_name(),
create_invite::v2::Request {
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(),
event: PduEvent::convert_to_outgoing_federation_event(pdu_json.clone()),
invite_room_state,

View File

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

View File

@ -84,8 +84,8 @@ pub enum FedDest {
impl FedDest {
fn into_https_string(self) -> String {
match self {
Self::Literal(addr) => format!("https://{}", addr),
Self::Named(host, port) => format!("https://{}{}", host, port),
Self::Literal(addr) => format!("https://{addr}"),
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 {
FedDest::Named(delegated_hostname, format!(":{}", port))
FedDest::Named(delegated_hostname, format!(":{port}"))
} else {
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 {
FedDest::Named(hostname.clone(), format!(":{}", port))
FedDest::Named(hostname.clone(), format!(":{port}"))
} else {
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()
.globals
.dns_resolver()
.srv_lookup(format!("_matrix._tcp.{}", hostname))
.srv_lookup(format!("_matrix._tcp.{hostname}"))
.await
.map(|srv| {
srv.iter().next().map(|result| {
@ -482,10 +482,7 @@ async fn request_well_known(destination: &str) -> Option<String> {
&services()
.globals
.default_client()
.get(&format!(
"https://{}/.well-known/matrix/server",
destination
))
.get(&format!("https://{destination}/.well-known/matrix/server"))
.send()
.await
.ok()?

View File

@ -197,7 +197,7 @@ impl fmt::Display for Config {
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>> {
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 {
engine: Arc::clone(self),

View File

@ -827,7 +827,7 @@ impl KeyValueDatabase {
let rule = rules_list.content.get(content_rule_transformation[0]);
if rule.is_some() {
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.insert(rule);
}
@ -850,7 +850,7 @@ impl KeyValueDatabase {
let rule = rules_list.underride.get(transformation[0]);
if let Some(rule) = rule {
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.insert(rule);
}

View File

@ -68,10 +68,7 @@ async fn main() {
let config = match raw_config.extract::<Config>() {
Ok(s) => s,
Err(e) => {
eprintln!(
"It looks like your config is invalid. The following error occurred: {}",
e
);
eprintln!("It looks like your config is invalid. The following error occurred: {e}");
std::process::exit(1);
}
};
@ -91,8 +88,7 @@ async fn main() {
Ok(s) => s,
Err(e) => {
eprintln!(
"It looks like your log config is invalid. The following error occurred: {}",
e
"It looks like your log config is invalid. The following error occurred: {e}"
);
EnvFilter::try_new("warn").unwrap()
}
@ -118,7 +114,7 @@ async fn main() {
let filter_layer = match EnvFilter::try_new(&config.log) {
Ok(s) => s,
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()
}
};
@ -534,6 +530,6 @@ fn method_to_filter(method: Method) -> MethodFilter {
Method::POST => MethodFilter::POST,
Method::PUT => MethodFilter::PUT,
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) => {
let markdown_message = format!(
"Encountered an error while handling the command:\n\
```\n{}\n```",
error,
```\n{error}\n```",
);
let html_message = format!(
"Encountered an error while handling the command:\n\
<pre>\n{}\n</pre>",
error,
<pre>\n{error}\n</pre>",
);
RoomMessageEventContent::text_html(markdown_message, html_message)
@ -338,17 +336,14 @@ impl Service {
match parsed_config {
Ok(yaml) => match services().appservice.register_appservice(yaml) {
Ok(id) => RoomMessageEventContent::text_plain(format!(
"Appservice registered with ID: {}.",
id
"Appservice registered with ID: {id}."
)),
Err(e) => RoomMessageEventContent::text_plain(format!(
"Failed to register appservice: {}",
e
"Failed to register appservice: {e}"
)),
},
Err(e) => RoomMessageEventContent::text_plain(format!(
"Could not parse appservice config: {}",
e
"Could not parse appservice config: {e}"
)),
}
} else {
@ -365,8 +360,7 @@ impl Service {
{
Ok(()) => RoomMessageEventContent::text_plain("Appservice unregistered."),
Err(e) => RoomMessageEventContent::text_plain(format!(
"Failed to unregister appservice: {}",
e
"Failed to unregister appservice: {e}"
)),
},
AdminCommand::ListAppservices => {
@ -459,8 +453,7 @@ impl Service {
.count();
let elapsed = start.elapsed();
RoomMessageEventContent::text_plain(format!(
"Loaded auth chain with length {} in {:?}",
count, elapsed
"Loaded auth chain with length {count} in {elapsed:?}"
))
} else {
RoomMessageEventContent::text_plain("Event not found.")
@ -474,30 +467,26 @@ impl Service {
Ok(value) => {
match ruma::signatures::reference_hash(&value, &RoomVersionId::V6) {
Ok(hash) => {
let event_id = EventId::parse(format!("${}", hash));
let event_id = EventId::parse(format!("${hash}"));
match serde_json::from_value::<PduEvent>(
serde_json::to_value(value).expect("value is json"),
) {
Ok(pdu) => RoomMessageEventContent::text_plain(format!(
"EventId: {:?}\n{:#?}",
event_id, pdu
"EventId: {event_id:?}\n{pdu:#?}"
)),
Err(e) => RoomMessageEventContent::text_plain(format!(
"EventId: {:?}\nCould not parse event: {}",
event_id, e
"EventId: {event_id:?}\nCould not parse event: {e}"
)),
}
}
Err(e) => RoomMessageEventContent::text_plain(format!(
"Could not parse PDU JSON: {:?}",
e
"Could not parse PDU JSON: {e:?}"
)),
}
}
Err(e) => RoomMessageEventContent::text_plain(format!(
"Invalid json in command body: {}",
e
"Invalid json in command body: {e}"
)),
}
} else {
@ -545,8 +534,7 @@ impl Service {
AdminCommand::DatabaseMemoryUsage => match services().globals.db.memory_usage() {
Ok(response) => RoomMessageEventContent::text_plain(response),
Err(e) => RoomMessageEventContent::text_plain(format!(
"Failed to get database memory usage: {}",
e
"Failed to get database memory usage: {e}"
)),
},
AdminCommand::ShowConfig => {
@ -561,8 +549,7 @@ impl Service {
Ok(id) => id,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {}",
e
"The supplied username is not a valid username: {e}"
)))
}
};
@ -589,12 +576,10 @@ impl Service {
.set_password(&user_id, Some(new_password.as_str()))
{
Ok(()) => RoomMessageEventContent::text_plain(format!(
"Successfully reset the password for user {}: {}",
user_id, new_password
"Successfully reset the password for user {user_id}: {new_password}"
)),
Err(e) => RoomMessageEventContent::text_plain(format!(
"Couldn't reset the password for user {}: {}",
user_id, e
"Couldn't reset the password for user {user_id}: {e}"
)),
}
}
@ -609,8 +594,7 @@ impl Service {
Ok(id) => id,
Err(e) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"The supplied username is not a valid username: {}",
e
"The supplied username is not a valid username: {e}"
)))
}
};
@ -676,8 +660,7 @@ impl Service {
let user_id = Arc::<UserId>::from(user_id);
if services().users.exists(&user_id)? {
RoomMessageEventContent::text_plain(format!(
"Making {} leave all rooms before deactivation...",
user_id
"Making {user_id} leave all rooms before deactivation..."
));
services().users.deactivate_account(&user_id)?;
@ -687,13 +670,11 @@ impl Service {
}
RoomMessageEventContent::text_plain(format!(
"User {} has been deactivated",
user_id
"User {user_id} has been deactivated"
))
} else {
RoomMessageEventContent::text_plain(format!(
"User {} doesn't exist on this server",
user_id
"User {user_id} doesn't exist on this server"
))
}
}
@ -709,8 +690,7 @@ impl Service {
Ok(user_id) => user_ids.push(user_id),
Err(_) => {
return Ok(RoomMessageEventContent::text_plain(format!(
"{} is not a valid username",
username
"{username} is not a valid username"
)))
}
}
@ -746,8 +726,7 @@ impl Service {
if admins.is_empty() {
RoomMessageEventContent::text_plain(format!(
"Deactivated {} accounts.",
deactivation_count
"Deactivated {deactivation_count} accounts."
))
} else {
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 {
// Replace `@conduit:servername:-subcmdname` with `@conduit:servername: subcmdname`
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

View File

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

View File

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

View File

@ -37,7 +37,7 @@ pub trait Data: Send + Sync {
room_id: &RoomId,
) -> 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).
fn server_rooms<'a>(

View File

@ -378,7 +378,7 @@ impl Service {
)?;
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
// the administrator can execute commands as conduit

View File

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