mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-01 21:07:34 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d12f75c271 | ||
|
|
83a7220c7b | ||
|
|
134211d0ec | ||
|
|
924e70c1e1 |
No files matched your search
@@ -56,7 +56,7 @@ repos:
|
||||
hooks:
|
||||
- id: cargo-clippy
|
||||
name: cargo clippy
|
||||
entry: cargo clippy --
|
||||
entry: cargo clippy -- -D warnings
|
||||
language: system
|
||||
pass_filenames: false
|
||||
types: [ rust ]
|
||||
|
||||
+2
-1
@@ -398,6 +398,7 @@ features = [
|
||||
"unstable-msc4484",
|
||||
"unstable-msc4540",
|
||||
"unstable-msc4560",
|
||||
"unstable-msc4563",
|
||||
"unstable-extensible-events",
|
||||
]
|
||||
|
||||
@@ -595,7 +596,7 @@ version = "0.3.18"
|
||||
version = "0.3.0"
|
||||
|
||||
[workspace.dependencies.resolvematrix]
|
||||
version = "1.6.0"
|
||||
version = "1.5.0"
|
||||
features = ["unstable-msc4188"]
|
||||
|
||||
[workspace.dependencies.serde_urlencoded]
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
Fixed read receipts for all but one of a user's threads not being sent over federation. Contributed by @eleboucher.
|
||||
@@ -0,0 +1 @@
|
||||
Added server-side support for [MSC4563: direct_message push rule](https://github.com/matrix-org/matrix-spec-proposals/pull/4563). Contributed by @nex.
|
||||
@@ -813,6 +813,18 @@
|
||||
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
|
||||
#forget_forced_upon_leave = false
|
||||
|
||||
# Set this to true to require authentication when looking up user profiles
|
||||
# through this server.
|
||||
#
|
||||
# By default this is false, allowing tools such as matrix.to to access
|
||||
# profiles of users on this server and on other servers.
|
||||
# Setting this to true will block those tools, and may block automated
|
||||
# crawlers from scraping users' profiles, although it will not block
|
||||
# other homeservers from accessing users' profiles.
|
||||
#
|
||||
# env: CONTINUWUITY_REQUIRE_AUTH_FOR_PROFILE_REQUESTS
|
||||
#require_auth_for_profile_requests = false
|
||||
|
||||
# Set this to true to require authentication to create a rendezvous
|
||||
# session. Rendezvous sessions are used for QR code login.
|
||||
#
|
||||
@@ -2796,6 +2808,18 @@
|
||||
# env: CONTINUWUITY_EXPERIMENTS__MSC4560
|
||||
#msc4560 = false
|
||||
|
||||
# MSC4563: `direct_message` push rule
|
||||
#
|
||||
# Creates a new kind of push rule that creates a notification if a message
|
||||
# is received in a room that is in the user's direct message list. This
|
||||
# more accurately identifies direct messages, rather than relying on a "DM
|
||||
# room" only consisting of two members.
|
||||
#
|
||||
# https://github.com/matrix-org/matrix-spec-proposals/pull/4563
|
||||
#
|
||||
# env: CONTINUWUITY_EXPERIMENTS__MSC4563
|
||||
#msc4563 = false
|
||||
|
||||
#[global.experiments.msc2815]
|
||||
# MSC2815: Proposal to allow room moderators to view redacted event content
|
||||
#
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
"message": "Welcome to Continuwuity! Important announcements about the project will appear here."
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"id": 22,
|
||||
"mention_room": true,
|
||||
"date": "2026-09-29",
|
||||
"message": "[Continuwuity 26.9.1](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v26.9.1) has just been released - this update features a fix for a **critical** security issue, please read the release notes for more information."
|
||||
"date": "2026-11-30",
|
||||
"message": "[Continuwuity v26.11.0](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v26.11.0) is out, and it's massively jam-packed with so much goodness I don't know where to start. It's time to get upgrading! If you're not already convinced, here are a couple key highlights:\n\n* Appservices now receive typing indicators and read receipts. Suddenly bridges feel more alive.\n* Continuwuity can now **export metrics** via OTLP or Prometheus! There's even a Grafana dashboard included in the repo to save you the hassle of having to build you own. How thoughtful.\n* Continuwuity is more decentralised than ever, because it's now able to function as a **key notary server** for other Matrix servers. Add your friends as trusted servers!\n* **QR code login**! As client support grows, you will have the option of skipping the password and emoji verification dance when adding a new device.\n* Jump to timestamp, less retries on gone servers, no more unauthenticated media at all, better performance and so so much more.\n* Also, security fixes. That makes it pretty important you get this.\n\nGo [read the changelog](https://forgejo.ellis.link/continuwuation/continuwuity/releases/tag/v26.11.0) - and upgrade right now"
|
||||
}
|
||||
]
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
#-------------------------------------------------------------------------------#
|
||||
# Qodana analysis is configured by qodana.yaml file #
|
||||
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
|
||||
#-------------------------------------------------------------------------------#
|
||||
|
||||
#################################################################################
|
||||
# WARNING: Do not store sensitive information in this file, #
|
||||
# as its contents will be included in the Qodana report. #
|
||||
#################################################################################
|
||||
version: "1.0"
|
||||
|
||||
#Specify inspection profile for code analysis
|
||||
profile:
|
||||
name: qodana.starter
|
||||
|
||||
#Enable inspections
|
||||
#include:
|
||||
# - name: <SomeEnabledInspectionId>
|
||||
|
||||
#Disable inspections
|
||||
#exclude:
|
||||
# - name: <SomeDisabledInspectionId>
|
||||
# paths:
|
||||
# - <path/where/not/run/inspection>
|
||||
|
||||
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
|
||||
#bootstrap: sh ./prepare-qodana.sh
|
||||
|
||||
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
|
||||
#plugins:
|
||||
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
|
||||
|
||||
# Quality gate. Will fail the CI/CD pipeline if any condition is not met
|
||||
# severityThresholds - configures maximum thresholds for different problem severities
|
||||
# testCoverageThresholds - configures minimum code coverage on a whole project and newly added code
|
||||
# Code Coverage is available in Ultimate and Ultimate Plus plans
|
||||
#failureConditions:
|
||||
# severityThresholds:
|
||||
# any: 15
|
||||
# critical: 5
|
||||
# testCoverageThresholds:
|
||||
# fresh: 70
|
||||
# total: 50
|
||||
|
||||
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
|
||||
linter: jetbrains/qodana-<linter>:2026.2
|
||||
@@ -29,7 +29,7 @@ pub(crate) async fn get_profile_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_profile::v3::Request>,
|
||||
) -> Result<get_profile::v3::Response> {
|
||||
if body.identity.is_none() {
|
||||
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
|
||||
return Err!(Request(Unauthorized(
|
||||
"This server requires authentication to access user profiles."
|
||||
)));
|
||||
@@ -46,7 +46,7 @@ pub(crate) async fn get_profile_field_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<get_profile_field::v3::Request>,
|
||||
) -> Result<get_profile_field::v3::Response> {
|
||||
if body.identity.is_none() {
|
||||
if services.config.require_auth_for_profile_requests && body.identity.is_none() {
|
||||
return Err!(Request(Unauthorized(
|
||||
"This server requires authentication to access user profiles."
|
||||
)));
|
||||
|
||||
@@ -9,7 +9,7 @@ use service::Services;
|
||||
|
||||
use crate::{Ruma, router::ClientIdentity};
|
||||
|
||||
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous`
|
||||
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous`
|
||||
pub(crate) async fn discover_rendezvous_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<discover_rendezvous::msc4388::Request>,
|
||||
@@ -20,7 +20,7 @@ pub(crate) async fn discover_rendezvous_route(
|
||||
)))
|
||||
}
|
||||
|
||||
/// `POST /_matrix/client/unstable/io.element.msc4388/rendezvous`
|
||||
/// `POST /_matrix/client/msc4388/io.element.msc4388/rendezvous/`
|
||||
pub(crate) async fn create_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<create_rendezvous_session::msc4388::Request>,
|
||||
@@ -32,7 +32,7 @@ pub(crate) async fn create_rendezvous_session_route(
|
||||
services.rendezvous.create_session(body.data.clone())
|
||||
}
|
||||
|
||||
/// `PUT /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}/{txn_id}`
|
||||
/// `PUT /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}/{txn_id}`
|
||||
pub(crate) async fn update_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<update_rendezvous_session::msc4388::Request>,
|
||||
@@ -45,30 +45,16 @@ pub(crate) async fn update_rendezvous_session_route(
|
||||
)
|
||||
}
|
||||
|
||||
/// `GET /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
|
||||
/// `GET /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
|
||||
pub(crate) async fn get_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
body: Ruma<get_rendezvous_session::msc4388::Request>,
|
||||
) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||
let is_navigation_mode = headers
|
||||
.get_all("Sec-Fetch-Mode")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.any(|mode| {
|
||||
mode.eq_ignore_ascii_case("navigate") || mode.eq_ignore_ascii_case("nested-navigate")
|
||||
});
|
||||
let is_navigation_dest = headers
|
||||
.get_all("Sec-Fetch-Dest")
|
||||
.iter()
|
||||
.filter_map(|v| v.to_str().ok())
|
||||
.any(|dest| {
|
||||
matches!(
|
||||
dest.to_ascii_lowercase().as_str(),
|
||||
"document" | "iframe" | "frame" | "object" | "embed" | "fencedframe"
|
||||
)
|
||||
});
|
||||
if is_navigation_mode || is_navigation_dest {
|
||||
if let Some(mode) = headers.get("Sec-Fetch-Mode")
|
||||
&& let Ok(mode) = mode.to_str()
|
||||
&& mode == "navigate"
|
||||
{
|
||||
return Err!(Request(Forbidden(
|
||||
"Rendezvous sessions do not accept browser navigation requests."
|
||||
)));
|
||||
@@ -77,7 +63,7 @@ pub(crate) async fn get_rendezvous_session_route(
|
||||
services.rendezvous.get_session(&body.id)
|
||||
}
|
||||
|
||||
/// `DELETE /_matrix/client/unstable/io.element.msc4388/rendezvous/{id}`
|
||||
/// `DELETE /_matrix/client/msc4388/io.element.msc4388/rendezvous/{id}`
|
||||
pub(crate) async fn delete_rendezvous_session_route(
|
||||
State(services): State<crate::State>,
|
||||
body: Ruma<delete_rendezvous_session::msc4388::Request>,
|
||||
|
||||
+5
-17
@@ -191,23 +191,11 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
|
||||
.ruma_route(&client::get_rtc_transports)
|
||||
.ruma_route(&client::get_rtc_transports_unstable)
|
||||
.ruma_route(&client::room_initial_sync_route)
|
||||
.merge(
|
||||
Router::new()
|
||||
.ruma_route(&client::discover_rendezvous_route)
|
||||
.ruma_route(&client::create_rendezvous_session_route)
|
||||
.ruma_route(&client::update_rendezvous_session_route)
|
||||
.ruma_route(&client::get_rendezvous_session_route)
|
||||
.ruma_route(&client::delete_rendezvous_session_route)
|
||||
.layer(axum::middleware::map_response(
|
||||
async |mut response: axum::response::Response| {
|
||||
response.headers_mut().insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
http::HeaderValue::from_static("no-store"),
|
||||
);
|
||||
response
|
||||
},
|
||||
)),
|
||||
)
|
||||
.ruma_route(&client::discover_rendezvous_route)
|
||||
.ruma_route(&client::create_rendezvous_session_route)
|
||||
.ruma_route(&client::update_rendezvous_session_route)
|
||||
.ruma_route(&client::get_rendezvous_session_route)
|
||||
.ruma_route(&client::delete_rendezvous_session_route)
|
||||
.ruma_route(&client::get_authorization_server_metadata_route)
|
||||
.merge(client::oauth::router(state))
|
||||
.route("/_continuwuity/server_version", get(client::continuwuity_server_version))
|
||||
|
||||
+3
-17
@@ -11,11 +11,7 @@ use axum::{
|
||||
use conduwuit::{Error, Result, err, error};
|
||||
use ruma::{
|
||||
CanonicalJsonObject,
|
||||
api::{
|
||||
IncomingRequest, IncomingRequestExt,
|
||||
auth_scheme::AuthScheme,
|
||||
error::{DeserializationError, FromHttpRequestError},
|
||||
},
|
||||
api::{IncomingRequest, IncomingRequestExt, auth_scheme::AuthScheme},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -118,18 +114,8 @@ where
|
||||
.await?;
|
||||
|
||||
// Deserialize the body
|
||||
let body_is_empty = body.is_empty();
|
||||
let body = R::try_from_http_request(request, &borrowed_path).map_err(|e| match e {
|
||||
| FromHttpRequestError::Deserialization(DeserializationError::Json(ref json_err))
|
||||
if body_is_empty || json_err.is_syntax() || json_err.is_eof() =>
|
||||
err!(Request(NotJson(debug_warn!("{e}")))),
|
||||
| FromHttpRequestError::Deserialization(DeserializationError::Utf8(_)) =>
|
||||
err!(Request(NotJson(debug_warn!("{e}")))),
|
||||
| FromHttpRequestError::Deserialization(
|
||||
DeserializationError::Ident(_) | DeserializationError::Query(_),
|
||||
) => err!(Request(InvalidParam(debug_warn!("{e}")))),
|
||||
| _ => err!(Request(BadJson(debug_warn!("{e}")))),
|
||||
})?;
|
||||
let body = R::try_from_http_request(request, &borrowed_path)
|
||||
.map_err(|e| err!(Request(BadJson(debug_warn!("{e}")))))?;
|
||||
|
||||
Ok(Self { body, json_body, identity })
|
||||
}
|
||||
|
||||
+1
-24
@@ -194,10 +194,6 @@ impl CheckAuth for AccessTokenOptional {
|
||||
authentication: Self::Output,
|
||||
query: AuthQueryParams,
|
||||
) -> Result<Self::Identity> {
|
||||
if R::RATE_LIMITED && is_rendezvous_create_route(TypeId::of::<R>()) {
|
||||
services.rendezvous.check_create_ratelimit(request_ip)?;
|
||||
}
|
||||
|
||||
if let Some(authentication) = authentication {
|
||||
check_access_token(
|
||||
services,
|
||||
@@ -282,11 +278,6 @@ impl CheckAuth for NoAccessToken {
|
||||
err!(Request(Unauthorized(warn!("Failed to extract authorization: {}", err))))
|
||||
})?;
|
||||
|
||||
let is_rendezvous_session = is_rendezvous_session_route(TypeId::of::<R>());
|
||||
if R::RATE_LIMITED && is_rendezvous_session {
|
||||
services.rendezvous.check_session_ratelimit(request_ip)?;
|
||||
}
|
||||
|
||||
if let Some(authentication) = authentication {
|
||||
check_access_token(services, &authentication, query, TypeId::of::<R>(), &[
|
||||
OAuthClientScope::ApiFullAccess,
|
||||
@@ -294,7 +285,7 @@ impl CheckAuth for NoAccessToken {
|
||||
.await
|
||||
.map(Some)
|
||||
} else {
|
||||
if R::RATE_LIMITED && !is_rendezvous_session {
|
||||
if R::RATE_LIMITED {
|
||||
check_unauthenticated_request_ratelimiting(services, request_ip)?;
|
||||
}
|
||||
|
||||
@@ -460,20 +451,6 @@ async fn check_appservice_token(services: &Services, token: &str) -> Result<Regi
|
||||
Ok(appservice_info)
|
||||
}
|
||||
|
||||
fn is_rendezvous_create_route(route: TypeId) -> bool {
|
||||
route == TypeId::of::<client::rendezvous::discover_rendezvous::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::create_rendezvous_session::msc4388::Request>()
|
||||
}
|
||||
|
||||
fn is_rendezvous_session_route(route: TypeId) -> bool {
|
||||
route == TypeId::of::<client::rendezvous::get_rendezvous_session::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::update_rendezvous_session::msc4388::Request>()
|
||||
|| route
|
||||
== TypeId::of::<client::rendezvous::delete_rendezvous_session::msc4388::Request>()
|
||||
}
|
||||
|
||||
fn check_unauthenticated_request_ratelimiting(services: &Services, ip: IpAddr) -> Result<()> {
|
||||
if services
|
||||
.config
|
||||
|
||||
@@ -201,7 +201,8 @@ async fn create_invite(
|
||||
.expect("must be able to create PDU object");
|
||||
invite_state.push(RawStrippedState::Pdu(serde_json::value::to_raw_value(&signed_event)?));
|
||||
|
||||
// We always mark the room as invited, because we don't act on invites through /send
|
||||
// We always mark the room as invited, because we don't act on invites
|
||||
// through /send
|
||||
services
|
||||
.rooms
|
||||
.state_cache
|
||||
|
||||
@@ -146,6 +146,19 @@ pub struct Experiments {
|
||||
/// default: false
|
||||
#[serde(default)]
|
||||
pub msc4560: SimpleExperiment,
|
||||
|
||||
/// MSC4563: `direct_message` push rule
|
||||
///
|
||||
/// Creates a new kind of push rule that creates a notification if a message
|
||||
/// is received in a room that is in the user's direct message list. This
|
||||
/// more accurately identifies direct messages, rather than relying on a "DM
|
||||
/// room" only consisting of two members.
|
||||
///
|
||||
/// https://github.com/matrix-org/matrix-spec-proposals/pull/4563
|
||||
///
|
||||
/// default: false
|
||||
#[serde(default)]
|
||||
pub msc4563: SimpleExperiment,
|
||||
}
|
||||
|
||||
/// Represents a "simple" experiment, which is either disabled or enabled.
|
||||
|
||||
+28
-21
@@ -920,6 +920,19 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub forget_forced_upon_leave: bool,
|
||||
|
||||
/// Set this to true to require authentication when looking up user profiles
|
||||
/// through this server.
|
||||
///
|
||||
/// By default this is false, allowing tools such as matrix.to to access
|
||||
/// profiles of users on this server and on other servers.
|
||||
/// Setting this to true will block those tools, and may block automated
|
||||
/// crawlers from scraping users' profiles, although it will not block
|
||||
/// other homeservers from accessing users' profiles.
|
||||
///
|
||||
/// default: false
|
||||
#[serde(default)]
|
||||
pub require_auth_for_profile_requests: bool,
|
||||
|
||||
/// Set this to true to require authentication to create a rendezvous
|
||||
/// session. Rendezvous sessions are used for QR code login.
|
||||
///
|
||||
@@ -2988,7 +3001,6 @@ const DEPRECATED_KEYS: &[&str] = &[
|
||||
"max_concurrent_requests",
|
||||
"otlp_protocol",
|
||||
"request_ip_source",
|
||||
"require_auth_for_profile_requests",
|
||||
"roomid_spacehierarchy_cache_capacity",
|
||||
"unredacted_content_max_age_secs",
|
||||
"well_known_client",
|
||||
@@ -3128,41 +3140,41 @@ fn default_database_backups_to_keep() -> i16 { 1 }
|
||||
|
||||
fn default_db_write_buffer_capacity_mb() -> f64 { 48.0 + parallelism_scaled_f64(4.0) }
|
||||
|
||||
fn default_db_cache_capacity_mb() -> f64 { 512.0 + parallelism_scaled_f64(512.0) }
|
||||
fn default_db_cache_capacity_mb() -> f64 { 128.0 + parallelism_scaled_f64(64.0) }
|
||||
|
||||
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(50_000).saturating_add(100_000) }
|
||||
fn default_pdu_cache_capacity() -> u32 { parallelism_scaled_u32(10_000).saturating_add(100_000) }
|
||||
|
||||
fn default_cache_capacity_modifier() -> f64 { 1.0 }
|
||||
|
||||
fn default_auth_chain_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(10_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_shorteventid_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(100_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_eventidshort_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(25_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_eventid_pdu_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(25_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_shortstatekey_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(100_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(10_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_statekeyshort_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(50_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(10_000).saturating_add(100_000)
|
||||
}
|
||||
|
||||
fn default_servernameevent_data_cache_capacity() -> u32 {
|
||||
parallelism_scaled_u32(100_000).saturating_add(100_000)
|
||||
parallelism_scaled_u32(100_000).saturating_add(500_000)
|
||||
}
|
||||
|
||||
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(500).clamp(100, 12000) }
|
||||
fn default_stateinfo_cache_capacity() -> u32 { parallelism_scaled_u32(100) }
|
||||
|
||||
fn default_dns_cache_entries() -> u32 { 32768 }
|
||||
|
||||
@@ -3384,20 +3396,15 @@ fn default_admin_log_capture() -> String {
|
||||
|
||||
fn default_admin_room_tag() -> String { "m.server_notice".to_owned() }
|
||||
|
||||
#[must_use]
|
||||
#[allow(clippy::as_conversions, clippy::cast_precision_loss)]
|
||||
pub fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
|
||||
fn parallelism_scaled_f64(val: f64) -> f64 { val * (sys::available_parallelism() as f64) }
|
||||
|
||||
#[must_use]
|
||||
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
|
||||
pub fn parallelism_scaled_u32(val: u32) -> u32 {
|
||||
val.saturating_mul(sys::available_parallelism() as u32)
|
||||
fn parallelism_scaled_u32(val: u32) -> u32 {
|
||||
let val = val.try_into().expect("failed to cast u32 to usize");
|
||||
parallelism_scaled(val).try_into().unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn parallelism_scaled(val: usize) -> usize {
|
||||
val.saturating_mul(sys::available_parallelism())
|
||||
}
|
||||
fn parallelism_scaled(val: usize) -> usize { val.saturating_mul(sys::available_parallelism()) }
|
||||
|
||||
fn default_db_pool_workers() -> usize {
|
||||
sys::available_parallelism()
|
||||
|
||||
@@ -171,14 +171,13 @@ impl Error {
|
||||
/// Returns the Matrix error code / error kind
|
||||
#[inline]
|
||||
pub fn kind(&self) -> ErrorKind {
|
||||
use ruma::api::error::ErrorKind::{InvalidParam, Unknown, Unrecognized};
|
||||
use ruma::api::error::ErrorKind::{Unknown, Unrecognized};
|
||||
|
||||
match self {
|
||||
| Self::Federation(_, error) | Self::Ruma(error) =>
|
||||
response::ruma_error_kind(error).clone(),
|
||||
| BadRequest(kind, ..) | Self::Request(kind, ..) => kind.clone(),
|
||||
| Self::FeatureDisabled(..) => Unrecognized,
|
||||
| Self::Path(_) | Self::Query(_) => InvalidParam,
|
||||
| _ => Unknown,
|
||||
}
|
||||
}
|
||||
@@ -195,7 +194,6 @@ impl Error {
|
||||
| Self::FeatureDisabled(..) => response::bad_request_code(&self.kind()),
|
||||
| Self::Reqwest(error) => error.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
|
||||
| Self::Conflict(_) => StatusCode::CONFLICT,
|
||||
| Self::Path(_) | Self::Query(_) => StatusCode::BAD_REQUEST,
|
||||
| Self::Io(error) => response::io_error_code(error.kind()),
|
||||
| Self::Uiaa(_) => StatusCode::UNAUTHORIZED,
|
||||
| _ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
|
||||
@@ -73,9 +73,6 @@ pub(super) fn bad_request_code(kind: &ErrorKind) -> StatusCode {
|
||||
// 413
|
||||
| TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
|
||||
// 409
|
||||
| ConcurrentWrite => StatusCode::CONFLICT,
|
||||
|
||||
// 404
|
||||
| Unrecognized | NotFound => StatusCode::NOT_FOUND,
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ pub type DigestOut = [u8; 256 / 8];
|
||||
/// Sha256 hash (input gather joined by 0xFF bytes)
|
||||
#[must_use]
|
||||
#[tracing::instrument(skip(inputs), level = "trace")]
|
||||
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||
pub fn delimited<'a, T, I>(mut inputs: I) -> DigestOut
|
||||
where
|
||||
I: Iterator<Item = T> + 'a,
|
||||
@@ -26,7 +25,6 @@ where
|
||||
/// Sha256 hash (input gather)
|
||||
#[must_use]
|
||||
#[tracing::instrument(skip(inputs), level = "trace")]
|
||||
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||
pub fn concat<'a, T, I>(inputs: I) -> DigestOut
|
||||
where
|
||||
I: Iterator<Item = T> + 'a,
|
||||
@@ -45,7 +43,6 @@ where
|
||||
#[inline]
|
||||
#[must_use]
|
||||
#[tracing::instrument(skip(input), level = "trace")]
|
||||
#[allow(clippy::unnecessary_fallible_conversions)]
|
||||
pub fn hash<T>(input: T) -> DigestOut
|
||||
where
|
||||
T: AsRef<[u8]>,
|
||||
|
||||
@@ -29,7 +29,7 @@ fn descriptor_cf_options(
|
||||
let mut opts = set_table_options(opts, &desc, cache)?;
|
||||
|
||||
opts.set_min_write_buffer_number(1);
|
||||
opts.set_max_write_buffer_number(3);
|
||||
opts.set_max_write_buffer_number(2);
|
||||
opts.set_write_buffer_size(desc.write_size);
|
||||
|
||||
opts.set_target_file_size_base(desc.file_size);
|
||||
|
||||
@@ -8,7 +8,7 @@ use axum::{
|
||||
extract::State,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use conduwuit::{Result, debug_warn, err, error, info, trace};
|
||||
use conduwuit::{Result, debug, debug_error, debug_warn, err, error, trace};
|
||||
use conduwuit_service::Services;
|
||||
use futures::FutureExt;
|
||||
use http::{Method, StatusCode, Uri};
|
||||
@@ -106,11 +106,11 @@ fn handle_result(method: &Method, uri: &Uri, result: Response) -> Result<Respons
|
||||
let reason = status.canonical_reason().unwrap_or("Unknown Reason");
|
||||
|
||||
if status.is_server_error() {
|
||||
info!(%method, %uri, "{code} {reason}");
|
||||
error!(%method, %uri, "{code} {reason}");
|
||||
} else if status.is_client_error() {
|
||||
info!(%method, %uri, "{code} {reason}");
|
||||
debug_error!(%method, %uri, "{code} {reason}");
|
||||
} else if status.is_redirection() {
|
||||
trace!(%method, %uri, "{code} {reason}");
|
||||
debug!(%method, %uri, "{code} {reason}");
|
||||
} else {
|
||||
trace!(%method, %uri, "{code} {reason}");
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ mod webpush;
|
||||
|
||||
use std::{fmt::Debug, mem, net::IpAddr, sync::Arc};
|
||||
|
||||
use assign::assign;
|
||||
use bytes::BytesMut;
|
||||
use conduwuit::{config::experiments::ToggledExperiment, utils::response::LimitReadExt};
|
||||
use conduwuit_core::{
|
||||
@@ -23,7 +24,10 @@ use ruma::{
|
||||
v1::{Device, Notification, NotificationCounts, NotificationPriority},
|
||||
},
|
||||
},
|
||||
events::{AnySyncTimelineEvent, TimelineEventType, room::power_levels::RoomPowerLevels},
|
||||
events::{
|
||||
AnySyncTimelineEvent, GlobalAccountDataEvent, GlobalAccountDataEventType,
|
||||
TimelineEventType, direct::DirectEventContent, room::power_levels::RoomPowerLevels,
|
||||
},
|
||||
push::{
|
||||
Action, HighlightTweakValue, PushConditionPowerLevelsCtx, PushConditionRoomCtx,
|
||||
PushFormat, Ruleset, Tweak,
|
||||
@@ -36,7 +40,7 @@ use url::Host;
|
||||
|
||||
pub use self::webpush::ActivationOutcome;
|
||||
use self::webpush::Vapid;
|
||||
use crate::{Dep, client, config, globals, rooms, sending, users};
|
||||
use crate::{Dep, account_data, client, config, globals, rooms, sending, users};
|
||||
|
||||
const PUSH_GATEWAY_SCHEMES: &[&str] = &["http", "https"];
|
||||
const WEBPUSH_SCHEMES: &[&str] = &["https"];
|
||||
@@ -57,6 +61,7 @@ pub struct Service {
|
||||
struct Services {
|
||||
server: Arc<Server>,
|
||||
globals: Dep<globals::Service>,
|
||||
account_data: Dep<account_data::Service>,
|
||||
config: Dep<config::Service>,
|
||||
client: Dep<client::Service>,
|
||||
state_accessor: Dep<rooms::state_accessor::Service>,
|
||||
@@ -86,6 +91,7 @@ impl crate::Service for Service {
|
||||
services: Services {
|
||||
server: args.server.clone(),
|
||||
globals: args.depend::<globals::Service>("globals"),
|
||||
account_data: args.depend::<account_data::Service>("account_data"),
|
||||
client: args.depend::<client::Service>("client"),
|
||||
config: args.depend::<config::Service>("config"),
|
||||
state_accessor: args
|
||||
@@ -488,11 +494,34 @@ impl Service {
|
||||
.await
|
||||
.unwrap_or_else(|_| user.localpart().to_owned());
|
||||
|
||||
PushConditionRoomCtx::new(
|
||||
room_id.to_owned(),
|
||||
room_joined_count,
|
||||
user.to_owned(),
|
||||
user_display_name,
|
||||
let is_direct = self.services.config.experiments.msc4563.is_enabled()
|
||||
&& self
|
||||
.services
|
||||
.account_data
|
||||
.get_global::<GlobalAccountDataEvent<DirectEventContent>>(
|
||||
user,
|
||||
GlobalAccountDataEventType::Direct,
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|direct| {
|
||||
direct
|
||||
.content
|
||||
.values()
|
||||
.flatten()
|
||||
.any(|dm_room_id| dm_room_id == room_id)
|
||||
.then_some(())
|
||||
})
|
||||
.is_some();
|
||||
|
||||
assign!(
|
||||
PushConditionRoomCtx::new(
|
||||
room_id.to_owned(),
|
||||
room_joined_count,
|
||||
user.to_owned(),
|
||||
user_display_name,
|
||||
),
|
||||
{ is_direct }
|
||||
)
|
||||
.with_power_levels(power_levels)
|
||||
}
|
||||
|
||||
@@ -1,38 +1,25 @@
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
|
||||
use conduwuit::{
|
||||
Err, Error, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils,
|
||||
};
|
||||
use governor::{
|
||||
DefaultKeyedRateLimiter, Quota, RateLimiter,
|
||||
clock::{Clock, DefaultClock},
|
||||
};
|
||||
use conduwuit::{Err, Result, SyncMappedMutexGuard, SyncMutex, SyncMutexGuard, at, err, utils};
|
||||
use lru_cache::LruCache;
|
||||
use nonzero_ext::nonzero;
|
||||
use ruma::{
|
||||
OwnedTransactionId,
|
||||
api::{
|
||||
client::rendezvous::{
|
||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||
update_rendezvous_session,
|
||||
},
|
||||
error::{ErrorKind, LimitExceededErrorData, RetryAfter},
|
||||
api::client::rendezvous::{
|
||||
create_rendezvous_session, delete_rendezvous_session, get_rendezvous_session,
|
||||
update_rendezvous_session,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct Service {
|
||||
sessions: SyncMutex<LruCache<String, Session>>,
|
||||
create_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||
session_ratelimiter: DefaultKeyedRateLimiter<IpAddr>,
|
||||
}
|
||||
|
||||
struct Session {
|
||||
data: String,
|
||||
created_at: Instant,
|
||||
created_at: SystemTime,
|
||||
last_sequence_token: String,
|
||||
transaction_sequences: LruCache<OwnedTransactionId, String>,
|
||||
}
|
||||
@@ -40,31 +27,20 @@ struct Session {
|
||||
impl Session {
|
||||
const SAVED_TRANSACTION_SEQUENCES: usize = 256;
|
||||
|
||||
fn new(data: String, sequence_token: String, now: Instant) -> Self {
|
||||
fn new(data: String, sequence_token: String) -> Self {
|
||||
Self {
|
||||
data,
|
||||
created_at: now,
|
||||
created_at: SystemTime::now(),
|
||||
last_sequence_token: sequence_token,
|
||||
transaction_sequences: LruCache::new(Self::SAVED_TRANSACTION_SEQUENCES),
|
||||
}
|
||||
}
|
||||
|
||||
fn time_remaining(&self, now: Instant) -> Option<Duration> {
|
||||
let age = now.saturating_duration_since(self.created_at);
|
||||
(age < Service::SESSION_MAX_AGE)
|
||||
.then(|| Service::SESSION_MAX_AGE.saturating_sub(age))
|
||||
.filter(|remaining| !remaining.is_zero())
|
||||
}
|
||||
|
||||
fn is_expired(&self, now: Instant) -> bool { self.time_remaining(now).is_none() }
|
||||
}
|
||||
|
||||
impl crate::Service for Service {
|
||||
fn build(_: crate::Args<'_>) -> Result<Arc<Self>> {
|
||||
Ok(Arc::new(Self {
|
||||
sessions: SyncMutex::new(LruCache::new(Self::MAX_SESSIONS)),
|
||||
create_ratelimiter: RateLimiter::keyed(Self::CREATE_RATELIMIT),
|
||||
session_ratelimiter: RateLimiter::keyed(Self::SESSION_RATELIMIT),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -72,64 +48,25 @@ impl crate::Service for Service {
|
||||
}
|
||||
|
||||
impl Service {
|
||||
const CREATE_RATELIMIT: Quota = Quota::per_minute(nonzero!(30_u32));
|
||||
const MAX_DATA_SIZE_BYTES: usize = 4096;
|
||||
const MAX_SESSIONS: usize = 256;
|
||||
const SESSION_MAX_AGE: Duration = Duration::from_secs(300);
|
||||
const SESSION_RATELIMIT: Quota = Quota::per_minute(nonzero!(300_u32));
|
||||
const TOKEN_LENGTH: usize = 32;
|
||||
|
||||
pub fn check_create_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||
Self::check_ratelimiter(&self.create_ratelimiter, ip)
|
||||
}
|
||||
|
||||
pub fn check_session_ratelimit(&self, ip: IpAddr) -> Result<()> {
|
||||
Self::check_ratelimiter(&self.session_ratelimiter, ip)
|
||||
}
|
||||
|
||||
fn check_ratelimiter(
|
||||
ratelimiter: &DefaultKeyedRateLimiter<IpAddr>,
|
||||
ip: IpAddr,
|
||||
) -> Result<()> {
|
||||
if let Err(not_until) = ratelimiter.check_key(&ip) {
|
||||
let wait_time = not_until.wait_time_from(DefaultClock::default().now());
|
||||
let mut data = LimitExceededErrorData::new();
|
||||
data.retry_after = Some(RetryAfter::Delay(wait_time));
|
||||
return Err(Error::BadRequest(
|
||||
ErrorKind::LimitExceeded(data),
|
||||
"Rate limit exceeded.",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_token() -> String { utils::random_string(Self::TOKEN_LENGTH) }
|
||||
|
||||
fn is_valid_opaque_id(id: &str) -> bool {
|
||||
!id.is_empty()
|
||||
&& id.len() <= 255
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~'))
|
||||
}
|
||||
|
||||
/// Lock and fetch an unexpired rendezvous session.
|
||||
fn lock_session(&self, id: &str) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||
self.lock_session_at(id, Instant::now())
|
||||
}
|
||||
|
||||
fn lock_session_at(
|
||||
&self,
|
||||
id: &str,
|
||||
now: Instant,
|
||||
) -> Result<SyncMappedMutexGuard<'_, Session>> {
|
||||
// We don't clear out expired sessions manually, the LRU cache will
|
||||
// evict them over time
|
||||
SyncMutexGuard::try_map_or_err(self.sessions.lock(), |sessions| {
|
||||
sessions
|
||||
.get_mut(id)
|
||||
.filter(|session| !session.is_expired(now))
|
||||
.filter(|session| {
|
||||
SystemTime::now()
|
||||
.duration_since(session.created_at)
|
||||
.is_ok_and(|duration| duration < Self::SESSION_MAX_AGE)
|
||||
})
|
||||
.ok_or_else(|| err!(Request(NotFound("Unknown session"))))
|
||||
})
|
||||
.map_err(at!(1))
|
||||
@@ -149,7 +86,7 @@ impl Service {
|
||||
|
||||
self.sessions
|
||||
.lock()
|
||||
.insert(id.clone(), Session::new(data, sequence_token.clone(), Instant::now()));
|
||||
.insert(id.clone(), Session::new(data, sequence_token.clone()));
|
||||
|
||||
Ok(create_rendezvous_session::msc4388::Response::new(
|
||||
id,
|
||||
@@ -166,12 +103,6 @@ impl Service {
|
||||
sequence_token: String,
|
||||
data: String,
|
||||
) -> Result<update_rendezvous_session::msc4388::Response> {
|
||||
if !Self::is_valid_opaque_id(transaction.as_str()) {
|
||||
return Err!(Request(InvalidParam(
|
||||
"Transaction ID does not comply with the opaque identifier grammar"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut session = self.lock_session(id)?;
|
||||
|
||||
// If the provided transaction ID was used already, we have to return
|
||||
@@ -206,12 +137,13 @@ impl Service {
|
||||
|
||||
/// Look up a rendezvous session by ID.
|
||||
pub fn get_session(&self, id: &str) -> Result<get_rendezvous_session::msc4388::Response> {
|
||||
let now = Instant::now();
|
||||
let session = self.lock_session_at(id, now)?;
|
||||
let session = self.lock_session(id)?;
|
||||
|
||||
let session_time_remaining = session
|
||||
.time_remaining(now)
|
||||
.unwrap_or_else(|| Duration::from_millis(1));
|
||||
let session_age = SystemTime::now()
|
||||
.duration_since(session.created_at)
|
||||
.unwrap_or(Duration::MAX);
|
||||
|
||||
let session_time_remaining = Self::SESSION_MAX_AGE.saturating_sub(session_age);
|
||||
|
||||
Ok(get_rendezvous_session::msc4388::Response::new(
|
||||
session.last_sequence_token.clone(),
|
||||
@@ -226,12 +158,8 @@ impl Service {
|
||||
id: &str,
|
||||
) -> Result<delete_rendezvous_session::msc4388::Response> {
|
||||
let mut sessions = self.sessions.lock();
|
||||
let now = Instant::now();
|
||||
|
||||
if sessions
|
||||
.remove(id)
|
||||
.is_some_and(|session| !session.is_expired(now))
|
||||
{
|
||||
if sessions.remove(id).is_some() {
|
||||
Ok(delete_rendezvous_session::msc4388::Response::new())
|
||||
} else {
|
||||
Err!(Request(NotFound("Unknown session")))
|
||||
|
||||
@@ -522,6 +522,13 @@ impl Service {
|
||||
let device_changes =
|
||||
self.select_edus_device_changes(server_name, batch, &max_edu_count, &events_len);
|
||||
|
||||
let receipts: OptionFuture<_> = self
|
||||
.server
|
||||
.config
|
||||
.allow_outgoing_read_receipts
|
||||
.then(|| self.select_edus_receipts(server_name, batch, &max_edu_count))
|
||||
.into();
|
||||
|
||||
let presence: OptionFuture<_> = self
|
||||
.server
|
||||
.config
|
||||
@@ -529,20 +536,11 @@ impl Service {
|
||||
.then(|| self.select_edus_presence(server_name, batch, &max_edu_count))
|
||||
.into();
|
||||
|
||||
let (device_changes, presence) = join!(device_changes, presence);
|
||||
let (device_changes, receipts, presence) = join!(device_changes, receipts, presence);
|
||||
|
||||
let mut events = device_changes;
|
||||
events.extend(presence.into_iter().flatten());
|
||||
|
||||
// leave a slot for the queued event, but always allow one receipt EDU
|
||||
let edu_limit = (EDU_LIMIT - 1).saturating_sub(events.len()).max(1);
|
||||
if self.server.config.allow_outgoing_read_receipts {
|
||||
// must be selected last, as it may lower max_edu_count
|
||||
events.extend(
|
||||
self.select_edus_receipts(server_name, batch, &max_edu_count, edu_limit)
|
||||
.await,
|
||||
);
|
||||
}
|
||||
events.extend(receipts.into_iter().flatten());
|
||||
|
||||
// TODO(nex): some EDUs like typing need flattening
|
||||
|
||||
@@ -618,11 +616,9 @@ impl Service {
|
||||
server_name: &ServerName,
|
||||
since: (u64, u64),
|
||||
max_edu_count: &AtomicU64,
|
||||
edu_limit: usize,
|
||||
) -> EduVec {
|
||||
) -> Option<EduBuf> {
|
||||
let num = AtomicUsize::new(0);
|
||||
let deferred = AtomicU64::new(u64::MAX);
|
||||
let rooms: Vec<_> = self
|
||||
let receipts: BTreeMap<OwnedRoomId, ReceiptMap> = self
|
||||
.services
|
||||
.state_cache
|
||||
.server_rooms(server_name)
|
||||
@@ -631,54 +627,33 @@ impl Service {
|
||||
return None;
|
||||
}
|
||||
|
||||
let maps = self
|
||||
.select_edus_receipts_room(
|
||||
&room_id,
|
||||
since,
|
||||
max_edu_count,
|
||||
&num,
|
||||
edu_limit,
|
||||
&deferred,
|
||||
)
|
||||
let receipt_map = self
|
||||
.select_edus_receipts_room(&room_id, since, max_edu_count, &num)
|
||||
.await;
|
||||
|
||||
(!maps.is_empty()).then_some((room_id, maps))
|
||||
(!receipt_map.read.is_empty()).then_some((room_id, receipt_map))
|
||||
})
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
// the next transaction starts at the first receipt that did not fit
|
||||
max_edu_count
|
||||
.fetch_min(deferred.load(Ordering::Relaxed).saturating_sub(1), Ordering::Relaxed);
|
||||
|
||||
let mut contents = Vec::<BTreeMap<OwnedRoomId, ReceiptMap>>::new();
|
||||
for (room_id, maps) in rooms {
|
||||
for (index, read) in maps.into_iter().enumerate() {
|
||||
if index == contents.len() {
|
||||
contents.push(BTreeMap::new());
|
||||
}
|
||||
contents[index].insert(room_id.clone(), ReceiptMap::new(read));
|
||||
}
|
||||
if receipts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
contents
|
||||
.into_iter()
|
||||
.map(|content| {
|
||||
let edu = Edu::Receipt(ReceiptContent::new(content));
|
||||
let receipt_content = Edu::Receipt(ReceiptContent::new(receipts));
|
||||
|
||||
let mut buf = EduBuf::new();
|
||||
serde_json::to_writer(&mut buf, &edu)
|
||||
.expect("Failed to serialize Receipt EDU to JSON vec");
|
||||
buf
|
||||
})
|
||||
.collect()
|
||||
let mut buf = EduBuf::new();
|
||||
serde_json::to_writer(&mut buf, &receipt_content)
|
||||
.expect("Failed to serialize Receipt EDU to JSON vec");
|
||||
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
/// Look for read receipts in this room
|
||||
#[tracing::instrument(
|
||||
name = "receipts",
|
||||
level = "trace",
|
||||
skip(self, since, max_edu_count, num, deferred)
|
||||
skip(self, since, max_edu_count, num)
|
||||
)]
|
||||
async fn select_edus_receipts_room(
|
||||
&self,
|
||||
@@ -686,16 +661,14 @@ impl Service {
|
||||
since: (u64, u64),
|
||||
max_edu_count: &AtomicU64,
|
||||
num: &AtomicUsize,
|
||||
edu_limit: usize,
|
||||
deferred: &AtomicU64,
|
||||
) -> Vec<BTreeMap<OwnedUserId, ReceiptData>> {
|
||||
) -> ReceiptMap {
|
||||
let receipts = self
|
||||
.services
|
||||
.read_receipt
|
||||
.readreceipts_since(room_id, Some(since.0));
|
||||
|
||||
pin_mut!(receipts);
|
||||
let mut maps = Vec::new();
|
||||
let mut read = BTreeMap::<OwnedUserId, ReceiptData>::new();
|
||||
while let Some((user_id, count, read_receipt)) = receipts.next().await {
|
||||
if count > since.1 {
|
||||
break;
|
||||
@@ -731,20 +704,14 @@ impl Service {
|
||||
|
||||
let receipt_data = ReceiptData::new(receipt, vec![event_id]);
|
||||
|
||||
let Some(index) = add_receipt(&mut maps, user_id, receipt_data, edu_limit) else {
|
||||
deferred.fetch_min(count, Ordering::Relaxed);
|
||||
break;
|
||||
};
|
||||
|
||||
// only a user's first receipt counts towards the limit
|
||||
if index == 0
|
||||
&& num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT
|
||||
{
|
||||
break;
|
||||
if read.insert(user_id, receipt_data).is_none() {
|
||||
if num.fetch_add(1, Ordering::Relaxed).saturating_add(1) >= SELECT_RECEIPT_LIMIT {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
maps
|
||||
ReceiptMap::new(read)
|
||||
}
|
||||
|
||||
/// Look for presence
|
||||
@@ -1143,27 +1110,3 @@ impl Service {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the receipt to the first map without one from the user and returns
|
||||
/// that map's index, or `None` if all `limit` maps have one.
|
||||
fn add_receipt(
|
||||
maps: &mut Vec<BTreeMap<OwnedUserId, ReceiptData>>,
|
||||
user_id: OwnedUserId,
|
||||
receipt: ReceiptData,
|
||||
limit: usize,
|
||||
) -> Option<usize> {
|
||||
let index = maps
|
||||
.iter()
|
||||
.position(|map| !map.contains_key(&user_id))
|
||||
.unwrap_or(maps.len());
|
||||
if index >= limit {
|
||||
return None;
|
||||
}
|
||||
|
||||
if index == maps.len() {
|
||||
maps.push(BTreeMap::new());
|
||||
}
|
||||
maps[index].insert(user_id, receipt);
|
||||
|
||||
Some(index)
|
||||
}
|
||||
@@ -1,19 +1,14 @@
|
||||
use std::{collections::BTreeMap, iter::once};
|
||||
use std::iter::once;
|
||||
|
||||
use conduwuit::{
|
||||
Error,
|
||||
matrix::{PartialPdu, pdu::sticky},
|
||||
};
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
use ruma::{
|
||||
RoomId, UserId,
|
||||
api::federation::transactions::edu::ReceiptData,
|
||||
events::{receipt::Receipt, sticky::StickyDurationMs},
|
||||
server_name, user_id,
|
||||
};
|
||||
use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name};
|
||||
use serde_json::{json, value::to_raw_value};
|
||||
|
||||
use super::{CurTransactionStatus, TransactionStatus, add_receipt};
|
||||
use super::{CurTransactionStatus, TransactionStatus};
|
||||
use crate::{
|
||||
sending::{Destination, EduBuf, SendingEvent},
|
||||
test_utils::{test_services, test_services_with},
|
||||
@@ -201,17 +196,3 @@ async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled(
|
||||
assert_eq!(active_after_startup, 0);
|
||||
assert_eq!(sending_after_startup, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_receipt_separates_receipts_of_one_user() {
|
||||
let alice = user_id!("@alice:example.org");
|
||||
let bob = user_id!("@bob:example.org");
|
||||
let receipt = || ReceiptData::new(Receipt::default(), vec![]);
|
||||
let mut maps = Vec::new();
|
||||
|
||||
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(0));
|
||||
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), Some(1));
|
||||
assert_eq!(add_receipt(&mut maps, bob.to_owned(), receipt(), 2), Some(0));
|
||||
assert_eq!(add_receipt(&mut maps, alice.to_owned(), receipt(), 2), None);
|
||||
assert_eq!(maps.iter().map(BTreeMap::len).collect::<Vec<_>>(), [2, 1]);
|
||||
}
|
||||
Reference in new issue
Block a user