go through a ton of pedantic clippy lints

Signed-off-by: strawberry <strawberry@puppygock.gay>
This commit is contained in:
strawberry 2024-03-02 20:55:02 -05:00 committed by June
parent 33727a3423
commit e2c7afe69c
61 changed files with 282 additions and 247 deletions

View file

@ -282,6 +282,7 @@ 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"
# let_underscore_untyped = "warn" # let_underscore_untyped = "warn"
lossy_float_literal = "warn" lossy_float_literal = "warn"
mem_forget = "warn" mem_forget = "warn"
@ -290,7 +291,9 @@ missing_assert_message = "warn"
# multiple_inherent_impl = "warn" # multiple_inherent_impl = "warn"
mutex_atomic = "warn" mutex_atomic = "warn"
# same_name_method = "warn" # same_name_method = "warn"
# semicolon_outside_block = "warn" semicolon_outside_block = "warn"
fn_to_numeric_cast = "warn"
fn_to_numeric_cast_with_truncation = "warn"
string_lit_chars_any = "warn" string_lit_chars_any = "warn"
suspicious_xor_used_as_pow = "warn" suspicious_xor_used_as_pow = "warn"
try_err = "warn" try_err = "warn"
@ -298,6 +301,10 @@ 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_truncation = "warn"
redundant_closure_for_method_calls = "warn"
# not in rust 1.75.0 (breaks CI) # not in rust 1.75.0 (breaks CI)
# infinite_loop = "warn" # infinite_loop = "warn"

View file

@ -30,7 +30,7 @@ where
Error::BadServerResponse("Invalid destination") Error::BadServerResponse("Invalid destination")
}) })
.unwrap() .unwrap()
.map(|body| body.freeze()); .map(bytes::BytesMut::freeze);
let mut parts = http_request.uri().clone().into_parts(); let mut parts = http_request.uri().clone().into_parts();
let old_path_and_query = parts.path_and_query.unwrap().as_str().to_owned(); let old_path_and_query = parts.path_and_query.unwrap().as_str().to_owned();

View file

@ -174,7 +174,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
stages: vec![AuthType::RegistrationToken], stages: vec![AuthType::RegistrationToken],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Default::default(), params: Box::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@ -186,7 +186,7 @@ pub async fn register_route(body: Ruma<register::v3::Request>) -> Result<registe
stages: vec![AuthType::Dummy], stages: vec![AuthType::Dummy],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Default::default(), params: Box::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@ -352,7 +352,7 @@ pub async fn change_password_route(
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Default::default(), params: Box::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@ -385,7 +385,7 @@ pub async fn change_password_route(
for id in services() for id in services()
.users .users
.all_device_ids(sender_user) .all_device_ids(sender_user)
.filter_map(|id| id.ok()) .filter_map(std::result::Result::ok)
.filter(|id| id != sender_device) .filter(|id| id != sender_device)
{ {
services().users.remove_device(sender_user, &id)?; services().users.remove_device(sender_user, &id)?;
@ -409,7 +409,7 @@ pub async fn change_password_route(
/// Note: Also works for Application Services /// Note: Also works for Application Services
pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> { pub async fn whoami_route(body: Ruma<whoami::v3::Request>) -> Result<whoami::v3::Response> {
let sender_user = body.sender_user.as_ref().expect("user is authenticated"); let sender_user = body.sender_user.as_ref().expect("user is authenticated");
let device_id = body.sender_device.as_ref().cloned(); let device_id = body.sender_device.clone();
Ok(whoami::v3::Response { Ok(whoami::v3::Response {
user_id: sender_user.clone(), user_id: sender_user.clone(),
@ -439,7 +439,7 @@ pub async fn deactivate_route(
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Default::default(), params: Box::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };

View file

@ -124,7 +124,7 @@ pub(crate) async fn get_alias_helper(
.send_federation_request( .send_federation_request(
room_alias.server_name(), room_alias.server_name(),
federation::query::get_room_information::v1::Request { federation::query::get_room_information::v1::Request {
room_alias: room_alias.to_owned(), room_alias: room_alias.clone(),
}, },
) )
.await?; .await?;
@ -138,7 +138,7 @@ pub(crate) async fn get_alias_helper(
.rooms .rooms
.state_cache .state_cache
.room_servers(&room_id) .room_servers(&room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
servers.push(extra_servers); servers.push(extra_servers);
} }
@ -224,7 +224,7 @@ pub(crate) async fn get_alias_helper(
.rooms .rooms
.state_cache .state_cache
.room_servers(&room_id) .room_servers(&room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
servers.push(extra_servers); servers.push(extra_servers);
} }

View file

@ -86,7 +86,7 @@ pub async fn get_backup_info_route(
etag: services() etag: services()
.key_backups .key_backups
.get_etag(sender_user, &body.version)?, .get_etag(sender_user, &body.version)?,
version: body.version.to_owned(), version: body.version.clone(),
}) })
} }
@ -139,7 +139,7 @@ pub async fn add_backup_keys_route(
room_id, room_id,
session_id, session_id,
key_data, key_data,
)? )?;
} }
} }
@ -185,7 +185,7 @@ pub async fn add_backup_keys_for_room_route(
&body.room_id, &body.room_id,
session_id, session_id,
key_data, key_data,
)? )?;
} }
Ok(add_backup_keys_for_room::v3::Response { Ok(add_backup_keys_for_room::v3::Response {

View file

@ -22,7 +22,7 @@ pub async fn get_context_route(
LazyLoadOptions::Enabled { LazyLoadOptions::Enabled {
include_redundant_members, include_redundant_members,
} => (true, *include_redundant_members), } => (true, *include_redundant_members),
_ => (false, false), LazyLoadOptions::Disabled => (false, false),
}; };
let mut lazy_loaded = HashSet::new(); let mut lazy_loaded = HashSet::new();
@ -79,7 +79,7 @@ pub async fn get_context_route(
.timeline .timeline
.pdus_until(sender_user, &room_id, base_token)? .pdus_until(sender_user, &room_id, base_token)?
.take(limit / 2) .take(limit / 2)
.filter_map(|r| r.ok()) // Remove buggy events .filter_map(std::result::Result::ok) // Remove buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@ -116,7 +116,7 @@ pub async fn get_context_route(
.timeline .timeline
.pdus_after(sender_user, &room_id, base_token)? .pdus_after(sender_user, &room_id, base_token)?
.take(limit / 2) .take(limit / 2)
.filter_map(|r| r.ok()) // Remove buggy events .filter_map(std::result::Result::ok) // Remove buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms

View file

@ -18,7 +18,7 @@ pub async fn get_devices_route(
let devices: Vec<device::Device> = services() let devices: Vec<device::Device> = services()
.users .users
.all_devices_metadata(sender_user) .all_devices_metadata(sender_user)
.filter_map(|r| r.ok()) // Filter out buggy devices .filter_map(std::result::Result::ok) // Filter out buggy devices
.collect(); .collect();
Ok(get_devices::v3::Response { devices }) Ok(get_devices::v3::Response { devices })
@ -83,7 +83,7 @@ pub async fn delete_device_route(
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Default::default(), params: Box::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@ -137,7 +137,7 @@ pub async fn delete_devices_route(
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Default::default(), params: Box::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@ -162,7 +162,7 @@ pub async fn delete_devices_route(
} }
for device_id in &body.devices { for device_id in &body.devices {
services().users.remove_device(sender_user, device_id)? services().users.remove_device(sender_user, device_id)?;
} }
Ok(delete_devices::v3::Response {}) Ok(delete_devices::v3::Response {})

View file

@ -111,7 +111,7 @@ pub async fn upload_signing_keys_route(
stages: vec![AuthType::Password], stages: vec![AuthType::Password],
}], }],
completed: Vec::new(), completed: Vec::new(),
params: Default::default(), params: Box::default(),
session: None, session: None,
auth_error: None, auth_error: None,
}; };
@ -230,14 +230,14 @@ pub async fn get_key_changes_route(
.map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?, .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`."))?,
), ),
) )
.filter_map(|r| r.ok()), .filter_map(std::result::Result::ok),
); );
for room_id in services() for room_id in services()
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
device_list_updates.extend( device_list_updates.extend(
services() services()
@ -251,7 +251,7 @@ pub async fn get_key_changes_route(
Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`.") Error::BadRequest(ErrorKind::InvalidParam, "Invalid `to`.")
})?), })?),
) )
.filter_map(|r| r.ok()), .filter_map(std::result::Result::ok),
); );
} }
Ok(get_key_changes::v3::Response { Ok(get_key_changes::v3::Response {

View file

@ -270,7 +270,7 @@ pub async fn get_content_thumbnail_route(
if services() if services()
.globals .globals
.prevent_media_downloads_from() .prevent_media_downloads_from()
.contains(&body.server_name.to_owned()) .contains(&body.server_name.clone())
{ {
info!("Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", mxc); info!("Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", mxc);
return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found.")); return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));

View file

@ -68,7 +68,7 @@ pub async fn join_room_by_id_route(
.iter() .iter()
.filter_map(|event| serde_json::from_str(event.json().get()).ok()) .filter_map(|event| serde_json::from_str(event.json().get()).ok())
.filter_map(|event: serde_json::Value| event.get("sender").cloned()) .filter_map(|event: serde_json::Value| event.get("sender").cloned())
.filter_map(|sender| sender.as_str().map(|s| s.to_owned())) .filter_map(|sender| sender.as_str().map(std::borrow::ToOwned::to_owned))
.filter_map(|sender| UserId::parse(sender).ok()) .filter_map(|sender| UserId::parse(sender).ok())
.map(|user| user.server_name().to_owned()), .map(|user| user.server_name().to_owned()),
); );
@ -123,7 +123,7 @@ pub async fn join_room_by_id_or_alias_route(
.iter() .iter()
.filter_map(|event| serde_json::from_str(event.json().get()).ok()) .filter_map(|event| serde_json::from_str(event.json().get()).ok())
.filter_map(|event: serde_json::Value| event.get("sender").cloned()) .filter_map(|event: serde_json::Value| event.get("sender").cloned())
.filter_map(|sender| sender.as_str().map(|s| s.to_owned())) .filter_map(|sender| sender.as_str().map(std::borrow::ToOwned::to_owned))
.filter_map(|sender| UserId::parse(sender).ok()) .filter_map(|sender| UserId::parse(sender).ok())
.map(|user| user.server_name().to_owned()), .map(|user| user.server_name().to_owned()),
); );
@ -441,7 +441,7 @@ pub async fn joined_rooms_route(
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect(), .collect(),
}) })
} }
@ -507,7 +507,7 @@ pub async fn joined_members_route(
.rooms .rooms
.state_cache .state_cache
.room_members(&body.room_id) .room_members(&body.room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
let display_name = services().users.displayname(&user_id)?; let display_name = services().users.displayname(&user_id)?;
let avatar_url = services().users.avatar_url(&user_id)?; let avatar_url = services().users.avatar_url(&user_id)?;
@ -963,7 +963,7 @@ async fn join_room_by_id_helper(
.rooms .rooms
.state_cache .state_cache
.room_members(restriction_room_id) .room_members(restriction_room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.find(|uid| uid.server_name() == services().globals.server_name()) .find(|uid| uid.server_name() == services().globals.server_name())
}); });
Some(authorized_user) Some(authorized_user)
@ -1384,7 +1384,7 @@ pub(crate) async fn invite_helper(
.rooms .rooms
.state_cache .state_cache
.room_servers(room_id) .room_servers(room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|server| &**server != services().globals.server_name()); .filter(|server| &**server != services().globals.server_name());
services().sending.send_pdu(servers, &pdu_id)?; services().sending.send_pdu(servers, &pdu_id)?;
@ -1593,7 +1593,7 @@ async fn remote_leave_room(user_id: &UserId, room_id: &RoomId) -> Result<()> {
.iter() .iter()
.filter_map(|event| serde_json::from_str(event.json().get()).ok()) .filter_map(|event| serde_json::from_str(event.json().get()).ok())
.filter_map(|event: serde_json::Value| event.get("sender").cloned()) .filter_map(|event: serde_json::Value| event.get("sender").cloned())
.filter_map(|sender| sender.as_str().map(|s| s.to_owned())) .filter_map(|sender| sender.as_str().map(std::borrow::ToOwned::to_owned))
.filter_map(|sender| UserId::parse(sender).ok()) .filter_map(|sender| UserId::parse(sender).ok())
.map(|user| user.server_name().to_owned()) .map(|user| user.server_name().to_owned())
.collect(); .collect();

View file

@ -199,7 +199,7 @@ pub async fn get_message_events_route(
.timeline .timeline
.pdus_after(sender_user, &body.room_id, from)? .pdus_after(sender_user, &body.room_id, from)?
.take(limit) .take(limit)
.filter_map(|r| r.ok()) // Filter out buggy events .filter_map(std::result::Result::ok) // Filter out buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@ -248,7 +248,7 @@ pub async fn get_message_events_route(
.timeline .timeline
.pdus_until(sender_user, &body.room_id, from)? .pdus_until(sender_user, &body.room_id, from)?
.take(limit) .take(limit)
.filter_map(|r| r.ok()) // Filter out buggy events .filter_map(std::result::Result::ok) // Filter out buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms

View file

@ -35,7 +35,7 @@ pub async fn set_displayname_route(
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
@ -70,7 +70,7 @@ pub async fn set_displayname_route(
room_id, room_id,
)) ))
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect(); .collect();
for (pdu_builder, room_id) in all_rooms_joined { for (pdu_builder, room_id) in all_rooms_joined {
@ -182,7 +182,7 @@ pub async fn set_avatar_url_route(
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.map(|room_id| { .map(|room_id| {
Ok::<_, Error>(( Ok::<_, Error>((
PduBuilder { PduBuilder {
@ -217,7 +217,7 @@ pub async fn set_avatar_url_route(
room_id, room_id,
)) ))
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect(); .collect();
for (pdu_builder, room_id) in all_joined_rooms { for (pdu_builder, room_id) in all_joined_rooms {

View file

@ -281,7 +281,7 @@ pub async fn get_pushrule_enabled_route(
let global = account_data.content.global; let global = account_data.content.global;
let enabled = global let enabled = global
.get(body.kind.clone(), &body.rule_id) .get(body.kind.clone(), &body.rule_id)
.map(|r| r.enabled()) .map(ruma::push::AnyPushRuleRef::enabled)
.ok_or(Error::BadRequest( .ok_or(Error::BadRequest(
ErrorKind::NotFound, ErrorKind::NotFound,
"Push rule not found.", "Push rule not found.",

View file

@ -140,7 +140,7 @@ pub async fn create_receipt_route(
receipts.insert(ReceiptType::Read, user_receipts); receipts.insert(ReceiptType::Read, user_receipts);
let mut receipt_content = BTreeMap::new(); let mut receipt_content = BTreeMap::new();
receipt_content.insert(body.event_id.to_owned(), receipts); receipt_content.insert(body.event_id.clone(), receipts);
services().rooms.edus.read_receipt.readreceipt_update( services().rooms.edus.read_receipt.readreceipt_update(
sender_user, sender_user,

View file

@ -46,7 +46,7 @@ pub async fn report_event_route(
.rooms .rooms
.state_cache .state_cache
.room_members(&pdu.room_id) .room_members(&pdu.room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.any(|user_id| user_id == *sender_user) .any(|user_id| user_id == *sender_user)
{ {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@ -85,7 +85,7 @@ pub async fn report_event_route(
sender_user.to_owned(), sender_user.to_owned(),
pdu.event_id, pdu.event_id,
pdu.room_id, pdu.room_id,
pdu.sender.to_owned(), pdu.sender.clone(),
body.score.unwrap_or_else(|| ruma::Int::from(0)), body.score.unwrap_or_else(|| ruma::Int::from(0)),
body.reason.as_deref().unwrap_or("") body.reason.as_deref().unwrap_or("")
), ),
@ -97,9 +97,9 @@ pub async fn report_event_route(
Report Info<ul><li>Report Score: {4}</li><li>Report Reason: {5}</li></ul></li>\ Report Info<ul><li>Report Score: {4}</li><li>Report Reason: {5}</li></ul></li>\
</ul></details>", </ul></details>",
sender_user.to_owned(), sender_user.to_owned(),
pdu.event_id.to_owned(), pdu.event_id.clone(),
pdu.room_id.to_owned(), pdu.room_id.clone(),
pdu.sender.to_owned(), pdu.sender.clone(),
body.score.unwrap_or_else(|| ruma::Int::from(0)), body.score.unwrap_or_else(|| ruma::Int::from(0)),
HtmlEscape(body.reason.as_deref().unwrap_or("")) HtmlEscape(body.reason.as_deref().unwrap_or(""))
), ),

View file

@ -122,7 +122,7 @@ pub async fn create_room_route(
None => room_id = RoomId::new(services().globals.server_name()), None => room_id = RoomId::new(services().globals.server_name()),
} }
} else { } else {
room_id = RoomId::new(services().globals.server_name()) room_id = RoomId::new(services().globals.server_name());
} }
// check if room ID doesn't already exist instead of erroring on auth check // check if room ID doesn't already exist instead of erroring on auth check
@ -380,7 +380,6 @@ pub async fn create_room_route(
// Figure out preset. We need it for preset specific events // Figure out preset. We need it for preset specific events
let preset = body.preset.clone().unwrap_or(match &body.visibility { let preset = body.preset.clone().unwrap_or(match &body.visibility {
room::Visibility::Private => RoomPreset::PrivateChat,
room::Visibility::Public => RoomPreset::PublicChat, room::Visibility::Public => RoomPreset::PublicChat,
_ => RoomPreset::PrivateChat, // Room visibility should not be custom _ => RoomPreset::PrivateChat, // Room visibility should not be custom
}); });
@ -672,7 +671,7 @@ pub async fn get_room_aliases_route(
.rooms .rooms
.alias .alias
.local_aliases_for_room(&body.room_id) .local_aliases_for_room(&body.room_id)
.filter_map(|a| a.ok()) .filter_map(std::result::Result::ok)
.collect(), .collect(),
}) })
} }
@ -932,7 +931,7 @@ pub async fn upgrade_room_route(
.rooms .rooms
.alias .alias
.local_aliases_for_room(&body.room_id) .local_aliases_for_room(&body.room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
services() services()
.rooms .rooms

View file

@ -27,7 +27,7 @@ pub async fn search_events_route(
.rooms .rooms
.state_cache .state_cache
.rooms_joined(sender_user) .rooms_joined(sender_user)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect() .collect()
}); });
@ -110,7 +110,7 @@ pub async fn search_events_route(
result: Some(result), result: Some(result),
}) })
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.skip(skip) .skip(skip)
.take(limit) .take(limit)
.collect(); .collect();

View file

@ -5,7 +5,10 @@ use ruma::{
api::client::{ api::client::{
error::ErrorKind, error::ErrorKind,
session::{ session::{
get_login_types, get_login_types::{
self,
v3::{ApplicationServiceLoginType, PasswordLoginType},
},
login::{ login::{
self, self,
v3::{DiscoveryInfo, HomeserverInfo}, v3::{DiscoveryInfo, HomeserverInfo},
@ -33,8 +36,8 @@ pub async fn get_login_types_route(
_body: Ruma<get_login_types::v3::Request>, _body: Ruma<get_login_types::v3::Request>,
) -> Result<get_login_types::v3::Response> { ) -> Result<get_login_types::v3::Response> {
Ok(get_login_types::v3::Response::new(vec![ Ok(get_login_types::v3::Response::new(vec![
get_login_types::v3::LoginType::Password(Default::default()), get_login_types::v3::LoginType::Password(PasswordLoginType::default()),
get_login_types::v3::LoginType::ApplicationService(Default::default()), get_login_types::v3::LoginType::ApplicationService(ApplicationServiceLoginType::default()),
])) ]))
} }

View file

@ -31,7 +31,7 @@ pub async fn send_state_event_for_key_route(
&body.room_id, &body.room_id,
&body.event_type, &body.event_type,
&body.body.body, // Yes, I hate it too &body.body.body, // Yes, I hate it too
body.state_key.to_owned(), body.state_key.clone(),
) )
.await?; .await?;
@ -64,7 +64,7 @@ pub async fn send_state_event_for_empty_key_route(
&body.room_id, &body.room_id,
&body.event_type.to_string().into(), &body.event_type.to_string().into(),
&body.body.body, &body.body.body,
body.state_key.to_owned(), body.state_key.clone(),
) )
.await?; .await?;

View file

@ -83,7 +83,7 @@ pub async fn sync_events_route(
Entry::Vacant(v) => { Entry::Vacant(v) => {
let (tx, rx) = tokio::sync::watch::channel(None); let (tx, rx) = tokio::sync::watch::channel(None);
v.insert((body.since.to_owned(), rx.clone())); v.insert((body.since.clone(), rx.clone()));
tokio::spawn(sync_helper_wrapper( tokio::spawn(sync_helper_wrapper(
sender_user.clone(), sender_user.clone(),
@ -202,7 +202,7 @@ async fn sync_helper(
LazyLoadOptions::Enabled { LazyLoadOptions::Enabled {
include_redundant_members: redundant, include_redundant_members: redundant,
} => (true, redundant), } => (true, redundant),
_ => (false, false), LazyLoadOptions::Disabled => (false, false),
}; };
let full_state = body.full_state; let full_state = body.full_state;
@ -225,7 +225,7 @@ async fn sync_helper(
services() services()
.users .users
.keys_changed(sender_user.as_ref(), since, None) .keys_changed(sender_user.as_ref(), since, None)
.filter_map(|r| r.ok()), .filter_map(std::result::Result::ok),
); );
let all_joined_rooms = services() let all_joined_rooms = services()
@ -285,7 +285,7 @@ async fn sync_helper(
); );
let insert_lock = mutex_insert.lock().await; let insert_lock = mutex_insert.lock().await;
drop(insert_lock); drop(insert_lock);
} };
let left_count = services() let left_count = services()
.rooms .rooms
@ -417,7 +417,7 @@ async fn sync_helper(
); );
let insert_lock = mutex_insert.lock().await; let insert_lock = mutex_insert.lock().await;
drop(insert_lock); drop(insert_lock);
} };
let invite_count = services() let invite_count = services()
.rooms .rooms
@ -444,7 +444,7 @@ async fn sync_helper(
.rooms .rooms
.user .user
.get_shared_rooms(vec![sender_user.clone(), user_id.clone()])? .get_shared_rooms(vec![sender_user.clone(), user_id.clone()])?
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter_map(|other_room_id| { .filter_map(|other_room_id| {
Some( Some(
services() services()
@ -604,7 +604,7 @@ async fn load_joined_room(
); );
let insert_lock = mutex_insert.lock().await; let insert_lock = mutex_insert.lock().await;
drop(insert_lock); drop(insert_lock);
} };
let (timeline_pdus, limited) = load_timeline(sender_user, room_id, sincecount, 10)?; let (timeline_pdus, limited) = load_timeline(sender_user, room_id, sincecount, 10)?;
@ -671,7 +671,7 @@ async fn load_joined_room(
.rooms .rooms
.timeline .timeline
.all_pdus(sender_user, room_id)? .all_pdus(sender_user, room_id)?
.filter_map(|pdu| pdu.ok()) // Ignore all broken pdus .filter_map(std::result::Result::ok) // Ignore all broken pdus
.filter(|(_, pdu)| pdu.kind == TimelineEventType::RoomMember) .filter(|(_, pdu)| pdu.kind == TimelineEventType::RoomMember)
.map(|(_, pdu)| { .map(|(_, pdu)| {
let content: RoomMemberEventContent = let content: RoomMemberEventContent =
@ -706,7 +706,7 @@ async fn load_joined_room(
} }
}) })
// Filter out buggy users // Filter out buggy users
.filter_map(|u| u.ok()) .filter_map(std::result::Result::ok)
// Filter for possible heroes // Filter for possible heroes
.flatten() .flatten()
{ {
@ -1011,7 +1011,7 @@ async fn load_joined_room(
services() services()
.users .users
.keys_changed(room_id.as_ref(), since, None) .keys_changed(room_id.as_ref(), since, None)
.filter_map(|r| r.ok()), .filter_map(std::result::Result::ok),
); );
let notification_count = if send_notification_counts { let notification_count = if send_notification_counts {
@ -1062,7 +1062,7 @@ async fn load_joined_room(
.edus .edus
.read_receipt .read_receipt
.readreceipts_since(room_id, since) .readreceipts_since(room_id, since)
.filter_map(|r| r.ok()) // Filter out buggy events .filter_map(std::result::Result::ok) // Filter out buggy events
.map(|(_, _, v)| v) .map(|(_, _, v)| v)
.collect(); .collect();
@ -1176,7 +1176,7 @@ fn share_encrypted_room(
.rooms .rooms
.user .user
.get_shared_rooms(vec![sender_user.to_owned(), user_id.to_owned()])? .get_shared_rooms(vec![sender_user.to_owned(), user_id.to_owned()])?
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|room_id| room_id != ignore_room) .filter(|room_id| room_id != ignore_room)
.filter_map(|other_room_id| { .filter_map(|other_room_id| {
Some( Some(
@ -1214,7 +1214,7 @@ pub async fn sync_events_v4_route(
sender_user.clone(), sender_user.clone(),
sender_device.clone(), sender_device.clone(),
conn_id.clone(), conn_id.clone(),
) );
} }
} }
@ -1229,7 +1229,7 @@ pub async fn sync_events_v4_route(
.rooms .rooms
.state_cache .state_cache
.rooms_joined(&sender_user) .rooms_joined(&sender_user)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if body.extensions.to_device.enabled.unwrap_or(false) { if body.extensions.to_device.enabled.unwrap_or(false) {
@ -1248,7 +1248,7 @@ pub async fn sync_events_v4_route(
services() services()
.users .users
.keys_changed(sender_user.as_ref(), globalsince, None) .keys_changed(sender_user.as_ref(), globalsince, None)
.filter_map(|r| r.ok()), .filter_map(std::result::Result::ok),
); );
for room_id in &all_joined_rooms { for room_id in &all_joined_rooms {
@ -1393,7 +1393,7 @@ pub async fn sync_events_v4_route(
services() services()
.users .users
.keys_changed(room_id.as_ref(), globalsince, None) .keys_changed(room_id.as_ref(), globalsince, None)
.filter_map(|r| r.ok()), .filter_map(std::result::Result::ok),
); );
} }
for user_id in left_encrypted_users { for user_id in left_encrypted_users {
@ -1401,7 +1401,7 @@ pub async fn sync_events_v4_route(
.rooms .rooms
.user .user
.get_shared_rooms(vec![sender_user.clone(), user_id.clone()])? .get_shared_rooms(vec![sender_user.clone(), user_id.clone()])?
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter_map(|other_room_id| { .filter_map(|other_room_id| {
Some( Some(
services() services()
@ -1585,7 +1585,7 @@ pub async fn sync_events_v4_route(
.state_accessor .state_accessor
.room_state_get(room_id, &state.0, &state.1) .room_state_get(room_id, &state.0, &state.1)
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.flatten() .flatten()
.map(|state| state.to_sync_state_event()) .map(|state| state.to_sync_state_event())
.collect(); .collect();
@ -1595,7 +1595,7 @@ pub async fn sync_events_v4_route(
.rooms .rooms
.state_cache .state_cache
.room_members(room_id) .room_members(room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|member| member != &sender_user) .filter(|member| member != &sender_user)
.map(|member| { .map(|member| {
Ok::<_, Error>( Ok::<_, Error>(
@ -1613,7 +1613,7 @@ pub async fn sync_events_v4_route(
}), }),
) )
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.flatten() .flatten()
.take(5) .take(5)
.collect::<Vec<_>>(); .collect::<Vec<_>>();

View file

@ -27,7 +27,7 @@ pub async fn get_threads_route(
.threads .threads
.threads_until(sender_user, &body.room_id, from, &body.include)? .threads_until(sender_user, &body.room_id, from, &body.include)?
.take(limit) .take(limit)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms

View file

@ -63,7 +63,7 @@ pub async fn send_event_to_device_route(
event.deserialize_as().map_err(|_| { event.deserialize_as().map_err(|_| {
Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid") Error::BadRequest(ErrorKind::InvalidParam, "Event is invalid")
})?, })?,
)? )?;
} }
DeviceIdOrAllDevices::AllDevices => { DeviceIdOrAllDevices::AllDevices => {

View file

@ -52,7 +52,7 @@ pub async fn search_users_route(
.rooms .rooms
.state_cache .state_cache
.rooms_joined(&user_id) .rooms_joined(&user_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.any(|room| { .any(|room| {
services() services()
.rooms .rooms

View file

@ -215,7 +215,7 @@ where
.event_handler .event_handler
.fetch_signing_keys_for_server( .fetch_signing_keys_for_server(
&x_matrix.origin, &x_matrix.origin,
vec![x_matrix.key.to_owned()], vec![x_matrix.key.clone()],
) )
.await; .await;

View file

@ -866,7 +866,7 @@ pub async fn send_transaction_message_route(
warn!( warn!(
"Could not fetch all signatures for PDUs from {}: {:?}", "Could not fetch all signatures for PDUs from {}: {:?}",
sender_servername, e sender_servername, e
) );
}); });
for (event_id, value, room_id) in parsed_pdus { for (event_id, value, room_id) in parsed_pdus {
@ -876,7 +876,7 @@ pub async fn send_transaction_message_route(
.roomid_mutex_federation .roomid_mutex_federation
.write() .write()
.unwrap() .unwrap()
.entry(room_id.to_owned()) .entry(room_id.clone())
.or_default(), .or_default(),
); );
let mutex_lock = mutex.lock().await; let mutex_lock = mutex.lock().await;
@ -1037,7 +1037,7 @@ pub async fn send_transaction_message_route(
"Event is invalid", "Event is invalid",
) )
})?, })?,
)? )?;
} }
DeviceIdOrAllDevices::AllDevices => { DeviceIdOrAllDevices::AllDevices => {
@ -1214,7 +1214,7 @@ pub async fn get_backfill_route(
.take(limit.try_into().unwrap()); .take(limit.try_into().unwrap());
let events = all_events let events = all_events
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|(_, e)| { .filter(|(_, e)| {
matches!( matches!(
services().rooms.state_accessor.server_can_see_event( services().rooms.state_accessor.server_can_see_event(
@ -1562,7 +1562,7 @@ pub async fn create_join_event_template_route(
.roomid_mutex_state .roomid_mutex_state
.write() .write()
.unwrap() .unwrap()
.entry(body.room_id.to_owned()) .entry(body.room_id.clone())
.or_default(), .or_default(),
); );
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
@ -1768,7 +1768,7 @@ async fn create_join_event(
.rooms .rooms
.state_cache .state_cache
.room_servers(room_id) .room_servers(room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|server| &**server != services().globals.server_name()); .filter(|server| &**server != services().globals.server_name());
services().sending.send_pdu(servers, &pdu_id)?; services().sending.send_pdu(servers, &pdu_id)?;
@ -1986,7 +1986,7 @@ pub async fn get_devices_route(
devices: services() devices: services()
.users .users
.all_devices_metadata(&body.user_id) .all_devices_metadata(&body.user_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter_map(|metadata| { .filter_map(|metadata| {
let device_id_string = metadata.device_id.as_str().to_owned(); let device_id_string = metadata.device_id.as_str().to_owned();
let device_display_name = match services().globals.allow_device_name_federation() { let device_display_name = match services().globals.allow_device_name_federation() {
@ -2062,11 +2062,11 @@ pub async fn get_profile_information_route(
match &body.field { match &body.field {
Some(ProfileField::DisplayName) => { Some(ProfileField::DisplayName) => {
displayname = services().users.displayname(&body.user_id)? displayname = services().users.displayname(&body.user_id)?;
} }
Some(ProfileField::AvatarUrl) => { Some(ProfileField::AvatarUrl) => {
avatar_url = services().users.avatar_url(&body.user_id)?; avatar_url = services().users.avatar_url(&body.user_id)?;
blurhash = services().users.blurhash(&body.user_id)? blurhash = services().users.blurhash(&body.user_id)?;
} }
// TODO: what to do with custom // TODO: what to do with custom
Some(_) => {} Some(_) => {}

View file

@ -66,7 +66,7 @@ impl PartialProxyConfig {
let mut excluded_because = None; // most specific reason it was excluded let mut excluded_because = None; // most specific reason it was excluded
if self.include.is_empty() { if self.include.is_empty() {
// treat empty include list as `*` // treat empty include list as `*`
included_because = Some(&WildCardedDomain::WildCard) included_because = Some(&WildCardedDomain::WildCard);
} }
for wc_domain in &self.include { for wc_domain in &self.include {
if wc_domain.matches(domain) { if wc_domain.matches(domain) {

View file

@ -40,7 +40,6 @@ fn db_options(rocksdb_cache: &rocksdb::Cache, config: &Config) -> rocksdb::Optio
let rocksdb_log_level = match config.rocksdb_log_level.as_ref() { let rocksdb_log_level = match config.rocksdb_log_level.as_ref() {
"debug" => Debug, "debug" => Debug,
"info" => Info, "info" => Info,
"warn" => Warn,
"error" => Error, "error" => Error,
"fatal" => Fatal, "fatal" => Fatal,
_ => Warn, _ => Warn,
@ -71,7 +70,7 @@ fn db_options(rocksdb_cache: &rocksdb::Cache, config: &Config) -> rocksdb::Optio
db_opts.set_block_based_table_factory(&block_based_options); db_opts.set_block_based_table_factory(&block_based_options);
db_opts.set_level_compaction_dynamic_level_bytes(true); db_opts.set_level_compaction_dynamic_level_bytes(true);
db_opts.create_if_missing(true); db_opts.create_if_missing(true);
db_opts.increase_parallelism(num_cpus::get() as i32); db_opts.increase_parallelism(num_cpus::get().try_into().unwrap_or_default());
//db_opts.set_max_open_files(config.rocksdb_max_open_files); //db_opts.set_max_open_files(config.rocksdb_max_open_files);
db_opts.set_compression_type(rocksdb::DBCompressionType::Zstd); db_opts.set_compression_type(rocksdb::DBCompressionType::Zstd);
db_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level); db_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
@ -79,7 +78,7 @@ fn db_options(rocksdb_cache: &rocksdb::Cache, config: &Config) -> rocksdb::Optio
// https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning // https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning
db_opts.set_max_background_jobs(6); db_opts.set_max_background_jobs(6);
db_opts.set_bytes_per_sync(1048576); db_opts.set_bytes_per_sync(1_048_576);
// https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes#ktoleratecorruptedtailrecords // https://github.com/facebook/rocksdb/wiki/WAL-Recovery-Modes#ktoleratecorruptedtailrecords
// //

View file

@ -21,7 +21,7 @@ impl service::account_data::Data for KeyValueDatabase {
data: &serde_json::Value, data: &serde_json::Value,
) -> Result<()> { ) -> Result<()> {
let mut prefix = room_id let mut prefix = room_id
.map(|r| r.to_string()) .map(std::string::ToString::to_string)
.unwrap_or_default() .unwrap_or_default()
.as_bytes() .as_bytes()
.to_vec(); .to_vec();
@ -71,7 +71,7 @@ impl service::account_data::Data for KeyValueDatabase {
kind: RoomAccountDataEventType, kind: RoomAccountDataEventType,
) -> Result<Option<Box<serde_json::value::RawValue>>> { ) -> Result<Option<Box<serde_json::value::RawValue>>> {
let mut key = room_id let mut key = room_id
.map(|r| r.to_string()) .map(std::string::ToString::to_string)
.unwrap_or_default() .unwrap_or_default()
.as_bytes() .as_bytes()
.to_vec(); .to_vec();
@ -106,7 +106,7 @@ impl service::account_data::Data for KeyValueDatabase {
let mut userdata = HashMap::new(); let mut userdata = HashMap::new();
let mut prefix = room_id let mut prefix = room_id
.map(|r| r.to_string()) .map(std::string::ToString::to_string)
.unwrap_or_default() .unwrap_or_default()
.as_bytes() .as_bytes()
.to_vec(); .to_vec();

View file

@ -13,7 +13,7 @@ impl service::appservice::Data for KeyValueDatabase {
self.cached_registrations self.cached_registrations
.write() .write()
.unwrap() .unwrap()
.insert(id.to_owned(), yaml.to_owned()); .insert(id.to_owned(), yaml.clone());
Ok(id.to_owned()) Ok(id.to_owned())
} }
@ -67,7 +67,7 @@ impl service::appservice::Data for KeyValueDatabase {
fn all(&self) -> Result<Vec<(String, Registration)>> { fn all(&self) -> Result<Vec<(String, Registration)>> {
self.iter_ids()? self.iter_ids()?
.filter_map(|id| id.ok()) .filter_map(std::result::Result::ok)
.map(move |id| { .map(move |id| {
Ok(( Ok((
id.clone(), id.clone(),

View file

@ -74,7 +74,7 @@ impl service::globals::Data for KeyValueDatabase {
.rooms .rooms
.state_cache .state_cache
.rooms_joined(user_id) .rooms_joined(user_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
let short_roomid = services() let short_roomid = services()
.rooms .rooms
@ -134,7 +134,7 @@ impl service::globals::Data for KeyValueDatabase {
} }
fn cleanup(&self) -> Result<()> { fn cleanup(&self) -> Result<()> {
self._db.cleanup() self.db.cleanup()
} }
fn memory_usage(&self) -> String { fn memory_usage(&self) -> String {
@ -158,7 +158,7 @@ our_real_users_cache: {our_real_users_cache}
appservice_in_room_cache: {appservice_in_room_cache} appservice_in_room_cache: {appservice_in_room_cache}
lasttimelinecount_cache: {lasttimelinecount_cache}\n" lasttimelinecount_cache: {lasttimelinecount_cache}\n"
); );
if let Ok(db_stats) = self._db.memory_usage() { if let Ok(db_stats) = self.db.memory_usage() {
response += &db_stats; response += &db_stats;
} }
@ -207,7 +207,7 @@ lasttimelinecount_cache: {lasttimelinecount_cache}\n"
self.global.insert(b"keypair", &keypair)?; self.global.insert(b"keypair", &keypair)?;
Ok::<_, Error>(keypair) Ok::<_, Error>(keypair)
}, },
|s| Ok(s.to_vec()), Ok,
)?; )?;
let mut parts = keypair_bytes.splitn(2, |&b| b == 0xff); let mut parts = keypair_bytes.splitn(2, |&b| b == 0xff);

View file

@ -283,7 +283,7 @@ impl service::key_backups::Data for KeyValueDatabase {
Ok::<_, Error>((session_id, key_data)) Ok::<_, Error>((session_id, key_data))
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect()) .collect())
} }

View file

@ -152,21 +152,21 @@ impl service::media::Data for KeyValueDatabase {
value.extend_from_slice( value.extend_from_slice(
data.title data.title
.as_ref() .as_ref()
.map(|t| t.as_bytes()) .map(std::string::String::as_bytes)
.unwrap_or_default(), .unwrap_or_default(),
); );
value.push(0xff); value.push(0xff);
value.extend_from_slice( value.extend_from_slice(
data.description data.description
.as_ref() .as_ref()
.map(|d| d.as_bytes()) .map(std::string::String::as_bytes)
.unwrap_or_default(), .unwrap_or_default(),
); );
value.push(0xff); value.push(0xff);
value.extend_from_slice( value.extend_from_slice(
data.image data.image
.as_ref() .as_ref()
.map(|i| i.as_bytes()) .map(std::string::String::as_bytes)
.unwrap_or_default(), .unwrap_or_default(),
); );
value.push(0xff); value.push(0xff);

View file

@ -15,7 +15,7 @@ impl service::rooms::alias::Data for KeyValueDatabase {
fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> { fn remove_alias(&self, alias: &RoomAliasId) -> Result<()> {
if let Some(room_id) = self.alias_roomid.get(alias.alias().as_bytes())? { if let Some(room_id) = self.alias_roomid.get(alias.alias().as_bytes())? {
let mut prefix = room_id.to_vec(); let mut prefix = room_id;
prefix.push(0xff); prefix.push(0xff);
for (key, _) in self.aliasid_alias.scan_prefix(prefix) { for (key, _) in self.aliasid_alias.scan_prefix(prefix) {

View file

@ -76,7 +76,7 @@ impl service::rooms::edus::typing::Data for KeyValueDatabase {
.map_err(|_| Error::bad_database("RoomTyping has invalid timestamp bytes."))?, .map_err(|_| Error::bad_database("RoomTyping has invalid timestamp bytes."))?,
)) ))
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.take_while(|&(_, timestamp)| timestamp < current_timestamp) .take_while(|&(_, timestamp)| timestamp < current_timestamp)
{ {
// This is an outdated edu (time > timestamp) // This is an outdated edu (time > timestamp)

View file

@ -4,11 +4,8 @@ use ruma::{EventId, RoomId, UserId};
use crate::{ use crate::{
database::KeyValueDatabase, database::KeyValueDatabase,
service::{ service::{self, rooms::timeline::PduCount},
self, services, utils, Error, PduEvent, Result,
rooms::timeline::{data::PduData, PduCount},
},
services, utils, Error, Result,
}; };
impl service::rooms::pdu_metadata::Data for KeyValueDatabase { impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
@ -25,7 +22,7 @@ impl service::rooms::pdu_metadata::Data for KeyValueDatabase {
shortroomid: u64, shortroomid: u64,
target: u64, target: u64,
until: PduCount, until: PduCount,
) -> PduData<'a> { ) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>> {
let prefix = target.to_be_bytes().to_vec(); let prefix = target.to_be_bytes().to_vec();
let mut current = prefix.clone(); let mut current = prefix.clone();

View file

@ -46,13 +46,13 @@ impl service::rooms::short::Data for KeyValueDatabase {
return Ok(Some(*short)); return Ok(Some(*short));
} }
let mut statekey = event_type.to_string().as_bytes().to_vec(); let mut statekey_vec = event_type.to_string().as_bytes().to_vec();
statekey.push(0xff); statekey_vec.push(0xff);
statekey.extend_from_slice(state_key.as_bytes()); statekey_vec.extend_from_slice(state_key.as_bytes());
let short = self let short = self
.statekey_shortstatekey .statekey_shortstatekey
.get(&statekey)? .get(&statekey_vec)?
.map(|shortstatekey| { .map(|shortstatekey| {
utils::u64_from_bytes(&shortstatekey) utils::u64_from_bytes(&shortstatekey)
.map_err(|_| Error::bad_database("Invalid shortstatekey in db.")) .map_err(|_| Error::bad_database("Invalid shortstatekey in db."))
@ -83,19 +83,19 @@ impl service::rooms::short::Data for KeyValueDatabase {
return Ok(*short); return Ok(*short);
} }
let mut statekey = event_type.to_string().as_bytes().to_vec(); let mut statekey_vec = event_type.to_string().as_bytes().to_vec();
statekey.push(0xff); statekey_vec.push(0xff);
statekey.extend_from_slice(state_key.as_bytes()); statekey_vec.extend_from_slice(state_key.as_bytes());
let short = match self.statekey_shortstatekey.get(&statekey)? { let short = match self.statekey_shortstatekey.get(&statekey_vec)? {
Some(shortstatekey) => utils::u64_from_bytes(&shortstatekey) Some(shortstatekey) => utils::u64_from_bytes(&shortstatekey)
.map_err(|_| Error::bad_database("Invalid shortstatekey in db."))?, .map_err(|_| Error::bad_database("Invalid shortstatekey in db."))?,
None => { None => {
let shortstatekey = services().globals.next_count()?; let shortstatekey = services().globals.next_count()?;
self.statekey_shortstatekey self.statekey_shortstatekey
.insert(&statekey, &shortstatekey.to_be_bytes())?; .insert(&statekey_vec, &shortstatekey.to_be_bytes())?;
self.shortstatekey_statekey self.shortstatekey_statekey
.insert(&shortstatekey.to_be_bytes(), &statekey)?; .insert(&shortstatekey.to_be_bytes(), &statekey_vec)?;
shortstatekey shortstatekey
} }
}; };

View file

@ -63,7 +63,7 @@ impl service::rooms::state::Data for KeyValueDatabase {
} }
for event_id in event_ids { for event_id in event_ids {
let mut key = prefix.to_owned(); let mut key = prefix.clone();
key.extend_from_slice(event_id.as_bytes()); key.extend_from_slice(event_id.as_bytes());
self.roomid_pduleaves.insert(&key, event_id.as_bytes())?; self.roomid_pduleaves.insert(&key, event_id.as_bytes())?;
} }

View file

@ -105,7 +105,10 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
let mut joined_servers = HashSet::new(); let mut joined_servers = HashSet::new();
let mut real_users = HashSet::new(); let mut real_users = HashSet::new();
for joined in self.room_members(room_id).filter_map(|r| r.ok()) { for joined in self
.room_members(room_id)
.filter_map(std::result::Result::ok)
{
joined_servers.insert(joined.server_name().to_owned()); joined_servers.insert(joined.server_name().to_owned());
if joined.server_name() == services().globals.server_name() if joined.server_name() == services().globals.server_name()
&& !services().users.is_deactivated(&joined).unwrap_or(true) && !services().users.is_deactivated(&joined).unwrap_or(true)
@ -115,7 +118,10 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
joinedcount += 1; joinedcount += 1;
} }
for _invited in self.room_members_invited(room_id).filter_map(|r| r.ok()) { for _invited in self
.room_members_invited(room_id)
.filter_map(std::result::Result::ok)
{
invitedcount += 1; invitedcount += 1;
} }
@ -130,7 +136,10 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
.unwrap() .unwrap()
.insert(room_id.to_owned(), Arc::new(real_users)); .insert(room_id.to_owned(), Arc::new(real_users));
for old_joined_server in self.room_servers(room_id).filter_map(|r| r.ok()) { for old_joined_server in self
.room_servers(room_id)
.filter_map(std::result::Result::ok)
{
if !joined_servers.remove(&old_joined_server) { if !joined_servers.remove(&old_joined_server) {
// Server not in room anymore // Server not in room anymore
let mut roomserver_id = room_id.as_bytes().to_vec(); let mut roomserver_id = room_id.as_bytes().to_vec();

View file

@ -70,7 +70,7 @@ impl service::rooms::threads::Data for KeyValueDatabase {
})?) })?)
.map_err(|_| Error::bad_database("Invalid UserId in threadid_userids.")) .map_err(|_| Error::bad_database("Invalid UserId in threadid_userids."))
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect(), .collect(),
)) ))
} else { } else {

View file

@ -5,11 +5,7 @@ use ruma::{
}; };
use tracing::error; use tracing::error;
use crate::{ use crate::{database::KeyValueDatabase, service, services, utils, Error, PduEvent, Result};
database::KeyValueDatabase,
service::{self, rooms::timeline::data::PduData},
services, utils, Error, PduEvent, Result,
};
use service::rooms::timeline::PduCount; use service::rooms::timeline::PduCount;
@ -232,7 +228,7 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
user_id: &UserId, user_id: &UserId,
room_id: &RoomId, room_id: &RoomId,
until: PduCount, until: PduCount,
) -> PduData<'a> { ) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>> {
let (prefix, current) = count_to_id(room_id, until, 1, true)?; let (prefix, current) = count_to_id(room_id, until, 1, true)?;
let user_id = user_id.to_owned(); let user_id = user_id.to_owned();
@ -254,7 +250,12 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
)) ))
} }
fn pdus_after<'a>(&'a self, user_id: &UserId, room_id: &RoomId, from: PduCount) -> PduData<'a> { fn pdus_after<'a>(
&'a self,
user_id: &UserId,
room_id: &RoomId,
from: PduCount,
) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>> {
let (prefix, current) = count_to_id(room_id, from, 1, false)?; let (prefix, current) = count_to_id(room_id, from, 1, false)?;
let user_id = user_id.to_owned(); let user_id = user_id.to_owned();

View file

@ -131,7 +131,7 @@ impl service::rooms::user::Data for KeyValueDatabase {
Ok::<_, Error>(room_id) Ok::<_, Error>(room_id)
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
}); });
// We use the default compare function because keys are sorted correctly (not reversed) // We use the default compare function because keys are sorted correctly (not reversed)

View file

@ -67,9 +67,9 @@ impl service::sending::Data for KeyValueDatabase {
for (outgoing_kind, event) in requests { for (outgoing_kind, event) in requests {
let mut key = outgoing_kind.get_prefix(); let mut key = outgoing_kind.get_prefix();
if let SendingEventType::Pdu(value) = &event { if let SendingEventType::Pdu(value) = &event {
key.extend_from_slice(value) key.extend_from_slice(value);
} else { } else {
key.extend_from_slice(&services().globals.next_count()?.to_be_bytes()) key.extend_from_slice(&services().globals.next_count()?.to_be_bytes());
} }
let value = if let SendingEventType::Edu(value) = &event { let value = if let SendingEventType::Edu(value) = &event {
&**value &**value

View file

@ -12,7 +12,7 @@ impl service::transaction_ids::Data for KeyValueDatabase {
) -> Result<()> { ) -> Result<()> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xff); key.push(0xff);
key.extend_from_slice(device_id.map(|d| d.as_bytes()).unwrap_or_default()); key.extend_from_slice(device_id.map(DeviceId::as_bytes).unwrap_or_default());
key.push(0xff); key.push(0xff);
key.extend_from_slice(txn_id.as_bytes()); key.extend_from_slice(txn_id.as_bytes());
@ -29,7 +29,7 @@ impl service::transaction_ids::Data for KeyValueDatabase {
) -> Result<Option<Vec<u8>>> { ) -> Result<Option<Vec<u8>>> {
let mut key = user_id.as_bytes().to_vec(); let mut key = user_id.as_bytes().to_vec();
key.push(0xff); key.push(0xff);
key.extend_from_slice(device_id.map(|d| d.as_bytes()).unwrap_or_default()); key.extend_from_slice(device_id.map(DeviceId::as_bytes).unwrap_or_default());
key.push(0xff); key.push(0xff);
key.extend_from_slice(txn_id.as_bytes()); key.extend_from_slice(txn_id.as_bytes());

View file

@ -34,7 +34,7 @@ impl service::uiaa::Data for KeyValueDatabase {
.read() .read()
.unwrap() .unwrap()
.get(&(user_id.to_owned(), device_id.to_owned(), session.to_owned())) .get(&(user_id.to_owned(), device_id.to_owned(), session.to_owned()))
.map(|j| j.to_owned()) .map(std::borrow::ToOwned::to_owned)
} }
fn update_uiaa_session( fn update_uiaa_session(

View file

@ -650,7 +650,7 @@ impl service::users::Data for KeyValueDatabase {
.rooms .rooms
.state_cache .state_cache
.rooms_joined(user_id) .rooms_joined(user_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
// Don't send key updates to unencrypted rooms // Don't send key updates to unencrypted rooms
if services() if services()
@ -855,7 +855,7 @@ impl service::users::Data for KeyValueDatabase {
.map_err(|_| Error::bad_database("ToDeviceId has invalid count bytes."))?, .map_err(|_| Error::bad_database("ToDeviceId has invalid count bytes."))?,
)) ))
}) })
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.take_while(|&(_, count)| count <= until) .take_while(|&(_, count)| count <= until)
{ {
self.todeviceid_events.remove(&key)?; self.todeviceid_events.remove(&key)?;

View file

@ -36,7 +36,7 @@ use tokio::{sync::mpsc, time::interval};
use tracing::{debug, error, info, warn}; use tracing::{debug, error, info, warn};
pub struct KeyValueDatabase { pub struct KeyValueDatabase {
_db: Arc<dyn KeyValueDatabaseEngine>, db: Arc<dyn KeyValueDatabaseEngine>,
//pub globals: globals::Globals, //pub globals: globals::Globals,
pub(super) global: Arc<dyn KvTree>, pub(super) global: Arc<dyn KvTree>,
@ -252,7 +252,7 @@ impl KeyValueDatabase {
let (presence_sender, presence_receiver) = mpsc::unbounded_channel(); let (presence_sender, presence_receiver) = mpsc::unbounded_channel();
let db_raw = Box::new(Self { let db_raw = Box::new(Self {
_db: builder.clone(), db: builder.clone(),
userid_password: builder.open_tree("userid_password")?, userid_password: builder.open_tree("userid_password")?,
userid_displayname: builder.open_tree("userid_displayname")?, userid_displayname: builder.open_tree("userid_displayname")?,
userid_avatarurl: builder.open_tree("userid_avatarurl")?, userid_avatarurl: builder.open_tree("userid_avatarurl")?,
@ -616,7 +616,7 @@ impl KeyValueDatabase {
Ok::<_, Error>(()) Ok::<_, Error>(())
}; };
for (k, seventid) in db._db.open_tree("stateid_shorteventid")?.iter() { for (k, seventid) in db.db.open_tree("stateid_shorteventid")?.iter() {
let sstatehash = utils::u64_from_bytes(&k[0..size_of::<u64>()]) let sstatehash = utils::u64_from_bytes(&k[0..size_of::<u64>()])
.expect("number of bytes is correct"); .expect("number of bytes is correct");
let sstatekey = k[size_of::<u64>()..].to_vec(); let sstatekey = k[size_of::<u64>()..].to_vec();
@ -789,7 +789,7 @@ impl KeyValueDatabase {
} }
// Force E2EE device list updates so we can send them over federation // Force E2EE device list updates so we can send them over federation
for user_id in services().users.iter().filter_map(|r| r.ok()) { for user_id in services().users.iter().filter_map(std::result::Result::ok) {
services().users.mark_device_key_update(&user_id)?; services().users.mark_device_key_update(&user_id)?;
} }
@ -799,7 +799,7 @@ impl KeyValueDatabase {
} }
if services().globals.database_version()? < 11 { if services().globals.database_version()? < 11 {
db._db db.db
.open_tree("userdevicesessionid_uiaarequest")? .open_tree("userdevicesessionid_uiaarequest")?
.clear()?; .clear()?;
services().globals.bump_database_version(11)?; services().globals.bump_database_version(11)?;
@ -974,7 +974,7 @@ impl KeyValueDatabase {
.into_iter() .into_iter()
.map(|x| &patterns.patterns()[x]) .map(|x| &patterns.patterns()[x])
.join(", ") .join(", ")
) );
} }
} }
} }
@ -998,7 +998,7 @@ impl KeyValueDatabase {
.into_iter() .into_iter()
.map(|x| &patterns.patterns()[x]) .map(|x| &patterns.patterns()[x])
.join(", ") .join(", ")
) );
} }
} }
} }
@ -1039,7 +1039,7 @@ impl KeyValueDatabase {
error!( error!(
"Could not set the configured emergency password for the conduit user: {}", "Could not set the configured emergency password for the conduit user: {}",
e e
) );
} }
}; };
@ -1059,7 +1059,7 @@ impl KeyValueDatabase {
pub fn flush(&self) -> Result<()> { pub fn flush(&self) -> Result<()> {
let start = std::time::Instant::now(); let start = std::time::Instant::now();
let res = self._db.flush(); let res = self.db.flush();
debug!("flush: took {:?}", start.elapsed()); debug!("flush: took {:?}", start.elapsed());
@ -1113,7 +1113,7 @@ impl KeyValueDatabase {
.send_message(RoomMessageEventContent::text_plain(format!( .send_message(RoomMessageEventContent::text_plain(format!(
"@room: the following is a message from the conduwuit puppy. it was sent on '{}':\n\n{}", "@room: the following is a message from the conduwuit puppy. it was sent on '{}':\n\n{}",
update.date, update.message update.date, update.message
))) )));
} }
} }
services() services()

View file

@ -442,14 +442,14 @@ impl Service {
.roomid_mutex_state .roomid_mutex_state
.write() .write()
.unwrap() .unwrap()
.entry(conduit_room.to_owned()) .entry(conduit_room.clone())
.or_default(), .or_default(),
); );
let state_lock = mutex_state.lock().await; let state_lock = mutex_state.lock().await;
if let Some(reply) = reply { if let Some(reply) = reply {
message_content.relates_to = Some(Reply { in_reply_to: InReplyTo { event_id: reply.into() } }) message_content.relates_to = Some(Reply { in_reply_to: InReplyTo { event_id: reply.into() } });
} }
services().rooms.timeline.build_and_append_pdu( services().rooms.timeline.build_and_append_pdu(
@ -618,7 +618,7 @@ impl Service {
if let Ok(appservices) = services() if let Ok(appservices) = services()
.appservice .appservice
.iter_ids() .iter_ids()
.map(|ids| ids.collect::<Vec<_>>()) .map(std::iter::Iterator::collect::<Vec<_>>)
{ {
let count = appservices.len(); let count = appservices.len();
let output = format!( let output = format!(
@ -626,7 +626,7 @@ impl Service {
count, count,
appservices appservices
.into_iter() .into_iter()
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
); );
@ -992,7 +992,7 @@ impl Service {
false => true, false => true,
}, },
Err(_) => false, Err(_) => false,
}) });
} }
for &user_id in &user_ids { for &user_id in &user_ids {
@ -1002,7 +1002,7 @@ impl Service {
} }
if services().users.deactivate_account(user_id).is_ok() { if services().users.deactivate_account(user_id).is_ok() {
deactivation_count += 1 deactivation_count += 1;
} }
} }
@ -1243,7 +1243,7 @@ impl Service {
continue; continue;
} }
room_ids.push(owned_room_id) room_ids.push(owned_room_id);
} }
Err(e) => { Err(e) => {
if force { if force {
@ -1441,7 +1441,7 @@ impl Service {
.rooms .rooms
.metadata .metadata
.iter_ids() .iter_ids()
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.map(Self::get_room_info) .map(Self::get_room_info)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1); rooms.sort_by_key(|r| r.1);
@ -1672,7 +1672,7 @@ impl Service {
.rooms .rooms
.directory .directory
.public_rooms() .public_rooms()
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.map(Self::get_room_info) .map(Self::get_room_info)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1); rooms.sort_by_key(|r| r.1);
@ -1933,7 +1933,7 @@ impl Service {
} }
DebugCommand::ForceDeviceListUpdates => { DebugCommand::ForceDeviceListUpdates => {
// Force E2EE device list updates for all users // Force E2EE device list updates for all users
for user_id in services().users.iter().filter_map(|r| r.ok()) { for user_id in services().users.iter().filter_map(std::result::Result::ok) {
services().users.mark_device_key_update(&user_id)?; services().users.mark_device_key_update(&user_id)?;
} }
RoomMessageEventContent::text_plain( RoomMessageEventContent::text_plain(
@ -2390,7 +2390,7 @@ impl Service {
// Set power level // Set power level
let mut users = BTreeMap::new(); let mut users = BTreeMap::new();
users.insert(conduit_user.to_owned(), 100.into()); users.insert(conduit_user.clone(), 100.into());
users.insert(user_id.to_owned(), 100.into()); users.insert(user_id.to_owned(), 100.into());
services() services()

View file

@ -249,9 +249,6 @@ impl Service {
if file_created_at >= user_duration { if file_created_at >= user_duration {
debug!("File is within user duration, pushing to list of file paths and keys to delete."); debug!("File is within user duration, pushing to list of file paths and keys to delete.");
remote_mxcs.push(mxc.to_string()); remote_mxcs.push(mxc.to_string());
} else {
// don't need to log this even in debug as it would be noisy
continue;
} }
} }
@ -331,7 +328,7 @@ impl Service {
Ok(Some(FileMeta { Ok(Some(FileMeta {
content_disposition, content_disposition,
content_type, content_type,
file: file.to_vec(), file: file.clone(),
})) }))
} else if let Ok((content_disposition, content_type, key)) = } else if let Ok((content_disposition, content_type, key)) =
self.db.search_file_metadata(mxc.clone(), 0, 0) self.db.search_file_metadata(mxc.clone(), 0, 0)
@ -354,7 +351,7 @@ impl Service {
return Ok(Some(FileMeta { return Ok(Some(FileMeta {
content_disposition, content_disposition,
content_type, content_type,
file: file.to_vec(), file: file.clone(),
})); }));
} }
@ -426,14 +423,14 @@ impl Service {
Ok(Some(FileMeta { Ok(Some(FileMeta {
content_disposition, content_disposition,
content_type, content_type,
file: thumbnail_bytes.to_vec(), file: thumbnail_bytes.clone(),
})) }))
} else { } else {
// Couldn't parse file to generate thumbnail, send original // Couldn't parse file to generate thumbnail, send original
Ok(Some(FileMeta { Ok(Some(FileMeta {
content_disposition, content_disposition,
content_type, content_type,
file: file.to_vec(), file: file.clone(),
})) }))
} }
} else { } else {

View file

@ -64,7 +64,7 @@ impl Service {
warn!("Failed to find destination {}: {}", destination, e); warn!("Failed to find destination {}: {}", destination, e);
Error::BadServerResponse("Invalid destination") Error::BadServerResponse("Invalid destination")
})? })?
.map(|body| body.freeze()); .map(bytes::BytesMut::freeze);
let reqwest_request = reqwest::Request::try_from(http_request)?; let reqwest_request = reqwest::Request::try_from(http_request)?;
@ -258,7 +258,7 @@ impl Service {
.iter() .iter()
.any(|t| matches!(t, Tweak::Highlight(true) | Tweak::Sound(_))) .any(|t| matches!(t, Tweak::Highlight(true) | Tweak::Sound(_)))
{ {
notifi.prio = NotificationPriority::High notifi.prio = NotificationPriority::High;
} }
if event_id_only { if event_id_only {
@ -285,7 +285,7 @@ impl Service {
Ok(()) Ok(())
} }
// TODO: Handle email // TODO: Handle email
PusherKind::Email(_) => Ok(()), //PusherKind::Email(_) => Ok(()),
_ => Ok(()), _ => Ok(()),
} }
} }

View file

@ -36,7 +36,10 @@ use ruma::{
use serde_json::value::RawValue as RawJsonValue; use serde_json::value::RawValue as RawJsonValue;
use tracing::{debug, error, info, trace, warn}; use tracing::{debug, error, info, trace, warn};
use crate::{service::*, services, Error, PduEvent}; use crate::{
service::{pdu, Arc, BTreeMap, HashMap, Result, RwLock},
services, Error, PduEvent,
};
use super::state_compressor::CompressedStateEvent; use super::state_compressor::CompressedStateEvent;
@ -63,7 +66,7 @@ impl Service {
/// 8. If not timeline event: stop /// 8. If not timeline event: stop
/// 9. Fetch any missing prev events doing all checks listed here starting at 1. These are timeline /// 9. Fetch any missing prev events doing all checks listed here starting at 1. These are timeline
/// events /// events
/// 10. Fetch missing state and auth chain events by calling /state_ids at backwards extremities /// 10. Fetch missing state and auth chain events by calling `/state_ids` at backwards extremities
/// doing all the checks in this list starting at 1. These are not timeline events /// doing all the checks in this list starting at 1. These are not timeline events
/// 11. Check the auth of the event passes based on the state of the event /// 11. Check the auth of the event passes based on the state of the event
/// 12. Ensure that the state is derived from the previous current state (i.e. we calculated by /// 12. Ensure that the state is derived from the previous current state (i.e. we calculated by
@ -101,7 +104,7 @@ impl Service {
// 1. Skip the PDU if we already have it as a timeline event // 1. Skip the PDU if we already have it as a timeline event
if let Some(pdu_id) = services().rooms.timeline.get_pdu_id(event_id)? { if let Some(pdu_id) = services().rooms.timeline.get_pdu_id(event_id)? {
return Ok(Some(pdu_id.to_vec())); return Ok(Some(pdu_id));
} }
let create_event = services() let create_event = services()
@ -202,7 +205,7 @@ impl Service {
e.insert((Instant::now(), 1)); e.insert((Instant::now(), 1));
} }
hash_map::Entry::Occupied(mut e) => { hash_map::Entry::Occupied(mut e) => {
*e.get_mut() = (Instant::now(), e.get().1 + 1) *e.get_mut() = (Instant::now(), e.get().1 + 1);
} }
} }
continue; continue;
@ -246,7 +249,7 @@ impl Service {
e.insert((Instant::now(), 1)); e.insert((Instant::now(), 1));
} }
hash_map::Entry::Occupied(mut e) => { hash_map::Entry::Occupied(mut e) => {
*e.get_mut() = (Instant::now(), e.get().1 + 1) *e.get_mut() = (Instant::now(), e.get().1 + 1);
} }
} }
} }
@ -440,7 +443,7 @@ impl Service {
if !matches!( if !matches!(
auth_events auth_events
.get(&(StateEventType::RoomCreate, "".to_owned())) .get(&(StateEventType::RoomCreate, "".to_owned()))
.map(|a| a.as_ref()), .map(std::convert::AsRef::as_ref),
Some(_) | None Some(_) | None
) { ) {
return Err(Error::BadRequest( return Err(Error::BadRequest(
@ -733,7 +736,9 @@ impl Service {
.get_shortstatekey(&StateEventType::RoomCreate, "")? .get_shortstatekey(&StateEventType::RoomCreate, "")?
.expect("Room exists"); .expect("Room exists");
if state.get(&create_shortstatekey).map(|id| id.as_ref()) if state
.get(&create_shortstatekey)
.map(std::convert::AsRef::as_ref)
!= Some(&create_event.event_id) != Some(&create_event.event_id)
{ {
return Err(Error::bad_database( return Err(Error::bad_database(
@ -1167,7 +1172,7 @@ impl Service {
} }
} }
} }
events_with_auth_events.push((id, None, events_in_reverse_order)) events_with_auth_events.push((id, None, events_in_reverse_order));
} }
// We go through all the signatures we see on the PDUs and their unresolved // We go through all the signatures we see on the PDUs and their unresolved
@ -1185,7 +1190,7 @@ impl Service {
warn!( warn!(
"Could not fetch all signatures for PDUs from {}: {:?}", "Could not fetch all signatures for PDUs from {}: {:?}",
origin, e origin, e
) );
}); });
let mut pdus = vec![]; let mut pdus = vec![];
@ -1565,7 +1570,7 @@ impl Service {
} }
drop(pkm); drop(pkm);
} };
if servers.is_empty() { if servers.is_empty() {
info!("server is empty, we had all keys locally, not fetching any keys"); info!("server is empty, we had all keys locally, not fetching any keys");

View file

@ -1,20 +1,18 @@
use std::sync::Arc; use std::sync::Arc;
use crate::{ use crate::{service::rooms::timeline::PduCount, PduEvent, Result};
service::rooms::timeline::{data::PduData, PduCount},
Result,
};
use ruma::{EventId, RoomId, UserId}; use ruma::{EventId, RoomId, UserId};
pub trait Data: Send + Sync { pub trait Data: Send + Sync {
fn add_relation(&self, from: u64, to: u64) -> Result<()>; fn add_relation(&self, from: u64, to: u64) -> Result<()>;
#[allow(clippy::type_complexity)]
fn relations_until<'a>( fn relations_until<'a>(
&'a self, &'a self,
user_id: &'a UserId, user_id: &'a UserId,
room_id: u64, room_id: u64,
target: u64, target: u64,
until: PduCount, until: PduCount,
) -> PduData<'a>; ) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>>;
fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Arc<EventId>]) -> Result<()>; fn mark_as_referenced(&self, room_id: &RoomId, event_ids: &[Arc<EventId>]) -> Result<()>;
fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result<bool>; fn is_event_referenced(&self, room_id: &RoomId, event_id: &EventId) -> Result<bool>;
fn mark_event_soft_failed(&self, event_id: &EventId) -> Result<()>; fn mark_event_soft_failed(&self, event_id: &EventId) -> Result<()>;

View file

@ -78,7 +78,7 @@ impl Service {
}) })
}) })
.take(limit) .take(limit)
.filter_map(|r| r.ok()) // Filter out buggy events .filter_map(std::result::Result::ok) // Filter out buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms
@ -125,7 +125,7 @@ impl Service {
}) })
}) })
.take(limit) .take(limit)
.filter_map(|r| r.ok()) // Filter out buggy events .filter_map(std::result::Result::ok) // Filter out buggy events
.filter(|(_, pdu)| { .filter(|(_, pdu)| {
services() services()
.rooms .rooms

View file

@ -62,11 +62,11 @@ impl Service {
let mut results = Vec::new(); let mut results = Vec::new();
while let Some(current_room) = { while let Some(current_room) = {
while stack.last().map_or(false, |s| s.is_empty()) { while stack.last().map_or(false, std::vec::Vec::is_empty) {
stack.pop(); stack.pop();
} }
if !stack.is_empty() { if !stack.is_empty() {
stack.last_mut().and_then(|s| s.pop()) stack.last_mut().and_then(std::vec::Vec::pop)
} else { } else {
None None
} }
@ -80,7 +80,7 @@ impl Service {
.roomid_spacechunk_cache .roomid_spacechunk_cache
.lock() .lock()
.unwrap() .unwrap()
.get_mut(&current_room.to_owned()) .get_mut(&current_room.clone())
.as_ref() .as_ref()
{ {
if let Some(cached) = cached { if let Some(cached) = cached {
@ -202,7 +202,7 @@ impl Service {
.send_federation_request( .send_federation_request(
server, server,
federation::space::get_hierarchy::v1::Request { federation::space::get_hierarchy::v1::Request {
room_id: current_room.to_owned(), room_id: current_room.clone(),
suggested_only, suggested_only,
}, },
) )

View file

@ -81,16 +81,15 @@ impl Service {
/// The user was a joined member at this state (potentially in the past) /// The user was a joined member at this state (potentially in the past)
fn user_was_joined(&self, shortstatehash: u64, user_id: &UserId) -> bool { fn user_was_joined(&self, shortstatehash: u64, user_id: &UserId) -> bool {
self.user_membership(shortstatehash, user_id) self.user_membership(shortstatehash, user_id)
.map(|s| s == MembershipState::Join) .is_ok_and(|s| s == MembershipState::Join) // Return sensible default, i.e. false
.unwrap_or_default() // Return sensible default, i.e. false
} }
/// The user was an invited or joined room member at this state (potentially /// The user was an invited or joined room member at this state (potentially
/// in the past) /// in the past)
fn user_was_invited(&self, shortstatehash: u64, user_id: &UserId) -> bool { fn user_was_invited(&self, shortstatehash: u64, user_id: &UserId) -> bool {
self.user_membership(shortstatehash, user_id) self.user_membership(shortstatehash, user_id)
.map(|s| s == MembershipState::Join || s == MembershipState::Invite) .is_ok_and(|s| s == MembershipState::Join || s == MembershipState::Invite)
.unwrap_or_default() // Return sensible default, i.e. false // Return sensible default, i.e. false
} }
/// Whether a server is allowed to see an event through federation, based on /// Whether a server is allowed to see an event through federation, based on
@ -102,9 +101,8 @@ impl Service {
room_id: &RoomId, room_id: &RoomId,
event_id: &EventId, event_id: &EventId,
) -> Result<bool> { ) -> Result<bool> {
let shortstatehash = match self.pdu_shortstatehash(event_id)? { let Some(shortstatehash) = self.pdu_shortstatehash(event_id)? else {
Some(shortstatehash) => shortstatehash, return Ok(true);
None => return Ok(true),
}; };
if let Some(visibility) = self if let Some(visibility) = self
@ -130,7 +128,7 @@ impl Service {
.rooms .rooms
.state_cache .state_cache
.room_members(room_id) .room_members(room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|member| member.server_name() == origin); .filter(|member| member.server_name() == origin);
let visibility = match history_visibility { let visibility = match history_visibility {

View file

@ -1,5 +1,7 @@
mod data; mod data;
use std::collections::BTreeMap;
pub use data::Data; pub use data::Data;
use ruma::{ use ruma::{
api::client::{error::ErrorKind, threads::get_threads::v1::IncludeThreads}, api::client::{error::ErrorKind, threads::get_threads::v1::IncludeThreads},
@ -56,7 +58,7 @@ impl Service {
if let CanonicalJsonValue::Object(unsigned) = root_pdu_json if let CanonicalJsonValue::Object(unsigned) = root_pdu_json
.entry("unsigned".to_owned()) .entry("unsigned".to_owned())
.or_insert_with(|| CanonicalJsonValue::Object(Default::default())) .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default()))
{ {
if let Some(mut relations) = unsigned if let Some(mut relations) = unsigned
.get("m.relations") .get("m.relations")

View file

@ -6,8 +6,6 @@ use crate::{PduEvent, Result};
use super::PduCount; use super::PduCount;
pub type PduData<'a> = Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>>;
pub trait Data: Send + Sync { pub trait Data: Send + Sync {
fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount>; fn last_timeline_count(&self, sender_user: &UserId, room_id: &RoomId) -> Result<PduCount>;
@ -68,12 +66,23 @@ pub trait Data: Send + Sync {
/// Returns an iterator over all events and their tokens in a room that happened before the /// Returns an iterator over all events and their tokens in a room that happened before the
/// event with id `until` in reverse-chronological order. /// event with id `until` in reverse-chronological order.
fn pdus_until<'a>(&'a self, user_id: &UserId, room_id: &RoomId, until: PduCount) #[allow(clippy::type_complexity)]
-> PduData<'a>; fn pdus_until<'a>(
&'a self,
user_id: &UserId,
room_id: &RoomId,
until: PduCount,
) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>>;
/// Returns an iterator over all events in a room that happened after the event with id `from` /// Returns an iterator over all events in a room that happened after the event with id `from`
/// in chronological order. /// in chronological order.
fn pdus_after<'a>(&'a self, user_id: &UserId, room_id: &RoomId, from: PduCount) -> PduData<'a>; #[allow(clippy::type_complexity)]
fn pdus_after<'a>(
&'a self,
user_id: &UserId,
room_id: &RoomId,
from: PduCount,
) -> Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>>;
fn increment_notification_counts( fn increment_notification_counts(
&self, &self,

View file

@ -243,7 +243,7 @@ impl Service {
if let Some(state_key) = &pdu.state_key { if let Some(state_key) = &pdu.state_key {
if let CanonicalJsonValue::Object(unsigned) = pdu_json if let CanonicalJsonValue::Object(unsigned) = pdu_json
.entry("unsigned".to_owned()) .entry("unsigned".to_owned())
.or_insert_with(|| CanonicalJsonValue::Object(Default::default())) .or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default()))
{ {
if let Some(shortstatehash) = services() if let Some(shortstatehash) = services()
.rooms .rooms
@ -400,8 +400,10 @@ impl Service {
}) })
}) })
.transpose()? .transpose()?
.map(|ev: PushRulesEvent| ev.content.global) .map_or_else(
.unwrap_or_else(|| Ruleset::server_default(user)); || Ruleset::server_default(user),
|ev: PushRulesEvent| ev.content.global,
);
let mut highlight = false; let mut highlight = false;
let mut notify = false; let mut notify = false;
@ -686,7 +688,7 @@ impl Service {
.rooms .rooms
.alias .alias
.local_aliases_for_room(&pdu.room_id) .local_aliases_for_room(&pdu.room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.any(|room_alias| aliases.is_match(room_alias.as_str())) .any(|room_alias| aliases.is_match(room_alias.as_str()))
}; };
@ -930,7 +932,7 @@ impl Service {
.filter(|v| v.starts_with('@')) .filter(|v| v.starts_with('@'))
.unwrap_or(sender.as_str()); .unwrap_or(sender.as_str());
let server_name = services().globals.server_name(); let server_name = services().globals.server_name();
let server_user = format!("@conduit:{}", server_name); let server_user = format!("@conduit:{server_name}");
let content = serde_json::from_str::<ExtractMembership>(pdu.content.get()) let content = serde_json::from_str::<ExtractMembership>(pdu.content.get())
.map_err(|_| Error::bad_database("Invalid content in pdu."))?; .map_err(|_| Error::bad_database("Invalid content in pdu."))?;
@ -947,7 +949,7 @@ impl Service {
.rooms .rooms
.state_cache .state_cache
.room_members(room_id) .room_members(room_id)
.filter_map(|m| m.ok()) .filter_map(std::result::Result::ok)
.filter(|m| m.server_name() == server_name) .filter(|m| m.server_name() == server_name)
.filter(|m| m != target) .filter(|m| m != target)
.count(); .count();
@ -973,7 +975,7 @@ impl Service {
.rooms .rooms
.state_cache .state_cache
.room_members(room_id) .room_members(room_id)
.filter_map(|m| m.ok()) .filter_map(std::result::Result::ok)
.filter(|m| m.server_name() == server_name) .filter(|m| m.server_name() == server_name)
.filter(|m| m != target) .filter(|m| m != target)
.count(); .count();
@ -1016,7 +1018,7 @@ impl Service {
.rooms .rooms
.state_cache .state_cache
.room_servers(room_id) .room_servers(room_id)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.collect(); .collect();
// In case we are kicking or banning a user, we need to inform their server of the change // In case we are kicking or banning a user, we need to inform their server of the change
@ -1217,7 +1219,7 @@ impl Service {
.roomid_mutex_federation .roomid_mutex_federation
.write() .write()
.unwrap() .unwrap()
.entry(room_id.to_owned()) .entry(room_id.clone())
.or_default(), .or_default(),
); );
let mutex_lock = mutex.lock().await; let mutex_lock = mutex.lock().await;

View file

@ -82,6 +82,7 @@ impl OutgoingKind {
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[allow(clippy::module_name_repetitions)]
pub enum SendingEventType { pub enum SendingEventType {
Pdu(Vec<u8>), // pduid Pdu(Vec<u8>), // pduid
Edu(Vec<u8>), // pdu json Edu(Vec<u8>), // pdu json
@ -130,7 +131,11 @@ impl Service {
// Retry requests we could not finish yet // Retry requests we could not finish yet
let mut initial_transactions = HashMap::<OutgoingKind, Vec<SendingEventType>>::new(); let mut initial_transactions = HashMap::<OutgoingKind, Vec<SendingEventType>>::new();
for (key, outgoing_kind, event) in self.db.active_requests().filter_map(|r| r.ok()) { for (key, outgoing_kind, event) in self
.db
.active_requests()
.filter_map(std::result::Result::ok)
{
let entry = initial_transactions let entry = initial_transactions
.entry(outgoing_kind.clone()) .entry(outgoing_kind.clone())
.or_default(); .or_default();
@ -160,7 +165,7 @@ impl Service {
self.db.delete_all_active_requests_for(&outgoing_kind)?; self.db.delete_all_active_requests_for(&outgoing_kind)?;
// Find events that have been added since starting the last request // Find events that have been added since starting the last request
let new_events = self.db.queued_requests(&outgoing_kind).filter_map(|r| r.ok()).take(30).collect::<Vec<_>>(); let new_events = self.db.queued_requests(&outgoing_kind).filter_map(std::result::Result::ok).take(30).collect::<Vec<_>>();
if !new_events.is_empty() { if !new_events.is_empty() {
// Insert pdus we found // Insert pdus we found
@ -247,7 +252,7 @@ impl Service {
for (_, e) in self for (_, e) in self
.db .db
.active_requests_for(outgoing_kind) .active_requests_for(outgoing_kind)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
{ {
events.push(e); events.push(e);
} }
@ -284,7 +289,7 @@ impl Service {
services() services()
.users .users
.keys_changed(room_id.as_ref(), since, None) .keys_changed(room_id.as_ref(), since, None)
.filter_map(|r| r.ok()) .filter_map(std::result::Result::ok)
.filter(|user_id| user_id.server_name() == services().globals.server_name()), .filter(|user_id| user_id.server_name() == services().globals.server_name()),
); );
@ -443,7 +448,7 @@ impl Service {
)?; )?;
for ((outgoing_kind, event), key) in requests.into_iter().zip(keys) { for ((outgoing_kind, event), key) in requests.into_iter().zip(keys) {
self.sender self.sender
.send((outgoing_kind.to_owned(), event, key)) .send((outgoing_kind.clone(), event, key))
.unwrap(); .unwrap();
} }
@ -513,7 +518,7 @@ impl Service {
), ),
) )
})? })?
.to_room_event()) .to_room_event());
} }
SendingEventType::Edu(_) => { SendingEventType::Edu(_) => {
// Appservices don't need EDUs (?) // Appservices don't need EDUs (?)
@ -600,13 +605,12 @@ impl Service {
} }
} }
let pusher = match services() let Some(pusher) = services()
.pusher .pusher
.get_pusher(userid, pushkey) .get_pusher(userid, pushkey)
.map_err(|e| (OutgoingKind::Push(userid.clone(), pushkey.clone()), e))? .map_err(|e| (OutgoingKind::Push(userid.clone(), pushkey.clone()), e))?
{ else {
Some(pusher) => pusher, continue;
None => continue,
}; };
let rules_for_user = services() let rules_for_user = services()
@ -618,8 +622,10 @@ impl Service {
) )
.unwrap_or_default() .unwrap_or_default()
.and_then(|event| serde_json::from_str::<PushRulesEvent>(event.get()).ok()) .and_then(|event| serde_json::from_str::<PushRulesEvent>(event.get()).ok())
.map(|ev: PushRulesEvent| ev.content.global) .map_or_else(
.unwrap_or_else(|| push::Ruleset::server_default(userid)); || push::Ruleset::server_default(userid),
|ev: PushRulesEvent| ev.content.global,
);
let unread: UInt = services() let unread: UInt = services()
.rooms .rooms

View file

@ -48,10 +48,10 @@ impl Service {
auth: &AuthData, auth: &AuthData,
uiaainfo: &UiaaInfo, uiaainfo: &UiaaInfo,
) -> Result<(bool, UiaaInfo)> { ) -> Result<(bool, UiaaInfo)> {
let mut uiaainfo = auth let mut uiaainfo = auth.session().map_or_else(
.session() || Ok(uiaainfo.clone()),
.map(|session| self.db.get_uiaa_session(user_id, device_id, session)) |session| self.db.get_uiaa_session(user_id, device_id, session),
.unwrap_or_else(|| Ok(uiaainfo.clone()))?; )?;
if uiaainfo.session.is_none() { if uiaainfo.session.is_none() {
uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH)); uiaainfo.session = Some(utils::random_string(SESSION_ID_LENGTH));
@ -64,14 +64,11 @@ impl Service {
password, password,
.. ..
}) => { }) => {
let username = match identifier { let UserIdentifier::UserIdOrLocalpart(username) = identifier else {
UserIdentifier::UserIdOrLocalpart(username) => username, return Err(Error::BadRequest(
_ => { ErrorKind::Unrecognized,
return Err(Error::BadRequest( "Identifier type not recognized.",
ErrorKind::Unrecognized, ));
"Identifier type not recognized.",
))
}
}; };
let user_id = UserId::parse_with_server_name( let user_id = UserId::parse_with_server_name(

View file

@ -100,7 +100,11 @@ impl Error {
let message = format!("{self}"); let message = format!("{self}");
use ErrorKind::*; use ErrorKind::{
Forbidden, GuestAccessForbidden, LimitExceeded, MissingToken, NotFound,
ThreepidAuthFailed, ThreepidDenied, TooLarge, Unauthorized, Unknown, UnknownToken,
Unrecognized, UserDeactivated, WrongRoomKeysVersion,
};
let (kind, status_code) = match self { let (kind, status_code) = match self {
Self::BadRequest(kind, _) => ( Self::BadRequest(kind, _) => (
kind.clone(), kind.clone(),

View file

@ -22,7 +22,7 @@ pub(crate) fn millis_since_unix_epoch() -> u64 {
} }
pub(crate) fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> { pub(crate) fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
let number = match old.map(|bytes| bytes.try_into()) { let number = match old.map(std::convert::TryInto::try_into) {
Some(Ok(bytes)) => { Some(Ok(bytes)) => {
let number = u64::from_be_bytes(bytes); let number = u64::from_be_bytes(bytes);
number + 1 number + 1
@ -94,7 +94,9 @@ pub(crate) fn common_elements(
check_order: impl Fn(&[u8], &[u8]) -> Ordering, check_order: impl Fn(&[u8], &[u8]) -> Ordering,
) -> Option<impl Iterator<Item = Vec<u8>>> { ) -> Option<impl Iterator<Item = Vec<u8>>> {
let first_iterator = iterators.next()?; let first_iterator = iterators.next()?;
let mut other_iterators = iterators.map(|i| i.peekable()).collect::<Vec<_>>(); let mut other_iterators = iterators
.map(std::iter::Iterator::peekable)
.collect::<Vec<_>>();
Some(first_iterator.filter(move |target| { Some(first_iterator.filter(move |target| {
other_iterators.iter_mut().all(|it| { other_iterators.iter_mut().all(|it| {