Compare commits

..
Author SHA1 Message Date
Renovate Bot ac7f8f6b9f chore(deps): update rust crate built to 0.9 2026-11-22 05:02:54 +00:00
29 changed files with 236 additions and 1103 deletions

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
name: Renovate
runs-on: ubuntu-latest
container:
image: ghcr.io/renovatebot/renovate:44.257.9@sha256:578179439fceea89646662dd583b27efdad8d1429e0cbd90681c40dde068589e
image: ghcr.io/renovatebot/renovate:44.241.0@sha256:22d22b4ca7d768b5b469309d34379783bf91cd94a58faecf1cd0f4528a65d21c
options: --tmpfs /tmp:exec
steps:
- name: Checkout
Generated
+3 -4
View File
@@ -497,7 +497,7 @@ dependencies = [
"regex",
"rustc-hash",
"shlex",
"syn 2.0.119",
"syn 3.0.10",
]
[[package]]
@@ -574,9 +574,9 @@ dependencies = [
[[package]]
name = "built"
version = "0.8.1"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
checksum = "6192709ebc97997197804bcbb092ef897b5a6a2f33e2c77779f694dbe90fec1e"
[[package]]
name = "bumpalo"
@@ -1127,7 +1127,6 @@ dependencies = [
"log",
"loole",
"lru-cache",
"mime",
"nonzero_ext",
"openidconnect",
"opentelemetry",
-3
View File
@@ -589,9 +589,6 @@ version = "0.10.4"
default-features = false
features = ["std"]
[workspace.dependencies.mime]
version = "0.3.18"
[workspace.dependencies.nonzero_ext]
version = "0.3.0"
-1
View File
@@ -1 +0,0 @@
URL previews no longer completely fail if downloading auxiliary content (images/videos/audio) fails. Contributed by @nex.
-1
View File
@@ -1 +0,0 @@
Network issues while refreshing an access token will no longer cause OAuth-compatible clients to be forcibly logged out. Contributed by @ginger.
-1
View File
@@ -1 +0,0 @@
Fix outgoing federation stalling after a sender worker panics. Contributed by @eleboucher.
-3
View File
@@ -71,9 +71,6 @@ Names below are as they appear in Prometheus. OTLP uses the dotted OpenTelemetry
| `continuwuity_sender_events_total` | counter | `destination`, `kind`, `outcome` | PDUs and EDUs sent in outgoing transactions |
| `continuwuity_sender_events_queued_total` | counter | `destination`, `kind` | PDUs and EDUs queued for sending |
| `continuwuity_sender_queue_depth` | gauge | | Messages waiting for the sender workers |
| `continuwuity_sender_requests` | gauge | `state` | Estimated outgoing requests stored as `queued` or `active` (in flight) |
| `continuwuity_sender_workers` | gauge | | Running sender workers; below the configured count means a worker is restarting |
| `continuwuity_sender_panics_total` | counter | `scope` | Panics caught in a single outgoing `transaction` or a whole sender `worker` |
| `continuwuity_users` | gauge | `origin` | Known `local` users, including deactivated, and `remote` users |
| `continuwuity_invites_total` | counter | `direction`, `destination`, `outcome` | Invites sent by local users or received over federation |
| `continuwuity_media_write_size_bytes` | histogram | `origin` | Media files written, from local uploads or cached remote media |
+1 -3
View File
@@ -2,7 +2,7 @@ use std::time::Duration;
use axum::extract::State;
use conduwuit::{
Err, Result, debug, err,
Err, Result, err,
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
};
use conduwuit_core::error;
@@ -219,12 +219,10 @@ pub(crate) async fn get_media_preview_route(
)));
}
debug!("Fetching a URL preview for {url} on behalf of {sender_user}");
let preview = services
.media
.get_url_preview(&url)
.await
.inspect(|_| debug!(user=%sender_user, %url, "Finished fetching a URL preview"))
.map_err(|error| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}")
+6 -22
View File
@@ -319,19 +319,6 @@ async fn check_access_token(
));
}
let session_info = services
.oauth
.get_session_info_for_device(&sender_user, &sender_device)
.await;
if let Some(session_info) = &session_info {
services.oauth.clear_previous_refresh_token(
&sender_user,
&sender_device,
session_info,
);
}
// Locked users can only use /logout and /logout/all
if services
.users
@@ -346,6 +333,12 @@ async fn check_access_token(
}
}
let session_info = services
.oauth
.get_session_info_for_device(&sender_user, &sender_device)
.await
.map(Box::new);
// Make sure the user has the right scopes to use the route
let mut user_scopes = if let Some(session_info) = &session_info {
session_info.scopes()
@@ -423,15 +416,6 @@ async fn check_access_token(
sender_device,
appservice_info: Box::new(appservice_info),
})
} else if services.users.is_previous_token(token).await {
// Return a soft-logout for previous tokens. This is necessary
// to make token refreshing idempotent.
Err(Error::Request(
ErrorKind::UnknownToken(assign!(UnknownTokenErrorData::new(), { soft_logout: true })),
"This token has expired".into(),
StatusCode::UNAUTHORIZED,
))
} else {
Err(Error::Request(
ErrorKind::UnknownToken(UnknownTokenErrorData::new()),
+1 -1
View File
@@ -27,7 +27,7 @@ crate-type = [
[dependencies]
[build-dependencies]
built = { version = "0.8", features = [] }
built = { version = "0.9", features = [] }
cargo_metadata = { version = "0.23.1" }
[lints]
workspace = true
-6
View File
@@ -21,7 +21,6 @@ pub struct Instruments {
pub sender_transaction_duration: Histogram<f64>,
pub sender_events: Counter<u64>,
pub sender_events_queued: Counter<u64>,
pub sender_panics: Counter<u64>,
pub media_write_size: Histogram<u64>,
pub media_read_size: Histogram<u64>,
@@ -117,11 +116,6 @@ impl Instruments {
.with_description("PDUs and EDUs queued for sending")
.with_unit("{event}")
.build(),
sender_panics: meter
.u64_counter("continuwuity.sender.panics")
.with_description("Panics caught in outgoing transactions and sender workers")
.with_unit("{panic}")
.build(),
media_write_size: size(
"continuwuity.media.write.size",
-4
View File
@@ -407,10 +407,6 @@ pub(super) static MAPS: &[Descriptor] = &[
name: "userdeviceid_token",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userdeviceid_previoustoken",
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userdevicesessionid_uiaainfo",
..descriptor::RANDOM_SMALL
-1
View File
@@ -105,7 +105,6 @@ itertools.workspace = true
log.workspace = true
loole.workspace = true
lru-cache.workspace = true
mime.workspace = true
nonzero_ext.workspace = true
p256.workspace = true
regex.workspace = true
+1 -1
View File
@@ -111,7 +111,7 @@ impl crate::Service for Service {
.local_address(url_preview_bind_addr)
.timeout(Duration::from_secs(config.url_preview_timeout))
.redirect(redirect::Policy::limited(3))
.user_agent(url_preview_user_agent.replace("<version>", conduwuit::version_ua()))
.user_agent(url_preview_user_agent)
.build()?,
external_resource: base(config, reqwest_dns_resolver.clone())?
-7
View File
@@ -223,8 +223,6 @@ impl Data {
x => x,
};*/
// TODO(nex): Oh my god this is awful when can we kill it
let title = match values
.next()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
@@ -323,11 +321,6 @@ impl Data {
video_height,
audio,
audio_size,
..Default::default() /* TODO(nex,silversys): This weird manual field
* de/serialisation just needs replacing with JSON storage to
* avoid this mess. This is consequently intentionally
* dropping information added later (like image alt text).
* I'll do it later. */
})
}
}
+90 -345
View File
@@ -7,79 +7,29 @@
use std::time::SystemTime;
#[cfg(feature = "url_preview")]
use conduwuit::info;
use conduwuit::{Err, Result, debug, err, utils::response::LimitReadExt};
use ipaddress::IPAddress;
use mime::Mime;
use ruma::OwnedMxcUri;
use serde::{Serialize, Serializer};
use serde::Serialize;
use url::Url;
use super::Service;
use crate::media::mxc::Mxc;
// serde `serialize_with` passes `&Option<T>` for `Option<T>` fields.
#[allow(clippy::ref_option)]
fn serialize_mime<S: Serializer>(mime: &Option<Mime>, serializer: S) -> Result<S::Ok, S::Error> {
match mime {
| Some(m) => serializer.serialize_str(m.as_ref()),
| None => serializer.serialize_none(),
}
}
#[derive(Serialize, Default, Debug)]
#[derive(Serialize, Default)]
pub struct UrlPreviewData {
// From https://ogp.me/
/// The title of your object as it should appear within the graph
/// "The Rock".
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:title"))]
pub title: Option<String>,
/// The type of your object, e.g., "video.movie".
#[serde(skip_serializing_if = "String::is_empty", rename(serialize = "og:type"))]
pub site_type: String,
/// The canonical URL of your object that will be used as its permanent ID
/// in the graph.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:url"))]
pub url: Option<String>,
/// A one to two sentence description of your object.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:description"))]
pub description: Option<String>,
/// The word that appears before this object's title in a sentence.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:determiner"))]
pub determiner: Option<String>,
/// The locale these tags are marked up in
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:locale"))]
pub locale: Option<String>,
/// If your object is part of a larger web site, the name which should be
/// displayed for the overall site.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:site_name"))]
pub site_name: Option<String>,
/// An image URL which should represent your object within the graph.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image"))]
pub image: Option<String>,
/// A MIME type for this image.
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_mime",
rename(serialize = "og:image:type")
)]
pub image_type: Option<Mime>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:image:size"))]
pub image_size: Option<usize>,
/// The number of pixels wide.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:width"))]
pub image_width: Option<u32>,
/// The number of pixels high.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:height"))]
pub image_height: Option<u32>,
/// A description of what is in the image (not a caption).
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:image:alt"))]
pub image_alt: Option<String>,
/// A URL to a video file that complements this object.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video"))]
pub video: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:video:size"))]
@@ -88,15 +38,6 @@ pub struct UrlPreviewData {
pub video_width: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:height"))]
pub video_height: Option<u32>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_mime",
rename(serialize = "og:video:type")
)]
pub video_type: Option<Mime>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:video:alt"))]
pub video_alt: Option<String>,
/// A URL to an audio file to accompany this object.
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "og:audio"))]
pub audio: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename(serialize = "matrix:audio:size"))]
@@ -137,39 +78,43 @@ impl Service {
}
async fn request_url_preview(&self, url: &Url) -> Result<UrlPreviewData> {
self.check_url_ip(url.as_str())?;
if let Ok(ip) = IPAddress::parse(url.host_str().expect("URL previously validated")) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
let client = &self.services.client.url_preview;
let response = client.head(url.as_str()).send().await?;
debug!(%url, "URL preview response headers: {:?}", response.headers());
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown(
"URL preview request returned HTTP {}",
response.status()
)));
if let Some(remote_addr) = response.remote_addr() {
debug!(%url, "URL preview response remote address: {:?}", remote_addr);
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
}
let Some(content_type) = response.headers().get(reqwest::header::CONTENT_TYPE) else {
return Err!(Request(Unknown(
"Response contains unknown, invalid, or missing Content-Type header"
)));
return Err!(Request(Unknown("Unknown or invalid Content-Type header")));
};
let content_type: Mime = content_type
let content_type = content_type
.to_str()
.map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?
.parse()
.map_err(|e| err!(Request(Unknown("Unknown or invalid Content-Type header: {e}"))))?;
let data = match (content_type.type_(), content_type.subtype()) {
| (mime::TEXT, mime::HTML) => self.download_html(url.as_str()).await?,
| (mime::IMAGE, _) => self.download_image(url.as_str()).await?,
| (mime::VIDEO, _) => self.download_video(url.as_str()).await?,
| (mime::AUDIO, _) => self.download_audio(url.as_str()).await?,
| _ => return Err!(Request(Unknown("Unsupported Content-Type: {content_type}"))),
let data = match content_type {
| html if html.starts_with("text/html") => self.download_html(url.as_str()).await?,
| img if img.starts_with("image/") => self.download_image(url.as_str(), None).await?,
| video if video.starts_with("video/") =>
self.download_video(url.as_str(), None).await?,
| audio if audio.starts_with("audio/") =>
self.download_audio(url.as_str(), None).await?,
| _ => return Err!(Request(Unknown("Unsupported Content-Type"))),
};
self.set_url_preview(url.as_str(), &data).await?;
@@ -178,16 +123,19 @@ impl Service {
}
#[cfg(feature = "url_preview")]
pub async fn download_image(&self, url: &str) -> Result<UrlPreviewData> {
pub async fn download_image(
&self,
url: &str,
preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
use conduwuit::utils::random_string;
use image::ImageReader;
let mut preview_data = UrlPreviewData::default();
use crate::media::mxc::Mxc;
self.check_url_ip(url)?;
let mut preview_data = preview_data.unwrap_or_default();
let response = self.services.client.url_preview.get(url).send().await?;
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown("Image download returned HTTP {}", response.status())));
}
@@ -209,13 +157,13 @@ impl Service {
.ok_or_else(|| err!(Request(Unknown("Downloaded file is not a supported image"))))?
.to_mime_type();
let (width, height) = reader.into_dimensions().map_err(|error| {
err!(Request(Unknown("Failed to read preview image dimensions: {error}")))
})?;
preview_data.image_width = Some(width);
preview_data.image_height = Some(height);
preview_data.image_size = Some(image.len());
preview_data.image_type = content_type.parse().ok();
if preview_data.image_height.is_none() || preview_data.image_width.is_none() {
let (width, height) = reader.into_dimensions().map_err(|error| {
err!(Request(Unknown("Failed to read preview image dimensions: {error}")))
})?;
preview_data.image_width.get_or_insert(width);
preview_data.image_height.get_or_insert(height);
}
let mxc = Mxc {
server_name: self.services.globals.server_name(),
@@ -231,9 +179,12 @@ impl Service {
}
#[cfg(feature = "url_preview")]
#[tracing::instrument(skip(self))]
pub async fn download_video(&self, url: &str) -> Result<UrlPreviewData> {
let mut preview_data = UrlPreviewData::default();
pub async fn download_video(
&self,
url: &str,
preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
let mut preview_data = preview_data.unwrap_or_default();
if self.services.globals.url_preview_allow_audio_video() {
let (url, size) = self.download_media(url).await?;
@@ -245,9 +196,12 @@ impl Service {
}
#[cfg(feature = "url_preview")]
#[tracing::instrument(skip(self))]
pub async fn download_audio(&self, url: &str) -> Result<UrlPreviewData> {
let mut preview_data = UrlPreviewData::default();
pub async fn download_audio(
&self,
url: &str,
preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
let mut preview_data = preview_data.unwrap_or_default();
if self.services.globals.url_preview_allow_audio_video() {
let (url, size) = self.download_media(url).await?;
@@ -258,18 +212,11 @@ impl Service {
Ok(preview_data)
}
#[tracing::instrument(skip(self))]
pub async fn download_media(&self, url: &str) -> Result<(OwnedMxcUri, usize)> {
use conduwuit::utils::random_string;
use http::header::CONTENT_TYPE;
self.check_url_ip(url)?;
let response = self.services.client.url_preview.get(url).send().await?;
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown("Media download returned HTTP {}", response.status())));
}
let content_type = response.headers().get(CONTENT_TYPE).cloned();
let media = response
.limit_read(
@@ -295,32 +242,41 @@ impl Service {
}
#[cfg(not(feature = "url_preview"))]
pub fn download_image(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
pub async fn download_image(
&self,
_url: &str,
_preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
}
#[cfg(not(feature = "url_preview"))]
pub fn download_video(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
pub async fn download_video(
&self,
_url: &str,
_preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
}
#[cfg(not(feature = "url_preview"))]
pub fn download_audio(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
pub async fn download_audio(
&self,
_url: &str,
_preview_data: Option<UrlPreviewData>,
) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
}
#[cfg(feature = "url_preview")]
#[tracing::instrument(skip(self))]
async fn download_html(&self, url: &str) -> Result<UrlPreviewData> {
use webpage::HTML;
let client = &self.services.client.url_preview;
let response = client.get(url).send().await?;
self.check_response_ip(&response)?;
if !response.status().is_success() {
return Err!(Request(Unknown("HTML download returned HTTP {}", response.status())));
}
let body = response
let body = client
.get(url)
.send()
.await?
.limit_read_text(
self.services
.server
@@ -330,138 +286,39 @@ impl Service {
.expect("u64 should fit in usize"),
)
.await?;
let Ok(html) = HTML::from_string(body, Some(url.to_owned()))
.inspect_err(|e| debug!(error=?e, "Failed to parse HTML data"))
else {
let Ok(html) = HTML::from_string(body.clone(), Some(url.to_owned())) else {
return Err!(Request(Unknown("Failed to parse HTML")));
};
let mut preview_data = UrlPreviewData::from(&html.opengraph);
debug!(parsed=?preview_data, deserialised=?html.opengraph, "Parsed opengraph data");
let mut preview_data = UrlPreviewData::default();
let base_url = Url::parse(url).ok();
let resolve_asset_url = |asset_url: &str| -> String {
base_url
.as_ref()
.and_then(|base| base.join(asset_url).ok())
.map_or_else(|| asset_url.to_owned(), Into::into)
};
if let Some(obj) = html
.opengraph
.images
.first()
.filter(|obj| !obj.url.is_empty())
{
let asset_url = resolve_asset_url(&obj.url);
info!(%asset_url, "Downloading preview image");
if let Ok(image_data) = self.download_image(&asset_url).await.inspect_err(
|e| info!(error=?e, %asset_url, "Could not download URL preview image"),
) {
preview_data.image = image_data.image;
preview_data.image_size = image_data.image_size;
// Prioritise what the top-level site specified, falling back to
// detected params.
preview_data.image_width = preview_data.image_width.or(image_data.image_width);
preview_data.image_height = preview_data.image_height.or(image_data.image_height);
preview_data.image_type = preview_data.image_type.or(image_data.image_type);
}
if let Some(obj) = html.opengraph.images.first() {
preview_data = self.download_image(&obj.url, Some(preview_data)).await?;
}
if let Some(obj) = html
.opengraph
.videos
.first()
.filter(|obj| !obj.url.is_empty())
{
let asset_url = resolve_asset_url(&obj.url);
info!(%asset_url, "Downloading preview video");
if let Ok(video_data) = self.download_video(&asset_url).await.inspect_err(
|e| info!(error=?e, %asset_url, "Could not download URL preview video"),
) {
preview_data.video = video_data.video;
preview_data.video_size = video_data.video_size;
}
if let Some(obj) = html.opengraph.videos.first() {
preview_data = self.download_video(&obj.url, Some(preview_data)).await?;
preview_data.video_width = obj.properties.get("width").and_then(|v| v.parse().ok());
preview_data.video_height = obj.properties.get("height").and_then(|v| v.parse().ok());
}
if let Some(obj) = html
.opengraph
.audios
.first()
.filter(|obj| !obj.url.is_empty())
{
let asset_url = resolve_asset_url(&obj.url);
info!(%asset_url, "Downloading URL preview audio");
if let Ok(audio_data) = self.download_audio(&asset_url).await.inspect_err(
|e| info!(error=?e, %asset_url, "Could not download URL preview audio"),
) {
preview_data.audio = audio_data.audio;
preview_data.audio_size = audio_data.audio_size;
}
if let Some(obj) = html.opengraph.audios.first() {
preview_data = self.download_audio(&obj.url, Some(preview_data)).await?;
}
// Provide defaults for some params
preview_data.title = preview_data.title.or(html.title);
preview_data.description = preview_data.description.or(html.description);
preview_data.url = preview_data.url.or_else(|| Some(url.to_owned()));
let props = html.opengraph.properties;
// We remove og:image:*, og:video:*, and og:audio:* if their respective
// prior-level properties are not present.
// We do this here instead of in the From<> impl because we can't know
// if we'll be able to fetch the media to convert it to an mxc that
// point.
if preview_data.image.is_none() {
preview_data.image_type = None;
preview_data.image_alt = None;
preview_data.image_height = None;
preview_data.image_width = None;
preview_data.image_size = None;
}
if preview_data.video.is_none() {
preview_data.video_type = None;
preview_data.video_alt = None;
preview_data.video_height = None;
preview_data.video_width = None;
preview_data.video_size = None;
}
if preview_data.audio.is_none() {
preview_data.audio_size = None;
}
/* use OpenGraph title/description, but fall back to HTML if not
* available */
preview_data.title = props.get("title").cloned().or(html.title);
preview_data.description = props.get("description").cloned().or(html.description);
Ok(preview_data)
}
#[cfg(not(feature = "url_preview"))]
#[allow(clippy::unused_self)]
fn download_html(&self, _url: &str) -> impl Future<Output = Result<UrlPreviewData>> {
std::future::ready(Err!(FeatureDisabled("url_preview")))
}
fn check_url_ip(&self, url: &str) -> Result<()> {
let parsed = Url::parse(url)
.map_err(|e| err!(Request(InvalidParam("Requested URL is not valid: {e}"))))?;
let Some(host) = parsed.host_str() else {
return Err!(Request(InvalidParam("Requested URL does not have a host")));
};
if let Ok(ip) = IPAddress::parse(host) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
Ok(())
}
fn check_response_ip(&self, response: &reqwest::Response) -> Result<()> {
if let Some(remote_addr) = response.remote_addr() {
debug!(url = %response.url(), "URL preview response remote address: {:?}", remote_addr);
if let Ok(ip) = IPAddress::parse(remote_addr.ip().to_string()) {
if !self.services.client.valid_cidr_range(&ip) {
return Err!(Request(Forbidden("Requesting from this address is forbidden")));
}
}
}
Ok(())
async fn download_html(&self, _url: &str) -> Result<UrlPreviewData> {
Err!(FeatureDisabled("url_preview"))
}
pub fn url_preview_allowed(&self, url: &Url) -> bool {
@@ -586,115 +443,3 @@ impl Service {
false
}
}
#[cfg(feature = "url_preview")]
impl From<&webpage::Opengraph> for UrlPreviewData {
fn from(og: &webpage::Opengraph) -> Self {
Self {
title: og.properties.get("title").cloned(),
description: og.properties.get("description").cloned(),
site_type: og.og_type.clone(),
url: og.properties.get("url").cloned(),
determiner: og.properties.get("determiner").cloned(),
locale: og.properties.get("locale").cloned(),
site_name: og.properties.get("site_name").cloned(),
image_type: og
.images
.first()
.and_then(|img| img.properties.get("type").and_then(|t| t.parse().ok())),
image_width: og
.images
.first()
.and_then(|img| img.properties.get("width").and_then(|w| w.parse().ok())),
image_height: og
.images
.first()
.and_then(|img| img.properties.get("height").and_then(|h| h.parse().ok())),
image_alt: og
.images
.first()
.and_then(|img| img.properties.get("alt").cloned()),
video_type: og
.videos
.first()
.and_then(|vid| vid.properties.get("type"))
.and_then(|t| t.parse().ok()),
video_width: og
.videos
.first()
.and_then(|vid| vid.properties.get("width"))
.and_then(|w| w.parse().ok()),
video_height: og
.videos
.first()
.and_then(|vid| vid.properties.get("height"))
.and_then(|h| h.parse().ok()),
video_alt: og
.videos
.first()
.and_then(|vid| vid.properties.get("alt").cloned()),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "url_preview")]
#[test]
fn test_urlpreviewdata_parses_correctly() {
use webpage::HTML;
use super::UrlPreviewData;
let html = r#"
<html>
<head>
<meta property="og:title" content="Test Title" />
<meta property="og:description" content="Test Description" />
<meta property="og:image" content="https://example.com/image.png" />
<meta property="og:url" content="https://example.com/index.html" />
<meta property="og:type" content="org.continuwuity.other" />
<meta property="og:site_name" content="Example Site" />
<meta property="og:image:alt" content="An example image" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:height" content="69" />
<meta property="og:image:width" content="420" />
<meta property="og:video" content="https://example.com/video.mp4" />
<meta property="og:audio" content="https://example.com/audio.ogg" />
</head>
<body></body>
</html>
"#;
let parsed_html =
HTML::from_string(html.to_owned(), Some("https://example.com".to_owned()))
.expect("Failed to parse HTML");
let data = UrlPreviewData::from(&parsed_html.opengraph);
assert_eq!(data.title, Some("Test Title".to_owned()));
assert_eq!(data.description, Some("Test Description".to_owned()));
assert_eq!(
data.image, None,
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
);
assert_eq!(
data.video, None,
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
);
assert_eq!(
data.audio, None,
"UrlPreviewData should not inherit HTTP/S URL from URL preview"
);
assert_eq!(data.url, Some("https://example.com/index.html".to_owned()));
assert_eq!(data.site_type, "org.continuwuity.other".to_owned());
assert_eq!(data.site_name, Some("Example Site".to_owned()));
assert_eq!(data.image_alt, Some("An example image".to_owned()));
assert_eq!(data.image_type, Some("image/png".parse().unwrap()));
assert_eq!(data.image_height, Some(69));
assert_eq!(data.image_width, Some(420));
assert_eq!(data.image_size, None, "*_size must be None when pulling from opengraph");
assert_eq!(data.video_size, None, "*_size must be None when pulling from opengraph");
assert_eq!(data.audio_size, None, "*_size must be None when pulling from opengraph");
}
}
-22
View File
@@ -18,28 +18,6 @@ impl Services {
},
);
self.gauge(
"continuwuity.sender.requests",
"Estimated outgoing requests stored as queued or in flight",
"{request}",
|services, observer| {
for (state, count) in services.sending.db.request_counts() {
if let Some(count) = count {
observer.observe(count, &[KeyValue::new("state", state)]);
}
}
},
);
self.gauge(
"continuwuity.sender.workers",
"Running sender workers",
"{worker}",
|services, observer| {
observe(observer, services.sending.workers_alive(), &[]);
},
);
self.gauge(
"continuwuity.federation.incoming.transactions.active",
"Incoming federation transactions currently being processed",
-2
View File
@@ -13,8 +13,6 @@ mod migrations;
mod service;
pub mod services;
pub mod state;
#[cfg(test)]
mod test_utils;
pub mod account_data;
pub mod admin;
+10 -77
View File
@@ -1,6 +1,5 @@
use std::{
collections::{BTreeSet, HashMap},
fmt::Write,
sync::Arc,
time::{Duration, SystemTime},
};
@@ -56,7 +55,7 @@ struct Services {
config: Dep<config::Service>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[derive(Debug, Deserialize, Serialize)]
pub struct SessionInfo {
pub client_id: String,
#[serde(deserialize_with = "client_metadata::btreeset_skip_err")]
@@ -65,8 +64,6 @@ pub struct SessionInfo {
temporary_scopes: BTreeSet<OAuthClientScope>,
#[serde(default)]
current_refresh_token: String,
#[serde(default)]
previous_refresh_token: Option<String>,
}
impl SessionInfo {
@@ -74,15 +71,6 @@ impl SessionInfo {
pub fn scopes(&self) -> BTreeSet<OAuthClientScope> {
self.scopes.union(&self.temporary_scopes).cloned().collect()
}
#[must_use]
pub fn scope_string(&self, device_id: &DeviceId) -> String {
let mut scopes = self.scopes().iter().join(" ");
let _ = write!(scopes, " urn:matrix:client:device:{device_id}");
scopes
}
}
#[derive(Debug, Deserialize, Serialize)]
@@ -258,24 +246,6 @@ impl Service {
.ok()
}
/// Clear a session's previous refresh token, if it has one.
pub fn clear_previous_refresh_token(
&self,
user_id: &UserId,
device_id: &DeviceId,
session_info: &SessionInfo,
) {
if session_info.previous_refresh_token.is_some() {
let mut session_info = session_info.clone();
session_info.previous_refresh_token = None;
self.db
.userdeviceid_oauthsessioninfo
.put((user_id, device_id), Json(session_info));
}
}
pub async fn request_authorization_code(
&self,
authorizing_user: OwnedUserId,
@@ -675,7 +645,6 @@ impl Service {
SessionInfo {
client_id: client_id.clone(),
current_refresh_token: Self::generate_token(),
previous_refresh_token: None,
scopes: requested_scopes.scopes,
temporary_scopes: BTreeSet::new(),
}
@@ -733,53 +702,15 @@ impl Service {
assert_eq!(&client_id, &session_info.client_id, "session info client id mismatch");
let new_refresh_token = Self::generate_token();
if refresh_token == session_info.current_refresh_token {
// The client is refreshing with their current refresh token.
// We need to generate a new refresh token and save this token as
// the previous one.
session_info
.current_refresh_token
.clone_from(&new_refresh_token);
// Remove the old previous token if it's set. This can only happen
// if the client decides to refresh twice in a row without using its
// new access token, since we'll also do this when the new access
// token is used for the first time.
if let Some(previous_refresh_token) = session_info.previous_refresh_token {
self.db
.refreshtoken_refreshtokeninfo
.remove(&previous_refresh_token);
}
session_info.previous_refresh_token = Some(refresh_token);
} else if Some(&refresh_token) == session_info.previous_refresh_token.as_ref() {
// The client is refreshing with their previous refresh token,
// probably because they didn't get the new one we made for them. We
// need to make a second new one, but we don't touch the existing
// previous one in case they don't get the second new one either.
// Wipe the current token, we're going to make a new one.
self.db
.refreshtoken_refreshtokeninfo
.remove(&session_info.current_refresh_token);
session_info
.current_refresh_token
.clone_from(&new_refresh_token);
} else {
// The client is trying to use a refresh token that isn't their
// current or previous one, but still has information in the
// database. This is definitely not a legal state, so we need to
// bail out.
panic!("refresh token is not current or previous for its session");
}
let scope = session_info.scope_string(&refresh_token_info.device_id);
// TODO: this doesn't include the device ID "scope", do any clients rely
// on that?
let scope = session_info.scopes.iter().join(" ");
let new_access_token = DeviceToken::new_random().with_max_age(Self::ACCESS_TOKEN_MAX_AGE);
let new_refresh_token = Self::generate_token();
session_info
.current_refresh_token
.clone_from(&new_refresh_token);
self.services
.users
@@ -798,6 +729,8 @@ impl Service {
Json(session_info),
);
self.db.refreshtoken_refreshtokeninfo.remove(&refresh_token);
drop(refresh_token);
self.db
.refreshtoken_refreshtokeninfo
.raw_put(&new_refresh_token, Json(refresh_token_info));
@@ -1,10 +1,14 @@
use conduwuit::PduEvent;
use std::sync::Arc;
use conduwuit::{
Config, PduEvent, Server,
log::{Log, LogLevelReloadHandles},
metrics::Metrics,
};
use futures::StreamExt;
use ruma::{RoomId, RoomVersionId, events::StateEventType};
use serde_json::json;
use crate::test_utils::test_services;
#[tokio::test]
async fn admitted_joins_do_not_disappear_after_a_merge() {
use conduwuit::matrix::PartialPdu;
@@ -16,7 +20,7 @@ async fn admitted_joins_do_not_disappear_after_a_merge() {
},
};
let (services, path, _database) = test_services().await;
let (services, path) = test_services().await;
let alice = UserId::parse("@alice:test.example").unwrap();
let bob = UserId::parse("@bob:bob.example").unwrap();
let charlie = UserId::parse("@charlie:charlie.example").unwrap();
@@ -208,6 +212,35 @@ async fn admitted_joins_do_not_disappear_after_a_merge() {
assert_eq!(results, [true, true], "both joined users must be able to send messages");
}
async fn test_services() -> (Arc<crate::Services>, std::path::PathBuf) {
let _ = rustls::crypto::ring::default_provider().install_default();
let path = std::env::temp_dir()
.join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>()));
std::fs::create_dir(&path).unwrap();
let config: Config = serde_json::from_value(json!({
"server_name": "test.example",
"database_path": path,
"db_cache_capacity_mb": 16.0,
"rocksdb_write_buffer_capacity_mb": 4.0,
"allow_local_presence": false,
"dns_servers": ["127.0.0.1"],
"allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true
}))
.unwrap();
let runtime = tokio::runtime::Handle::current();
let server = Arc::new(Server::new(
config,
Some(runtime.clone()),
Log {
reload: LogLevelReloadHandles::default(),
capture: Arc::default(),
},
Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None),
));
let services = crate::Services::build(server).await.unwrap();
(services, path)
}
fn cache_key(
services: &crate::Services,
server: &ruma::ServerName,
+27 -73
View File
@@ -3,7 +3,6 @@ use std::{fmt::Debug, sync::Arc};
use conduwuit::{
Error, Result, at, utils,
utils::{ReadyExt, stream::TryIgnore},
warn,
};
use database::{Database, Deserialized, Map};
use futures::{Stream, StreamExt};
@@ -170,51 +169,6 @@ impl Data {
})
}
/// Destinations with at least one queued request not yet in flight.
///
/// Seeks past each destination's key prefix so large per-destination
/// backlogs are skipped in O(destinations) seeks rather than scanning
/// every queued event.
pub(super) async fn queued_destinations(&self) -> Vec<Destination> {
let mut dests = Vec::new();
let mut cursor = Vec::new();
while let Some(key) = self
.servernameevent_data
.raw_keys_from(&cursor)
.ignore_err()
.next()
.await
{
match parse_destination(key) {
| Ok((dest, _)) => {
let prefix = dest.get_prefix();
dests.push(dest);
let Some(next) = next_prefix(&prefix) else {
break;
};
cursor = next;
},
| Err(e) => {
warn!(?key, "invalid queued request key: {e}");
cursor = key.to_vec();
cursor.push(0);
},
}
}
dests
}
/// Estimated number of requests waiting to be sent and in flight.
pub(crate) fn request_counts(&self) -> [(&'static str, Option<u64>); 2] {
[
("queued", &self.servernameevent_data),
("active", &self.servercurrentevent_data),
]
.map(|(state, map)| (state, map.property_integer(c"rocksdb.estimate-num-keys").ok()))
}
pub(super) fn set_latest_educount(&self, server_name: &ServerName, last_count: u64) {
self.servername_educount.raw_put(server_name, last_count);
}
@@ -228,17 +182,9 @@ impl Data {
}
}
/// Smallest byte slice strictly greater than every key starting with `prefix`.
fn next_prefix(prefix: &[u8]) -> Option<Vec<u8>> {
let pos = prefix.iter().rposition(|&b| b < u8::MAX)?;
let mut next = prefix[..=pos].to_vec();
next[pos] = next[pos].saturating_add(1);
Some(next)
}
fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> {
fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> {
// Appservices start with a plus
if key.starts_with(b"+") {
Ok::<_, Error>(if key.starts_with(b"+") {
let mut parts = key[1..].splitn(2, |&b| b == 0xFF);
let server = parts.next().expect("splitn always returns one element");
@@ -250,7 +196,14 @@ fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> {
Error::bad_database("Invalid server bytes in server_currenttransaction")
})?;
Ok((Destination::Appservice(server), event))
(
Destination::Appservice(server),
if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
SendingEvent::Edu(value.into())
},
)
} else if key.starts_with(b"$") {
let mut parts = key[1..].splitn(3, |&b| b == 0xFF);
@@ -270,7 +223,15 @@ fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> {
.next()
.ok_or_else(|| Error::bad_database("Invalid bytes in servercurrentpdus."))?;
Ok((Destination::Push(user_id, pushkey_string), event))
(
Destination::Push(user_id, pushkey_string),
if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
// I'm pretty sure this should never be called
SendingEvent::Edu(value.into())
},
)
} else {
let mut parts = key.splitn(2, |&b| b == 0xFF);
@@ -283,22 +244,15 @@ fn parse_destination(key: &[u8]) -> Result<(Destination, &[u8])> {
Error::bad_database("Invalid server bytes in server_currenttransaction")
})?;
Ok((
(
Destination::Federation(ServerName::parse(&server).map_err(|_| {
Error::bad_database("Invalid server string in server_currenttransaction")
})?),
event,
))
}
}
fn parse_servercurrentevent(key: &[u8], value: &[u8]) -> Result<(Destination, SendingEvent)> {
let (dest, event) = parse_destination(key)?;
let event = if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
SendingEvent::Edu(value.into())
};
Ok((dest, event))
if value.is_empty() {
SendingEvent::Pdu(event.into())
} else {
SendingEvent::Edu(value.into())
},
)
})
}
+25 -115
View File
@@ -3,19 +3,12 @@ mod appservice;
mod data;
mod dest;
mod sender;
#[cfg(test)]
mod tests;
use std::{
collections::HashMap,
fmt::Debug,
hash::{DefaultHasher, Hash, Hasher},
iter::once,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
},
time::{Duration, Instant},
sync::Arc,
};
use async_trait::async_trait;
@@ -26,7 +19,7 @@ use conduwuit::{
utils::{ReadyExt, TryReadyExt, available_parallelism, math::usize_from_u64_truncated},
warn,
};
use futures::{FutureExt, Stream, StreamExt, stream::FuturesUnordered};
use futures::{FutureExt, Stream, StreamExt};
use ruma::{
OwnedServerName, RoomId, ServerName, UserId,
api::{
@@ -34,7 +27,7 @@ use ruma::{
federation::authentication::ServerSignatures, path_builder::PathBuilder,
},
};
use tokio::{task, task::JoinSet, time::sleep};
use tokio::{task, task::JoinSet};
use self::data::Data;
pub use self::{
@@ -56,7 +49,6 @@ pub struct Service {
server: Arc<Server>,
services: Services,
channels: Vec<(loole::Sender<Msg>, loole::Receiver<Msg>)>,
workers_alive: AtomicUsize,
}
struct Services {
@@ -95,8 +87,6 @@ pub type EduVec = SmallVec<[EduBuf; EDU_VEC_CAP]>;
const EDU_BUF_CAP: usize = 128;
const EDU_VEC_CAP: usize = 1;
const WORKER_RESTART_DELAY: Duration = Duration::from_millis(2500);
const WORKER_RESTART_DELAY_MAX: Duration = Duration::from_secs(30);
#[async_trait]
impl crate::Service for Service {
@@ -121,67 +111,36 @@ impl crate::Service for Service {
federation: args.depend::<federation::Service>("federation"),
},
channels: (0..num_senders).map(|_| loole::unbounded()).collect(),
workers_alive: AtomicUsize::new(0),
}))
}
async fn worker(self: Arc<Self>) -> Result {
if self.server.config.startup_netburst {
self.dispatch_queued(None).await;
}
let num_senders = self.channels.len();
let mut senders = JoinSet::new();
let mut shards = HashMap::new();
let mut started = vec![Instant::now(); num_senders];
let mut failures = vec![0_u32; num_senders];
let mut restarts = FuturesUnordered::new();
for id in 0..num_senders {
self.spawn_sender(&mut senders, &mut shards, id, false);
}
loop {
tokio::select! {
Some(ret) = senders.join_next_with_id() => {
self.workers_alive.fetch_sub(1, Ordering::Relaxed);
let (task_id, panicked) = match &ret {
| Ok((task_id, _)) => (*task_id, false),
| Err(error) => (error.id(), error.is_panic()),
};
let shard = shards.remove(&task_id).expect("sender worker has a shard");
if panicked {
self.server
.metrics
.instruments
.sender_panics
.add(1, &[KeyValue::new("scope", "worker")]);
}
if self.channels[shard].1.is_closed() || !self.server.running() {
debug!(shard, ?ret, "sender worker finished");
continue;
}
// A worker that ran a while before failing starts over from
// the shortest delay.
failures[shard] = if started[shard].elapsed() > WORKER_RESTART_DELAY_MAX {
1
let mut senders =
self.channels
.iter()
.enumerate()
.fold(JoinSet::new(), |mut joinset, (id, _)| {
let self_ = self.clone();
let worker = self_.sender(id);
let worker = if self.unconstrained() {
task::unconstrained(worker).boxed()
} else {
failures[shard].saturating_add(1)
worker.boxed()
};
let delay = restart_delay(failures[shard]);
error!(shard, ?ret, ?delay, "sender worker unexpectedly finished, restarting");
restarts.push(sleep(delay).map(move |()| shard));
let runtime = self.server.runtime();
let _abort = joinset.spawn_on(worker, runtime);
joinset
});
while let Some(ret) = senders.join_next_with_id().await {
match ret {
| Ok((id, error)) => {
debug!(?id, ?error, "sender worker finished");
},
Some(shard) = restarts.next() => {
if !self.channels[shard].1.is_closed() && self.server.running() {
started[shard] = Instant::now();
self.spawn_sender(&mut senders, &mut shards, shard, true);
}
| Err(error) => {
error!(id = ?error.id(), ?error, "sender worker failed");
},
() = self.server.until_shutdown(), if !restarts.is_empty() => restarts.clear(),
else => break,
}
}
@@ -202,25 +161,6 @@ impl crate::Service for Service {
}
impl Service {
fn spawn_sender(
self: &Arc<Self>,
senders: &mut JoinSet<Result>,
shards: &mut HashMap<task::Id, usize>,
id: usize,
restarted: bool,
) {
let worker = self.clone().sender(id, restarted);
let worker = if crate::Service::unconstrained(&**self) {
task::unconstrained(worker).boxed()
} else {
worker.boxed()
};
let handle = senders.spawn_on(worker, self.server.runtime());
shards.insert(handle.id(), id);
self.workers_alive.fetch_add(1, Ordering::Relaxed);
}
#[tracing::instrument(skip(self, pdu_id, user, pushkey), level = "debug")]
pub fn send_pdu_push(&self, pdu_id: &RawPduId, user: &UserId, pushkey: String) -> Result {
let dest = Destination::Push(user.to_owned(), pushkey);
@@ -540,32 +480,10 @@ impl Service {
sender.send(msg).map_err(|e| err!("{e}"))
}
/// Wakes workers for every destination that has unsent queued requests, so
/// a backlog with nothing in flight is drained without waiting for a new
/// event. Uses `SendingEvent::Flush` so a message racing with already-
/// buffered channel items cannot re-insert and duplicate a sent request.
async fn dispatch_queued(&self, shard: Option<usize>) {
for dest in self.db.queued_destinations().await {
let id = self.shard_id(&dest);
if shard.is_none_or(|shard| shard == id) {
self.channels[id]
.0
.send(Msg {
dest,
event: SendingEvent::Flush,
queue_id: Vec::new(),
})
.ok();
}
}
}
pub fn queue_depth(&self) -> usize {
self.channels.iter().map(|(sender, _)| sender.len()).sum()
}
pub fn workers_alive(&self) -> usize { self.workers_alive.load(Ordering::Relaxed) }
pub(super) fn shard_id(&self, dest: &Destination) -> usize {
if self.channels.len() <= 1 {
return 0;
@@ -601,11 +519,3 @@ fn num_senders(args: &crate::Args<'_>) -> usize {
worker_count.clamp(MIN_SENDERS, max_senders)
}
}
/// Delay before restarting a worker after its `failures`-th consecutive
/// failure, doubling each time.
fn restart_delay(failures: u32) -> Duration {
WORKER_RESTART_DELAY
.saturating_mul(2_u32.saturating_pow(failures.saturating_sub(1)))
.min(WORKER_RESTART_DELAY_MAX)
}
+33 -90
View File
@@ -1,7 +1,6 @@
use std::{
collections::{BTreeMap, HashMap, HashSet},
fmt::Debug,
panic::AssertUnwindSafe,
sync::{
Arc,
atomic::{AtomicU64, AtomicUsize, Ordering},
@@ -56,17 +55,11 @@ use serde_json::value::{RawValue as RawJsonValue, to_raw_value};
use super::{Destination, EduBuf, EduVec, Msg, SendingEvent, Service, data::QueueItem};
#[cfg(test)]
mod tests;
#[derive(Debug)]
enum TransactionStatus {
Running,
/// Number of times failed, time of last failure, and whether local backoff
/// applies even for federation destinations (e.g. after a local panic when
/// the remote was not marked unhealthy).
Failed(u32, Instant, bool),
Retrying(u32), // number of times failed
Failed(u32, Instant), // number of times failed, time of last failure
Retrying(u32), // number of times failed
}
type SendingError = (Destination, Box<Error>);
@@ -85,18 +78,12 @@ pub const EDU_LIMIT: usize = 100;
impl Service {
#[tracing::instrument(skip(self), level = "debug")]
pub(super) async fn sender(self: Arc<Self>, id: usize, restarted: bool) -> Result {
pub(super) async fn sender(self: Arc<Self>, id: usize) -> Result {
let mut statuses: CurTransactionStatus = CurTransactionStatus::new();
let mut futures: SendingFutures<'_> = FuturesUnordered::new();
// The previous worker of this shard may have dropped requests it had
// taken from the channel.
if restarted {
self.dispatch_queued(Some(id)).await;
}
info!(shard = id, "Running startup netburst");
self.startup_netburst(id, restarted, &mut futures, &mut statuses)
self.startup_netburst(id, &mut futures, &mut statuses)
.boxed()
.await;
info!(shard = id, "Finished startup netburst");
@@ -155,12 +142,7 @@ impl Service {
) {
match response {
| Ok(dest) => self.handle_response_ok(&dest, futures, statuses).await,
// A bug on our side, not the remote's fault: retry with local
// backoff without marking the remote unhealthy.
| Err((dest, e)) if e.is_panic() =>
Self::handle_response_err(dest, statuses, &e, true),
| Err((dest, e)) => {
let mut local_backoff = false;
if let Destination::Federation(dest) = &dest {
if self.services.federation.should_mark_stale(&e)
|| e.status_code() == StatusCode::NOT_FOUND
@@ -171,30 +153,22 @@ impl Service {
} else if e.status_code() != StatusCode::OK {
debug!("{dest} is now unhealthy due to error response: {e:?}");
self.services.federation.hit_unhealthy(dest.clone(), None);
} else {
local_backoff = true;
}
}
Self::handle_response_err(dest, statuses, &e, local_backoff);
Self::handle_response_err(dest, statuses, &e);
},
}
}
/// Handles a response error, incrementing the backoff factor.
fn handle_response_err(
dest: Destination,
statuses: &mut CurTransactionStatus,
er: &Error,
local_backoff: bool,
) {
fn handle_response_err(dest: Destination, statuses: &mut CurTransactionStatus, er: &Error) {
debug!(dest = ?dest, "{er:?}");
let dest2 = dest.clone();
statuses.entry(dest).and_modify(|e| {
*e = match e {
| TransactionStatus::Running =>
TransactionStatus::Failed(1, Instant::now(), local_backoff),
| TransactionStatus::Running => TransactionStatus::Failed(1, Instant::now()),
| &mut TransactionStatus::Retrying(ref n) =>
TransactionStatus::Failed(n.saturating_add(1), Instant::now(), local_backoff),
TransactionStatus::Failed(n.saturating_add(1), Instant::now()),
| TransactionStatus::Failed(..) => {
panic!(
"Request to {dest2:?} that was not even running ({e:?}) failed: {er:?}"
@@ -300,8 +274,7 @@ impl Service {
}
/// Performs startup netburst, which sends any previously queued up but not
/// yet sent requests immediately. A restarted worker always resends its
/// shard's requests in flight.
/// yet sent requests immediately.
#[tracing::instrument(
name = "netburst",
level = "debug",
@@ -312,11 +285,9 @@ impl Service {
async fn startup_netburst<'a>(
&'a self,
id: usize,
restarted: bool,
futures: &mut SendingFutures<'a>,
statuses: &mut CurTransactionStatus,
) {
let delivering = restarted || self.server.config.startup_netburst;
let keep =
usize::try_from(self.server.config.startup_netburst_keep).unwrap_or(usize::MAX);
let mut txns = HashMap::<Destination, Vec<SendingEvent>>::new();
@@ -331,7 +302,7 @@ impl Service {
let over_budget =
self.server.config.startup_netburst_keep >= 0 && entry.len() >= keep;
if over_budget && !self.survives_netburst_trim(&event, delivering).await {
if over_budget && !self.survives_netburst_trim(&event).await {
warn!(
startup_netburst_keep = self.server.config.startup_netburst_keep,
queue_size = entry.len(),
@@ -344,12 +315,8 @@ impl Service {
}
}
if !delivering {
return;
}
for (dest, events) in txns {
if !events.is_empty() {
if self.server.config.startup_netburst && !events.is_empty() {
statuses.insert(dest.clone(), TransactionStatus::Running);
futures.push(self.send_events(dest, events));
}
@@ -357,10 +324,10 @@ impl Service {
}
/// Whether this event skips the netburst budget, which MSC4354 asks of
/// still-sticky events. Only a delivering netburst drains this queue, so
/// when nothing will deliver it there is nothing to keep the event for.
async fn survives_netburst_trim(&self, event: &SendingEvent, delivering: bool) -> bool {
if !delivering {
/// still-sticky events. Only netburst delivers this queue, so with it
/// disabled there is nothing to keep the event for.
async fn survives_netburst_trim(&self, event: &SendingEvent) -> bool {
if !self.server.config.startup_netburst {
return false;
}
@@ -458,17 +425,12 @@ impl Service {
allow = false; // already running
trace!("Transaction is already running for {dest:?}");
},
| TransactionStatus::Failed(tries, time, local_backoff) => {
if *local_backoff
&& time.elapsed() < self.server.config.sender_retry_backoff(*tries)
{
allow = false;
trace!("{dest:?} is in local backoff, refusing send");
} else {
| TransactionStatus::Failed(tries, _) => {
if allow {
*e = TransactionStatus::Retrying(*tries);
trace!("Previous transaction failed for {dest:?} ({e:?}), will retry");
retry = true;
}
retry = true;
},
});
@@ -487,7 +449,7 @@ impl Service {
statuses
.entry(dest.clone())
.and_modify(|e| match e {
| TransactionStatus::Failed(tries, time, _) => {
| TransactionStatus::Failed(tries, time) => {
let retry_after = self.server.config.sender_retry_backoff(*tries);
if time.elapsed() < retry_after {
debug_warn!("Not retrying destination for another {retry_after:?}");
@@ -810,7 +772,6 @@ impl Service {
});
let start = Instant::now();
let panic_dest = dest.clone();
let send = match dest {
| Destination::Federation(server) =>
self.send_events_dest_federation(server, events).boxed(),
@@ -819,42 +780,24 @@ impl Service {
self.send_events_dest_push(user_id, pushkey, events).boxed(),
};
AssertUnwindSafe(send)
.catch_unwind()
.map(move |result| {
result.unwrap_or_else(|panic| {
let error = Error::from_panic(panic);
error!(dest = ?panic_dest, ?error, "Panicked while sending transaction");
self.server
.metrics
.instruments
.sender_panics
.add(1, &[KeyValue::new("scope", "transaction")]);
Err((panic_dest, Box::new(error)))
})
})
.inspect(move |result| {
let instruments = &self.server.metrics.instruments;
let outcome =
KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" });
instruments
.sender_transaction_duration
.record(start.elapsed().as_secs_f64(), &[
send.inspect(move |result| {
let instruments = &self.server.metrics.instruments;
let outcome =
KeyValue::new("outcome", if result.is_ok() { "success" } else { "failure" });
instruments
.sender_transaction_duration
.record(start.elapsed().as_secs_f64(), &[destination.clone(), outcome.clone()]);
for (kind, count) in [("pdu", pdus), ("edu", edus)] {
if count > 0 {
instruments.sender_events.add(count, &[
destination.clone(),
KeyValue::new("kind", kind),
outcome.clone(),
]);
for (kind, count) in [("pdu", pdus), ("edu", edus)] {
if count > 0 {
instruments.sender_events.add(count, &[
destination.clone(),
KeyValue::new("kind", kind),
outcome.clone(),
]);
}
}
})
.boxed()
}
})
.boxed()
}
#[tracing::instrument(
-198
View File
@@ -1,198 +0,0 @@
use std::iter::once;
use conduwuit::{
Error,
matrix::{PartialPdu, pdu::sticky},
};
use futures::{StreamExt, stream::FuturesUnordered};
use ruma::{RoomId, UserId, events::sticky::StickyDurationMs, server_name};
use serde_json::{json, value::to_raw_value};
use super::{CurTransactionStatus, TransactionStatus};
use crate::{
sending::{Destination, EduBuf, SendingEvent},
test_utils::{test_services, test_services_with},
};
#[tokio::test]
async fn panicked_transaction_is_kept_for_retry_without_blaming_the_remote() {
let (services, path, _database) = test_services().await;
let sending = &services.sending;
let server = server_name!("remote.example");
let dest = Destination::Federation(server.to_owned());
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
sending.db.queue_requests(once((&event, &dest)));
let in_flight: Vec<_> = sending.db.queued_requests(&dest).collect().await;
sending.db.mark_as_active(in_flight.iter());
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::from([(dest.clone(), TransactionStatus::Running)]);
let panic = Error::from_panic(Box::new("boom"));
sending
.handle_response(Err((dest.clone(), Box::new(panic))), &mut futures, &mut statuses)
.await;
let active: Vec<_> = sending
.db
.active_requests_for(&dest)
.map(|(key, _)| key)
.collect()
.await;
let retry_after = sending.services.federation.retry_after(server);
let sending_next = futures.len();
let failed = matches!(statuses.get(&dest), Some(TransactionStatus::Failed(1, _, true)));
let immediate_retry = sending.should_attempt_send(&dest, &mut statuses).unwrap();
drop(futures);
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(
active,
in_flight
.into_iter()
.map(|(key, _)| key)
.collect::<Vec<_>>()
);
assert_eq!(sending_next, 0);
assert!(failed);
assert_eq!(immediate_retry, (false, false));
assert_eq!(retry_after, None);
}
#[tokio::test]
async fn restarted_worker_resends_trimmed_in_flight_requests() {
let (services, path, _database) =
test_services_with(json!({ "startup_netburst_keep": 1 })).await;
let sending = &services.sending;
let dest = Destination::Federation(server_name!("remote.example").to_owned());
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
for _ in 0..3 {
sending.db.queue_requests(once((&event, &dest)));
}
let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await;
sending.db.mark_as_active(queued.iter());
let id = sending.shard_id(&dest);
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::new();
sending
.startup_netburst(id, true, &mut futures, &mut statuses)
.await;
let active = sending.db.active_requests_for(&dest).count().await;
let sending_now = futures.len();
drop(futures);
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(active, 1);
assert_eq!(sending_now, 1);
}
#[tokio::test]
async fn restarted_worker_keeps_sticky_events_when_startup_netburst_is_disabled() {
let (services, path, _database) =
test_services_with(json!({ "startup_netburst": false, "startup_netburst_keep": 0 }))
.await;
let alice = UserId::parse("@alice:test.example").unwrap();
let bootstrap = services
.rooms
.state
.mutex
.lock("!bootstrap:test.example")
.await;
let create_id = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
event_type: "m.room.create".into(),
content: to_raw_value(&json!({ "room_version": "12" })).unwrap(),
state_key: Some("".into()),
..Default::default()
},
&alice,
None,
&bootstrap,
)
.await
.unwrap();
drop(bootstrap);
let room = RoomId::parse(create_id.as_str().replacen('$', "!", 1)).unwrap();
let lock = services.rooms.state.mutex.lock(&room).await;
services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
event_type: "m.room.member".into(),
content: to_raw_value(&json!({ "membership": "join" })).unwrap(),
state_key: Some(alice.as_str().into()),
..Default::default()
},
&alice,
Some(&room),
&lock,
)
.await
.unwrap();
let sticky_id = services
.rooms
.timeline
.build_and_append_pdu(
PartialPdu {
event_type: "m.room.message".into(),
content: to_raw_value(&json!({ "msgtype": "m.text", "body": "sticky" })).unwrap(),
sticky: Some(sticky::object(StickyDurationMs::new_clamped(600_000_u32))),
..Default::default()
},
&alice,
Some(&room),
&lock,
)
.await
.unwrap();
drop(lock);
let raw_pdu_id = services
.rooms
.timeline
.get_pdu_id(&sticky_id)
.await
.unwrap();
let sending = &services.sending;
let dest = Destination::Federation(server_name!("remote.example").to_owned());
let event = SendingEvent::Pdu(raw_pdu_id);
sending.db.queue_requests(once((&event, &dest)));
let queued: Vec<_> = sending.db.queued_requests(&dest).collect().await;
sending.db.mark_as_active(queued.iter());
let id = sending.shard_id(&dest);
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::new();
sending
.startup_netburst(id, true, &mut futures, &mut statuses)
.await;
let active_after_restart = sending.db.active_requests_for(&dest).count().await;
let sending_after_restart = futures.len();
drop(futures);
let mut futures = FuturesUnordered::new();
let mut statuses = CurTransactionStatus::new();
sending
.startup_netburst(id, false, &mut futures, &mut statuses)
.await;
let active_after_startup = sending.db.active_requests_for(&dest).count().await;
let sending_after_startup = futures.len();
drop(futures);
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(active_after_restart, 1);
assert_eq!(sending_after_restart, 1);
assert_eq!(active_after_startup, 0);
assert_eq!(sending_after_startup, 0);
}
-41
View File
@@ -1,41 +0,0 @@
use std::{iter::once, time::Duration};
use futures::StreamExt;
use ruma::server_name;
use super::{Destination, EduBuf, SendingEvent, restart_delay};
use crate::test_utils::test_services;
#[tokio::test]
async fn queued_destinations_lists_each_destination_with_unsent_requests() {
let (services, path, _database) = test_services().await;
let db = &services.sending.db;
let queued_sub = Destination::Federation(server_name!("queued.example.org").to_owned());
let queued = Destination::Federation(server_name!("queued.example").to_owned());
let appservice = Destination::Appservice("bridge".to_owned());
let active = Destination::Federation(server_name!("active.example").to_owned());
let event = SendingEvent::Edu(EduBuf::from_slice(br#"{"edu_type":"m.typing"}"#));
db.queue_requests(once((&event, &queued)));
db.queue_requests(once((&event, &queued)));
db.queue_requests(once((&event, &queued_sub)));
db.queue_requests(once((&event, &appservice)));
db.queue_requests(once((&event, &active)));
let in_flight: Vec<_> = db.queued_requests(&active).collect().await;
db.mark_as_active(in_flight.iter());
let dests = db.queued_destinations().await;
drop(services);
std::fs::remove_dir_all(path).unwrap();
assert_eq!(dests, [appservice, queued_sub, queued]);
}
#[test]
fn restart_delay_doubles_up_to_the_cap() {
assert_eq!(restart_delay(1), Duration::from_millis(2500));
assert_eq!(restart_delay(2), Duration::from_secs(5));
assert_eq!(restart_delay(4), Duration::from_secs(20));
assert_eq!(restart_delay(5), Duration::from_secs(30));
assert_eq!(restart_delay(u32::MAX), Duration::from_secs(30));
}
-52
View File
@@ -1,52 +0,0 @@
use std::{path::PathBuf, sync::Arc};
use conduwuit::{
Config, Server,
log::{Log, LogLevelReloadHandles},
metrics::Metrics,
};
use serde_json::json;
use tokio::sync::{Mutex, MutexGuard};
/// RocksDB's default `Env` is shared by the whole process and closing a
/// database stops its background threads, so tests must not keep databases
/// open in parallel. Hold the returned guard until the services are dropped.
static DATABASE: Mutex<()> = Mutex::const_new(());
type TestServices = (Arc<crate::Services>, PathBuf, MutexGuard<'static, ()>);
pub(crate) async fn test_services() -> TestServices { test_services_with(json!({})).await }
pub(crate) async fn test_services_with(overrides: serde_json::Value) -> TestServices {
let guard = DATABASE.lock().await;
let _ = rustls::crypto::ring::default_provider().install_default();
let path = std::env::temp_dir()
.join(format!("continuwuity-shared-state-{:016x}", rand::random::<u64>()));
std::fs::create_dir(&path).unwrap();
let mut config = json!({
"server_name": "test.example",
"database_path": path,
"db_cache_capacity_mb": 16.0,
"rocksdb_write_buffer_capacity_mb": 4.0,
"allow_local_presence": false,
"dns_servers": ["127.0.0.1"],
"allow_invalid_tls_certificates_yes_i_know_what_the_fuck_i_am_doing_with_this_and_i_know_this_is_insecure": true
});
config
.as_object_mut()
.unwrap()
.extend(overrides.as_object().unwrap().clone());
let config: Config = serde_json::from_value(config).unwrap();
let runtime = tokio::runtime::Handle::current();
let server = Arc::new(Server::new(
config,
Some(runtime.clone()),
Log {
reload: LogLevelReloadHandles::default(),
capture: Arc::default(),
},
Metrics::new(Some(runtime), opentelemetry::global::meter("test"), None),
));
let services = crate::Services::build(server).await.unwrap();
(services, path, guard)
}
-6
View File
@@ -632,12 +632,6 @@ impl super::Service {
}
}
// Discard this device's previous token entry if the current token
// isn't expired.
self.db
.userdeviceid_previoustoken
.del((&user_id, &device_id));
Some((user_id, device_id, AccessTokenStatus::Valid))
}
+1 -17
View File
@@ -184,13 +184,8 @@ impl super::Service {
// Remove old token
if let Ok(old_token) = self.db.userdeviceid_token.qry(&key).await {
self.db.token_userdeviceid.remove(&old_token);
self.db.userdeviceid_tokenexpires.remove(&old_token);
// It will be removed from userdeviceid_token by the insert later
// Save the previous token only if we don't already have one saved
// for this device.
if !self.db.userdeviceid_previoustoken.contains(&key).await {
self.db.userdeviceid_previoustoken.put_raw(key, &old_token);
}
}
// Assign token to user device combination
@@ -212,17 +207,6 @@ impl super::Service {
Ok(())
}
/// Returns whether the provided token was previously used by a device
/// before a token refresh, and therefore should cause a soft-logout.
pub async fn is_previous_token(&self, token: &str) -> bool {
self.db
.userdeviceid_previoustoken
.stream::<Ignore, String>()
.ignore_err()
.ready_any(|(_, previous_token)| previous_token == token)
.await
}
/// Pushes a new to-device event into a device's inbox.
pub async fn add_to_device_event(
&self,
-2
View File
@@ -83,7 +83,6 @@ struct Data {
userdeviceid_tokenexpires: Arc<Map>,
userdeviceid_metadata: Arc<Map>,
userdeviceid_token: Arc<Map>,
userdeviceid_previoustoken: Arc<Map>,
userfilterid_filter: Arc<Map>,
userid_avatarurl: Arc<Map>,
userid_deactivated: Arc<Map>,
@@ -135,7 +134,6 @@ impl crate::Service for Service {
remoteuserid_remoteuser: args.db["remoteuserid_remoteuser"].clone(),
userdeviceid_metadata: args.db["userdeviceid_metadata"].clone(),
userdeviceid_token: args.db["userdeviceid_token"].clone(),
userdeviceid_previoustoken: args.db["userdeviceid_previoustoken"].clone(),
userfilterid_filter: args.db["userfilterid_filter"].clone(),
userid_avatarurl: args.db["userid_avatarurl"].clone(),
userid_deactivated: args.db["userid_deactivated"].clone(),