fix every clippy warning possible, remove io_uring as default feature

this project's codebase is so horrendous, im shocked that no one has ran
clippy at all. it had ~200 total lint warnings, some with performance
issues and unsoundness, and the rest just very ugly codebase. i have sat
down and fixed as many of these as possible and i am exhausted.
i haven't fixed some extremely complex ones, but i brought it down from
~200 to ~30.

i have also removed io_uring as a default feature due to it falling
under the same category as linux eBPF: major kernel attack surface for
minimal performance gains. this also makes it impossible to cross-compile
from macOS to Linux because io_uring does not exist in Darwin land.
there are far better ways to achieve better performance than io_uring on
the codebase level.

Signed-off-by: strawberry <june@girlboss.ceo>
This commit is contained in:
strawberry 2023-11-27 00:39:50 -05:00
parent 19d1b484e0
commit 54a3f47851
33 changed files with 312 additions and 314 deletions

View file

@ -5,6 +5,8 @@ use std::{
time::Instant,
};
use std::fmt::Write;
use clap::{Parser, Subcommand};
use regex::Regex;
use ruma::{
@ -27,7 +29,7 @@ use ruma::{
EventId, OwnedRoomAliasId, OwnedRoomId, RoomAliasId, RoomId, RoomVersionId, ServerName, UserId,
};
use serde_json::value::to_raw_value;
use tokio::sync::{mpsc, Mutex, MutexGuard};
use tokio::sync::{mpsc, Mutex};
use crate::{
api::client_server::{leave_all_rooms, AUTO_GEN_PASSWORD_LENGTH},
@ -194,19 +196,19 @@ enum RoomAliasCommand {
room_id: Box<RoomId>,
/// The alias localpart to use (`alias`, not `#alias:servername.tld`)
room_alias_localpart: Box<String>,
room_alias_localpart: String,
},
/// Remove an alias
Remove {
/// The alias localpart to remove (`alias`, not `#alias:servername.tld`)
room_alias_localpart: Box<String>,
room_alias_localpart: String,
},
/// Show which room is using an alias
Which {
/// The alias localpart to look up (`alias`, not `#alias:servername.tld`)
room_alias_localpart: Box<String>,
room_alias_localpart: String,
},
/// List aliases currently being used
@ -802,13 +804,12 @@ impl Service {
"<table><caption>Room list - page {page}</caption>\n<tr><th>id</th>\t<th>members</th>\t<th>name</th></tr>\n{}</table>",
rooms
.iter()
.map(|(id, members, name)| format!(
"<tr><td>{}</td>\t<td>{}</td>\t<td>{}</td></tr>\n",
escape_html(&id.to_string()),
.fold(String::new(), |mut output, (id, members, name)| {
writeln!(output, "<tr><td>{}</td>\t<td>{}</td>\t<td>{}</td></tr>", escape_html(id.as_ref()),
members,
escape_html(name),
))
.collect::<String>()
escape_html(name)).unwrap();
output
})
);
RoomMessageEventContent::text_html(output_plain, output_html)
}
@ -886,7 +887,7 @@ impl Service {
Ok(None) => {
RoomMessageEventContent::text_plain("Alias isn't in use.")
}
Err(err) => RoomMessageEventContent::text_plain(&format!(
Err(err) => RoomMessageEventContent::text_plain(format!(
"Unable to lookup alias: {}",
err
)),
@ -904,27 +905,29 @@ impl Service {
.collect();
match aliases {
Ok(aliases) => {
let plain_list: String = aliases
.iter()
.map(|alias| format!("- {}\n", alias))
.collect();
let plain_list: String =
aliases.iter().fold(String::new(), |mut output, alias| {
writeln!(output, "- {}", alias).unwrap();
output
});
let html_list: String = aliases
.iter()
.map(|alias| {
format!(
"<li>{}</li>\n",
escape_html(&alias.to_string())
let html_list: String =
aliases.iter().fold(String::new(), |mut output, alias| {
writeln!(
output,
"<li>{}</li>",
escape_html(alias.as_ref())
)
})
.collect();
.unwrap();
output
});
let plain = format!("Aliases for {}:\n{}", room_id, plain_list);
let html =
format!("Aliases for {}:\n<ul>{}</ul>", room_id, html_list);
RoomMessageEventContent::text_html(plain, html)
}
Err(err) => RoomMessageEventContent::text_plain(&format!(
Err(err) => RoomMessageEventContent::text_plain(format!(
"Unable to list aliases: {}",
err
)),
@ -936,30 +939,39 @@ impl Service {
match aliases {
Ok(aliases) => {
let server_name = services().globals.server_name();
let plain_list: String = aliases
.iter()
.map(|(id, alias)| {
format!("- #{}:{} -> {}\n", alias, server_name, id)
})
.collect();
let html_list: String = aliases
.iter()
.map(|(id, alias)| {
format!(
"<li>#{}:{} -> {}</li>\n",
escape_html(&alias.to_string()),
server_name,
escape_html(&id.to_string())
let plain_list: String = aliases.iter().fold(
String::new(),
|mut output, (alias, id)| {
writeln!(
output,
"- #{}:{} -> {}",
alias, server_name, id
)
})
.collect();
.unwrap();
output
},
);
let html_list: String = aliases.iter().fold(
String::new(),
|mut output, (alias, id)| {
writeln!(
output,
"<li>#{}:{} -> {}</li>",
escape_html(alias.as_ref()),
server_name,
escape_html(id.as_ref())
)
.unwrap();
output
},
);
let plain = format!("Aliases:\n{}", plain_list);
let html = format!("Aliases:\n<ul>{}</ul>", html_list);
RoomMessageEventContent::text_html(plain, html)
}
Err(err) => RoomMessageEventContent::text_plain(&format!(
Err(err) => RoomMessageEventContent::text_plain(format!(
"Unable to list aliases: {}",
err
)),
@ -971,7 +983,7 @@ impl Service {
RoomDirectoryCommand::Publish { room_id } => {
match services().rooms.directory.set_public(&room_id) {
Ok(()) => RoomMessageEventContent::text_plain("Room published"),
Err(err) => RoomMessageEventContent::text_plain(&format!(
Err(err) => RoomMessageEventContent::text_plain(format!(
"Unable to update room: {}",
err
)),
@ -980,7 +992,7 @@ impl Service {
RoomDirectoryCommand::Unpublish { room_id } => {
match services().rooms.directory.set_not_public(&room_id) {
Ok(()) => RoomMessageEventContent::text_plain("Room unpublished"),
Err(err) => RoomMessageEventContent::text_plain(&format!(
Err(err) => RoomMessageEventContent::text_plain(format!(
"Unable to update room: {}",
err
)),
@ -1023,13 +1035,10 @@ impl Service {
"<table><caption>Room directory - page {page}</caption>\n<tr><th>id</th>\t<th>members</th>\t<th>name</th></tr>\n{}</table>",
rooms
.iter()
.map(|(id, members, name)| format!(
"<tr><td>{}</td>\t<td>{}</td>\t<td>{}</td></tr>\n",
escape_html(&id.to_string()),
members,
escape_html(name),
))
.collect::<String>()
.fold(String::new(), |mut output, (id, members, name)| {
writeln!(output, "<tr><td>{}</td>\t<td>{}</td>\t<td>{}</td></tr>", escape_html(id.as_ref()), members, escape_html(name.as_ref())).unwrap();
output
})
);
RoomMessageEventContent::text_html(output_plain, output_html)
}

View file

@ -164,7 +164,7 @@ impl Service {
.dns_resolver(Arc::new(Resolver::new(Box::new(move |domain| {
let read_guard = name_override.read().unwrap();
let (override_name, port) = read_guard.get(domain)?;
let first_name = override_name.get(0)?;
let first_name = override_name.first()?;
Some(SocketAddr::new(*first_name, *port))
}))))
.build()?;

View file

@ -35,19 +35,19 @@ impl Service {
.db
.create_file_metadata(mxc, 0, 0, content_disposition, content_type)?;
let path: std::path::PathBuf;
if cfg!(feature = "sha256_media") {
path = services().globals.get_media_file_new(&key);
let path = if cfg!(feature = "sha256_media") {
services().globals.get_media_file_new(&key)
} else {
path = services().globals.get_media_file(&key);
}
#[allow(deprecated)]
services().globals.get_media_file(&key)
};
let mut f = File::create(path).await?;
f.write_all(file).await?;
Ok(())
}
/// Uploads or replaces a file thumbnail.
#[allow(clippy::too_many_arguments)]
pub async fn upload_thumbnail(
&self,
mxc: String,
@ -61,12 +61,13 @@ impl Service {
self.db
.create_file_metadata(mxc, width, height, content_disposition, content_type)?;
let path: std::path::PathBuf;
if cfg!(feature = "sha256_media") {
path = services().globals.get_media_file_new(&key);
let path = if cfg!(feature = "sha256_media") {
services().globals.get_media_file_new(&key)
} else {
path = services().globals.get_media_file(&key);
}
#[allow(deprecated)]
services().globals.get_media_file(&key)
};
let mut f = File::create(path).await?;
f.write_all(file).await?;
@ -78,12 +79,13 @@ impl Service {
if let Ok((content_disposition, content_type, key)) =
self.db.search_file_metadata(mxc, 0, 0)
{
let path: std::path::PathBuf;
if cfg!(feature = "sha256_media") {
path = services().globals.get_media_file_new(&key);
let path = if cfg!(feature = "sha256_media") {
services().globals.get_media_file_new(&key)
} else {
path = services().globals.get_media_file(&key);
}
#[allow(deprecated)]
services().globals.get_media_file(&key)
};
let mut file = Vec::new();
BufReader::new(File::open(path).await?)
.read_to_end(&mut file)
@ -136,12 +138,13 @@ impl Service {
self.db.search_file_metadata(mxc.clone(), width, height)
{
// Using saved thumbnail
let path: std::path::PathBuf;
if cfg!(feature = "sha256_media") {
path = services().globals.get_media_file_new(&key);
let path = if cfg!(feature = "sha256_media") {
services().globals.get_media_file_new(&key)
} else {
path = services().globals.get_media_file(&key);
}
#[allow(deprecated)]
services().globals.get_media_file(&key)
};
let mut file = Vec::new();
File::open(path).await?.read_to_end(&mut file).await?;
@ -154,12 +157,13 @@ impl Service {
self.db.search_file_metadata(mxc.clone(), 0, 0)
{
// Generate a thumbnail
let path: std::path::PathBuf;
if cfg!(feature = "sha256_media") {
path = services().globals.get_media_file_new(&key);
let path = if cfg!(feature = "sha256_media") {
services().globals.get_media_file_new(&key)
} else {
path = services().globals.get_media_file(&key);
}
#[allow(deprecated)]
services().globals.get_media_file(&key)
};
let mut file = Vec::new();
File::open(path).await?.read_to_end(&mut file).await?;
@ -229,12 +233,13 @@ impl Service {
content_type.as_deref(),
)?;
let path: std::path::PathBuf;
if cfg!(feature = "sha256_media") {
path = services().globals.get_media_file_new(&thumbnail_key);
let path = if cfg!(feature = "sha256_media") {
services().globals.get_media_file_new(&thumbnail_key)
} else {
path = services().globals.get_media_file(&thumbnail_key);
}
#[allow(deprecated)]
services().globals.get_media_file(&thumbnail_key)
};
let mut f = File::create(path).await?;
f.write_all(&thumbnail_bytes).await?;
@ -337,7 +342,7 @@ mod tests {
// r.push(base64::encode_config(key, base64::URL_SAFE_NO_PAD));
// use the sha256 hash of the key as the file name instead of the key itself
// this is because the base64 encoded key can be longer than 255 characters.
r.push(general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(&key)));
r.push(general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(key)));
// Check that the file path is not longer than 255 characters
// (255 is the maximum length of a file path on most file systems)
assert!(

View file

@ -383,10 +383,9 @@ impl PartialEq for PduEvent {
self.event_id == other.event_id
}
}
#[allow(clippy::non_canonical_partial_ord_impl)]
impl PartialOrd for PduEvent {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.event_id.partial_cmp(&other.event_id)
Some(self.cmp(other))
}
}
impl Ord for PduEvent {

View file

@ -182,7 +182,7 @@ fn process_presence_timer(user_id: OwnedUserId) -> Result<()> {
}
}
let new_state = match (&presence_state, last_active_ago.map(|ago| u64::from(ago))) {
let new_state = match (&presence_state, last_active_ago.map(u64::from)) {
(PresenceState::Online, Some(ago)) if ago >= idle_timeout => {
Some(PresenceState::Unavailable)
}

View file

@ -92,7 +92,7 @@ impl Service {
));
}
services().rooms.event_handler.acl_check(origin, &room_id)?;
services().rooms.event_handler.acl_check(origin, room_id)?;
// 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)? {
@ -277,6 +277,7 @@ impl Service {
r
}
#[allow(clippy::too_many_arguments)]
fn handle_outlier_pdu<'a>(
&'a self,
origin: &'a ServerName,

View file

@ -40,6 +40,7 @@ impl Service {
}
}
#[allow(clippy::too_many_arguments)]
pub fn paginate_relations_with_filter(
&self,
sender_user: &UserId,
@ -82,7 +83,7 @@ impl Service {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
.user_can_see_event(sender_user, room_id, &pdu.event_id)
.unwrap_or(false)
})
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`
@ -106,7 +107,7 @@ impl Service {
let events_before: Vec<_> = services()
.rooms
.pdu_metadata
.relations_until(sender_user, &room_id, target, from)?
.relations_until(sender_user, room_id, target, from)?
.filter(|r| {
r.as_ref().map_or(true, |(_, pdu)| {
filter_event_type.as_ref().map_or(true, |t| &pdu.kind == t)
@ -129,7 +130,7 @@ impl Service {
services()
.rooms
.state_accessor
.user_can_see_event(sender_user, &room_id, &pdu.event_id)
.user_can_see_event(sender_user, room_id, &pdu.event_id)
.unwrap_or(false)
})
.take_while(|&(k, _)| Some(k) != to) // Stop at `to`

View file

@ -134,7 +134,7 @@ impl Service {
if serde_json::from_str::<SpaceChildEventContent>(pdu.content.get())
.ok()
.and_then(|c| Some(c.via))
.map(|c| c.via)
.map_or(true, |v| v.is_empty())
{
continue;
@ -199,7 +199,7 @@ impl Service {
if let Ok(response) = services()
.sending
.send_federation_request(
&server,
server,
federation::space::get_hierarchy::v1::Request {
room_id: current_room.to_owned(),
suggested_only,
@ -237,7 +237,7 @@ impl Service {
.room
.allowed_room_ids
.into_iter()
.map(|room| AllowRule::room_membership(room))
.map(AllowRule::room_membership)
.collect(),
})
}
@ -247,7 +247,7 @@ impl Service {
.room
.allowed_room_ids
.into_iter()
.map(|room| AllowRule::room_membership(room))
.map(AllowRule::room_membership)
.collect(),
})
}
@ -315,7 +315,7 @@ impl Service {
canonical_alias: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomCanonicalAlias, "")?
.room_state_get(room_id, &StateEventType::RoomCanonicalAlias, "")?
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomCanonicalAliasEventContent| c.alias)
@ -323,11 +323,11 @@ impl Service {
Error::bad_database("Invalid canonical alias event in database.")
})
})?,
name: services().rooms.state_accessor.get_name(&room_id)?,
name: services().rooms.state_accessor.get_name(room_id)?,
num_joined_members: services()
.rooms
.state_cache
.room_joined_count(&room_id)?
.room_joined_count(room_id)?
.unwrap_or_else(|| {
warn!("Room {} has no member count", room_id);
0
@ -338,7 +338,7 @@ impl Service {
topic: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomTopic, "")?
.room_state_get(room_id, &StateEventType::RoomTopic, "")?
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomTopicEventContent| Some(c.topic))
@ -350,7 +350,7 @@ impl Service {
world_readable: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomHistoryVisibility, "")?
.room_state_get(room_id, &StateEventType::RoomHistoryVisibility, "")?
.map_or(Ok(false), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomHistoryVisibilityEventContent| {
@ -365,7 +365,7 @@ impl Service {
guest_can_join: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomGuestAccess, "")?
.room_state_get(room_id, &StateEventType::RoomGuestAccess, "")?
.map_or(Ok(false), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomGuestAccessEventContent| {
@ -378,7 +378,7 @@ impl Service {
avatar_url: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomAvatar, "")?
.room_state_get(room_id, &StateEventType::RoomAvatar, "")?
.map(|s| {
serde_json::from_str(s.content.get())
.map(|c: RoomAvatarEventContent| c.url)
@ -391,7 +391,7 @@ impl Service {
let join_rule = services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomJoinRules, "")?
.room_state_get(room_id, &StateEventType::RoomJoinRules, "")?
.map(|s| {
serde_json::from_str(s.content.get())
.map(|c: RoomJoinRulesEventContent| c.join_rule)
@ -417,7 +417,7 @@ impl Service {
room_type: services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomCreate, "")?
.room_state_get(room_id, &StateEventType::RoomCreate, "")?
.map(|s| {
serde_json::from_str::<RoomCreateEventContent>(s.content.get()).map_err(|e| {
error!("Invalid room create event in database: {}", e);
@ -457,7 +457,7 @@ impl Service {
SpaceRoomJoinRule::Invite => services()
.rooms
.state_cache
.is_joined(sender_user, &room_id)?,
.is_joined(sender_user, room_id)?,
_ => false,
};
@ -481,17 +481,14 @@ impl Service {
match join_rule {
JoinRule::Restricted(r) => {
for rule in &r.allow {
match rule {
join_rules::AllowRule::RoomMembership(rm) => {
if let Ok(true) = services()
.rooms
.state_cache
.is_joined(sender_user, &rm.room_id)
{
return Ok(true);
}
if let join_rules::AllowRule::RoomMembership(rm) = rule {
if let Ok(true) = services()
.rooms
.state_cache
.is_joined(sender_user, &rm.room_id)
{
return Ok(true);
}
_ => {}
}
}

View file

@ -41,7 +41,7 @@ impl Service {
services()
.rooms
.state_compressor
.parse_compressed_state_event(&new)
.parse_compressed_state_event(new)
.ok()
.map(|(_, id)| id)
}) {
@ -409,7 +409,7 @@ impl Service {
services()
.rooms
.state_compressor
.parse_compressed_state_event(&compressed)
.parse_compressed_state_event(compressed)
.ok()
})
.filter_map(|(shortstatekey, event_id)| {

View file

@ -180,7 +180,7 @@ impl Service {
return Ok(*visibility);
}
let currently_member = services().rooms.state_cache.is_joined(&user_id, &room_id)?;
let currently_member = services().rooms.state_cache.is_joined(user_id, room_id)?;
let history_visibility = self
.state_get(shortstatehash, &StateEventType::RoomHistoryVisibility, "")?
@ -197,11 +197,11 @@ impl Service {
HistoryVisibility::Shared => currently_member,
HistoryVisibility::Invited => {
// Allow if any member on requesting server was AT LEAST invited, else deny
self.user_was_invited(shortstatehash, &user_id)
self.user_was_invited(shortstatehash, user_id)
}
HistoryVisibility::Joined => {
// Allow if any member on requested server was joined, else deny
self.user_was_joined(shortstatehash, &user_id)
self.user_was_joined(shortstatehash, user_id)
}
_ => {
error!("Unknown history visibility {history_visibility}");
@ -221,10 +221,10 @@ impl Service {
/// the room's history_visibility at that event's state.
#[tracing::instrument(skip(self, user_id, room_id))]
pub fn user_can_see_state_events(&self, user_id: &UserId, room_id: &RoomId) -> Result<bool> {
let currently_member = services().rooms.state_cache.is_joined(&user_id, &room_id)?;
let currently_member = services().rooms.state_cache.is_joined(user_id, room_id)?;
let history_visibility = self
.room_state_get(&room_id, &StateEventType::RoomHistoryVisibility, "")?
.room_state_get(room_id, &StateEventType::RoomHistoryVisibility, "")?
.map_or(Ok(HistoryVisibility::Shared), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomHistoryVisibilityEventContent| c.history_visibility)
@ -276,7 +276,7 @@ impl Service {
services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomName, "")?
.room_state_get(room_id, &StateEventType::RoomName, "")?
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map(|c: RoomNameEventContent| Some(c.name))
@ -294,7 +294,7 @@ impl Service {
services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomAvatar, "")?
.room_state_get(room_id, &StateEventType::RoomAvatar, "")?
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map_err(|_| Error::bad_database("Invalid room avatar event in database."))
@ -309,7 +309,7 @@ impl Service {
services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomMember, user_id.as_str())?
.room_state_get(room_id, &StateEventType::RoomMember, user_id.as_str())?
.map_or(Ok(None), |s| {
serde_json::from_str(s.content.get())
.map_err(|_| Error::bad_database("Invalid room member event in database."))

View file

@ -164,7 +164,7 @@ impl Service {
for removed in statediffremoved.iter() {
if !parent_new.remove(removed) {
// It was not added in the parent and we removed it
parent_removed.insert(removed.clone());
parent_removed.insert(*removed);
}
// Else it was added in the parent and we removed it again. We can forget this change
}
@ -172,7 +172,7 @@ impl Service {
for new in statediffnew.iter() {
if !parent_removed.remove(new) {
// It was not touched in the parent and we added it
parent_new.insert(new.clone());
parent_new.insert(*new);
}
// Else it was removed in the parent and we added it again. We can forget this change
}
@ -217,7 +217,7 @@ impl Service {
for removed in statediffremoved.iter() {
if !parent_new.remove(removed) {
// It was not added in the parent and we removed it
parent_removed.insert(removed.clone());
parent_removed.insert(*removed);
}
// Else it was added in the parent and we removed it again. We can forget this change
}
@ -225,7 +225,7 @@ impl Service {
for new in statediffnew.iter() {
if !parent_removed.remove(new) {
// It was not touched in the parent and we added it
parent_new.insert(new.clone());
parent_new.insert(*new);
}
// Else it was removed in the parent and we added it again. We can forget this change
}

View file

@ -26,7 +26,7 @@ impl Service {
self.db.threads_until(user_id, room_id, until, include)
}
pub fn add_to_thread<'a>(&'a self, root_event_id: &EventId, pdu: &PduEvent) -> Result<()> {
pub fn add_to_thread(&self, root_event_id: &EventId, pdu: &PduEvent) -> Result<()> {
let root_id = &services()
.rooms
.timeline
@ -103,7 +103,7 @@ impl Service {
}
let mut users = Vec::new();
if let Some(userids) = self.db.get_participants(&root_id)? {
if let Some(userids) = self.db.get_participants(root_id)? {
users.extend_from_slice(&userids);
users.push(pdu.sender.clone());
} else {

View file

@ -58,8 +58,8 @@ impl PduCount {
}
pub fn try_from_string(token: &str) -> Result<Self> {
if token.starts_with('-') {
token[1..].parse().map(PduCount::Backfilled)
if let Some(stripped_token) = token.strip_prefix('-') {
stripped_token.parse().map(PduCount::Backfilled)
} else {
token.parse().map(PduCount::Normal)
}
@ -90,18 +90,6 @@ impl Ord for PduCount {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn comparisons() {
assert!(PduCount::Normal(1) < PduCount::Normal(2));
assert!(PduCount::Backfilled(2) < PduCount::Backfilled(1));
assert!(PduCount::Normal(1) > PduCount::Backfilled(1));
assert!(PduCount::Backfilled(1) < PduCount::Normal(1));
}
}
pub struct Service {
pub db: &'static dyn Data,
@ -112,7 +100,7 @@ pub struct Service {
impl Service {
#[tracing::instrument(skip(self))]
pub fn first_pdu_in_room(&self, room_id: &RoomId) -> Result<Option<Arc<PduEvent>>> {
self.all_pdus(&user_id!("@doesntmatter:conduit.rs"), &room_id)?
self.all_pdus(user_id!("@doesntmatter:conduit.rs"), room_id)?
.next()
.map(|o| o.map(|(_, p)| Arc::new(p)))
.transpose()
@ -475,7 +463,7 @@ impl Service {
let to_conduit = body.starts_with(&format!("{server_user}: "))
|| body.starts_with(&format!("{server_user} "))
|| body == format!("{server_user}:")
|| body == format!("{server_user}");
|| body == server_user;
// This will evaluate to false if the emergency password is set up so that
// the administrator can execute commands as conduit
@ -867,7 +855,7 @@ impl Service {
.map_err(|_| Error::bad_database("Invalid content in pdu."))?;
if content.membership == MembershipState::Leave {
if target == &server_user {
if target == server_user {
warn!("Conduit user cannot leave from admins room");
return Err(Error::BadRequest(
ErrorKind::Forbidden,
@ -893,7 +881,7 @@ impl Service {
}
if content.membership == MembershipState::Ban && pdu.state_key().is_some() {
if target == &server_user {
if target == server_user {
warn!("Conduit user cannot be banned in admins room");
return Err(Error::BadRequest(
ErrorKind::Forbidden,
@ -1067,7 +1055,7 @@ impl Service {
#[tracing::instrument(skip(self, room_id))]
pub async fn backfill_if_required(&self, room_id: &RoomId, from: PduCount) -> Result<()> {
let first_pdu = self
.all_pdus(&user_id!("@doesntmatter:conduit.rs"), &room_id)?
.all_pdus(user_id!("@doesntmatter:conduit.rs"), room_id)?
.next()
.expect("Room is not empty")?;
@ -1079,7 +1067,7 @@ impl Service {
let power_levels: RoomPowerLevelsEventContent = services()
.rooms
.state_accessor
.room_state_get(&room_id, &StateEventType::RoomPowerLevels, "")?
.room_state_get(room_id, &StateEventType::RoomPowerLevels, "")?
.map(|ev| {
serde_json::from_str(ev.content.get())
.map_err(|_| Error::bad_database("invalid m.room.power_levels event"))
@ -1110,11 +1098,9 @@ impl Service {
.await;
match response {
Ok(response) => {
let mut pub_key_map = RwLock::new(BTreeMap::new());
let pub_key_map = RwLock::new(BTreeMap::new());
for pdu in response.pdus {
if let Err(e) = self
.backfill_pdu(backfill_server, pdu, &mut pub_key_map)
.await
if let Err(e) = self.backfill_pdu(backfill_server, pdu, &pub_key_map).await
{
warn!("Failed to add backfilled pdu: {e}");
}
@ -1161,13 +1147,13 @@ impl Service {
services()
.rooms
.event_handler
.fetch_required_signing_keys([&value], &pub_key_map)
.fetch_required_signing_keys([&value], pub_key_map)
.await?;
services()
.rooms
.event_handler
.handle_incoming_pdu(origin, &event_id, &room_id, value, false, &pub_key_map)
.handle_incoming_pdu(origin, &event_id, &room_id, value, false, pub_key_map)
.await?;
let value = self.get_pdu_json(&event_id)?.expect("We just created it");
@ -1200,24 +1186,21 @@ impl Service {
drop(insert_lock);
match pdu.kind {
TimelineEventType::RoomMessage => {
#[derive(Deserialize)]
struct ExtractBody {
body: Option<String>,
}
let content = serde_json::from_str::<ExtractBody>(pdu.content.get())
.map_err(|_| Error::bad_database("Invalid content in pdu."))?;
if let Some(body) = content.body {
services()
.rooms
.search
.index_pdu(shortroomid, &pdu_id, &body)?;
}
if pdu.kind == TimelineEventType::RoomMessage {
#[derive(Deserialize)]
struct ExtractBody {
body: Option<String>,
}
let content = serde_json::from_str::<ExtractBody>(pdu.content.get())
.map_err(|_| Error::bad_database("Invalid content in pdu."))?;
if let Some(body) = content.body {
services()
.rooms
.search
.index_pdu(shortroomid, &pdu_id, &body)?;
}
_ => {}
}
drop(mutex_lock);
@ -1225,3 +1208,15 @@ impl Service {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn comparisons() {
assert!(PduCount::Normal(1) < PduCount::Normal(2));
assert!(PduCount::Backfilled(2) < PduCount::Backfilled(1));
assert!(PduCount::Normal(1) > PduCount::Backfilled(1));
assert!(PduCount::Backfilled(1) < PduCount::Normal(1));
}
}

View file

@ -132,7 +132,7 @@ impl Service {
for (key, outgoing_kind, event) in self.db.active_requests().filter_map(|r| r.ok()) {
let entry = initial_transactions
.entry(outgoing_kind.clone())
.or_insert_with(Vec::new);
.or_default();
if entry.len() > 30 {
warn!(

View file

@ -139,10 +139,10 @@ impl Service {
cached
.subscriptions
.extend(request.room_subscriptions.clone().into_iter());
.extend(request.room_subscriptions.clone());
request
.room_subscriptions
.extend(cached.subscriptions.clone().into_iter());
.extend(cached.subscriptions.clone());
request.extensions.e2ee.enabled = request
.extensions