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

@ -442,14 +442,14 @@ impl Service {
.roomid_mutex_state
.write()
.unwrap()
.entry(conduit_room.to_owned())
.entry(conduit_room.clone())
.or_default(),
);
let state_lock = mutex_state.lock().await;
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(
@ -618,7 +618,7 @@ impl Service {
if let Ok(appservices) = services()
.appservice
.iter_ids()
.map(|ids| ids.collect::<Vec<_>>())
.map(std::iter::Iterator::collect::<Vec<_>>)
{
let count = appservices.len();
let output = format!(
@ -626,7 +626,7 @@ impl Service {
count,
appservices
.into_iter()
.filter_map(|r| r.ok())
.filter_map(std::result::Result::ok)
.collect::<Vec<_>>()
.join(", ")
);
@ -992,7 +992,7 @@ impl Service {
false => true,
},
Err(_) => false,
})
});
}
for &user_id in &user_ids {
@ -1002,7 +1002,7 @@ impl Service {
}
if services().users.deactivate_account(user_id).is_ok() {
deactivation_count += 1
deactivation_count += 1;
}
}
@ -1243,7 +1243,7 @@ impl Service {
continue;
}
room_ids.push(owned_room_id)
room_ids.push(owned_room_id);
}
Err(e) => {
if force {
@ -1441,7 +1441,7 @@ impl Service {
.rooms
.metadata
.iter_ids()
.filter_map(|r| r.ok())
.filter_map(std::result::Result::ok)
.map(Self::get_room_info)
.collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1);
@ -1672,7 +1672,7 @@ impl Service {
.rooms
.directory
.public_rooms()
.filter_map(|r| r.ok())
.filter_map(std::result::Result::ok)
.map(Self::get_room_info)
.collect::<Vec<_>>();
rooms.sort_by_key(|r| r.1);
@ -1933,7 +1933,7 @@ impl Service {
}
DebugCommand::ForceDeviceListUpdates => {
// 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)?;
}
RoomMessageEventContent::text_plain(
@ -2390,7 +2390,7 @@ impl Service {
// Set power level
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());
services()

View file

@ -249,9 +249,6 @@ impl Service {
if file_created_at >= user_duration {
debug!("File is within user duration, pushing to list of file paths and keys to delete.");
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 {
content_disposition,
content_type,
file: file.to_vec(),
file: file.clone(),
}))
} else if let Ok((content_disposition, content_type, key)) =
self.db.search_file_metadata(mxc.clone(), 0, 0)
@ -354,7 +351,7 @@ impl Service {
return Ok(Some(FileMeta {
content_disposition,
content_type,
file: file.to_vec(),
file: file.clone(),
}));
}
@ -426,14 +423,14 @@ impl Service {
Ok(Some(FileMeta {
content_disposition,
content_type,
file: thumbnail_bytes.to_vec(),
file: thumbnail_bytes.clone(),
}))
} else {
// Couldn't parse file to generate thumbnail, send original
Ok(Some(FileMeta {
content_disposition,
content_type,
file: file.to_vec(),
file: file.clone(),
}))
}
} else {

View file

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

View file

@ -36,7 +36,10 @@ use ruma::{
use serde_json::value::RawValue as RawJsonValue;
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;
@ -63,7 +66,7 @@ impl Service {
/// 8. If not timeline event: stop
/// 9. Fetch any missing prev events doing all checks listed here starting at 1. These are timeline
/// 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
/// 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
@ -101,7 +104,7 @@ impl Service {
// 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)? {
return Ok(Some(pdu_id.to_vec()));
return Ok(Some(pdu_id));
}
let create_event = services()
@ -202,7 +205,7 @@ impl Service {
e.insert((Instant::now(), 1));
}
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;
@ -246,7 +249,7 @@ impl Service {
e.insert((Instant::now(), 1));
}
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!(
auth_events
.get(&(StateEventType::RoomCreate, "".to_owned()))
.map(|a| a.as_ref()),
.map(std::convert::AsRef::as_ref),
Some(_) | None
) {
return Err(Error::BadRequest(
@ -733,7 +736,9 @@ impl Service {
.get_shortstatekey(&StateEventType::RoomCreate, "")?
.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)
{
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
@ -1185,7 +1190,7 @@ impl Service {
warn!(
"Could not fetch all signatures for PDUs from {}: {:?}",
origin, e
)
);
});
let mut pdus = vec![];
@ -1565,7 +1570,7 @@ impl Service {
}
drop(pkm);
}
};
if servers.is_empty() {
info!("server is empty, we had all keys locally, not fetching any keys");

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -6,8 +6,6 @@ use crate::{PduEvent, Result};
use super::PduCount;
pub type PduData<'a> = Result<Box<dyn Iterator<Item = Result<(PduCount, PduEvent)>> + 'a>>;
pub trait Data: Send + Sync {
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
/// event with id `until` in reverse-chronological order.
fn pdus_until<'a>(&'a self, user_id: &UserId, room_id: &RoomId, until: PduCount)
-> PduData<'a>;
#[allow(clippy::type_complexity)]
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`
/// 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(
&self,

View file

@ -243,7 +243,7 @@ impl Service {
if let Some(state_key) = &pdu.state_key {
if let CanonicalJsonValue::Object(unsigned) = pdu_json
.entry("unsigned".to_owned())
.or_insert_with(|| CanonicalJsonValue::Object(Default::default()))
.or_insert_with(|| CanonicalJsonValue::Object(BTreeMap::default()))
{
if let Some(shortstatehash) = services()
.rooms
@ -400,8 +400,10 @@ impl Service {
})
})
.transpose()?
.map(|ev: PushRulesEvent| ev.content.global)
.unwrap_or_else(|| Ruleset::server_default(user));
.map_or_else(
|| Ruleset::server_default(user),
|ev: PushRulesEvent| ev.content.global,
);
let mut highlight = false;
let mut notify = false;
@ -686,7 +688,7 @@ impl Service {
.rooms
.alias
.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()))
};
@ -930,7 +932,7 @@ impl Service {
.filter(|v| v.starts_with('@'))
.unwrap_or(sender.as_str());
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())
.map_err(|_| Error::bad_database("Invalid content in pdu."))?;
@ -947,7 +949,7 @@ impl Service {
.rooms
.state_cache
.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 != target)
.count();
@ -973,7 +975,7 @@ impl Service {
.rooms
.state_cache
.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 != target)
.count();
@ -1016,7 +1018,7 @@ impl Service {
.rooms
.state_cache
.room_servers(room_id)
.filter_map(|r| r.ok())
.filter_map(std::result::Result::ok)
.collect();
// 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
.write()
.unwrap()
.entry(room_id.to_owned())
.entry(room_id.clone())
.or_default(),
);
let mutex_lock = mutex.lock().await;

View file

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

View file

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