feat: Persist queue in database & resume on startup

This commit is contained in:
timedout committed 2026-12-01 18:15:15 +00:00
1 parent d97c2d7038
commit c9a3f9f907
5 files changed
+108 -20

No files matched your search

Generated
+1
View File
@@ -1155,6 +1155,7 @@ dependencies = [
"sha2 0.11.2",
"termimad",
"tokio",
"tokio-stream",
"tracing",
"url",
"web-push-native",
+3
View File
@@ -269,6 +269,9 @@ features = [
[workspace.dependencies.tokio-metrics]
version = "0.5.2"
[workspace.dependencies.tokio-stream]
version = "0.1.19"
[workspace.dependencies.wildmatch]
version = "2.7.0"
+1
View File
@@ -122,6 +122,7 @@ sha2.workspace = true
termimad.workspace = true
termimad.optional = true
tokio.workspace = true
tokio-stream.workspace = true
tracing.workspace = true
url.workspace = true
web-push-native.workspace = true
+65
View File
@@ -0,0 +1,65 @@
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()
}
}
+38 -20
View File
@@ -1,6 +1,8 @@
mod data;
use std::{
collections::{HashMap, hash_map::Entry},
sync::Arc,
sync::{Arc, OnceLock},
time::{Duration, Instant},
};
@@ -8,11 +10,13 @@ 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,
@@ -32,9 +36,9 @@ pub struct Services {
}
pub struct Service {
queues: SyncMutex<HashMap<OwnedRoomId, UnboundedSender<QueueJob>>>,
send: Sender<QueueJob>,
recv: tokio::sync::Mutex<mpsc::Receiver<QueueJob>>,
data: data::Data,
queues: SyncMutex<HashMap<OwnedRoomId, UnboundedSender<(u64, QueueJob)>>>,
send: OnceLock<Sender<(u64, QueueJob)>>,
shutdown: Notify,
services: Services,
}
@@ -45,12 +49,11 @@ impl crate::Service for Service {
where
Self: Sized,
{
let (send, recv) = mpsc::channel(1);
Ok(Arc::new(Self {
data: data::Data::new(&args),
queues: SyncMutex::new(HashMap::new()),
shutdown: Notify::new(),
send,
recv: tokio::sync::Mutex::new(recv),
send: OnceLock::new(),
services: Services {
event_handler: args.depend("rooms::event_handler"),
server: args.server.clone(),
@@ -59,12 +62,22 @@ impl crate::Service for Service {
}
async fn worker(self: Arc<Self>) -> Result<()> {
let mut recv = self.recv.lock().await;
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;
debug!(latest_job_id, "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 job = tokio::select! {
let Some((job_id, job)) = tokio::select! (
() = self.shutdown.notified() => {
info!("Shutting down");
yielding.close();
@@ -76,18 +89,17 @@ impl crate::Service for Service {
self.queues.lock().remove(&room_id);
}
continue;
}
job = recv.recv() => job
};
let Some(job) = job else {
debug!("No job (channel closed)");
},
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).unwrap();
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
@@ -96,7 +108,7 @@ impl crate::Service for Service {
| Entry::Vacant(entry) => {
let room_id = entry.key().to_owned();
let (sender, receiver) = mpsc::unbounded_channel();
sender.send(job).unwrap(); // TODO: handle error
sender.send((job_id, job)).unwrap(); // TODO: handle error
handles.spawn_on(
Self::room_worker(self.clone(), room_id, receiver, yielder.clone()),
@@ -133,8 +145,11 @@ impl crate::Service for Service {
impl Service {
pub async fn new_job(&self, job: QueueJob) -> Result<()> {
let job_id = self.data.save_job(&job).await?;
self.send
.send(job)
.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}"))
}
@@ -143,7 +158,7 @@ impl Service {
async fn room_worker(
self: Arc<Self>,
room_id: OwnedRoomId,
mut channel: UnboundedReceiver<QueueJob>,
mut channel: UnboundedReceiver<(u64, QueueJob)>,
yielder: Sender<OwnedRoomId>,
) {
debug!("Room worker starting up");
@@ -162,11 +177,12 @@ impl Service {
},
job = channel.recv() => job
};
let Some(job) = job else {
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(),
@@ -178,7 +194,7 @@ impl Service {
.mutex_federation
.lock(room_id.as_str())
.await;
debug!(event_id=%job.event_id, origin=%job.origin, "Acquired room federation lock");
debug!(%job_id, event_id=%job.event_id, origin=%job.origin, "Acquired room federation lock");
let event_type = KeyValue::new(
"type",
@@ -197,6 +213,7 @@ impl Service {
.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",
@@ -223,6 +240,7 @@ impl Service {
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct QueueJob {
pub origin: OwnedServerName,
pub event_id: OwnedEventId,