mirror of
https://forgejo.ellis.link/continuwuation/continuwuity.git
synced 2026-12-02 05:17:33 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
032e5ce65b | ||
|
|
c316d8f969 |
No files matched your search
@@ -5,8 +5,6 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
concurrency:
|
concurrency:
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ repos:
|
|||||||
- id: check-added-large-files
|
- id: check-added-large-files
|
||||||
|
|
||||||
- repo: https://github.com/crate-ci/typos
|
- repo: https://github.com/crate-ci/typos
|
||||||
rev: v1.52.2
|
rev: v1.53.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: typos
|
- id: typos
|
||||||
- id: typos
|
- id: typos
|
||||||
@@ -62,3 +62,11 @@ repos:
|
|||||||
types: [ rust ]
|
types: [ rust ]
|
||||||
stages:
|
stages:
|
||||||
- pre-push
|
- pre-push
|
||||||
|
|
||||||
|
- repo: https://code.forgejo.org/forgejo/runner
|
||||||
|
rev: v13.2.1
|
||||||
|
hooks:
|
||||||
|
- id: forgejo-runner-validate
|
||||||
|
stages:
|
||||||
|
- pre-commit
|
||||||
|
files: ".forgejo/*"
|
||||||
Generated
-1
@@ -1155,7 +1155,6 @@ dependencies = [
|
|||||||
"sha2 0.11.2",
|
"sha2 0.11.2",
|
||||||
"termimad",
|
"termimad",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-stream",
|
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
"web-push-native",
|
"web-push-native",
|
||||||
|
|||||||
@@ -269,9 +269,6 @@ features = [
|
|||||||
[workspace.dependencies.tokio-metrics]
|
[workspace.dependencies.tokio-metrics]
|
||||||
version = "0.5.2"
|
version = "0.5.2"
|
||||||
|
|
||||||
[workspace.dependencies.tokio-stream]
|
|
||||||
version = "0.1.19"
|
|
||||||
|
|
||||||
[workspace.dependencies.wildmatch]
|
[workspace.dependencies.wildmatch]
|
||||||
version = "2.7.0"
|
version = "2.7.0"
|
||||||
|
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
Add a new parallel room handler queue system. Slow rooms no longer bog down federation across the entire server. Contributed by @nex.
|
|
||||||
+52
-27
@@ -44,10 +44,7 @@ use ruma::{
|
|||||||
to_device::DeviceIdOrAllDevices,
|
to_device::DeviceIdOrAllDevices,
|
||||||
};
|
};
|
||||||
use service::{
|
use service::{
|
||||||
rooms::{
|
rooms::event_handler::{DagBuilderTree, build_local_dag},
|
||||||
event_handler::{DagBuilderTree, build_local_dag},
|
|
||||||
queue::QueueJob,
|
|
||||||
},
|
|
||||||
transactions::{FederationTxnState, TransactionError, TxnKey, WrappedTransactionResponse},
|
transactions::{FederationTxnState, TransactionError, TxnKey, WrappedTransactionResponse},
|
||||||
};
|
};
|
||||||
use tokio::sync::watch::{Receiver, Sender};
|
use tokio::sync::watch::{Receiver, Sender};
|
||||||
@@ -335,6 +332,14 @@ async fn handle_room(
|
|||||||
room_id: OwnedRoomId,
|
room_id: OwnedRoomId,
|
||||||
pdus: impl Iterator<Item = Pdu> + Send,
|
pdus: impl Iterator<Item = Pdu> + Send,
|
||||||
) -> std::result::Result<Vec<(OwnedEventId, Result)>, TransactionError> {
|
) -> std::result::Result<Vec<(OwnedEventId, Result)>, TransactionError> {
|
||||||
|
let arrived = millis_since_unix_epoch();
|
||||||
|
let _room_lock = services
|
||||||
|
.rooms
|
||||||
|
.event_handler
|
||||||
|
.mutex_federation
|
||||||
|
.lock(room_id.as_str())
|
||||||
|
.await;
|
||||||
|
|
||||||
let room_id = &room_id;
|
let room_id = &room_id;
|
||||||
let mut pdu_map: HashMap<OwnedEventId, CanonicalJsonObject> = pdus
|
let mut pdu_map: HashMap<OwnedEventId, CanonicalJsonObject> = pdus
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -354,30 +359,50 @@ async fn handle_room(
|
|||||||
let value = pdu_map
|
let value = pdu_map
|
||||||
.remove(&event_id)
|
.remove(&event_id)
|
||||||
.expect("sorted event IDs must be from the original map");
|
.expect("sorted event IDs must be from the original map");
|
||||||
let room_id = match value
|
services
|
||||||
.get("room_id")
|
.server
|
||||||
.and_then(CanonicalJsonValue::as_str)
|
.check_running()
|
||||||
.map(|v| v.try_into().map_err(Into::into))
|
.map_err(|_| TransactionError::ShuttingDown)?;
|
||||||
{
|
let event_type = KeyValue::new(
|
||||||
| Some(Ok(v)) => v,
|
"type",
|
||||||
| Some(Err(e)) => {
|
pdu_type_label(value.get("type").and_then(CanonicalJsonValue::as_str)),
|
||||||
results.push((event_id, Err(e)));
|
);
|
||||||
continue;
|
let origin_server_ts = value
|
||||||
},
|
.get("origin_server_ts")
|
||||||
| None => {
|
.and_then(CanonicalJsonValue::as_integer)
|
||||||
results
|
.and_then(|ts| u64::try_from(i64::from(ts)).ok());
|
||||||
.push((event_id, Err!(Request(BadJson("PDU is missing a room_id field")))));
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let job = QueueJob {
|
|
||||||
room_id,
|
|
||||||
event_id: event_id.clone(),
|
|
||||||
origin: origin.to_owned(),
|
|
||||||
object: value,
|
|
||||||
};
|
|
||||||
|
|
||||||
results.push((event_id, services.rooms.queue.new_job(job).await));
|
let start = Instant::now();
|
||||||
|
let result = services
|
||||||
|
.rooms
|
||||||
|
.event_handler
|
||||||
|
.handle_incoming_pdu(origin, room_id, &event_id, value, false)
|
||||||
|
.boxed()
|
||||||
|
.await
|
||||||
|
.map(|_| ());
|
||||||
|
|
||||||
|
let outcome = KeyValue::new("outcome", match &result {
|
||||||
|
| Ok(()) => "accepted",
|
||||||
|
| Err(Error::BadRequest(ErrorKind::Forbidden, ..)) => "forbidden",
|
||||||
|
| Err(Error::BadRequest(ErrorKind::InvalidParam | ErrorKind::BadJson, ..)) =>
|
||||||
|
"invalid",
|
||||||
|
| Err(_) => "error",
|
||||||
|
});
|
||||||
|
let instruments = &services.server.metrics.instruments;
|
||||||
|
instruments
|
||||||
|
.federation_incoming_pdu_duration
|
||||||
|
.record(start.elapsed().as_secs_f64(), std::slice::from_ref(&outcome));
|
||||||
|
if let (Ok(()), Some(ts)) = (&result, origin_server_ts) {
|
||||||
|
let lag = arrived.saturating_sub(ts);
|
||||||
|
instruments
|
||||||
|
.federation_incoming_pdu_lag
|
||||||
|
.record(Duration::from_millis(lag).as_secs_f64(), &[]);
|
||||||
|
}
|
||||||
|
instruments
|
||||||
|
.federation_incoming_pdus
|
||||||
|
.add(1, &[event_type, outcome]);
|
||||||
|
|
||||||
|
results.push((event_id, result));
|
||||||
}
|
}
|
||||||
Ok(results)
|
Ok(results)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -395,10 +395,6 @@ pub(super) static MAPS: &[Descriptor] = &[
|
|||||||
block_size: 512,
|
block_size: 512,
|
||||||
..descriptor::RANDOM
|
..descriptor::RANDOM
|
||||||
},
|
},
|
||||||
Descriptor {
|
|
||||||
name: "txn_jobid_job",
|
|
||||||
..descriptor::RANDOM
|
|
||||||
},
|
|
||||||
Descriptor {
|
Descriptor {
|
||||||
name: "url_previews",
|
name: "url_previews",
|
||||||
..descriptor::RANDOM
|
..descriptor::RANDOM
|
||||||
|
|||||||
+29
-31
@@ -11,8 +11,8 @@ version.workspace = true
|
|||||||
[lib]
|
[lib]
|
||||||
path = "mod.rs"
|
path = "mod.rs"
|
||||||
crate-type = [
|
crate-type = [
|
||||||
"rlib",
|
"rlib",
|
||||||
# "dylib",
|
# "dylib",
|
||||||
]
|
]
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
@@ -23,61 +23,61 @@ bindgen-static = [
|
|||||||
"conduwuit-database/bindgen-static"
|
"conduwuit-database/bindgen-static"
|
||||||
]
|
]
|
||||||
brotli_compression = [
|
brotli_compression = [
|
||||||
"conduwuit-core/brotli_compression",
|
"conduwuit-core/brotli_compression",
|
||||||
"reqwest/brotli",
|
"reqwest/brotli",
|
||||||
]
|
]
|
||||||
console = [
|
console = [
|
||||||
"dep:rustyline-async",
|
"dep:rustyline-async",
|
||||||
"dep:termimad",
|
"dep:termimad",
|
||||||
]
|
]
|
||||||
element_hacks = []
|
element_hacks = []
|
||||||
gzip_compression = [
|
gzip_compression = [
|
||||||
"conduwuit-core/gzip_compression",
|
"conduwuit-core/gzip_compression",
|
||||||
"reqwest/gzip",
|
"reqwest/gzip",
|
||||||
]
|
]
|
||||||
http3 = [
|
http3 = [
|
||||||
"reqwest/http3"
|
"reqwest/http3"
|
||||||
]
|
]
|
||||||
io_uring = [
|
io_uring = [
|
||||||
"conduwuit-database/io_uring",
|
"conduwuit-database/io_uring",
|
||||||
]
|
]
|
||||||
jemalloc = [
|
jemalloc = [
|
||||||
"conduwuit-core/jemalloc",
|
"conduwuit-core/jemalloc",
|
||||||
"conduwuit-database/jemalloc",
|
"conduwuit-database/jemalloc",
|
||||||
]
|
]
|
||||||
jemalloc_conf = [
|
jemalloc_conf = [
|
||||||
"conduwuit-core/jemalloc_conf",
|
"conduwuit-core/jemalloc_conf",
|
||||||
"conduwuit-database/jemalloc_conf",
|
"conduwuit-database/jemalloc_conf",
|
||||||
]
|
]
|
||||||
jemalloc_prof = [
|
jemalloc_prof = [
|
||||||
"conduwuit-core/jemalloc_prof",
|
"conduwuit-core/jemalloc_prof",
|
||||||
"conduwuit-database/jemalloc_prof",
|
"conduwuit-database/jemalloc_prof",
|
||||||
]
|
]
|
||||||
jemalloc_stats = [
|
jemalloc_stats = [
|
||||||
"conduwuit-core/jemalloc_stats",
|
"conduwuit-core/jemalloc_stats",
|
||||||
"conduwuit-database/jemalloc_stats",
|
"conduwuit-database/jemalloc_stats",
|
||||||
]
|
]
|
||||||
media_thumbnail = [
|
media_thumbnail = [
|
||||||
"dep:image",
|
"dep:image",
|
||||||
]
|
]
|
||||||
release_max_log_level = [
|
release_max_log_level = [
|
||||||
"conduwuit-core/release_max_log_level",
|
"conduwuit-core/release_max_log_level",
|
||||||
"conduwuit-database/release_max_log_level",
|
"conduwuit-database/release_max_log_level",
|
||||||
"log/max_level_trace",
|
"log/max_level_trace",
|
||||||
"log/release_max_level_info",
|
"log/release_max_level_info",
|
||||||
"tracing/max_level_trace",
|
"tracing/max_level_trace",
|
||||||
"tracing/release_max_level_info",
|
"tracing/release_max_level_info",
|
||||||
]
|
]
|
||||||
systemd = [
|
systemd = [
|
||||||
"dep:sd-notify",
|
"dep:sd-notify",
|
||||||
]
|
]
|
||||||
url_preview = [
|
url_preview = [
|
||||||
"dep:image",
|
"dep:image",
|
||||||
"dep:webpage",
|
"dep:webpage",
|
||||||
]
|
]
|
||||||
zstd_compression = [
|
zstd_compression = [
|
||||||
"conduwuit-core/zstd_compression",
|
"conduwuit-core/zstd_compression",
|
||||||
"conduwuit-database/zstd_compression",
|
"conduwuit-database/zstd_compression",
|
||||||
"reqwest/zstd",
|
"reqwest/zstd",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -122,7 +122,6 @@ sha2.workspace = true
|
|||||||
termimad.workspace = true
|
termimad.workspace = true
|
||||||
termimad.optional = true
|
termimad.optional = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tokio-stream.workspace = true
|
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
url.workspace = true
|
url.workspace = true
|
||||||
web-push-native.workspace = true
|
web-push-native.workspace = true
|
||||||
@@ -137,7 +136,6 @@ openidconnect.workspace = true
|
|||||||
# which is necessary to call `danger_accept_invalid_certs`.
|
# which is necessary to call `danger_accept_invalid_certs`.
|
||||||
reqwest_0_12.workspace = true
|
reqwest_0_12.workspace = true
|
||||||
rand.workspace = true
|
rand.workspace = true
|
||||||
opentelemetry.workspace = true
|
|
||||||
|
|
||||||
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
|
||||||
sd-notify.workspace = true
|
sd-notify.workspace = true
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ pub mod membership;
|
|||||||
pub mod metadata;
|
pub mod metadata;
|
||||||
pub mod outlier;
|
pub mod outlier;
|
||||||
pub mod pdu_metadata;
|
pub mod pdu_metadata;
|
||||||
pub mod queue;
|
|
||||||
pub mod read_receipt;
|
pub mod read_receipt;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
pub mod short;
|
pub mod short;
|
||||||
@@ -33,7 +32,6 @@ pub struct Service {
|
|||||||
pub metadata: Arc<metadata::Service>,
|
pub metadata: Arc<metadata::Service>,
|
||||||
pub outlier: Arc<outlier::Service>,
|
pub outlier: Arc<outlier::Service>,
|
||||||
pub pdu_metadata: Arc<pdu_metadata::Service>,
|
pub pdu_metadata: Arc<pdu_metadata::Service>,
|
||||||
pub queue: Arc<queue::Service>,
|
|
||||||
pub read_receipt: Arc<read_receipt::Service>,
|
pub read_receipt: Arc<read_receipt::Service>,
|
||||||
pub search: Arc<search::Service>,
|
pub search: Arc<search::Service>,
|
||||||
pub short: Arc<short::Service>,
|
pub short: Arc<short::Service>,
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use conduwuit::{Result, utils::stream::TryIgnore};
|
|
||||||
use database::{Deserialized, Json, Map};
|
|
||||||
|
|
||||||
pub(super) struct Data {
|
|
||||||
pub global: Arc<Map>,
|
|
||||||
jobcounter_mutex: tokio::sync::RwLock<()>,
|
|
||||||
pub txn_jobid_job: Arc<Map>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Data {
|
|
||||||
pub(super) fn new(services: &crate::Args<'_>) -> Self {
|
|
||||||
Self {
|
|
||||||
global: services.db["global"].clone(),
|
|
||||||
jobcounter_mutex: tokio::sync::RwLock::new(()),
|
|
||||||
txn_jobid_job: services.db["txn_jobid_job"].clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the current job counter value.
|
|
||||||
#[must_use]
|
|
||||||
pub(super) async fn current_job_id(&self) -> u64 {
|
|
||||||
let _lock = self.jobcounter_mutex.read().await;
|
|
||||||
self.global
|
|
||||||
.get("txn_jobcounter")
|
|
||||||
.await
|
|
||||||
.deserialized()
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Increments the global job counter, returning the new value.
|
|
||||||
#[must_use]
|
|
||||||
pub(super) async fn next_job_id(&self) -> u64 {
|
|
||||||
let _lock = self.jobcounter_mutex.write().await;
|
|
||||||
let current = self
|
|
||||||
.global
|
|
||||||
.get("txn_jobcounter")
|
|
||||||
.await
|
|
||||||
.deserialized::<u64>()
|
|
||||||
.unwrap_or_default();
|
|
||||||
let next = current.checked_add(1).unwrap_or(current);
|
|
||||||
self.global.insert("txn_jobcounter", next.to_be_bytes());
|
|
||||||
next
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Saves a job and returns its ID.
|
|
||||||
pub(super) async fn save_job(&self, job: &super::QueueJob) -> Result<u64> {
|
|
||||||
let job_id = self.next_job_id().await;
|
|
||||||
self.txn_jobid_job.raw_put(job_id.to_be_bytes(), Json(job));
|
|
||||||
Ok(job_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Removes a job from the database.
|
|
||||||
#[inline]
|
|
||||||
pub(super) fn finish_job(&self, job_id: u64) {
|
|
||||||
self.txn_jobid_job.remove(&job_id.to_be_bytes());
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn stream_all_pending_jobs(
|
|
||||||
&self,
|
|
||||||
) -> impl futures::Stream<Item = (u64, super::QueueJob)> + '_ {
|
|
||||||
self.txn_jobid_job.stream().ignore_err()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,259 +0,0 @@
|
|||||||
mod data;
|
|
||||||
|
|
||||||
use std::{
|
|
||||||
collections::{HashMap, hash_map::Entry},
|
|
||||||
sync::{Arc, OnceLock},
|
|
||||||
time::{Duration, Instant},
|
|
||||||
};
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use conduwuit::{
|
|
||||||
Error, Result, Server, SyncMutex, debug, err, error, info, utils::millis_since_unix_epoch,
|
|
||||||
};
|
|
||||||
use futures::StreamExt;
|
|
||||||
use opentelemetry::KeyValue;
|
|
||||||
use ruma::{
|
|
||||||
CanonicalJsonObject, CanonicalJsonValue, OwnedEventId, OwnedRoomId, OwnedServerName,
|
|
||||||
api::error::ErrorKind, events::TimelineEventType,
|
|
||||||
};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use tokio::{
|
|
||||||
sync::{
|
|
||||||
Notify, mpsc,
|
|
||||||
mpsc::{Sender, UnboundedReceiver, UnboundedSender},
|
|
||||||
},
|
|
||||||
task::JoinSet,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
rooms,
|
|
||||||
service::{Args, Dep},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct Services {
|
|
||||||
event_handler: Dep<rooms::event_handler::Service>,
|
|
||||||
server: Arc<Server>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Service {
|
|
||||||
data: data::Data,
|
|
||||||
queues: SyncMutex<HashMap<OwnedRoomId, UnboundedSender<(u64, QueueJob)>>>,
|
|
||||||
send: OnceLock<Sender<(u64, QueueJob)>>,
|
|
||||||
shutdown: Notify,
|
|
||||||
services: Services,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl crate::Service for Service {
|
|
||||||
fn build(args: Args<'_>) -> Result<Arc<Self>>
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
Ok(Arc::new(Self {
|
|
||||||
data: data::Data::new(&args),
|
|
||||||
queues: SyncMutex::new(HashMap::new()),
|
|
||||||
shutdown: Notify::new(),
|
|
||||||
send: OnceLock::new(),
|
|
||||||
services: Services {
|
|
||||||
event_handler: args.depend("rooms::event_handler"),
|
|
||||||
server: args.server.clone(),
|
|
||||||
},
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn worker(self: Arc<Self>) -> Result<()> {
|
|
||||||
let (send, recv) = mpsc::channel(5);
|
|
||||||
self.send
|
|
||||||
.set(send)
|
|
||||||
.expect("send channel cannot already be set during worker init");
|
|
||||||
let mut recv = tokio_stream::wrappers::ReceiverStream::new(recv);
|
|
||||||
let mut handles = JoinSet::new();
|
|
||||||
let (yielder, mut yielding) = mpsc::channel(5);
|
|
||||||
|
|
||||||
let latest_job_id = self.data.current_job_id().await;
|
|
||||||
let backlog_count = self.data.txn_jobid_job.count().await;
|
|
||||||
debug!(latest_job_id, backlog_count, "Starting room queue worker");
|
|
||||||
|
|
||||||
let backlog = std::pin::pin!(self.data.stream_all_pending_jobs());
|
|
||||||
let mut combined_recv = backlog.chain(&mut recv);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let Some((job_id, job)) = tokio::select! (
|
|
||||||
() = self.shutdown.notified() => {
|
|
||||||
info!("Shutting down");
|
|
||||||
yielding.close();
|
|
||||||
recv.close();
|
|
||||||
break;
|
|
||||||
},
|
|
||||||
room_id = yielding.recv() => {
|
|
||||||
if let Some(room_id) = room_id {
|
|
||||||
self.queues.lock().remove(&room_id);
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
},
|
|
||||||
job = combined_recv.next() => job,
|
|
||||||
) else {
|
|
||||||
debug!("Room queue worker channel closed without shutdown?");
|
|
||||||
break;
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut queues = self.queues.lock();
|
|
||||||
match queues.entry(job.room_id.clone()) {
|
|
||||||
| Entry::Occupied(entry) => {
|
|
||||||
entry.get().send((job_id, job)).unwrap();
|
|
||||||
// TODO: handle error
|
|
||||||
// It might be possible for a self-reaping worker to close
|
|
||||||
// at the same time we try to send to it, which will cause
|
|
||||||
// this send to return a "channel closed" error.
|
|
||||||
},
|
|
||||||
| Entry::Vacant(entry) => {
|
|
||||||
let room_id = entry.key().to_owned();
|
|
||||||
let (sender, receiver) = mpsc::unbounded_channel();
|
|
||||||
sender.send((job_id, job)).unwrap(); // TODO: handle error
|
|
||||||
|
|
||||||
handles.spawn_on(
|
|
||||||
Self::room_worker(self.clone(), room_id, receiver, yielder.clone()),
|
|
||||||
self.services.server.runtime(),
|
|
||||||
);
|
|
||||||
entry.insert(sender);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the loop broke, make sure that the shutdown signal was sent, so
|
|
||||||
// that any room workers are guaranteed to shut down as soon as
|
|
||||||
// possible.
|
|
||||||
self.interrupt();
|
|
||||||
|
|
||||||
while let Some(ret) = handles.join_next_with_id().await {
|
|
||||||
match ret {
|
|
||||||
| Ok((id, ())) => {
|
|
||||||
debug!(?id, "room queue worker finished");
|
|
||||||
},
|
|
||||||
| Err(error) => {
|
|
||||||
error!(id = ?error.id(), ?error, "room queue worker failed");
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn interrupt(&self) { self.shutdown.notify_waiters(); }
|
|
||||||
|
|
||||||
fn name(&self) -> &'static str { module_path!() }
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Service {
|
|
||||||
pub async fn new_job(&self, job: QueueJob) -> Result<()> {
|
|
||||||
let job_id = self.data.save_job(&job).await?;
|
|
||||||
self.send
|
|
||||||
.get()
|
|
||||||
.expect("send channel must be set before new_job is called")
|
|
||||||
.send((job_id, job))
|
|
||||||
.await
|
|
||||||
.map_err(|e| err!("failed to send PDU to worker: {e}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tracing::instrument(skip(self,channel,yielder), fields(%room_id))]
|
|
||||||
async fn room_worker(
|
|
||||||
self: Arc<Self>,
|
|
||||||
room_id: OwnedRoomId,
|
|
||||||
mut channel: UnboundedReceiver<(u64, QueueJob)>,
|
|
||||||
yielder: Sender<OwnedRoomId>,
|
|
||||||
) {
|
|
||||||
debug!("Room worker starting up");
|
|
||||||
loop {
|
|
||||||
let job = tokio::select! {
|
|
||||||
() = self.shutdown.notified() => {
|
|
||||||
debug!("Room worker shutting down");
|
|
||||||
channel.close();
|
|
||||||
return;
|
|
||||||
},
|
|
||||||
() = tokio::time::sleep(Duration::from_mins(5)) => {
|
|
||||||
debug!("Room worker self-reaping (no activity in 5 minutes)");
|
|
||||||
yielder.send(room_id).await.ok();
|
|
||||||
debug!("Room worker reaped. Goodbye.");
|
|
||||||
return;
|
|
||||||
},
|
|
||||||
job = channel.recv() => job
|
|
||||||
};
|
|
||||||
let Some((job_id, job)) = job else {
|
|
||||||
debug!("Room worker channel closed without shutdown?");
|
|
||||||
break;
|
|
||||||
};
|
|
||||||
debug!(
|
|
||||||
%job_id,
|
|
||||||
event_id=%job.event_id,
|
|
||||||
origin=%job.origin,
|
|
||||||
backpressure=%channel.len(),
|
|
||||||
"Handling incoming job"
|
|
||||||
);
|
|
||||||
let _room_lock = self
|
|
||||||
.services
|
|
||||||
.event_handler
|
|
||||||
.mutex_federation
|
|
||||||
.lock(room_id.as_str())
|
|
||||||
.await;
|
|
||||||
debug!(%job_id, event_id=%job.event_id, origin=%job.origin, "Acquired room federation lock");
|
|
||||||
|
|
||||||
let event_type = KeyValue::new(
|
|
||||||
"type",
|
|
||||||
pdu_type_label(job.object.get("type").and_then(CanonicalJsonValue::as_str)),
|
|
||||||
);
|
|
||||||
let origin_server_ts = job
|
|
||||||
.object
|
|
||||||
.get("origin_server_ts")
|
|
||||||
.and_then(CanonicalJsonValue::as_integer)
|
|
||||||
.and_then(|ts| u64::try_from(i64::from(ts)).ok());
|
|
||||||
|
|
||||||
let start = Instant::now();
|
|
||||||
|
|
||||||
let result = self
|
|
||||||
.services
|
|
||||||
.event_handler
|
|
||||||
.handle_incoming_pdu(&job.origin, &job.room_id, &job.event_id, job.object, false)
|
|
||||||
.await;
|
|
||||||
self.data.finish_job(job_id);
|
|
||||||
|
|
||||||
let outcome = KeyValue::new("outcome", match &result {
|
|
||||||
| Ok(_) => "accepted",
|
|
||||||
| Err(Error::BadRequest(ErrorKind::Forbidden, ..)) => "forbidden",
|
|
||||||
| Err(Error::BadRequest(ErrorKind::InvalidParam | ErrorKind::BadJson, ..)) =>
|
|
||||||
"invalid",
|
|
||||||
| Err(_) => "error",
|
|
||||||
});
|
|
||||||
let instruments = &self.services.server.metrics.instruments;
|
|
||||||
instruments
|
|
||||||
.federation_incoming_pdu_duration
|
|
||||||
.record(start.elapsed().as_secs_f64(), std::slice::from_ref(&outcome));
|
|
||||||
if let (Ok(_), Some(ts)) = (&result, origin_server_ts) {
|
|
||||||
let lag = millis_since_unix_epoch().saturating_sub(ts);
|
|
||||||
instruments
|
|
||||||
.federation_incoming_pdu_lag
|
|
||||||
.record(Duration::from_millis(lag).as_secs_f64(), &[]);
|
|
||||||
}
|
|
||||||
instruments
|
|
||||||
.federation_incoming_pdus
|
|
||||||
.add(1, &[event_type, outcome]);
|
|
||||||
debug!(event_id=%job.event_id, origin=%job.origin, "Job finished");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
|
||||||
pub struct QueueJob {
|
|
||||||
pub origin: OwnedServerName,
|
|
||||||
pub event_id: OwnedEventId,
|
|
||||||
pub room_id: OwnedRoomId,
|
|
||||||
pub object: CanonicalJsonObject,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Known event types, or `other`, so remote servers cannot create new
|
|
||||||
/// attribute values.
|
|
||||||
fn pdu_type_label(event_type: Option<&str>) -> String {
|
|
||||||
match event_type.map(TimelineEventType::from) {
|
|
||||||
| Some(TimelineEventType::_Custom(_)) | None => "other".to_owned(),
|
|
||||||
| Some(event_type) => event_type.to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -101,7 +101,6 @@ impl Services {
|
|||||||
metadata: build!(rooms::metadata::Service),
|
metadata: build!(rooms::metadata::Service),
|
||||||
outlier: build!(rooms::outlier::Service),
|
outlier: build!(rooms::outlier::Service),
|
||||||
pdu_metadata: build!(rooms::pdu_metadata::Service),
|
pdu_metadata: build!(rooms::pdu_metadata::Service),
|
||||||
queue: build!(rooms::queue::Service),
|
|
||||||
read_receipt: build!(rooms::read_receipt::Service),
|
read_receipt: build!(rooms::read_receipt::Service),
|
||||||
search: build!(rooms::search::Service),
|
search: build!(rooms::search::Service),
|
||||||
short: build!(rooms::short::Service),
|
short: build!(rooms::short::Service),
|
||||||
|
|||||||
Reference in new issue
Block a user