Fix spans in tokio::spawn-ed tasks

tokio::spawn is a span boundary, the spawned future has no parent span.

For short futures, we simply inherit the current span with
`.in_current_span()`.

For long running futures containing a sleeping infinite loop, we don't
actually want a span on the entire task or even the entire loop body,
both would result in very long spans. Instead, we put the outermost span
(created using #[tracing::instrument] or .instrument()) around the
actual work happening after the sleep, which results in a new root span
being created after every sleep.
This commit is contained in:
Lambda 2024-05-19 21:39:13 +00:00
parent 5e9e5b76bc
commit ac42e0bfff
3 changed files with 109 additions and 70 deletions

View file

@ -22,7 +22,7 @@ use ruma::{
CanonicalJsonValue, EventId, OwnedDeviceId, OwnedEventId, OwnedRoomId,
OwnedUserId, RoomId, UserId,
};
use tracing::{debug, error, info, warn};
use tracing::{debug, error, info, info_span, warn, Instrument};
use crate::{
service::rooms::timeline::PduCount, services, utils, Config, Error,
@ -1200,26 +1200,31 @@ impl KeyValueDatabase {
loop {
#[cfg(unix)]
tokio::select! {
_ = i.tick() => {
let msg = tokio::select! {
_ = i.tick() => || {
debug!("cleanup: Timer ticked");
}
_ = s.recv() => {
},
_ = s.recv() => || {
debug!("cleanup: Received SIGHUP");
}
},
};
#[cfg(not(unix))]
{
let msg = {
i.tick().await;
debug!("cleanup: Timer ticked")
}
|| debug!("cleanup: Timer ticked")
};
let start = Instant::now();
if let Err(e) = services().globals.cleanup() {
error!("cleanup: Errored: {}", e);
} else {
debug!("cleanup: Finished in {:?}", start.elapsed());
async {
msg();
let start = Instant::now();
if let Err(e) = services().globals.cleanup() {
error!("cleanup: Errored: {}", e);
} else {
debug!("cleanup: Finished in {:?}", start.elapsed());
}
}
.instrument(info_span!("database_cleanup"))
.await;
}
});
}