record FoundIn with metrics instead of traces

This is much more efficient in terms of network use and data storage,
and also easier to visualize.
This commit is contained in:
Charles Hall 2024-06-04 13:26:23 -07:00
parent 7076c13058
commit 72860d98db
No known key found for this signature in database
GPG key ID: 7B8E0645816E07CF
8 changed files with 139 additions and 67 deletions

View file

@ -67,7 +67,7 @@ use tracing::{debug, error, field, warn};
use crate::{ use crate::{
api::client_server::{self, claim_keys_helper, get_keys_helper}, api::client_server::{self, claim_keys_helper, get_keys_helper},
observability::FoundIn, observability::{FoundIn, FoundKind, METRICS},
service::pdu::{gen_event_id_canonical_json, PduBuilder}, service::pdu::{gen_event_id_canonical_json, PduBuilder},
services, utils, Ar, Error, PduEvent, Ra, Result, services, utils, Ar, Error, PduEvent, Ra, Result,
}; };
@ -128,7 +128,7 @@ impl FedDest {
} }
} }
#[tracing::instrument(skip(request), fields(destination_cache_result, url))] #[tracing::instrument(skip(request), fields(url))]
pub(crate) async fn send_request<T>( pub(crate) async fn send_request<T>(
destination: &ServerName, destination: &ServerName,
request: T, request: T,
@ -159,7 +159,7 @@ where
.cloned(); .cloned();
let (actual_destination, host) = if let Some(result) = cached_result { let (actual_destination, host) = if let Some(result) = cached_result {
FoundIn::Cache.record("destination_cache_result"); METRICS.record_lookup(FoundKind::FederationDestination, FoundIn::Cache);
result result
} else { } else {
write_destination_to_cache = true; write_destination_to_cache = true;
@ -298,7 +298,10 @@ where
let response = let response =
T::IncomingResponse::try_from_http_response(http_response); T::IncomingResponse::try_from_http_response(http_response);
if response.is_ok() && write_destination_to_cache { if response.is_ok() && write_destination_to_cache {
FoundIn::Remote.record("destination_cache_result"); METRICS.record_lookup(
FoundKind::FederationDestination,
FoundIn::Remote,
);
services() services()
.globals .globals
.actual_destination_cache .actual_destination_cache

View file

@ -1,19 +1,23 @@
use std::{collections::HashSet, mem::size_of, sync::Arc}; use std::{collections::HashSet, mem::size_of, sync::Arc};
use crate::{ use crate::{
database::KeyValueDatabase, observability::FoundIn, service, utils, Result, database::KeyValueDatabase,
observability::{FoundIn, FoundKind, METRICS},
service, utils, Result,
}; };
impl service::rooms::auth_chain::Data for KeyValueDatabase { impl service::rooms::auth_chain::Data for KeyValueDatabase {
#[tracing::instrument(skip(self, key), fields(cache_result))] #[tracing::instrument(skip(self, key))]
fn get_cached_eventid_authchain( fn get_cached_eventid_authchain(
&self, &self,
key: &[u64], key: &[u64],
) -> Result<Option<Arc<HashSet<u64>>>> { ) -> Result<Option<Arc<HashSet<u64>>>> {
let found_kind = FoundKind::AuthChain;
// Check RAM cache // Check RAM cache
if let Some(result) = self.auth_chain_cache.lock().unwrap().get_mut(key) if let Some(result) = self.auth_chain_cache.lock().unwrap().get_mut(key)
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(Some(Arc::clone(result))); return Ok(Some(Arc::clone(result)));
} }
@ -34,7 +38,7 @@ impl service::rooms::auth_chain::Data for KeyValueDatabase {
}); });
if let Some(chain) = chain { if let Some(chain) = chain {
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
let chain = Arc::new(chain); let chain = Arc::new(chain);
// Cache in RAM // Cache in RAM
@ -47,7 +51,7 @@ impl service::rooms::auth_chain::Data for KeyValueDatabase {
} }
} }
FoundIn::Nothing.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Nothing);
Ok(None) Ok(None)
} }

View file

@ -3,30 +3,33 @@ use std::sync::Arc;
use ruma::{events::StateEventType, EventId, RoomId}; use ruma::{events::StateEventType, EventId, RoomId};
use crate::{ use crate::{
database::KeyValueDatabase, observability::FoundIn, service, services, database::KeyValueDatabase,
utils, Error, Result, observability::{FoundIn, FoundKind, METRICS},
service, services, utils, Error, Result,
}; };
impl service::rooms::short::Data for KeyValueDatabase { impl service::rooms::short::Data for KeyValueDatabase {
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result<u64> { fn get_or_create_shorteventid(&self, event_id: &EventId) -> Result<u64> {
let found_kind = FoundKind::EventIdToShort;
if let Some(short) = if let Some(short) =
self.eventidshort_cache.lock().unwrap().get_mut(event_id) self.eventidshort_cache.lock().unwrap().get_mut(event_id)
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(*short); return Ok(*short);
} }
let short = if let Some(shorteventid) = let short = if let Some(shorteventid) =
self.eventid_shorteventid.get(event_id.as_bytes())? self.eventid_shorteventid.get(event_id.as_bytes())?
{ {
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
utils::u64_from_bytes(&shorteventid).map_err(|_| { utils::u64_from_bytes(&shorteventid).map_err(|_| {
Error::bad_database("Invalid shorteventid in db.") Error::bad_database("Invalid shorteventid in db.")
})? })?
} else { } else {
FoundIn::Nothing.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Nothing);
let shorteventid = services().globals.next_count()?; let shorteventid = services().globals.next_count()?;
self.eventid_shorteventid self.eventid_shorteventid
@ -50,13 +53,15 @@ impl service::rooms::short::Data for KeyValueDatabase {
event_type: &StateEventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
) -> Result<Option<u64>> { ) -> Result<Option<u64>> {
let found_kind = FoundKind::StateKeyToShort;
if let Some(short) = self if let Some(short) = self
.statekeyshort_cache .statekeyshort_cache
.lock() .lock()
.unwrap() .unwrap()
.get_mut(&(event_type.clone(), state_key.to_owned())) .get_mut(&(event_type.clone(), state_key.to_owned()))
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(Some(*short)); return Ok(Some(*short));
} }
@ -75,32 +80,34 @@ impl service::rooms::short::Data for KeyValueDatabase {
.transpose()?; .transpose()?;
if let Some(s) = short { if let Some(s) = short {
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.statekeyshort_cache self.statekeyshort_cache
.lock() .lock()
.unwrap() .unwrap()
.insert((event_type.clone(), state_key.to_owned()), s); .insert((event_type.clone(), state_key.to_owned()), s);
} else { } else {
FoundIn::Nothing.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Nothing);
} }
Ok(short) Ok(short)
} }
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
fn get_or_create_shortstatekey( fn get_or_create_shortstatekey(
&self, &self,
event_type: &StateEventType, event_type: &StateEventType,
state_key: &str, state_key: &str,
) -> Result<u64> { ) -> Result<u64> {
let found_kind = FoundKind::CreateStateKeyToShort;
if let Some(short) = self if let Some(short) = self
.statekeyshort_cache .statekeyshort_cache
.lock() .lock()
.unwrap() .unwrap()
.get_mut(&(event_type.clone(), state_key.to_owned())) .get_mut(&(event_type.clone(), state_key.to_owned()))
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(*short); return Ok(*short);
} }
@ -111,13 +118,13 @@ impl service::rooms::short::Data for KeyValueDatabase {
let short = if let Some(shortstatekey) = let short = if let Some(shortstatekey) =
self.statekey_shortstatekey.get(&db_key)? self.statekey_shortstatekey.get(&db_key)?
{ {
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
utils::u64_from_bytes(&shortstatekey).map_err(|_| { utils::u64_from_bytes(&shortstatekey).map_err(|_| {
Error::bad_database("Invalid shortstatekey in db.") Error::bad_database("Invalid shortstatekey in db.")
})? })?
} else { } else {
FoundIn::Nothing.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Nothing);
let shortstatekey = services().globals.next_count()?; let shortstatekey = services().globals.next_count()?;
self.statekey_shortstatekey self.statekey_shortstatekey
@ -135,15 +142,17 @@ impl service::rooms::short::Data for KeyValueDatabase {
Ok(short) Ok(short)
} }
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
fn get_eventid_from_short( fn get_eventid_from_short(
&self, &self,
shorteventid: u64, shorteventid: u64,
) -> Result<Arc<EventId>> { ) -> Result<Arc<EventId>> {
let found_kind = FoundKind::ShortToEventId;
if let Some(id) = if let Some(id) =
self.shorteventid_cache.lock().unwrap().get_mut(&shorteventid) self.shorteventid_cache.lock().unwrap().get_mut(&shorteventid)
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(Arc::clone(id)); return Ok(Arc::clone(id));
} }
@ -165,7 +174,7 @@ impl service::rooms::short::Data for KeyValueDatabase {
Error::bad_database("EventId in shorteventid_eventid is invalid.") Error::bad_database("EventId in shorteventid_eventid is invalid.")
})?; })?;
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.shorteventid_cache self.shorteventid_cache
.lock() .lock()
@ -175,15 +184,17 @@ impl service::rooms::short::Data for KeyValueDatabase {
Ok(event_id) Ok(event_id)
} }
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
fn get_statekey_from_short( fn get_statekey_from_short(
&self, &self,
shortstatekey: u64, shortstatekey: u64,
) -> Result<(StateEventType, String)> { ) -> Result<(StateEventType, String)> {
let found_kind = FoundKind::ShortToStateKey;
if let Some(id) = if let Some(id) =
self.shortstatekey_cache.lock().unwrap().get_mut(&shortstatekey) self.shortstatekey_cache.lock().unwrap().get_mut(&shortstatekey)
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(id.clone()); return Ok(id.clone());
} }
@ -218,7 +229,7 @@ impl service::rooms::short::Data for KeyValueDatabase {
let result = (event_type, state_key); let result = (event_type, state_key);
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.shortstatekey_cache self.shortstatekey_cache
.lock() .lock()

View file

@ -8,7 +8,7 @@ use ruma::{
use crate::{ use crate::{
database::KeyValueDatabase, database::KeyValueDatabase,
observability::FoundIn, observability::{FoundIn, FoundKind, METRICS},
service::{self, appservice::RegistrationInfo}, service::{self, appservice::RegistrationInfo},
services, utils, Error, Result, services, utils, Error, Result,
}; };
@ -171,19 +171,21 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
Ok(()) Ok(())
} }
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
fn get_our_real_users( fn get_our_real_users(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
) -> Result<Arc<HashSet<OwnedUserId>>> { ) -> Result<Arc<HashSet<OwnedUserId>>> {
let found_kind = FoundKind::OurRealUsers;
let maybe = let maybe =
self.our_real_users_cache.read().unwrap().get(room_id).cloned(); self.our_real_users_cache.read().unwrap().get(room_id).cloned();
if let Some(users) = maybe { if let Some(users) = maybe {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
Ok(users) Ok(users)
} else { } else {
self.update_joined_count(room_id)?; self.update_joined_count(room_id)?;
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
Ok(Arc::clone( Ok(Arc::clone(
self.our_real_users_cache.read().unwrap().get(room_id).unwrap(), self.our_real_users_cache.read().unwrap().get(room_id).unwrap(),
)) ))
@ -192,13 +194,15 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
#[tracing::instrument( #[tracing::instrument(
skip(self, appservice), skip(self, appservice),
fields(cache_result, appservice_id = appservice.registration.id), fields(appservice_id = appservice.registration.id),
)] )]
fn appservice_in_room( fn appservice_in_room(
&self, &self,
room_id: &RoomId, room_id: &RoomId,
appservice: &RegistrationInfo, appservice: &RegistrationInfo,
) -> Result<bool> { ) -> Result<bool> {
let found_kind = FoundKind::AppserviceInRoom;
let maybe = self let maybe = self
.appservice_in_room_cache .appservice_in_room_cache
.read() .read()
@ -208,7 +212,7 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
.copied(); .copied();
if let Some(b) = maybe { if let Some(b) = maybe {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
Ok(b) Ok(b)
} else { } else {
let bridge_user_id = UserId::parse_with_server_name( let bridge_user_id = UserId::parse_with_server_name(
@ -225,7 +229,7 @@ impl service::rooms::state_cache::Data for KeyValueDatabase {
}) })
}); });
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.appservice_in_room_cache self.appservice_in_room_cache
.write() .write()
.unwrap() .unwrap()

View file

@ -8,17 +8,20 @@ use service::rooms::timeline::PduCount;
use tracing::error; use tracing::error;
use crate::{ use crate::{
database::KeyValueDatabase, observability::FoundIn, service, services, database::KeyValueDatabase,
utils, Error, PduEvent, Result, observability::{FoundIn, FoundKind, METRICS},
service, services, utils, Error, PduEvent, Result,
}; };
impl service::rooms::timeline::Data for KeyValueDatabase { impl service::rooms::timeline::Data for KeyValueDatabase {
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
fn last_timeline_count( fn last_timeline_count(
&self, &self,
sender_user: &UserId, sender_user: &UserId,
room_id: &RoomId, room_id: &RoomId,
) -> Result<PduCount> { ) -> Result<PduCount> {
let found_kind = FoundKind::LastTimelineCount;
match self match self
.lasttimelinecount_cache .lasttimelinecount_cache
.lock() .lock()
@ -35,15 +38,15 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
r.ok() r.ok()
}) })
{ {
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
Ok(*v.insert(last_count.0)) Ok(*v.insert(last_count.0))
} else { } else {
FoundIn::Nothing.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Nothing);
Ok(PduCount::Normal(0)) Ok(PduCount::Normal(0))
} }
} }
hash_map::Entry::Occupied(o) => { hash_map::Entry::Occupied(o) => {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
Ok(*o.get()) Ok(*o.get())
} }
} }
@ -125,10 +128,12 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
/// Returns the pdu. /// Returns the pdu.
/// ///
/// Checks the `eventid_outlierpdu` Tree if not found in the timeline. /// Checks the `eventid_outlierpdu` Tree if not found in the timeline.
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
fn get_pdu(&self, event_id: &EventId) -> Result<Option<Arc<PduEvent>>> { fn get_pdu(&self, event_id: &EventId) -> Result<Option<Arc<PduEvent>>> {
let found_kind = FoundKind::Pdu;
if let Some(p) = self.pdu_cache.lock().unwrap().get_mut(event_id) { if let Some(p) = self.pdu_cache.lock().unwrap().get_mut(event_id) {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(Some(Arc::clone(p))); return Ok(Some(Arc::clone(p)));
} }
@ -149,14 +154,14 @@ impl service::rooms::timeline::Data for KeyValueDatabase {
)? )?
.map(Arc::new) .map(Arc::new)
{ {
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.pdu_cache self.pdu_cache
.lock() .lock()
.unwrap() .unwrap()
.insert(event_id.to_owned(), Arc::clone(&pdu)); .insert(event_id.to_owned(), Arc::clone(&pdu));
Ok(Some(pdu)) Ok(Some(pdu))
} else { } else {
FoundIn::Nothing.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Nothing);
Ok(None) Ok(None)
} }
} }

View file

@ -18,7 +18,7 @@ use opentelemetry_sdk::{
metrics::{new_view, Aggregation, Instrument, SdkMeterProvider, Stream}, metrics::{new_view, Aggregation, Instrument, SdkMeterProvider, Stream},
Resource, Resource,
}; };
use strum::AsRefStr; use strum::{AsRefStr, IntoStaticStr};
use tokio::time::Instant; use tokio::time::Instant;
use tracing_flame::{FlameLayer, FlushGuard}; use tracing_flame::{FlameLayer, FlushGuard};
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Layer, Registry}; use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Layer, Registry};
@ -41,8 +41,31 @@ impl Drop for Guard {
} }
} }
/// A kind of data that gets looked up
///
/// See also [`Metrics::record_lookup`].
// Keep variants sorted
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Clone, Copy, AsRefStr, IntoStaticStr)]
pub(crate) enum FoundKind {
AppserviceInRoom,
AuthChain,
CreateStateKeyToShort,
EventIdToShort,
FederationDestination,
LastTimelineCount,
OurRealUsers,
Pdu,
ShortToEventId,
ShortToStateKey,
StateInfo,
StateKeyToShort,
VisibilityForServer,
VisibilityForUser,
}
/// Type to record cache performance in a tracing span field. /// Type to record cache performance in a tracing span field.
#[derive(Clone, Copy, AsRefStr)] #[derive(Clone, Copy, AsRefStr, IntoStaticStr)]
pub(crate) enum FoundIn { pub(crate) enum FoundIn {
/// Found in cache /// Found in cache
Cache, Cache,
@ -55,14 +78,6 @@ pub(crate) enum FoundIn {
Nothing, Nothing,
} }
impl FoundIn {
/// Record the current value to the current [`tracing::Span`]
// TODO: use tracing::Value instead if it ever becomes accessible
pub(crate) fn record(self, field: &str) {
tracing::Span::current().record(field, self.as_ref());
}
}
/// Initialize observability /// Initialize observability
pub(crate) fn init(config: &Config) -> Result<Guard, error::Observability> { pub(crate) fn init(config: &Config) -> Result<Guard, error::Observability> {
let config_filter_layer = || EnvFilter::try_new(&config.log); let config_filter_layer = || EnvFilter::try_new(&config.log);
@ -137,6 +152,9 @@ pub(crate) struct Metrics {
/// Histogram of HTTP requests /// Histogram of HTTP requests
http_requests_histogram: opentelemetry::metrics::Histogram<f64>, http_requests_histogram: opentelemetry::metrics::Histogram<f64>,
/// Counts where data is found from
lookup: opentelemetry::metrics::Counter<u64>,
} }
impl Metrics { impl Metrics {
@ -182,9 +200,15 @@ impl Metrics {
.with_description("Histogram of HTTP requests") .with_description("Histogram of HTTP requests")
.init(); .init();
let lookup = meter
.u64_counter("lookup")
.with_description("Counts where data is found from")
.init();
Metrics { Metrics {
otel_state: (registry, provider), otel_state: (registry, provider),
http_requests_histogram, http_requests_histogram,
lookup,
} }
} }
@ -194,6 +218,17 @@ impl Metrics {
.encode_to_string(&self.otel_state.0.gather()) .encode_to_string(&self.otel_state.0.gather())
.expect("should be able to encode metrics") .expect("should be able to encode metrics")
} }
/// Record that some data was found in a particular storage location
pub(crate) fn record_lookup(&self, kind: FoundKind, r#in: FoundIn) {
self.lookup.add(
1,
&[
KeyValue::new("kind", <&str>::from(kind)),
KeyValue::new("in", <&str>::from(r#in)),
],
);
}
} }
/// Track HTTP metrics by converting this into an [`axum`] layer /// Track HTTP metrics by converting this into an [`axum`] layer

View file

@ -28,8 +28,9 @@ use tokio::sync::MutexGuard;
use tracing::{error, warn}; use tracing::{error, warn};
use crate::{ use crate::{
observability::FoundIn, service::pdu::PduBuilder, services, Error, observability::{FoundIn, FoundKind, METRICS},
PduEvent, Result, service::pdu::PduBuilder,
services, Error, PduEvent, Result,
}; };
pub(crate) struct Service { pub(crate) struct Service {
@ -123,13 +124,15 @@ impl Service {
/// Whether a server is allowed to see an event through federation, based on /// Whether a server is allowed to see an event through federation, based on
/// the room's history_visibility at that event's state. /// the room's history_visibility at that event's state.
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
pub(crate) fn server_can_see_event( pub(crate) fn server_can_see_event(
&self, &self,
origin: &ServerName, origin: &ServerName,
room_id: &RoomId, room_id: &RoomId,
event_id: &EventId, event_id: &EventId,
) -> Result<bool> { ) -> Result<bool> {
let found_kind = FoundKind::VisibilityForServer;
let Some(shortstatehash) = self.pdu_shortstatehash(event_id)? else { let Some(shortstatehash) = self.pdu_shortstatehash(event_id)? else {
return Ok(true); return Ok(true);
}; };
@ -140,7 +143,7 @@ impl Service {
.unwrap() .unwrap()
.get_mut(&(origin.to_owned(), shortstatehash)) .get_mut(&(origin.to_owned(), shortstatehash))
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(*visibility); return Ok(*visibility);
} }
@ -191,7 +194,7 @@ impl Service {
} }
}; };
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.server_visibility_cache self.server_visibility_cache
.lock() .lock()
.unwrap() .unwrap()
@ -202,13 +205,15 @@ impl Service {
/// Whether a user is allowed to see an event, based on /// Whether a user is allowed to see an event, based on
/// the room's history_visibility at that event's state. /// the room's history_visibility at that event's state.
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
pub(crate) fn user_can_see_event( pub(crate) fn user_can_see_event(
&self, &self,
user_id: &UserId, user_id: &UserId,
room_id: &RoomId, room_id: &RoomId,
event_id: &EventId, event_id: &EventId,
) -> Result<bool> { ) -> Result<bool> {
let found_kind = FoundKind::VisibilityForUser;
let Some(shortstatehash) = self.pdu_shortstatehash(event_id)? else { let Some(shortstatehash) = self.pdu_shortstatehash(event_id)? else {
return Ok(true); return Ok(true);
}; };
@ -219,7 +224,7 @@ impl Service {
.unwrap() .unwrap()
.get_mut(&(user_id.to_owned(), shortstatehash)) .get_mut(&(user_id.to_owned(), shortstatehash))
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(*visibility); return Ok(*visibility);
} }
@ -262,7 +267,7 @@ impl Service {
} }
}; };
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.user_visibility_cache self.user_visibility_cache
.lock() .lock()
.unwrap() .unwrap()

View file

@ -10,7 +10,10 @@ use lru_cache::LruCache;
use ruma::{EventId, RoomId}; use ruma::{EventId, RoomId};
use self::data::StateDiff; use self::data::StateDiff;
use crate::{observability::FoundIn, services, utils, Result}; use crate::{
observability::{FoundIn, FoundKind, METRICS},
services, utils, Result,
};
#[derive(Clone)] #[derive(Clone)]
pub(crate) struct CompressedStateLayer { pub(crate) struct CompressedStateLayer {
@ -33,15 +36,17 @@ impl Service {
/// Returns a stack with info on shortstatehash, full state, added diff and /// Returns a stack with info on shortstatehash, full state, added diff and
/// removed diff for the selected shortstatehash and each parent layer. /// removed diff for the selected shortstatehash and each parent layer.
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
#[tracing::instrument(skip(self), fields(cache_result))] #[tracing::instrument(skip(self))]
pub(crate) fn load_shortstatehash_info( pub(crate) fn load_shortstatehash_info(
&self, &self,
shortstatehash: u64, shortstatehash: u64,
) -> Result<Vec<CompressedStateLayer>> { ) -> Result<Vec<CompressedStateLayer>> {
let found_kind = FoundKind::StateInfo;
if let Some(r) = if let Some(r) =
self.stateinfo_cache.lock().unwrap().get_mut(&shortstatehash) self.stateinfo_cache.lock().unwrap().get_mut(&shortstatehash)
{ {
FoundIn::Cache.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Cache);
return Ok(r.clone()); return Ok(r.clone());
} }
@ -76,7 +81,7 @@ impl Service {
}] }]
}; };
FoundIn::Database.record("cache_result"); METRICS.record_lookup(found_kind, FoundIn::Database);
self.stateinfo_cache self.stateinfo_cache
.lock() .lock()
.unwrap() .unwrap()