Compare commits

..
Author SHA1 Message Date
Henry-Hiles 3e598a6f71 chore: Swap unwrap_or out for expect, as it can never fail 2026-12-04 10:19:32 -05:00
Henry-Hiles 148a025f36 chore: Address review feedback on #2583 2026-12-04 00:55:08 -05:00
Henry-Hiles 4d88bb84f5 chore: Address review comments for #2583 2026-12-04 00:55:08 -05:00
Henry-Hiles 2d6260792d chore: Address review comments for #2583 2026-12-04 00:55:08 -05:00
Henry-Hilesandnew-years-eve 6a1f29cd03 feat: Delayed events support
Includes stable support.

Co-authored-by: new-years-eve <new-years-evening@proton.me>
2026-12-04 00:55:08 -05:00
nex 2f356eaa91 meta: Unbreak PR template
The colon in `fixes` and `closes` apparently caused forgejo to not pick up the references properly.
2026-12-04 00:34:49 +00:00
Renovate Bot e6afb63648 chore(deps): update pre-commit hook forgejo/runner to v13.3.0 2026-12-03 18:51:00 +00:00
Renovate Bot ac7f79bd26 chore(deps): update rust-zerover-patch-updates 2026-12-03 18:50:10 +00:00
Ginger 5f2b73db9d chore: News fragment 2026-12-03 18:49:39 +00:00
Ginger 1a616146d0 refactor: Remove element_hacks 2026-12-03 18:49:39 +00:00
35 changed files with 1044 additions and 106 deletions

No files matched your search

+4 -3
View File
@@ -17,7 +17,7 @@ go to "files changed", and click on the "+" symbol in the line number gutter,
and attach comments to the lines that you think would benefit from some clarification. and attach comments to the lines that you think would benefit from some clarification.
--> -->
This pull request... This pull request... <!-- do not forget to write here! -->
<!-- Example: <!-- Example:
This pull request allows us to warp through time and space ten times faster than before by This pull request allows us to warp through time and space ten times faster than before by
@@ -26,8 +26,8 @@ efficient. This resolves the common issue where we have to wait more than 10 mil
engage, use, and disengage the warp drive when travelling between galaxies. engage, use, and disengage the warp drive when travelling between galaxies.
--> -->
<!-- Closes: #... --> <!-- Closes #... -->
<!-- Fixes: #... --> <!-- Fixes #... -->
<!-- Uncomment the above line(s) if your pull request fixes an issue or closes another pull request <!-- Uncomment the above line(s) if your pull request fixes an issue or closes another pull request
by superseding it. Replace `#...` with the issue/pr number, such as `#123`. --> by superseding it. Replace `#...` with the issue/pr number, such as `#123`. -->
@@ -73,6 +73,7 @@ Notes on these requirements:
main, it's difficult to get out cleanly, so put on your best dress, smile for the cameras! main, it's difficult to get out cleanly, so put on your best dress, smile for the cameras!
--> -->
<!-- Do not delete below this line -->
[c1]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md [c1]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md
[c2]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/docs/development/code_style.mdx [c2]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/docs/development/code_style.mdx
[c1pc]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#pre-commit-checks [c1pc]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#pre-commit-checks
+2 -2
View File
@@ -69,7 +69,7 @@ jobs:
CARGO_INCREMENTAL=${{ env.BUILDKIT_ENDPOINT != '' && '1' || '0' }} CARGO_INCREMENTAL=${{ env.BUILDKIT_ENDPOINT != '' && '1' || '0' }}
TARGET_CPU= TARGET_CPU=
RUST_PROFILE=release RUST_PROFILE=release
CARGO_FEATURES=default,http3 CARGO_FEATURES=default
platforms: ${{ matrix.platform }} platforms: ${{ matrix.platform }}
labels: ${{ steps.prepare.outputs.metadata_labels }} labels: ${{ steps.prepare.outputs.metadata_labels }}
annotations: ${{ steps.prepare.outputs.metadata_annotations }} annotations: ${{ steps.prepare.outputs.metadata_annotations }}
@@ -154,7 +154,7 @@ jobs:
CARGO_INCREMENTAL=${{ env.BUILDKIT_ENDPOINT != '' && '1' || '0' }} CARGO_INCREMENTAL=${{ env.BUILDKIT_ENDPOINT != '' && '1' || '0' }}
TARGET_CPU=${{ matrix.target_cpu }} TARGET_CPU=${{ matrix.target_cpu }}
RUST_PROFILE=release-max-perf RUST_PROFILE=release-max-perf
CARGO_FEATURES=default,http3,release_max_log_level CARGO_FEATURES=default,release_max_log_level
platforms: ${{ matrix.platform }} platforms: ${{ matrix.platform }}
labels: ${{ steps.prepare.outputs.metadata_labels }} labels: ${{ steps.prepare.outputs.metadata_labels }}
annotations: ${{ steps.prepare.outputs.metadata_annotations }} annotations: ${{ steps.prepare.outputs.metadata_annotations }}
+1 -1
View File
@@ -64,7 +64,7 @@ repos:
- pre-push - pre-push
- repo: https://code.forgejo.org/forgejo/runner - repo: https://code.forgejo.org/forgejo/runner
rev: v13.2.1 rev: v13.3.0
hooks: hooks:
- id: forgejo-runner-validate - id: forgejo-runner-validate
stages: stages:
Generated
+14 -14
View File
@@ -1026,7 +1026,7 @@ dependencies = [
"serde-saphyr", "serde-saphyr",
"serde_json", "serde_json",
"serde_regex", "serde_regex",
"sha2 0.11.2", "sha2 0.11.3",
"smallstr", "smallstr",
"smallvec", "smallvec",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -1152,7 +1152,7 @@ dependencies = [
"serde-saphyr", "serde-saphyr",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
"sha2 0.11.2", "sha2 0.11.3",
"termimad", "termimad",
"tokio", "tokio",
"tracing", "tracing",
@@ -1866,7 +1866,7 @@ dependencies = [
"curve25519-dalek", "curve25519-dalek",
"ed25519", "ed25519",
"serde", "serde",
"sha2 0.11.2", "sha2 0.11.3",
"signature 3.0.0", "signature 3.0.0",
"subtle", "subtle",
"zeroize", "zeroize",
@@ -3245,9 +3245,9 @@ dependencies = [
[[package]] [[package]]
name = "lettre" name = "lettre"
version = "0.11.24" version = "0.11.25"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f294f3d7cdb313e578acef7d7727d4e8d897e0fcd0d6d58c19959cec95073f19" checksum = "15000d8223b52e56d577590183331413c0ef732ebdd9c9b6aebce15824aba899"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64 0.23.1", "base64 0.23.1",
@@ -4182,7 +4182,7 @@ dependencies = [
"elliptic-curve 0.14.3", "elliptic-curve 0.14.3",
"primefield", "primefield",
"primeorder 0.14.0", "primeorder 0.14.0",
"sha2 0.11.2", "sha2 0.11.3",
] ]
[[package]] [[package]]
@@ -4196,7 +4196,7 @@ dependencies = [
"fiat-crypto", "fiat-crypto",
"primefield", "primefield",
"primeorder 0.14.0", "primeorder 0.14.0",
"sha2 0.11.2", "sha2 0.11.3",
] ]
[[package]] [[package]]
@@ -5226,7 +5226,7 @@ dependencies = [
"ruma-common", "ruma-common",
"ruma-events", "ruma-events",
"serde_json", "serde_json",
"sha2 0.11.2", "sha2 0.11.3",
"thiserror 2.0.21", "thiserror 2.0.21",
] ]
@@ -5327,9 +5327,9 @@ dependencies = [
[[package]] [[package]]
name = "rustls" name = "rustls"
version = "0.23.46" version = "0.23.47"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" checksum = "4ac0e747c10d93d873fd4c50b26ef47ad92d1bfb48f6922003bb514070f6e88c"
dependencies = [ dependencies = [
"aws-lc-rs", "aws-lc-rs",
"log", "log",
@@ -5704,7 +5704,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9"
dependencies = [ dependencies = [
"annotate-snippets", "annotate-snippets",
"base64 0.23.1", "base64 0.22.1",
"encoding_rs_io", "encoding_rs_io",
"granit-parser", "granit-parser",
"nohash-hasher", "nohash-hasher",
@@ -5909,9 +5909,9 @@ dependencies = [
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.11.2" version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"cpufeatures 0.3.1", "cpufeatures 0.3.1",
@@ -7120,7 +7120,7 @@ dependencies = [
"hkdf 0.13.0", "hkdf 0.13.0",
"http", "http",
"p256 0.13.2", "p256 0.13.2",
"sha2 0.11.2", "sha2 0.11.3",
] ]
[[package]] [[package]]
+1
View File
@@ -385,6 +385,7 @@ features = [
"unstable-msc4203", "unstable-msc4203",
"unstable-msc4310", "unstable-msc4310",
"unstable-msc4380", "unstable-msc4380",
"unstable-msc4140",
"unstable-msc4143", "unstable-msc4143",
"unstable-msc4293", "unstable-msc4293",
"unstable-msc4363", "unstable-msc4363",
+1
View File
@@ -0,0 +1 @@
Add support for delayed events (MSC4140), including the stable endpoints and the `m.delayed_events` capability. The limits can be configured with `delayed_events_max_delay_ms` and `delayed_events_max_scheduled`. Contributed by @eve and @Henry-Hiles.
+1
View File
@@ -0,0 +1 @@
The `element_hacks` build feature, which has done almost nothing for many versions, has been removed completely. Contributed by @ginger.
+13
View File
@@ -813,6 +813,19 @@
# env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE # env: CONTINUWUITY_FORGET_FORCED_UPON_LEAVE
#forget_forced_upon_leave = false #forget_forced_upon_leave = false
# The maximum delay in milliseconds for delayed events (MSC4140). Setting
# this or `delayed_events_max_scheduled` to 0 disables delayed events.
#
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_DELAY_MS
#delayed_events_max_delay_ms = 604800000
# The maximum number of delayed events each user can have scheduled at
# once. Setting this or `delayed_events_max_delay_ms` to 0 disables
# delayed events.
#
# env: CONTINUWUITY_DELAYED_EVENTS_MAX_SCHEDULED
#delayed_events_max_scheduled = 100
# Set this to true to require authentication when looking up user profiles # Set this to true to require authentication when looking up user profiles
# through this server. # through this server.
# #
+1 -1
View File
@@ -102,7 +102,7 @@ look like this:
RUSTFLAGS="--cfg tokio_unstable" cargo +nightly build \ RUSTFLAGS="--cfg tokio_unstable" cargo +nightly build \
--release \ --release \
--no-default-features \ --no-default-features \
--features=systemd,element_hacks,gzip_compression,brotli_compression,zstd_compression,tokio_console --features=systemd,gzip_compression,brotli_compression,zstd_compression,tokio_console
``` ```
You will also need to enable the `tokio_console` config option in Continuwuity You will also need to enable the `tokio_console` config option in Continuwuity
+1 -1
View File
@@ -146,7 +146,7 @@ cargo clippy \
--locked \ --locked \
--profile test \ --profile test \
--no-default-features \ --no-default-features \
--features=console,systemd,element_hacks,direct_tls,perf_measurements,brotli_compression \ --features=console,systemd,direct_tls,perf_measurements,brotli_compression \
--color=always \ --color=always \
-- \ -- \
-D warnings -D warnings
-3
View File
@@ -21,9 +21,6 @@ brotli_compression = [
"conduwuit-service/brotli_compression", "conduwuit-service/brotli_compression",
"reqwest/brotli", "reqwest/brotli",
] ]
element_hacks = [
"conduwuit-service/element_hacks",
]
gzip_compression = [ gzip_compression = [
"conduwuit-core/gzip_compression", "conduwuit-core/gzip_compression",
"conduwuit-service/gzip_compression", "conduwuit-service/gzip_compression",
+13 -4
View File
@@ -1,16 +1,20 @@
use std::collections::{BTreeMap, BTreeSet}; use std::{
collections::{BTreeMap, BTreeSet},
time::Duration,
};
use axum::extract::State; use axum::extract::State;
use conduwuit::{Result, Server, config::experiments::ToggledExperiment}; use conduwuit::{Result, Server, config::experiments::ToggledExperiment};
use ruma::{ use ruma::{
RoomVersionId, RoomVersionId, UInt,
api::{ api::{
OAuthClientScope, OAuthClientScope,
client::discovery::get_capabilities::{ client::discovery::get_capabilities::{
self, self,
v3::{ v3::{
AdminCapability, Capabilities, GetLoginTokenCapability, ProfileFieldsCapability, AdminCapability, Capabilities, DelayedEventsCapability, GetLoginTokenCapability,
RoomVersionStability, RoomVersionsCapability, ThirdPartyIdChangesCapability, ProfileFieldsCapability, RoomVersionStability, RoomVersionsCapability,
ThirdPartyIdChangesCapability,
}, },
}, },
}, },
@@ -64,6 +68,11 @@ pub(crate) async fn get_capabilities_route(
assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }), assign!(ProfileFieldsCapability::new(true), { disallowed: Some(services.oidc.restricted_profile_fields()) }),
); );
capabilities.delayed_events = Some(assign!(DelayedEventsCapability::new(), {
max_delay_ms: Some(Duration::from_millis(services.config.delayed_events_max_delay_ms)),
max_scheduled: Some(UInt::new_saturating(services.config.delayed_events_max_scheduled)),
}));
capabilities.set( capabilities.set(
"org.matrix.msc4174.webpush", "org.matrix.msc4174.webpush",
json!({ json!({
+144
View File
@@ -0,0 +1,144 @@
use axum::extract::State;
use conduwuit::{Err, Result};
use ruma::{
api::client::delayed_events::{
get_delayed_event, schedule_delayed_event,
update_delayed_event::{self, UpdateAction},
},
events::TimelineEventType,
signatures::MAX_PDU_BYTES,
};
use serde_json::{Map as JsonMap, Value as JsonValue};
use service::rooms::delayed_events::NewDelayedEvent;
use crate::{Ruma, client_ip::ClientIp};
/// The largest content we accept for a delayed event, leaving 4 KiB of the PDU
/// size limit for the rest of the event (IDs, hashes, signatures, etc).
const MAX_CONTENT_BYTES: usize = MAX_PDU_BYTES - 4096;
/// # `PUT /_matrix/client/v3/rooms/{roomId}/delayed_event/{eventType}/{txnId}`
///
/// Schedules an event to be sent into a room after a delay.
pub(crate) async fn schedule_delayed_event_route(
State(services): State<crate::State>,
ClientIp(client_ip): ClientIp,
body: Ruma<schedule_delayed_event::v3::Request>,
) -> Result<schedule_delayed_event::v3::Response> {
let sender_user = body.identity.expect_sender_user()?;
let sender_device = body.identity.sender_device();
if services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
services
.users
.update_device_last_seen(sender_user, sender_device, client_ip)
.await;
let Some(max_delay) = services.rooms.delayed_events.max_delay() else {
return Err!(Request(Forbidden("Delayed events are disabled on this server.")));
};
if body.delay_ms.is_zero() {
return Err!(Request(BadJson("delay_ms must be greater than 0.")));
}
if body.delay_ms > max_delay {
return Err!(Request(DelayTooLarge(
"The requested delay exceeds the maximum of {}ms.",
max_delay.as_millis()
)));
}
if serde_json::from_str::<JsonMap<String, JsonValue>>(body.content.json().get()).is_err() {
return Err!(Request(BadJson("The event content must be a JSON object.")));
}
// The full PDU is size checked again when it is sent.
if body.content.json().get().len() > MAX_CONTENT_BYTES {
return Err!(Request(TooLarge(
"The event content exceeds the maximum of {MAX_CONTENT_BYTES} bytes."
)));
}
// Auth is checked again when the event is sent
let is_own_membership = body.event_type == TimelineEventType::RoomMember
&& body.state_key.as_deref() == Some(sender_user.as_str());
if !is_own_membership
&& !services
.rooms
.state_cache
.is_joined(sender_user, &body.room_id)
.await
{
return Err!(Request(Forbidden("You are not joined to this room.")));
}
let timestamp =
if body.identity.is_appservice() || services.admin.user_is_admin(sender_user).await {
body.timestamp
} else {
None
};
let body = body.body;
let delay_id = services
.rooms
.delayed_events
.schedule(sender_user, sender_device, &body.txn_id, NewDelayedEvent {
room_id: body.room_id,
event_type: body.event_type,
state_key: body.state_key,
content: body.content,
delay: body.delay_ms,
timestamp,
sticky_duration_ms: body.sticky_duration_ms,
})
.await?;
Ok(schedule_delayed_event::v3::Response::new(delay_id))
}
/// # `POST /_matrix/client/v1/delayed_events/{delayId}/{action}`
///
/// Restarts, sends or cancels a scheduled delayed event.
pub(crate) async fn update_delayed_event_route(
State(services): State<crate::State>,
body: Ruma<update_delayed_event::v1::Request>,
) -> Result<update_delayed_event::v1::Response> {
let sender_user = body.identity.expect_sender_user()?;
let update_delayed_event::v1::Request { delay_id, action, .. } = body.body;
// Cancelling is still allowed, since it only stops activity.
if action != UpdateAction::Cancel && services.users.is_suspended(sender_user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
services
.rooms
.delayed_events
.update(sender_user, &delay_id, action)
.await?;
Ok(update_delayed_event::v1::Response::new())
}
/// # `GET /_matrix/client/v1/delayed_events/{delayId}`
///
/// Returns a scheduled or finalized delayed event.
pub(crate) async fn get_delayed_event_route(
State(services): State<crate::State>,
body: Ruma<get_delayed_event::v1::Request>,
) -> Result<get_delayed_event::v1::Response> {
let sender_user = body.identity.expect_sender_user()?;
let delayed_event = services
.rooms
.delayed_events
.get(sender_user, &body.delay_id)
.await?;
Ok(get_delayed_event::v1::Response::new(delayed_event))
}
+2
View File
@@ -7,6 +7,7 @@ pub(super) mod backup;
pub(super) mod capabilities; pub(super) mod capabilities;
pub(super) mod context; pub(super) mod context;
pub(super) mod dehydrated_device; pub(super) mod dehydrated_device;
pub(super) mod delayed_events;
pub(super) mod device; pub(super) mod device;
pub(super) mod directory; pub(super) mod directory;
pub(super) mod filter; pub(super) mod filter;
@@ -52,6 +53,7 @@ pub(super) use backup::*;
pub(super) use capabilities::*; pub(super) use capabilities::*;
pub(super) use context::*; pub(super) use context::*;
pub(super) use dehydrated_device::*; pub(super) use dehydrated_device::*;
pub(super) use delayed_events::*;
pub(super) use device::*; pub(super) use device::*;
pub(super) use directory::*; pub(super) use directory::*;
pub(super) use filter::*; pub(super) use filter::*;
+7 -6
View File
@@ -559,15 +559,16 @@ pub(crate) async fn create_room_route(
match services match services
.rooms .rooms
.timeline .timeline
.send_state_event_for_key( .send_timeline_event(
PartialPdu {
event_type: event_type.to_string().into(),
content: content.into_json(),
state_key: Some(state_key.into()),
..Default::default()
},
sender_user, sender_user,
&room_id, &room_id,
&state_lock, &state_lock,
&event_type,
&content,
&state_key,
None,
None,
) )
.boxed() .boxed()
.await .await
+2 -14
View File
@@ -40,20 +40,8 @@ pub(crate) async fn send_message_event_route(
.update_device_last_seen(sender_user, sender_device, client_ip) .update_device_last_seen(sender_user, sender_device, client_ip)
.await; .await;
// Forbid m.room.encrypted if encryption is disabled
if MessageLikeEventType::RoomEncrypted == body.event_type && !services.config.allow_encryption
{
return Err!(Request(Forbidden("Encryption has been disabled")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await; let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
if body.event_type == MessageLikeEventType::CallInvite
&& services.rooms.directory.is_public_room(&body.room_id).await
{
return Err!(Request(Forbidden("Room call invites are not allowed in public rooms")));
}
// Check if this is a new transaction id // Check if this is a new transaction id
if let Ok(response) = services if let Ok(response) = services
.transactions .transactions
@@ -91,7 +79,7 @@ pub(crate) async fn send_message_event_route(
let event_id = services let event_id = services
.rooms .rooms
.timeline .timeline
.build_and_append_pdu( .send_timeline_event(
PartialPdu { PartialPdu {
event_type: body.event_type.clone().into(), event_type: body.event_type.clone().into(),
content, content,
@@ -108,7 +96,7 @@ pub(crate) async fn send_message_event_route(
..Default::default() ..Default::default()
}, },
sender_user, sender_user,
Some(&body.room_id), &body.room_id,
&state_lock, &state_lock,
) )
.await?; .await?;
+19 -10
View File
@@ -1,7 +1,13 @@
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
use axum::extract::State; use axum::extract::State;
use conduwuit::{Err, Result, err, matrix::Event}; use conduwuit::{
Err, Result, err,
matrix::{
Event,
pdu::{PartialPdu, sticky},
},
};
use futures::{FutureExt, TryStreamExt}; use futures::{FutureExt, TryStreamExt};
use ruma::{ use ruma::{
RoomId, RoomId,
@@ -42,19 +48,22 @@ pub(crate) async fn send_state_event_for_key_route(
let event_id = services let event_id = services
.rooms .rooms
.timeline .timeline
.send_state_event_for_key( .send_timeline_event(
sender_user, PartialPdu {
&body.room_id, event_type: body.event_type.to_string().into(),
&state_lock, content: body.body.body.clone().into_json(),
&body.event_type, state_key: Some(body.state_key.as_str().into()),
&body.body.body, sticky: body.sticky_duration_ms.map(sticky::object),
&body.state_key, timestamp: if body.identity.is_appservice() {
body.sticky_duration_ms,
if body.identity.is_appservice() {
body.timestamp body.timestamp
} else { } else {
None None
}, },
..Default::default()
},
sender_user,
&body.room_id,
&state_lock,
) )
.boxed() .boxed()
.await?; .await?;
+3
View File
@@ -163,6 +163,9 @@ pub fn build(router: Router<State>, state: State) -> Router<State> {
.ruma_route(&client::update_device_route) .ruma_route(&client::update_device_route)
.ruma_route(&client::delete_device_route) .ruma_route(&client::delete_device_route)
.ruma_route(&client::delete_devices_route) .ruma_route(&client::delete_devices_route)
.ruma_route(&client::schedule_delayed_event_route)
.ruma_route(&client::update_delayed_event_route)
.ruma_route(&client::get_delayed_event_route)
.ruma_route(&client::get_tags_route) .ruma_route(&client::get_tags_route)
.ruma_route(&client::update_tag_route) .ruma_route(&client::update_tag_route)
.ruma_route(&client::delete_tag_route) .ruma_route(&client::delete_tag_route)
+19
View File
@@ -920,6 +920,21 @@ pub struct Config {
#[serde(default)] #[serde(default)]
pub forget_forced_upon_leave: bool, pub forget_forced_upon_leave: bool,
/// The maximum delay in milliseconds for delayed events (MSC4140). Setting
/// this or `delayed_events_max_scheduled` to 0 disables delayed events.
///
/// default: 604800000
#[serde(default = "default_delayed_events_max_delay_ms")]
pub delayed_events_max_delay_ms: u64,
/// The maximum number of delayed events each user can have scheduled at
/// once. Setting this or `delayed_events_max_delay_ms` to 0 disables
/// delayed events.
///
/// default: 100
#[serde(default = "default_delayed_events_max_scheduled")]
pub delayed_events_max_scheduled: u64,
/// Set this to true to require authentication when looking up user profiles /// Set this to true to require authentication when looking up user profiles
/// through this server. /// through this server.
/// ///
@@ -3444,6 +3459,10 @@ fn default_unauthenticated_request_ratelimit<K: Hash + Eq + Clone>() -> PerMinut
PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap())) PerMinuteRatelimiter::new(Quota::per_minute(30.try_into().unwrap()))
} }
fn default_delayed_events_max_delay_ms() -> u64 { 7 * 24 * 60 * 60 * 1000 }
fn default_delayed_events_max_scheduled() -> u64 { 100 }
fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] } fn default_additional_scopes() -> Vec<Scope> { vec![Scope::new("profile".to_owned())] }
// NOTE: This must be declared *after* every config struct in this file. The // NOTE: This must be declared *after* every config struct in this file. The
+2
View File
@@ -69,9 +69,11 @@ impl Pdu {
if context.user_id.is_none_or(|u| u != self.sender()) { if context.user_id.is_none_or(|u| u != self.sender()) {
unsigned.remove("transaction_id"); unsigned.remove("transaction_id");
unsigned.remove("delay_id");
} }
} else { } else {
unsigned.remove("transaction_id"); unsigned.remove("transaction_id");
unsigned.remove("delay_id");
} }
if let Some(expires_at) = self if let Some(expires_at) = self
+3
View File
@@ -53,5 +53,8 @@ pub fn unstable_features(experiments: &Experiments) -> BTreeMap<String, bool> {
// Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354) // Sticky events (https://github.com/matrix-org/matrix-spec-proposals/pull/4354)
// Proposal merged, expected for spec v1.20/v2.0 // Proposal merged, expected for spec v1.20/v2.0
("org.matrix.msc4354".to_owned(), true), ("org.matrix.msc4354".to_owned(), true),
// Delayed events (https://github.com/matrix-org/matrix-spec-proposals/pull/4140)
// Proposal merged, expected for spec v1.20/v2.0
("org.matrix.msc4140.stable".to_owned(), true),
]) ])
} }
+16
View File
@@ -543,4 +543,20 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "websessionid_session", name: "websessionid_session",
..descriptor::RANDOM_SMALL ..descriptor::RANDOM_SMALL
}, },
Descriptor {
name: "delayid_scheduleddelayedevent",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "delayid_finalizeddelayedevent",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "useriddelayid",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "useridfinalizedtsdelayid",
..descriptor::RANDOM_SMALL
},
]; ];
+1 -6
View File
@@ -49,13 +49,12 @@ assets = [
default = [ default = [
"standard", "standard",
"jemalloc", "jemalloc",
"aws_lc_rs", "ring",
"bindgen-runtime", # replace with bindgen-static on alpine "bindgen-runtime", # replace with bindgen-static on alpine
] ]
standard = [ standard = [
"brotli_compression", "brotli_compression",
"direct_tls", "direct_tls",
"element_hacks",
"gzip_compression", "gzip_compression",
"io_uring", "io_uring",
"jemalloc_conf", "jemalloc_conf",
@@ -86,10 +85,6 @@ console = [
direct_tls = [ direct_tls = [
"conduwuit-router/direct_tls" "conduwuit-router/direct_tls"
] ]
element_hacks = [
"conduwuit-service/element_hacks",
"conduwuit-router/element_hacks",
]
gzip_compression = [ gzip_compression = [
"conduwuit-core/gzip_compression", "conduwuit-core/gzip_compression",
"conduwuit-router/gzip_compression", "conduwuit-router/gzip_compression",
+1 -1
View File
@@ -43,7 +43,7 @@ pub fn run_with_args(args: &Args) -> Result<()> {
#[cfg(feature = "aws_lc_rs")] #[cfg(feature = "aws_lc_rs")]
rustls::crypto::aws_lc_rs::default_provider() rustls::crypto::aws_lc_rs::default_provider()
.install_default() .install_default()
.expect("failed to initialise aws_lc_rs rustls crypto provider"); .expect("failed to initialise ring rustls crypto provider");
#[cfg(all(feature = "ring", not(feature = "aws_lc_rs")))] #[cfg(all(feature = "ring", not(feature = "aws_lc_rs")))]
rustls::crypto::ring::default_provider() rustls::crypto::ring::default_provider()
-3
View File
@@ -27,9 +27,6 @@ direct_tls = [
"axum-server/tls-rustls-no-provider", "axum-server/tls-rustls-no-provider",
"dep:axum-server-dual-protocol", "dep:axum-server-dual-protocol",
] ]
element_hacks = [
"conduwuit-api/element_hacks",
]
gzip_compression = [ gzip_compression = [
"conduwuit-admin/gzip_compression", "conduwuit-admin/gzip_compression",
"conduwuit-api/gzip_compression", "conduwuit-api/gzip_compression",
+1 -2
View File
@@ -30,7 +30,6 @@ console = [
"dep:rustyline-async", "dep:rustyline-async",
"dep:termimad", "dep:termimad",
] ]
element_hacks = []
gzip_compression = [ gzip_compression = [
"conduwuit-core/gzip_compression", "conduwuit-core/gzip_compression",
"reqwest/gzip", "reqwest/gzip",
@@ -149,4 +148,4 @@ ignored = ["reqwest_0_12"]
[dev-dependencies] [dev-dependencies]
opentelemetry.workspace = true opentelemetry.workspace = true
rustls = { workspace = true, features = ["aws_lc_rs"] } rustls = { workspace = true, features = ["ring"] }
+596
View File
@@ -0,0 +1,596 @@
mod submission_queue;
use std::{
collections::BTreeMap,
fmt::Write,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::{Duration, SystemTime},
};
use async_trait::async_trait;
use conduwuit::{
Err, Error, Result, Server, debug_warn, err, error,
matrix::pdu::{PartialPdu, sticky},
utils::{
self, MutexMap,
stream::{ReadyExt, TryIgnore},
},
};
use database::{Deserialized, Ignore, Interfix, Json, Map};
use futures::StreamExt;
use http::StatusCode;
use loole::Sender;
use ruma::{
DeviceId, MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedTransactionId,
OwnedUserId, TransactionId, UserId,
api::{
client::delayed_events::{
DelayedEvent, DelayedEventCancelled, DelayedEventError, DelayedEventOutcome,
DelayedEventSent, FinalizedDelayedEvent as FinalizedDelayedEventData,
update_delayed_event::UpdateAction,
},
error::{ErrorKind, LimitExceededErrorData, RetryAfter, StandardErrorBody},
},
events::{AnyTimelineEventContent, TimelineEventType, sticky::StickyDurationMs},
serde::Raw,
};
use serde::{Deserialize, Serialize};
use submission_queue::{QueueUpdate, SubmissionQueue};
use tokio::sync::Mutex;
use crate::{Dep, config, rooms, transactions, users};
const DELAY_ID_LENGTH: usize = 32;
/// The retention limits for finalized delayed events recommended by MSC4140.
const FINALIZED_RETENTION: Duration = Duration::from_hours(7 * 24);
const MAX_FINALIZED_PER_USER: usize = 1000;
struct Data {
delayid_scheduleddelayedevent: Arc<Map>,
delayid_finalizeddelayedevent: Arc<Map>,
useriddelayid: Arc<Map>,
useridfinalizedtsdelayid: Arc<Map>,
}
struct Services {
server: Arc<Server>,
config: Dep<config::Service>,
state: Dep<rooms::state::Service>,
timeline: Dep<rooms::timeline::Service>,
transactions: Dep<transactions::Service>,
users: Dep<users::Service>,
}
pub struct Service {
db: Data,
services: Services,
/// Ensures each delayed event is only finalized once.
event_locks: MutexMap<String, ()>,
transaction_locks: MutexMap<OwnedUserId, ()>,
submission_queue: Mutex<SubmissionQueue>,
submission_queue_sender: Sender<QueueUpdate>,
interrupt: Sender<()>,
mem_usage: AtomicUsize,
}
#[async_trait]
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
let (sender, receiver) = loole::unbounded();
let (interrupt_sender, interrupt_receiver) = loole::bounded(1);
Ok(Arc::new(Self {
db: Data {
delayid_scheduleddelayedevent: args.db["delayid_scheduleddelayedevent"].clone(),
delayid_finalizeddelayedevent: args.db["delayid_finalizeddelayedevent"].clone(),
useriddelayid: args.db["useriddelayid"].clone(),
useridfinalizedtsdelayid: args.db["useridfinalizedtsdelayid"].clone(),
},
services: Services {
server: args.server.clone(),
config: args.depend::<config::Service>("config"),
state: args.depend::<rooms::state::Service>("rooms::state"),
timeline: args.depend::<rooms::timeline::Service>("rooms::timeline"),
transactions: args.depend::<transactions::Service>("transactions"),
users: args.depend::<users::Service>("users"),
},
event_locks: MutexMap::new(),
transaction_locks: MutexMap::new(),
submission_queue: Mutex::new(SubmissionQueue::new(receiver, interrupt_receiver)),
submission_queue_sender: sender,
interrupt: interrupt_sender,
mem_usage: AtomicUsize::new(0),
}))
}
async fn worker(self: Arc<Self>) -> Result { submission_queue::worker(&self).await }
fn interrupt(&self) { self.interrupt.try_send(()).ok(); }
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result {
let mem_usage = self.mem_usage.load(Ordering::Relaxed);
writeln!(out, "submission_queue: {mem_usage} bytes")?;
Ok(())
}
}
pub struct NewDelayedEvent {
pub room_id: OwnedRoomId,
pub event_type: TimelineEventType,
pub state_key: Option<String>,
pub content: Raw<AnyTimelineEventContent>,
pub delay: Duration,
pub timestamp: Option<MilliSecondsSinceUnixEpoch>,
pub sticky_duration_ms: Option<StickyDurationMs>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ScheduledDelayedEvent {
user_id: OwnedUserId,
room_id: OwnedRoomId,
event_type: TimelineEventType,
state_key: Option<String>,
content: Raw<AnyTimelineEventContent>,
delay: Duration,
delayed_since: SystemTime,
timestamp: Option<MilliSecondsSinceUnixEpoch>,
sticky_duration_ms: Option<StickyDurationMs>,
}
impl ScheduledDelayedEvent {
fn send_time(&self) -> SystemTime {
// Can't overflow on Unix, where SystemTime holds i64 seconds and the
// delay is at most u64::MAX milliseconds.
self.delayed_since
.checked_add(self.delay)
.expect("send time must not overflow SystemTime")
}
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
DelayedEvent::new(
delay_id,
self.room_id,
self.event_type,
self.state_key,
self.content,
self.delay,
MilliSecondsSinceUnixEpoch::from_system_time(self.delayed_since)
.unwrap_or_else(MilliSecondsSinceUnixEpoch::now),
)
}
}
#[derive(Debug, Serialize, Deserialize)]
struct FinalizedDelayedEvent {
event: ScheduledDelayedEvent,
finalized: FinalizedDelayedEventData,
}
impl FinalizedDelayedEvent {
fn into_delayed_event(self, delay_id: String) -> DelayedEvent {
let mut event = self.event.into_delayed_event(delay_id);
event.finalized = Some(self.finalized);
event
}
fn satisfies(&self, action: &UpdateAction) -> bool {
matches!(
(action, &self.finalized.outcome),
(UpdateAction::Send, DelayedEventOutcome::Sent(_))
| (
UpdateAction::Cancel,
DelayedEventOutcome::Cancelled(_) | DelayedEventOutcome::Error(_)
)
)
}
}
impl Service {
/// Returns the maximum delay users may request, or `None` if delayed events
/// are disabled.
#[must_use]
pub fn max_delay(&self) -> Option<Duration> {
let config = &self.services.config;
(config.delayed_events_max_delay_ms > 0 && config.delayed_events_max_scheduled > 0)
.then(|| Duration::from_millis(config.delayed_events_max_delay_ms))
}
/// Stores a new delayed event and queues it for sending, returning its
/// delay ID. Retries with the same transaction ID return the same delay ID.
pub async fn schedule(
&self,
user_id: &UserId,
device_id: Option<&DeviceId>,
txn_id: &TransactionId,
event: NewDelayedEvent,
) -> Result<String> {
let txn_id: OwnedTransactionId = format!("delayed_event/{txn_id}").into();
let _lock = self.transaction_locks.lock(user_id).await;
if let Ok(response) = self
.services
.transactions
.get_client_txn(user_id, device_id, &txn_id)
.await
{
return utils::string_from_bytes(&response)
.map_err(|e| err!(Database("Invalid delay ID in transaction data: {e}")));
}
self.check_scheduled_limit(user_id).await?;
let delay_id = utils::random_string(DELAY_ID_LENGTH);
let event = ScheduledDelayedEvent {
user_id: user_id.to_owned(),
room_id: event.room_id,
event_type: event.event_type,
state_key: event.state_key,
content: event.content,
delay: event.delay,
delayed_since: SystemTime::now(),
timestamp: event.timestamp,
sticky_duration_ms: event.sticky_duration_ms,
};
let send_time = event.send_time();
self.db
.delayid_scheduleddelayedevent
.raw_put(&delay_id, Json(&event));
self.db
.useriddelayid
.put_raw((user_id, delay_id.as_str()), []);
self.services.transactions.add_client_txnid(
user_id,
device_id,
&txn_id,
delay_id.as_bytes(),
);
self.submission_queue_sender
.send(QueueUpdate::Schedule(send_time, delay_id.clone()))
.map_err(|_| err!("The delayed events worker is not running"))?;
Ok(delay_id)
}
/// Returns `M_LIMIT_EXCEEDED` if the user already has the maximum number of
/// delayed events scheduled, with `Retry-After` set to when the next one is
/// due.
async fn check_scheduled_limit(&self, user_id: &UserId) -> Result {
let max_scheduled = usize::try_from(self.services.config.delayed_events_max_scheduled)
.unwrap_or(usize::MAX);
let send_times: Vec<SystemTime> = self
.user_delay_ids(user_id)
.filter_map(async |delay_id| {
self.get_scheduled(&delay_id)
.await
.map(|event| event.send_time())
})
.collect()
.await;
if send_times.len() < max_scheduled {
return Ok(());
}
let retry_after = send_times
.iter()
.min()
.and_then(|time| time.duration_since(SystemTime::now()).ok())
.unwrap_or_default();
let retry_after = Duration::from_secs(
retry_after
.as_millis()
// MSC4140 requires rounding up to the nearest second.
.div_ceil(1000)
.try_into()
.unwrap_or(u64::MAX),
);
let mut data = LimitExceededErrorData::new();
data.retry_after = Some(RetryAfter::Delay(retry_after));
Err(Error::Request(
ErrorKind::LimitExceeded(data),
"The maximum number of delayed events has been reached.".into(),
StatusCode::TOO_MANY_REQUESTS,
))
}
/// Restarts, sends or cancels one of the user's delayed events. Repeating
/// an action on an event that was already finalized the same way succeeds,
/// and conflicting actions return 409.
pub async fn update(&self, user_id: &UserId, delay_id: &str, action: UpdateAction) -> Result {
let _lock = self.event_locks.lock(delay_id).await;
if let Some(mut event) = self.get_scheduled(delay_id).await {
if event.user_id != user_id {
return Err!(Request(NotFound("No delayed event with this ID was found.")));
}
return match action {
| UpdateAction::Restart => {
event.delayed_since = SystemTime::now();
self.db
.delayid_scheduleddelayedevent
.raw_put(delay_id, Json(&event));
self.queue(QueueUpdate::Schedule(event.send_time(), delay_id.to_owned()));
Ok(())
},
| UpdateAction::Send => {
// On error, the event stays scheduled, as recommended by
// MSC4140.
let event_id = self.send(delay_id, &event).await?;
self.finalize(
delay_id,
event,
DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
)
.await;
Ok(())
},
| UpdateAction::Cancel => {
self.finalize(
delay_id,
event,
DelayedEventOutcome::Cancelled(DelayedEventCancelled::new()),
)
.await;
Ok(())
},
| _ => Err!(Request(InvalidParam("Unknown delayed event action."))),
};
}
match self.get_finalized(delay_id).await {
| Some(finalized) if finalized.event.user_id == user_id =>
if finalized.satisfies(&action) {
Ok(())
} else {
Err(Error::Request(
ErrorKind::Unknown,
"The delayed event has already been finalized with a different outcome."
.into(),
StatusCode::CONFLICT,
))
},
| _ => Err!(Request(NotFound("No delayed event with this ID was found."))),
}
}
/// Returns one of the user's delayed events, whether scheduled or
/// finalized.
pub async fn get(&self, user_id: &UserId, delay_id: &str) -> Result<DelayedEvent> {
if let Some(event) = self.get_scheduled(delay_id).await
&& event.user_id == user_id
{
return Ok(event.into_delayed_event(delay_id.to_owned()));
}
if let Some(finalized) = self.get_finalized(delay_id).await
&& finalized.event.user_id == user_id
{
return Ok(finalized.into_delayed_event(delay_id.to_owned()));
}
Err!(Request(NotFound("No delayed event with this ID was found.")))
}
/// Removes a user's scheduled delayed events without keeping them for
/// lookup, for account deactivation.
pub async fn remove_all_for_user(&self, user_id: &UserId) {
self.user_delay_ids(user_id)
.for_each(async |delay_id| {
let _lock = self.event_locks.lock(delay_id.as_str()).await;
self.db
.delayid_scheduleddelayedevent
.remove(delay_id.as_str());
self.db.useriddelayid.del((user_id, delay_id.as_str()));
self.queue(QueueUpdate::Remove(delay_id));
})
.await;
}
/// Updates the worker's submission queue. This only fails if the worker has
/// stopped, and it rebuilds the queue from the database when it starts.
fn queue(&self, update: QueueUpdate) { self.submission_queue_sender.send(update).ok(); }
/// Sends the delayed event if it is due, otherwise requeues it for its send
/// time. Called by the worker, which records any error on the finalized
/// event as there is no client to return it to.
async fn send_if_due(&self, delay_id: &str) {
let _lock = self.event_locks.lock(delay_id).await;
let Some(event) = self.get_scheduled(delay_id).await else {
return;
};
let send_time = event.send_time();
if send_time > SystemTime::now() {
self.queue(QueueUpdate::Schedule(send_time, delay_id.to_owned()));
return;
}
let outcome = match self.send(delay_id, &event).await {
| Ok(event_id) => DelayedEventOutcome::Sent(DelayedEventSent::new(event_id)),
| Err(error) => {
debug_warn!(%delay_id, %error, "Failed to send delayed event");
let error = StandardErrorBody::new(error.kind(), error.message());
DelayedEventOutcome::Error(DelayedEventError::new(error))
},
};
self.finalize(delay_id, event, outcome).await;
}
/// Sends the delayed event into its room with the same checks as a normal
/// send, using the room state at the time of sending.
async fn send(&self, delay_id: &str, event: &ScheduledDelayedEvent) -> Result<OwnedEventId> {
if self.services.users.is_suspended(&event.user_id).await? {
return Err!(Request(UserSuspended(
"You cannot perform this action while suspended."
)));
}
let content = event.content.clone().into_json();
let redacts = (event.event_type == TimelineEventType::RoomRedaction)
.then(|| serde_json::from_str::<MaybeRedaction>(content.get()).ok())
.flatten()
.and_then(|redaction| redaction.redacts);
let mut unsigned = BTreeMap::new();
unsigned.insert("delay_id".to_owned(), delay_id.into());
let partial_pdu = PartialPdu {
event_type: event.event_type.clone(),
content,
state_key: event.state_key.clone().map(Into::into),
timestamp: event.timestamp,
sticky: event.sticky_duration_ms.map(sticky::object),
unsigned: Some(unsigned),
redacts,
};
let state_lock = self.services.state.mutex.lock(&event.room_id).await;
self.services
.timeline
.send_timeline_event(partial_pdu, &event.user_id, &event.room_id, &state_lock)
.await
}
/// Moves a scheduled delayed event to the finalized events, where it can
/// still be looked up until it is pruned.
async fn finalize(
&self,
delay_id: &str,
event: ScheduledDelayedEvent,
outcome: DelayedEventOutcome,
) {
let user_id = event.user_id.clone();
let finalized_ts = MilliSecondsSinceUnixEpoch::now();
// The finalized event is written before the scheduled one is removed,
// so it isn't lost if the server stops in between.
self.db.delayid_finalizeddelayedevent.raw_put(
delay_id,
Json(FinalizedDelayedEvent {
event,
finalized: FinalizedDelayedEventData::new(outcome, finalized_ts),
}),
);
self.db
.useridfinalizedtsdelayid
.put_raw((&user_id, u64::from(finalized_ts.get()), delay_id), []);
self.db.useriddelayid.del((&user_id, delay_id));
self.db.delayid_scheduleddelayedevent.remove(delay_id);
self.queue(QueueUpdate::Remove(delay_id.to_owned()));
self.limit_finalized(&user_id).await;
}
/// Removes the user's oldest finalized delayed events beyond
/// [`MAX_FINALIZED_PER_USER`].
async fn limit_finalized(&self, user_id: &UserId) {
let prefix = (user_id, Interfix);
let count = self
.db
.useridfinalizedtsdelayid
.keys_prefix_raw(&prefix)
.count()
.await;
self.db
.useridfinalizedtsdelayid
.keys_prefix(&prefix)
.ignore_err()
.take(count.saturating_sub(MAX_FINALIZED_PER_USER))
.ready_for_each(|(_, finalized_ts, delay_id): (Ignore, u64, &str)| {
self.remove_finalized(user_id, finalized_ts, delay_id);
})
.await;
}
fn remove_finalized(&self, user_id: &UserId, finalized_ts: u64, delay_id: &str) {
self.db
.useridfinalizedtsdelayid
.del((user_id, finalized_ts, delay_id));
self.db.delayid_finalizeddelayedevent.remove(delay_id);
}
/// Removes finalized delayed events older than [`FINALIZED_RETENTION`].
/// Called periodically by the worker. Only the index keys are scanned, so
/// the events themselves are never deserialized.
async fn prune_finalized(&self) {
let Some(cutoff) = SystemTime::now()
.checked_sub(FINALIZED_RETENTION)
.and_then(MilliSecondsSinceUnixEpoch::from_system_time)
else {
return;
};
let cutoff = u64::from(cutoff.get());
self.db
.useridfinalizedtsdelayid
.keys::<(OwnedUserId, u64, &str)>()
.ignore_err()
.ready_filter(|(_, finalized_ts, _)| *finalized_ts < cutoff)
.ready_for_each(|(user_id, finalized_ts, delay_id)| {
self.remove_finalized(&user_id, finalized_ts, delay_id);
})
.await;
}
async fn get_scheduled(&self, delay_id: &str) -> Option<ScheduledDelayedEvent> {
self.db
.delayid_scheduleddelayedevent
.get(delay_id)
.await
.deserialized()
.inspect_err(|e| {
if !e.is_not_found() {
error!(%delay_id, "Invalid scheduled delayed event in the database: {e}");
}
})
.ok()
}
async fn get_finalized(&self, delay_id: &str) -> Option<FinalizedDelayedEvent> {
self.db
.delayid_finalizeddelayedevent
.get(delay_id)
.await
.deserialized()
.inspect_err(|e| {
if !e.is_not_found() {
error!(%delay_id, "Invalid finalized delayed event in the database: {e}");
}
})
.ok()
}
/// Streams the delay IDs of the user's scheduled delayed events.
fn user_delay_ids<'a>(
&'a self,
user_id: &'a UserId,
) -> impl futures::Stream<Item = String> + Send + 'a {
self.db
.useriddelayid
.keys_prefix(&(user_id, Interfix))
.ignore_err()
.map(|(_, delay_id): (Ignore, &str)| delay_id.to_owned())
}
}
#[derive(Deserialize)]
struct MaybeRedaction {
redacts: Option<OwnedEventId>,
}
@@ -0,0 +1,130 @@
use std::{
collections::{BTreeSet, HashMap},
sync::{Arc, atomic::Ordering},
time::{Duration, SystemTime},
};
use conduwuit::{Result, utils::stream::TryIgnore};
use futures::StreamExt;
use loole::Receiver;
use tokio::{
select,
time::{MissedTickBehavior, interval, sleep},
};
use super::{DELAY_ID_LENGTH, ScheduledDelayedEvent, Service};
const PRUNE_INTERVAL: Duration = Duration::from_hours(1);
pub(super) enum QueueUpdate {
/// Queues the delayed event to be sent at the given time, replacing any
/// existing entry for it.
Schedule(SystemTime, String),
/// Removes a delayed event that was finalized before it was due.
Remove(String),
}
pub(super) struct SubmissionQueue {
receiver: Receiver<QueueUpdate>,
interrupt: Receiver<()>,
queue: BTreeSet<(SystemTime, String)>,
send_times: HashMap<String, SystemTime>,
}
impl SubmissionQueue {
pub(super) fn new(receiver: Receiver<QueueUpdate>, interrupt: Receiver<()>) -> Self {
Self {
receiver,
interrupt,
queue: BTreeSet::new(),
send_times: HashMap::new(),
}
}
fn schedule(&mut self, time: SystemTime, delay_id: String) {
if let Some(old_time) = self.send_times.insert(delay_id.clone(), time) {
self.queue.remove(&(old_time, delay_id.clone()));
}
self.queue.insert((time, delay_id));
}
fn remove(&mut self, delay_id: String) {
if let Some(time) = self.send_times.remove(&delay_id) {
self.queue.remove(&(time, delay_id));
}
}
fn pop(&mut self) -> Option<String> {
let (_, delay_id) = self.queue.pop_first()?;
self.send_times.remove(&delay_id);
Some(delay_id)
}
}
pub(super) async fn worker(service: &Arc<Service>) -> Result {
let mut queue = service
.submission_queue
.try_lock()
.expect("only one delayed events worker should be running");
let receiver = queue.receiver.clone();
let interrupt = queue.interrupt.clone();
let scheduled: Vec<_> = service
.db
.delayid_scheduleddelayedevent
.stream::<'_, &str, ScheduledDelayedEvent>()
.ignore_err()
.map(|(delay_id, event)| (event.send_time(), delay_id.to_owned()))
.collect()
.await;
for (time, delay_id) in scheduled {
queue.schedule(time, delay_id);
}
let mut prune = interval(PRUNE_INTERVAL);
prune.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
let mem_usage = queue.queue.len().saturating_mul(
// Each delay ID and send time is stored in both the queue and the
// index.
DELAY_ID_LENGTH
.saturating_add(size_of::<SystemTime>())
.saturating_mul(2),
);
service.mem_usage.store(mem_usage, Ordering::Relaxed);
let next_due = async {
let (time, _) = queue.queue.first()?;
if let Ok(wait) = time.duration_since(SystemTime::now()) {
sleep(wait).await;
}
queue.pop()
};
// All of these are cancellation-safe
select! {
Some(delay_id) = next_due => {
// Sent in the background so one slow room doesn't hold up the others.
let task_service = service.clone();
service.services.server.runtime().spawn(async move {
task_service.send_if_due(&delay_id).await;
});
},
Ok(update) = receiver.recv_async() => match update {
| QueueUpdate::Schedule(time, delay_id) => queue.schedule(time, delay_id),
| QueueUpdate::Remove(delay_id) => queue.remove(delay_id),
},
_ = prune.tick() => {
let task_service = service.clone();
service.services.server.runtime().spawn(async move {
task_service.prune_finalized().await;
});
},
_ = interrupt.recv_async() => break,
}
}
Ok(())
}
+1 -2
View File
@@ -75,8 +75,7 @@ impl Service {
"lazy loading should be enabled by your options" "lazy loading should be enabled by your options"
); );
let include_redundant = cfg!(feature = "element_hacks") let include_redundant = ctx.options.is_some_and(Options::include_redundant_members);
|| ctx.options.is_some_and(Options::include_redundant_members);
let witness = self let witness = self
.witness(ctx, senders.iter().map(AsRef::as_ref)) .witness(ctx, senders.iter().map(AsRef::as_ref))
+2
View File
@@ -1,5 +1,6 @@
pub mod alias; pub mod alias;
pub mod auth_chain; pub mod auth_chain;
pub mod delayed_events;
pub mod directory; pub mod directory;
pub mod event_handler; pub mod event_handler;
pub mod lazy_loading; pub mod lazy_loading;
@@ -26,6 +27,7 @@ pub struct Service {
pub alias: Arc<alias::Service>, pub alias: Arc<alias::Service>,
pub auth_chain: Arc<auth_chain::Service>, pub auth_chain: Arc<auth_chain::Service>,
pub directory: Arc<directory::Service>, pub directory: Arc<directory::Service>,
pub delayed_events: Arc<delayed_events::Service>,
pub event_handler: Arc<event_handler::Service>, pub event_handler: Arc<event_handler::Service>,
pub lazy_loading: Arc<lazy_loading::Service>, pub lazy_loading: Arc<lazy_loading::Service>,
pub membership: Arc<membership::Service>, pub membership: Arc<membership::Service>,
+32 -32
View File
@@ -2,13 +2,13 @@
pub(crate) use conduwuit::{ pub(crate) use conduwuit::{
Err, Event, Result, err, Err, Event, Result, err,
matrix::pdu::{PartialPdu, UnsignedContext, sticky}, matrix::pdu::{PartialPdu, UnsignedContext},
trace, trace,
}; };
use ruma::{ use ruma::{
MilliSecondsSinceUnixEpoch, OwnedEventId, RoomId, UserId, OwnedEventId, RoomId, UserId,
events::{ events::{
AnyStateEventContent, AnyTimelineEvent, StateEventType, AnyStateEventContent, AnyTimelineEvent, MessageLikeEventType, StateEventType,
room::{ room::{
canonical_alias::RoomCanonicalAliasEventContent, canonical_alias::RoomCanonicalAliasEventContent,
history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent}, history_visibility::{HistoryVisibility, RoomHistoryVisibilityEventContent},
@@ -16,7 +16,6 @@ use ruma::{
member::RoomMemberEventContent, member::RoomMemberEventContent,
server_acl::RoomServerAclEventContent, server_acl::RoomServerAclEventContent,
}, },
sticky::StickyDurationMs,
}, },
serde::Raw, serde::Raw,
}; };
@@ -24,42 +23,43 @@ use ruma::{
use crate::rooms::state::RoomMutexGuard; use crate::rooms::state::RoomMutexGuard;
impl super::Service { impl super::Service {
#[allow(clippy::too_many_arguments)] /// Checks that a local user may send an event, then sends it.
pub async fn send_state_event_for_key( pub async fn send_timeline_event(
&self, &self,
mut partial_pdu: PartialPdu,
sender: &UserId, sender: &UserId,
room_id: &RoomId, room_id: &RoomId,
state_lock: &RoomMutexGuard, state_lock: &RoomMutexGuard,
event_type: &StateEventType,
content: &Raw<AnyStateEventContent>,
state_key: &str,
sticky_duration_ms: Option<StickyDurationMs>,
timestamp: Option<MilliSecondsSinceUnixEpoch>,
) -> Result<OwnedEventId> { ) -> Result<OwnedEventId> {
let content: Raw<AnyStateEventContent> = content.clone(); if let Some(state_key) = &partial_pdu.state_key {
self.assert_allowed_to_send_state_event(room_id, event_type, state_key, &content) let content = Raw::<AnyStateEventContent>::from_json(partial_pdu.content);
.await?; self.assert_allowed_to_send_state_event(
room_id,
let content = serde_json::from_str(content.json().get()) &partial_pdu.event_type.to_string().into(),
.map_err(|e| err!(Request(BadJson("Invalid JSON body: {e}"))))?; state_key,
&content,
let event_id = self
.build_and_append_pdu(
PartialPdu {
event_type: event_type.to_string().into(),
content,
sticky: sticky_duration_ms.map(sticky::object),
state_key: Some(state_key.into()),
timestamp,
..Default::default()
},
sender,
Some(room_id),
state_lock,
) )
.await?; .await?;
partial_pdu.content = content.into_json();
} else {
self.assert_allowed_to_send_message_event(
&partial_pdu.event_type.to_string().into(),
)?;
}
Ok(event_id) self.build_and_append_pdu(partial_pdu, sender, Some(room_id), state_lock)
.await
}
fn assert_allowed_to_send_message_event(&self, event_type: &MessageLikeEventType) -> Result {
// Forbid m.room.encrypted if encryption is disabled
if *event_type == MessageLikeEventType::RoomEncrypted
&& !self.services.config.allow_encryption
{
return Err!(Request(Forbidden("Encryption has been disabled")));
}
Ok(())
} }
async fn assert_allowed_to_send_state_event( async fn assert_allowed_to_send_state_event(
+1
View File
@@ -94,6 +94,7 @@ impl Services {
rooms: rooms::Service { rooms: rooms::Service {
alias: build!(rooms::alias::Service), alias: build!(rooms::alias::Service),
auth_chain: build!(rooms::auth_chain::Service), auth_chain: build!(rooms::auth_chain::Service),
delayed_events: build!(rooms::delayed_events::Service),
directory: build!(rooms::directory::Service), directory: build!(rooms::directory::Service),
event_handler: build!(rooms::event_handler::Service), event_handler: build!(rooms::event_handler::Service),
lazy_loading: build!(rooms::lazy_loading::Service), lazy_loading: build!(rooms::lazy_loading::Service),
+1 -1
View File
@@ -19,7 +19,7 @@ pub(crate) async fn test_services() -> TestServices { test_services_with(json!({
pub(crate) async fn test_services_with(overrides: serde_json::Value) -> TestServices { pub(crate) async fn test_services_with(overrides: serde_json::Value) -> TestServices {
let guard = DATABASE.lock().await; let guard = DATABASE.lock().await;
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); let _ = rustls::crypto::ring::default_provider().install_default();
let path = std::env::temp_dir() let path = std::env::temp_dir()
.join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>())); .join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>()));
std::fs::create_dir(&path).unwrap(); std::fs::create_dir(&path).unwrap();
+6
View File
@@ -466,6 +466,12 @@ impl super::Service {
// Mark user as deactivated // Mark user as deactivated
self.db.userid_deactivated.insert(user_id, ""); self.db.userid_deactivated.insert(user_id, "");
// Delayed events must not be sent after deactivation
self.services
.delayed_events
.remove_all_for_user(user_id)
.await;
// TODO: Unhook 3PID // TODO: Unhook 3PID
Ok(()) Ok(())
} }
+3
View File
@@ -57,6 +57,7 @@ struct Services {
alias: Dep<alias::Service>, alias: Dep<alias::Service>,
appservice: Dep<appservice::Service>, appservice: Dep<appservice::Service>,
config: Dep<config::Service>, config: Dep<config::Service>,
delayed_events: Dep<rooms::delayed_events::Service>,
firstrun: Dep<firstrun::Service>, firstrun: Dep<firstrun::Service>,
globals: Dep<globals::Service>, globals: Dep<globals::Service>,
membership: Dep<membership::Service>, membership: Dep<membership::Service>,
@@ -110,6 +111,8 @@ impl crate::Service for Service {
alias: args.depend::<alias::Service>("rooms::alias"), alias: args.depend::<alias::Service>("rooms::alias"),
appservice: args.depend::<appservice::Service>("appservice"), appservice: args.depend::<appservice::Service>("appservice"),
config: args.depend::<config::Service>("config"), config: args.depend::<config::Service>("config"),
delayed_events: args
.depend::<rooms::delayed_events::Service>("rooms::delayed_events"),
firstrun: args.depend::<firstrun::Service>("firstrun"), firstrun: args.depend::<firstrun::Service>("firstrun"),
globals: args.depend::<globals::Service>("globals"), globals: args.depend::<globals::Service>("globals"),
membership: args.depend::<membership::Service>("rooms::membership"), membership: args.depend::<membership::Service>("rooms::membership"),