diff --git a/Justfile b/Justfile index 3d9fb7ab92..7df65e3c24 100644 --- a/Justfile +++ b/Justfile @@ -661,11 +661,12 @@ test-unit: cargo nextest run -p buzz-relay --lib -E 'test(/^concurrency_limits::tests::/) + test(/^feature_flags::tests::/) + test(=handlers::auth::tests::auth_cap_sheds_a_verified_login_with_a_bare_close)' # Relay read caches: the admitted-connection index, the shared-read # gates (open set, restriction, tenant host), the community-active - # cache, tenant host cache, the + # cache, tenant host cache, the access caches' refill fences and + # member snapshot age, the # overlong-host rejection and the ban disconnect's restriction-cache # drop. Infra-free; the # database URL refuses at once. Keep scripts/run-tests.sh in step. - cargo nextest run -p buzz-relay --lib -E 'test(=state::tests::admitted_index_follows_every_key_change) + test(/^shared_reads::tests::/) + test(/^membership_cache::tests::/) + test(/^community_active::tests::/) + test(=state::tests::concurrent_open_channel_misses_share_the_in_flight_read) + test(=state::tests::concurrent_restriction_and_host_misses_share_the_in_flight_read) + test(=tenant::tests::app_state_resolver_serves_fresh_cached_hosts_only) + test(=tenant::tests::an_overlong_host_fails_closed_before_the_resolver) + test(=state::tests::disconnect_drops_the_cached_restriction_row)' + cargo nextest run -p buzz-relay --lib -E 'test(=state::tests::admitted_index_follows_every_key_change) + test(/^shared_reads::tests::/) + test(/^membership_cache::tests::/) + test(/^community_active::tests::/) + test(=state::tests::concurrent_open_channel_misses_share_the_in_flight_read) + test(=state::tests::a_member_read_that_straddles_an_invalidation_is_not_cached) + test(=state::tests::a_member_snapshot_ages_from_its_read_not_its_insert) + test(=state::tests::overlapping_member_reads_cache_the_first_to_finish) + test(=state::tests::an_open_read_that_straddles_an_invalidation_is_not_cached) + test(=state::tests::concurrent_restriction_and_host_misses_share_the_in_flight_read) + test(=tenant::tests::app_state_resolver_serves_fresh_cached_hosts_only) + test(=tenant::tests::an_overlong_host_fails_closed_before_the_resolver) + test(=state::tests::disconnect_drops_the_cached_restriction_row)' # Retain partially consumed mesh receives across housekeeping ticks. cargo nextest run -p buzz-relay --lib -E 'test(=mesh_boot::tests::demo_echo_retains_pending_receive_across_housekeeping_ticks)' # boot_lifecycle spawns the real relay binary and asserts its startup diff --git a/crates/buzz-db/src/store/channel_members.rs b/crates/buzz-db/src/store/channel_members.rs index 64dfd3bc67..a60f736d51 100644 --- a/crates/buzz-db/src/store/channel_members.rs +++ b/crates/buzz-db/src/store/channel_members.rs @@ -1696,6 +1696,31 @@ pub async fn get_accessible_channel_ids( Ok(ids) } +/// Channel IDs split by how a query reaches them: the legacy-type channels +/// in its implicit scope, and the named-only channels with their type (see +/// [`get_readable_named_only_channels`]). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ChannelSet { + /// Channels of legacy types ([`buzz_core::channel::LEGACY_CHANNEL_TYPES`]). + pub implicit: Vec, + /// Channels of every other type, with the type as text. + pub named_only: Vec<(Uuid, String)>, +} + +impl FromIterator<(Uuid, String)> for ChannelSet { + fn from_iter>(rows: I) -> Self { + let mut set = Self::default(); + for (id, channel_type) in rows { + if buzz_core::channel::LEGACY_CHANNEL_TYPES.contains(&channel_type.as_str()) { + set.implicit.push(id); + } else { + set.named_only.push((id, channel_type)); + } + } + set + } +} + /// The member half of [`get_accessible_channel_ids`]: legacy-type channels /// where the pubkey is an active member. pub async fn get_member_channel_ids( @@ -1703,28 +1728,43 @@ pub async fn get_member_channel_ids( community_id: CommunityId, pubkey: &[u8], ) -> Result> { + Ok(get_member_channels_read_at(pool, community_id, pubkey) + .await? + .value + .implicit) +} + +/// Every channel where the pubkey is an active member, split by type, with +/// when its connection was checked out. Its implicit half is +/// [`get_member_channel_ids`]; its named-only half is the member part of +/// [`get_readable_named_only_channels`]. +pub async fn get_member_channels_read_at( + pool: &PgPool, + community_id: CommunityId, + pubkey: &[u8], +) -> Result> { let mut connection = crate::observability::acquire_writer( pool, crate::observability::WriterOperation::Authorization, ) .await?; - let sql = format!( + let read_at = std::time::Instant::now(); + let rows: Vec<(Uuid, String)> = sqlx::query_as( r#" - SELECT cm.channel_id + SELECT cm.channel_id, c.channel_type::text FROM channel_members cm JOIN channels c ON cm.community_id = c.community_id AND cm.channel_id = c.id AND c.deleted_at IS NULL WHERE cm.community_id = $1 AND cm.pubkey = $2 AND cm.removed_at IS NULL - AND {member_types} "#, - member_types = crate::store::channel::legacy_channel_type_sql("c.channel_type"), - ); - // Built only from the constant type list. - sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) - .bind(community_id.as_uuid()) - .bind(pubkey) - .fetch_all(&mut *connection) - .await - .map_err(Into::into) + ) + .bind(community_id.as_uuid()) + .bind(pubkey) + .fetch_all(&mut *connection) + .await?; + Ok(ReadAt { + value: rows.into_iter().collect(), + read_at, + }) } /// The open half of [`get_accessible_channel_ids`]: listed open channels of @@ -1733,37 +1773,39 @@ pub async fn get_listed_open_channel_ids( pool: &PgPool, community_id: CommunityId, ) -> Result> { - Ok(get_listed_open_channel_ids_read_at(pool, community_id) + Ok(get_listed_open_channels_read_at(pool, community_id) .await? - .value) + .value + .implicit) } -/// [`get_listed_open_channel_ids`], with when its connection was checked out. -pub async fn get_listed_open_channel_ids_read_at( +/// Every listed open channel, split by type, with when its connection was +/// checked out. Its implicit half is [`get_listed_open_channel_ids`]; its +/// named-only half is the listed part of [`get_readable_named_only_channels`]. +pub async fn get_listed_open_channels_read_at( pool: &PgPool, community_id: CommunityId, -) -> Result>> { +) -> Result> { let mut connection = crate::observability::acquire_writer( pool, crate::observability::WriterOperation::Authorization, ) .await?; let read_at = std::time::Instant::now(); - let sql = format!( + let rows: Vec<(Uuid, String)> = sqlx::query_as( r#" - SELECT id + SELECT id, channel_type::text FROM channels WHERE community_id = $1 AND visibility = 'open' AND NOT unlisted AND deleted_at IS NULL - AND {open_types} "#, - open_types = crate::store::channel::legacy_channel_type_sql("channel_type"), - ); - // Built only from the constant type list. - let value = sqlx::query_scalar(sqlx::AssertSqlSafe(sql)) - .bind(community_id.as_uuid()) - .fetch_all(&mut *connection) - .await?; - Ok(ReadAt { value, read_at }) + ) + .bind(community_id.as_uuid()) + .fetch_all(&mut *connection) + .await?; + Ok(ReadAt { + value: rows.into_iter().collect(), + read_at, + }) } /// Appends the channels of `more` that `ids` lacks. @@ -1794,7 +1836,9 @@ pub struct ReadableNamedOnlyChannel { /// one also has it through [`get_accessible_channel_ids`]; listing it here /// as well is harmless, since a filter's scope is deduplicated. /// -/// Uncached, so a caller can trust it for a channel the request names. A +/// Uncached, so a caller can trust it for a channel the request names. With +/// no names, it is the named-only halves of [`get_member_channels_read_at`] and +/// [`get_listed_open_channels_read_at`] together, which the relay caches. A /// read reaches one only by naming it, or, for system channels, by opting in /// to them. The opt-in needs every listed system channel, so those are all /// loaded; an unlisted channel is loaded only when named, since a community @@ -2844,35 +2888,29 @@ impl Db { get_active_membership_ids_bulk_read_at(&self.pool, community_id, pubkeys, limit).await } - /// Channel IDs where a pubkey is an active member. See [`get_member_channel_ids`]. + /// Every channel where a pubkey is an active member, split by type, with + /// when its connection was checked out. See [`get_member_channels_read_at`]. + /// The span keeps the name of the read it replaced, so dashboards keep + /// their history. #[datastore_span(name = "get_member_channel_ids", system = "postgresql")] - pub async fn get_member_channel_ids( + pub async fn get_member_channels_read_at( &self, community_id: CommunityId, pubkey: &[u8], - ) -> Result> { - get_member_channel_ids(&self.pool, community_id, pubkey).await + ) -> Result> { + get_member_channels_read_at(&self.pool, community_id, pubkey).await } - /// A community's listed open channel IDs. See [`get_listed_open_channel_ids`]. - pub async fn get_listed_open_channel_ids( - &self, - community_id: CommunityId, - ) -> Result> { - Ok(self - .get_listed_open_channel_ids_read_at(community_id) - .await? - .value) - } - - /// [`Self::get_listed_open_channel_ids`], with when its connection was - /// checked out, for caches that bound staleness from the read. + /// Every listed open channel, split by type, with when its connection + /// was checked out, for caches that bound staleness from the read. See + /// [`get_listed_open_channels_read_at`]. The span keeps the name of the + /// read it replaced, so dashboards keep their history. #[datastore_span(name = "get_listed_open_channel_ids", system = "postgresql")] - pub async fn get_listed_open_channel_ids_read_at( + pub async fn get_listed_open_channels_read_at( &self, community_id: CommunityId, - ) -> Result>> { - get_listed_open_channel_ids_read_at(&self.pool, community_id).await + ) -> Result> { + get_listed_open_channels_read_at(&self.pool, community_id).await } /// The channels of non-legacy types a pubkey can read (member, or open diff --git a/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs b/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs index dbba7b7bd8..4c81acf7a7 100644 --- a/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs +++ b/crates/buzz-db/src/store/unlisted_channels_postgres_tests.rs @@ -422,3 +422,102 @@ async fn channel_created_unlisted_is_never_listed() { assert!(f.implicit(&f.owner).await.contains(&chat)); } } + +/// The relay caches the member and listed-open channel sets and serves a +/// request's named-only channels from them when it names nothing else. Their +/// named-only halves together must equal the uncached read with no names, +/// and their implicit halves the accessible set, for a member and a non-member. +/// Mutation: restrict `get_member_channels_read_at` or +/// `get_listed_open_channels_read_at` to legacy types, or drop `NOT unlisted` +/// from the latter → RED. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn cached_channel_sets_match_the_uncached_named_only_read() { + let f = Fixture::new().await; + let system_private = f + .typed_channel( + "system-private", + ChannelType::System, + ChannelVisibility::Private, + ) + .await; + let system_listed = f + .typed_channel( + "system-listed", + ChannelType::System, + ChannelVisibility::Open, + ) + .await; + let system_unlisted = f + .typed_channel( + "system-unlisted", + ChannelType::System, + ChannelVisibility::Open, + ) + .await; + f.set_unlisted(system_unlisted, true).await; + let stream_listed = f.channel("stream-listed", ChannelVisibility::Open).await; + let stream_unlisted = f.channel("stream-unlisted", ChannelVisibility::Open).await; + f.set_unlisted(stream_unlisted, true).await; + let stream_private = f + .channel("stream-private", ChannelVisibility::Private) + .await; + + let sorted = |mut ids: Vec| { + ids.sort_unstable(); + ids + }; + let open = + f.db.get_listed_open_channels_read_at(f.community) + .await + .expect("listed open channels") + .value; + assert_eq!(open.implicit, [stream_listed]); + assert_eq!(open.named_only, [(system_listed, "system".to_owned())]); + + for (reader, member_named_only) in [ + ( + &f.owner, + sorted(vec![system_private, system_listed, system_unlisted]), + ), + (&f.outsider, Vec::new()), + ] { + let member = + f.db.get_member_channels_read_at(f.community, &reader.public_key().to_bytes()) + .await + .expect("member channels") + .value; + assert_eq!( + sorted(member.named_only.iter().map(|(id, _)| *id).collect()), + member_named_only + ); + let mut cached: Vec<(Uuid, String)> = member.named_only.clone(); + cached.extend( + open.named_only + .iter() + .filter(|(id, _)| !member.named_only.iter().any(|(have, _)| have == id)) + .cloned(), + ); + cached.sort_unstable(); + let mut uncached = f.named_only(reader, &[]).await; + uncached.sort_unstable(); + assert_eq!( + cached, uncached, + "named-only halves match the uncached read" + ); + + let mut implicit = member.implicit.clone(); + crate::channel_members::merge_channel_ids(&mut implicit, &open.implicit); + assert_eq!(sorted(implicit), sorted(f.implicit(reader).await)); + } + // The owner is a member of every stream channel, listed or not. + let owner = + f.db.get_member_channels_read_at(f.community, &f.owner.public_key().to_bytes()) + .await + .expect("owner member channels") + .value; + assert_eq!( + sorted(owner.implicit), + sorted(vec![stream_listed, stream_unlisted, stream_private]) + ); +} diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index c27bbb25c7..39a2ab9718 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -1798,13 +1798,20 @@ async fn query_member_events( } // Get channels this user can access — same enforcement as WS REQ handler. - let mut accessible_channels = state - .get_accessible_channel_ids_cached(tenant.community(), &pubkey_bytes) + let mut access = state + .get_channel_access_cached(tenant.community(), &pubkey_bytes) .await .map_err(|e| internal_error(&format!("channel access lookup: {e}")))?; + let mut accessible_channels = std::mem::take(&mut access.implicit); // Named-only channels (system, and types added later) are outside // `accessible_channels`; a filter that names one reads it in its own // scope only (see `handlers::system_channels`). + // A strong read must see the caller's own just-accepted write, such as a + // system channel it just created, so its named-only access comes from the + // database rather than a cached membership a peer pod may not have dropped. + let strong = raw_filters + .iter() + .any(|raw| matches!(extract_consistency(raw), Consistency::Strong)); let mut named_only = crate::handlers::system_channels::readable_named_only_channels_for_filters( state, @@ -1812,6 +1819,7 @@ async fn query_member_events( &pubkey_bytes, &filters, &accessible_channels, + (!strong).then_some(&access), None, ) .await @@ -2449,10 +2457,11 @@ async fn count_member_events( } // Get channels this user can access. - let mut accessible_channels = state - .get_accessible_channel_ids_cached(tenant.community(), &pubkey_bytes) + let mut access = state + .get_channel_access_cached(tenant.community(), &pubkey_bytes) .await .map_err(|e| internal_error(&format!("channel access lookup: {e}")))?; + let mut accessible_channels = std::mem::take(&mut access.implicit); // Named-only channels (system, and types added later) are outside // `accessible_channels`; a filter that names one reads it in its own // scope only (see `handlers::system_channels`). @@ -2463,6 +2472,7 @@ async fn count_member_events( &pubkey_bytes, &filters, &accessible_channels, + Some(&access), None, ) .await diff --git a/crates/buzz-relay/src/handlers/count.rs b/crates/buzz-relay/src/handlers/count.rs index 3672ce6b30..685a533157 100644 --- a/crates/buzz-relay/src/handlers/count.rs +++ b/crates/buzz-relay/src/handlers/count.rs @@ -88,11 +88,11 @@ pub async fn handle_count( }; // Get channels this user can access — same enforcement as WS REQ handler. - let mut accessible_channels = match state - .get_accessible_channel_ids_cached(conn.tenant.community(), &pubkey_bytes) + let (mut accessible_channels, cached_access) = match state + .get_channel_access_cached(conn.tenant.community(), &pubkey_bytes) .await { - Ok(ids) => ids, + Ok(mut access) => (std::mem::take(&mut access.implicit), access), Err(e) => { warn!(sub_id = %sub_id, error_kind = %e.kind(), "Failed to get accessible channels"); conn.send(RelayMessage::closed(&sub_id, DATABASE_ERROR_CLOSED)); @@ -117,6 +117,7 @@ pub async fn handle_count( &pubkey_bytes, &filters, &accessible_channels, + Some(&cached_access), token_channel_ids.as_deref(), ) .await diff --git a/crates/buzz-relay/src/handlers/req.rs b/crates/buzz-relay/src/handlers/req.rs index cd19e86dcb..6f0bdbde56 100644 --- a/crates/buzz-relay/src/handlers/req.rs +++ b/crates/buzz-relay/src/handlers/req.rs @@ -146,16 +146,16 @@ pub async fn handle_admitted_req( let (named_channels, live_names) = super::system_channels::channels_named_by_filters(&filters, MAX_EXPLICIT_CHANNEL_VALUES); - let mut accessible_channels = if filters_are_nip43_membership_only(&filters) { + let (mut accessible_channels, cached_access) = if filters_are_nip43_membership_only(&filters) { metrics::counter!("buzz_req_global_access_resolution_skips_total", "kind" => "13534") .increment(1); - Vec::new() + (Vec::new(), crate::state::ChannelAccess::default()) } else { match state - .get_accessible_channel_ids_cached(conn.tenant.community(), &pubkey_bytes) + .get_channel_access_cached(conn.tenant.community(), &pubkey_bytes) .await { - Ok(ids) => ids, + Ok(mut access) => (std::mem::take(&mut access.implicit), access), Err(e) => { warn!(conn_id = %conn_id, error_kind = %e.kind(), "Failed to get accessible channels"); super::close::close_if_owner( @@ -183,6 +183,7 @@ pub async fn handle_admitted_req( &pubkey_bytes, &filters, &accessible_channels, + Some(&cached_access), token_channel_ids.as_deref(), ) .await diff --git a/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs b/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs index 530f6db3bb..7f26400af1 100644 --- a/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/system_channel_postgres_tests.rs @@ -84,7 +84,38 @@ async fn req(f: &Fixture, reader: &Keys, filter: Value) -> Vec { /// [`req`] with several filters in one REQ. async fn req_all(f: &Fixture, reader: &Keys, filters: Value) -> Vec { - let (conn, mut rx) = test_conn(&f.tenant, reader); + req_all_scoped(f, reader, filters, None).await +} + +/// A test connection for `reader`, scoped to `channels` like a token when +/// given. +fn scoped_conn( + f: &Fixture, + reader: &Keys, + channels: Option>, +) -> ( + Arc, + tokio::sync::mpsc::Receiver, +) { + let (conn, rx) = test_conn(&f.tenant, reader); + if channels.is_some() { + let mut auth = conn.auth_state.lock().expect("auth state"); + let crate::connection::AuthState::Authenticated(ctx) = &mut *auth else { + panic!("test connection is authenticated"); + }; + ctx.channel_ids = channels; + } + (conn, rx) +} + +/// [`req_all`] on a connection scoped to `channels` when given. +async fn req_all_scoped( + f: &Fixture, + reader: &Keys, + filters: Value, + channels: Option>, +) -> Vec { + let (conn, mut rx) = scoped_conn(f, reader, channels); let filters: Vec = serde_json::from_value(filters).expect("filters"); let before = vec![None; filters.len()]; crate::handlers::req::handle_req("s".into(), filters, before, conn, f.state.clone()).await; @@ -110,7 +141,17 @@ async fn count(f: &Fixture, reader: &Keys, filter: Value) -> u64 { /// [`count`] with several filters in one COUNT. async fn count_all(f: &Fixture, reader: &Keys, filters: Value) -> u64 { - let (conn, mut rx) = test_conn(&f.tenant, reader); + count_all_scoped(f, reader, filters, None).await +} + +/// [`count_all`] on a connection scoped to `channels` when given. +async fn count_all_scoped( + f: &Fixture, + reader: &Keys, + filters: Value, + channels: Option>, +) -> u64 { + let (conn, mut rx) = scoped_conn(f, reader, channels); let filters: Vec = serde_json::from_value(filters).expect("filters"); crate::handlers::count::handle_count("c".into(), filters, conn, f.state.clone()).await; while let Ok(frame) = rx.try_recv() { @@ -1769,12 +1810,12 @@ async fn named_channels_missing_from_a_stale_cache_still_route_live() { let reader_hex = reader.public_key().to_hex(); // This pod cached the reader's access set before the join. let stale = || { - f.state.member_channels_cache.insert( + f.state.seed_member_channels( ( f.tenant.community(), reader.public_key().to_bytes().to_vec(), ), - Vec::new(), + Default::default(), ); }; @@ -1815,3 +1856,107 @@ async fn named_channels_missing_from_a_stale_cache_still_route_live() { mixed.close(&f).await; assert_eq!(refcount(&f, EventTopic::Channel(channel)).await, 0); } + +/// A token scoped to one of two readable system channels reads only that one +/// through WebSocket REQ and COUNT, whether the request's named-only access +/// comes from the access caches (discovery alone) or from the database (a +/// sibling filter names a channel outside the cached sets). +/// Mutation: pass `None` instead of the token scope to +/// `readable_named_only_channels_for_filters` in `req.rs` or `count.rs` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_token_scope_narrows_system_channels_on_both_access_paths() { + let f = fixture().await; + let owner = Keys::generate(); + let owner_hex = owner.public_key().to_hex(); + let allowed = create_channel(&f.state, &f.tenant, &owner, &[&["channel_type", "system"]]).await; + let other = create_channel(&f.state, &f.tenant, &owner, &[&["channel_type", "system"]]).await; + // A stranger's unlisted open channel: readable by name, but in neither + // cached set for the owner, so naming it takes the database path. + let stranger = Keys::generate(); + let unlisted = create_channel(&f.state, &f.tenant, &stranger, &[]).await; + edit_channel( + &f.state, + &f.tenant, + &stranger, + unlisted, + &[&["visibility", "open"], &["unlisted", "true"]], + ) + .await + .expect("open the channel unlisted"); + let discovery = json!({"kinds": [39002], "#p": [owner_hex], "#t": ["system"]}); + let by_name = json!({"kinds": [9], "#h": [unlisted.to_string()]}); + + // Unscoped, discovery finds both, so the scoped results below are the + // token's doing. + assert_eq!( + sorted(req(&f, &owner, discovery.clone()).await), + sorted(vec![ + group_state_id(&f, allowed, 39002).await, + group_state_id(&f, other, 39002).await, + ]), + "unscoped discovery" + ); + let token = || Some(vec![allowed, unlisted]); + let roster = vec![group_state_id(&f, allowed, 39002).await]; + for (path, filters) in [ + ("cache", json!([discovery.clone()])), + ("database", json!([discovery.clone(), by_name.clone()])), + ] { + assert_eq!( + req_all_scoped(&f, &owner, filters.clone(), token()).await, + roster, + "REQ via {path}" + ); + assert_eq!( + count_all_scoped(&f, &owner, filters, token()).await, + 1, + "COUNT via {path}" + ); + } +} + +/// A strong `POST /query` sees a system channel its caller just created even +/// when this pod's cached member set predates the create (a peer pod that has +/// not yet seen the membership invalidation). This is buzz-app's +/// create-then-look-up-by-label sequence. +/// Mutation: pass the cached access for strong reads in +/// `query_member_events` → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_strong_query_sees_a_just_created_system_channel_past_a_stale_cache() { + let f = fixture().await; + let owner = Keys::generate(); + let owner_hex = owner.public_key().to_hex(); + let label = "agent-config"; + let channel = create_channel( + &f.state, + &f.tenant, + &owner, + &[&["channel_type", "system"], &["t", label]], + ) + .await; + let stale = || { + f.state.seed_member_channels( + (f.tenant.community(), owner.public_key().to_bytes().to_vec()), + Default::default(), + ); + }; + let lookup = json!({"kinds": [39000], "#P": [owner_hex], "#t": [label]}); + let mut strong = lookup.clone(); + strong["consistency"] = json!("strong"); + + // The stale entry is in effect: a default read answers from it. + stale(); + assert_eq!( + bridge_ids(bridge(&f, &owner, "/query", json!([lookup])).await), + Vec::::new(), + "default read answers from the stale cache" + ); + stale(); + assert_eq!( + bridge_ids(bridge(&f, &owner, "/query", json!([strong])).await), + [group_state_id(&f, channel, 39000).await], + "strong read takes named-only access from the database" + ); +} diff --git a/crates/buzz-relay/src/handlers/system_channels.rs b/crates/buzz-relay/src/handlers/system_channels.rs index 85f28e5fe0..6fa4828801 100644 --- a/crates/buzz-relay/src/handlers/system_channels.rs +++ b/crates/buzz-relay/src/handlers/system_channels.rs @@ -46,35 +46,45 @@ pub(crate) struct NamedOnlyChannels { } impl NamedOnlyChannels { - /// From `(id, channel_type)` rows of non-legacy channels. - pub(crate) fn from_typed(rows: impl IntoIterator) -> Self { - let mut channels = Self::default(); - for (id, channel_type) in rows { - channels.insert(id, &channel_type); - } - channels + /// From `(id, channel_type)` rows of non-legacy channels. A repeated + /// channel is kept once. + pub(crate) fn from_typed>(rows: impl IntoIterator) -> Self { + Self::from_rows( + rows.into_iter() + .map(|(id, channel_type)| (id, channel_type, true)), + ) } /// From [`buzz_db::channel_members::get_readable_named_only_channels`], /// which says which channels the opt-in may add. pub(crate) fn from_readable( - rows: impl IntoIterator, + rows: &[buzz_db::channel_members::ReadableNamedOnlyChannel], ) -> Self { + Self::from_rows( + rows.iter() + .map(|row| (row.id, row.channel_type.as_str(), row.opt_in)), + ) + } + + /// `(id, channel_type, opt_in)` rows; the first row for a channel wins. + fn from_rows>(rows: impl IntoIterator) -> Self { let mut channels = Self::default(); - for row in rows { - channels.insert_with_opt_in(row.id, &row.channel_type, row.opt_in); + let mut seen = HashSet::new(); + for (id, channel_type, opt_in) in rows { + if seen.insert(id) { + channels.push(id, channel_type.as_ref(), opt_in); + } } channels } fn insert(&mut self, id: Uuid, channel_type: &str) { - self.insert_with_opt_in(id, channel_type, true); + if !self.ids.contains(&id) { + self.push(id, channel_type, true); + } } - fn insert_with_opt_in(&mut self, id: Uuid, channel_type: &str, opt_in: bool) { - if self.ids.contains(&id) { - return; - } + fn push(&mut self, id: Uuid, channel_type: &str, opt_in: bool) { self.ids.push(id); if opt_in && channel_type == buzz_core::channel::ChannelType::System.as_str() { self.system.push(id); @@ -282,16 +292,28 @@ pub(crate) fn filter_live_scope( } } -/// Load the named-only channels the reader can read, narrowed to the token's +/// The named-only channels the reader can read, narrowed to the token's /// channel scope, when at least one filter could use them. Returns an empty -/// set, without a database read, when no filter opts in or names a channel -/// outside the implicit set. +/// set when no filter opts in or names a channel outside the implicit set. +/// +/// `cached` is the reader's access from +/// [`AppState::get_channel_access_cached`], read with `implicit`. Its +/// named-only channels are the non-legacy ones the reader is a member of +/// and the listed open ones. It answers +/// the opt-in, which needs exactly those, and every name it holds. Only a +/// request that names a channel outside both sets, such as an unlisted open +/// channel, reads the database, so a fleet reconnect costs no extra read per +/// client. +/// +/// `None` reads the database regardless, for a request that must see the +/// caller's own just-accepted write (a strong read). pub(crate) async fn readable_named_only_channels_for_filters( state: &AppState, community: CommunityId, pubkey: &[u8], filters: &[Filter], implicit: &[Uuid], + cached: Option<&crate::state::ChannelAccess>, token_channel_ids: Option<&[Uuid]>, ) -> Result { if !filters @@ -301,12 +323,26 @@ pub(crate) async fn readable_named_only_channels_for_filters( return Ok(NamedOnlyChannels::default()); } let named = named_outside(filters, implicit); - let mut readable = NamedOnlyChannels::from_readable( - state - .db - .get_readable_named_only_channels(community, pubkey, &named) - .await?, - ); + let cached = cached.filter(|cached| { + let ids: HashSet = cached.named_only().map(|(id, _)| *id).collect(); + named.iter().all(|id| ids.contains(id)) + }); + let mut readable = if let Some(cached) = cached { + metrics::counter!("buzz_named_only_channel_reads_total", "source" => "cache").increment(1); + NamedOnlyChannels::from_typed( + cached + .named_only() + .map(|(id, channel_type)| (*id, channel_type.as_str())), + ) + } else { + metrics::counter!("buzz_named_only_channel_reads_total", "source" => "db").increment(1); + NamedOnlyChannels::from_readable( + &state + .db + .get_readable_named_only_channels(community, pubkey, &named) + .await?, + ) + }; if let Some(allowed) = token_channel_ids { readable.retain(allowed); } @@ -621,4 +657,100 @@ mod tests { &implicit )); } + + /// A request whose named-only needs the cached access sets cover reads + /// no database: the connect-time system discovery (`#t:["system"]`) and a + /// name of a cached system channel. A name outside both sets still reads + /// the database. The database is unreachable, so any read fails. + /// Mutation: always take the database branch, or drop either cached + /// half from `get_channel_access_cached` → RED. + #[tokio::test] + async fn cached_access_answers_named_only_needs_without_a_database_read() { + let state = crate::state::tests::test_state_with_unreachable_database_url( + "postgres://buzz@127.0.0.1:1/buzz", + ) + .await; + let community = CommunityId::from_uuid(Uuid::new_v4()); + let reader = Keys::generate().public_key().to_bytes().to_vec(); + let [stream, member_system, listed_system, unknown] = [(); 4].map(|()| Uuid::new_v4()); + state.seed_member_channels( + (community, reader.clone()), + buzz_db::channel_members::ChannelSet { + implicit: vec![stream], + // A member of a listed system channel has it in both halves. + named_only: vec![ + (member_system, "system".to_owned()), + (listed_system, "system".to_owned()), + ], + }, + ); + state.open_channels_cache.insert( + community, + std::sync::Arc::new(crate::state::OpenChannels { + ids: Vec::new(), + named_only: vec![(listed_system, "system".to_owned())], + read_at: std::time::Instant::now(), + }), + ); + let access = state + .get_channel_access_cached(community, &reader) + .await + .expect("both halves are cached"); + assert_eq!(access.implicit, [stream]); + + let read_with = |filters: Vec, token: Option>, cached: bool| { + let state = state.clone(); + let reader = reader.clone(); + let access = access.clone(); + async move { + readable_named_only_channels_for_filters( + &state, + community, + &reader, + &filters, + &access.implicit, + cached.then_some(&access), + token.as_deref(), + ) + .await + } + }; + let read = |filters: Vec, token: Option>| read_with(filters, token, true); + let discovery = filter(serde_json::json!({ + "kinds": [39002], "#p": [hex::encode(&reader)], "#t": ["system"] + })); + let named = read(vec![discovery.clone()], None) + .await + .expect("discovery is served from the cache"); + assert_eq!(named.ids(), &[member_system, listed_system], "each once"); + assert_eq!( + filter_channel_scope(&discovery, &access.implicit, &named).as_ref(), + &[stream, member_system, listed_system] + ); + + let by_h = filter(serde_json::json!({"kinds": [9], "#h": [member_system.to_string()]})); + let named = read(vec![by_h.clone()], None) + .await + .expect("a cached name is served from the cache"); + assert_eq!( + filter_channel_scope(&by_h, &access.implicit, &named).as_ref(), + &[stream, member_system] + ); + + // The token scope still narrows a cached answer. + let scoped = read(vec![discovery.clone()], Some(vec![stream, listed_system])) + .await + .expect("discovery is served from the cache"); + assert_eq!(scoped.ids(), &[listed_system]); + + let outside = filter(serde_json::json!({"kinds": [9], "#h": [unknown.to_string()]})); + assert!( + read(vec![discovery.clone(), outside], None).await.is_err(), + "a name outside the cached sets reads the database" + ); + assert!( + read_with(vec![discovery], None, false).await.is_err(), + "without the cache, discovery reads the database" + ); + } } diff --git a/crates/buzz-relay/src/lib.rs b/crates/buzz-relay/src/lib.rs index 79dfef388e..991602a03b 100644 --- a/crates/buzz-relay/src/lib.rs +++ b/crates/buzz-relay/src/lib.rs @@ -50,6 +50,8 @@ pub mod handlers; pub mod invite_token; /// Fixed-schema evidence for the relay's earliest startup steps. pub mod lifecycle; +/// Fences cache refills against invalidation. +mod load_fence; mod membership_cache; /// Inter-relay mesh startup wiring (`BUZZ_MESH` seam). pub mod mesh_boot; diff --git a/crates/buzz-relay/src/load_fence.rs b/crates/buzz-relay/src/load_fence.rs new file mode 100644 index 0000000000..76548f3c2d --- /dev/null +++ b/crates/buzz-relay/src/load_fence.rs @@ -0,0 +1,100 @@ +//! Fences a cache's refills against its invalidation. +//! +//! A refill reads, then publishes. If an invalidation for its key runs while +//! it reads, its result may predate the change that the invalidation +//! announced: publishing it would undo the invalidation for the cache's whole +//! lifetime. A fence gives each refill a token, drops the token on +//! invalidation, and lets a refill publish only while its token is current. + +use std::hash::Hash; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// The token shared by the refills in flight per key, and a lock that orders +/// publication against invalidation. The lock is held only for cache operations, never +/// across a read. +pub(crate) struct LoadFence { + loads: moka::sync::Cache>, + lock: Mutex<()>, +} + +/// A refill's claim to publish; see [`LoadFence::begin`]. +pub(crate) struct Load(Arc<()>); + +impl LoadFence +where + K: Hash + Eq + Clone + Send + Sync + 'static, +{ + /// Tokens for up to `max_capacity` keys. A token evicted before its + /// refill ends only stops that refill from publishing, so the bounds fail + /// safe. + pub(crate) fn new(max_capacity: u64) -> Self { + Self { + loads: moka::sync::Cache::builder() + .max_capacity(max_capacity) + .time_to_live(Duration::from_secs(60)) + .support_invalidation_closures() + .build(), + lock: Mutex::new(()), + } + } + + /// Starts a refill of `key`. Refills that overlap share one token, so the + /// first to finish publishes; only an invalidation stops them. + pub(crate) fn begin(&self, key: &K) -> Load { + let _lock = self.lock(); + Load(self.loads.get_with(key.clone(), || Arc::new(()))) + } + + /// Runs `publish` if no invalidation of `key` and no other refill's + /// publication happened since `load` began. Publishing drops the token, + /// so the refills that shared it leave the published entry alone. + pub(crate) fn publish(&self, key: &K, load: Load, publish: impl FnOnce()) { + let _lock = self.lock(); + if self + .loads + .get(key) + .is_some_and(|current| Arc::ptr_eq(¤t, &load.0)) + { + self.loads.invalidate(key); + publish(); + } + } + + /// Stops refills of `key` in flight from publishing, then runs `drop`, + /// which removes the cached entry. + pub(crate) fn invalidate(&self, key: &K, drop: impl FnOnce()) { + let _lock = self.lock(); + self.loads.invalidate(key); + drop(); + } + + /// [`Self::invalidate`] for every key matching `matches`. + pub(crate) fn invalidate_matching( + &self, + matches: impl Fn(&K) -> bool + Send + Sync + 'static, + drop: impl FnOnce(), + ) { + let _lock = self.lock(); + if let Err(error) = self.loads.invalidate_entries_if(move |key, _| matches(key)) { + // `new` enables invalidation closures. If that ever regresses, + // stop every refill rather than let a stale one publish. + tracing::error!( + ?error, + "scoped load-fence invalidation unavailable; stopping all refills" + ); + self.loads.invalidate_all(); + } + drop(); + } + + /// Whether a refill of `key` is in flight. + #[cfg(test)] + pub(crate) fn is_loading(&self, key: &K) -> bool { + self.loads.contains_key(key) + } + + fn lock(&self) -> std::sync::MutexGuard<'_, ()> { + self.lock.lock().unwrap_or_else(|e| e.into_inner()) + } +} diff --git a/crates/buzz-relay/src/push_runtime.rs b/crates/buzz-relay/src/push_runtime.rs index dbee317241..e08ed23f80 100644 --- a/crates/buzz-relay/src/push_runtime.rs +++ b/crates/buzz-relay/src/push_runtime.rs @@ -997,7 +997,7 @@ mod tests { .into_iter() .map(|keys| (channel, author(keys))) .collect(), - named_only: NamedOnlyChannels::from_typed([]), + named_only: NamedOnlyChannels::default(), listed: Default::default(), }; let relay = nostr::Keys::generate(); @@ -1046,7 +1046,7 @@ mod tests { ..lease(&agent) }], memberships: [(channel, author(&agent))].into_iter().collect(), - named_only: NamedOnlyChannels::from_typed([]), + named_only: NamedOnlyChannels::default(), listed: Default::default(), }; let event = EventBuilder::new(Kind::Custom(9), "workflow output") diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index 361cf6d371..b6f9ced80f 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -1378,6 +1378,12 @@ impl Default for ConnectionManager { /// that left the open set elsewhere stays granted here. pub const OPEN_CHANNELS_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(1); +/// How long a pod uses a reader's cached member channels after the database +/// read that produced them began (its connection checkout). Every membership +/// write drops the reader's entry on every pod, so this bounds only a pod +/// that misses that best-effort notification. +pub const MEMBER_CHANNELS_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(10); + /// How long a pod serves a cached ban/timeout row after the database read /// that produced it began, at its connection checkout (see /// [`AppState::restriction_cache`]). Every restriction write drops the @@ -1399,16 +1405,54 @@ pub const TENANT_HOST_CACHE_MAX_AGE: std::time::Duration = /// give up and read on their own. pub const SHARED_READ_STATEMENT_WAIT: std::time::Duration = std::time::Duration::from_secs(1); -/// A community's listed open channel IDs and when the read that listed them +/// A community's listed open channels and when the read that listed them /// checked out its connection. #[derive(Debug)] pub struct OpenChannels { - /// The community's listed open channel IDs. + /// The community's listed open channel IDs of legacy types. pub ids: Vec, + /// The community's listed open channels of other types, with their type. + pub named_only: Vec<(Uuid, String)>, /// When the database read that listed them checked out its connection. pub read_at: Instant, } +/// A reader's member channels and when the read that listed them checked out +/// its connection. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemberChannels { + /// The channels, split into legacy and named-only types. + pub set: Arc, + /// When the database read that listed them checked out its connection. + pub read_at: Instant, +} + +/// A reader's channel access from the two access caches. See +/// [`AppState::get_channel_access_cached`]. +#[derive(Debug, Clone, Default)] +pub struct ChannelAccess { + /// The implicit channel set, as from + /// [`AppState::get_accessible_channel_ids_cached`]. + pub implicit: Vec, + member: Arc, + open: Option>, +} + +impl ChannelAccess { + /// The reader's channels of non-legacy types that it is a member of or + /// that are open and listed, with their type. A channel in both halves + /// appears twice. This is the part of + /// [`buzz_db::channel_members::get_readable_named_only_channels`] that + /// does not depend on which channels a request names, so a request that + /// names only these needs no other access read. + pub fn named_only(&self) -> impl Iterator + '_ { + self.member + .named_only + .iter() + .chain(self.open.iter().flat_map(|open| open.named_only.iter())) + } +} + /// Minimum spacing between live thread-summary emits for one thread root on /// one relay pod. See [`AppState::thread_summary_refresh`]. pub const THREAD_SUMMARY_REFRESH_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1); @@ -1492,16 +1536,22 @@ pub struct AppState { pub local_event_ids: Arc>, /// All active memberships per community and user, shared by channel checks. pub(crate) membership_cache: Arc, - /// Member channel IDs cache: (community_id, pubkey_bytes) → the legacy-type - /// channels the pubkey is an active member of. Short TTL (10s) — - /// invalidated on membership changes and community-wide channel changes. - #[allow(clippy::type_complexity)] - pub member_channels_cache: Arc), Vec>>, + /// Member channels cache: (community_id, pubkey_bytes) → the channels the + /// pubkey is an active member of. Invalidated on membership changes and + /// community-wide channel changes, and used only for + /// [`MEMBER_CHANNELS_MAX_AGE`] after its read's connection checkout. + pub member_channels_cache: Arc), MemberChannels>>, + /// Keeps a [`Self::member_channels_cache`] read that straddles an + /// invalidation of its key from being cached. + member_channels_loads: Arc)>>, /// Listed open channel IDs per community, the half of every reader's /// accessible set that does not depend on the reader. Invalidated with /// the community's accessible channels, and used only for /// [`OPEN_CHANNELS_MAX_AGE`] after its read's connection checkout. pub open_channels_cache: Arc>>, + /// Keeps an [`Self::open_channels_cache`] read that straddles an + /// invalidation of its community from being cached. + open_channels_loads: Arc>, /// Lets concurrent misses on [`Self::open_channels_cache`] share one read. pub(crate) open_channels_reads: Arc>, /// Per-community channel visibility string, used to gate the private-channel fan-out @@ -1834,13 +1884,16 @@ impl AppState { membership_cache: Arc::new(crate::membership_cache::MembershipCache::new( shared_read_wait, )), + // Readers use an entry only for `MEMBER_CHANNELS_MAX_AGE`; the + // TTL, which starts later, at insert, just reclaims memory. member_channels_cache: Arc::new( moka::sync::Cache::builder() .max_capacity(10_000) - .time_to_live(std::time::Duration::from_secs(10)) + .time_to_live(MEMBER_CHANNELS_MAX_AGE) .support_invalidation_closures() .build(), ), + member_channels_loads: Arc::new(crate::load_fence::LoadFence::new(10_000)), // Readers use an entry only for `OPEN_CHANNELS_MAX_AGE`; the TTL // just reclaims memory and keeps expired entries around long // enough to count their misses as `expired` rather than `absent`. @@ -1850,6 +1903,7 @@ impl AppState { .time_to_live(std::time::Duration::from_secs(10)) .build(), ), + open_channels_loads: Arc::new(crate::load_fence::LoadFence::new(10_000)), open_channels_reads: Arc::new(crate::shared_reads::SharedReads::new( 10_000, shared_read_wait, @@ -2152,8 +2206,9 @@ impl AppState { pubkey: &[u8], ) { self.membership_cache.invalidate(community_id, pubkey); - self.member_channels_cache - .invalidate(&(community_id, pubkey.to_vec())); + let key = (community_id, pubkey.to_vec()); + self.member_channels_loads + .invalidate(&key, || self.member_channels_cache.invalidate(&key)); } /// Invalidate all users' accessible-channels cache (e.g. new open channel created). @@ -2164,20 +2219,27 @@ impl AppState { /// Local-only accessible-channels drop. See [`invalidate_membership_local`]. pub(crate) fn invalidate_all_accessible_channels_local(&self, community_id: CommunityId) { - self.open_channels_cache.invalidate(&community_id); - if let Err(error) = self - .member_channels_cache - .invalidate_entries_if(move |(entry_community, _), _| *entry_community == community_id) - { - // AppState enables invalidation closures at construction time. If - // that invariant ever regresses, prefer over-invalidating to - // serving stale access state. - tracing::error!( - ?error, - "community-scoped accessible-channel invalidation unavailable; falling back to full invalidation" - ); - self.member_channels_cache.invalidate_all(); - } + self.open_channels_loads.invalidate(&community_id, || { + self.open_channels_cache.invalidate(&community_id); + }); + self.member_channels_loads.invalidate_matching( + move |(entry_community, _)| *entry_community == community_id, + || { + let entries = self.member_channels_cache.invalidate_entries_if( + move |(entry_community, _), _| *entry_community == community_id, + ); + if let Err(error) = entries { + // AppState enables invalidation closures at construction + // time. If that invariant ever regresses, prefer + // over-invalidating to serving stale access state. + tracing::error!( + ?error, + "community-scoped accessible-channel invalidation unavailable; falling back to full invalidation" + ); + self.member_channels_cache.invalidate_all(); + } + }, + ); } /// Invalidate the cached visibility for a single channel (e.g. after a flip). @@ -2693,22 +2755,78 @@ impl AppState { community_id: CommunityId, pubkey: &[u8], ) -> Result, buzz_db::DbError> { - let key = (community_id, pubkey.to_vec()); - let mut ids = match self.member_channels_cache.get(&key) { - Some(cached) => { - metrics::counter!("buzz_accessible_channels_cache_hits_total").increment(1); - cached - } - None => { - metrics::counter!("buzz_accessible_channels_cache_misses_total").increment(1); - let ids = self.db.get_member_channel_ids(community_id, pubkey).await?; - self.member_channels_cache.insert(key, ids.clone()); - ids - } + Ok(self + .get_channel_access_cached(community_id, pubkey) + .await? + .implicit) + } + + /// [`Self::get_accessible_channel_ids_cached`] as `implicit`, plus the + /// reader's named-only channels from the same two cached reads (see + /// [`ChannelAccess::named_only`]). + pub async fn get_channel_access_cached( + &self, + community_id: CommunityId, + pubkey: &[u8], + ) -> Result { + let member = self + .member_channels( + (community_id, pubkey.to_vec()), + self.db.get_member_channels_read_at(community_id, pubkey), + ) + .await?; + let open = self + .open_channels( + community_id, + self.db.get_listed_open_channels_read_at(community_id), + ) + .await?; + let mut implicit = member.implicit.clone(); + buzz_db::channel_members::merge_channel_ids(&mut implicit, &open.ids); + Ok(ChannelAccess { + implicit, + member, + open: Some(open), + }) + } + + /// The member half for `key` from [`Self::member_channels_cache`] while it + /// is younger than [`MEMBER_CHANNELS_MAX_AGE`], else from `read`. + /// + /// A read answers its own request, but is cached only if no invalidation + /// for its key ran while it read. Otherwise a read that saw a membership + /// just before its removal would grant it to later requests for the + /// entry's whole life. + async fn member_channels( + &self, + key: (CommunityId, Vec), + read: impl std::future::Future< + Output = Result< + buzz_db::ReadAt, + buzz_db::DbError, + >, + >, + ) -> Result, buzz_db::DbError> { + if let Some(cached) = self + .member_channels_cache + .get(&key) + .filter(|member| member.read_at.elapsed() < MEMBER_CHANNELS_MAX_AGE) + { + metrics::counter!("buzz_accessible_channels_cache_hits_total").increment(1); + return Ok(cached.set); + } + metrics::counter!("buzz_accessible_channels_cache_misses_total").increment(1); + let load = self.member_channels_loads.begin(&key); + let read = read.await?; + let member = MemberChannels { + set: Arc::new(read.value), + read_at: read.read_at, }; - let open = self.open_channels(community_id).await?; - buzz_db::channel_members::merge_channel_ids(&mut ids, &open.ids); - Ok(ids) + let set = member.set.clone(); + self.member_channels_loads.publish(&key, load, || { + self.member_channels_cache.insert(key.clone(), member); + }); + Ok(set) } /// The community's open set from [`Self::open_channels_cache`] while it @@ -2721,9 +2839,18 @@ impl AppState { /// A waiter also stops waiting once the leader has had the writer pool's /// acquire timeout plus [`SHARED_READ_STATEMENT_WAIT`], and reads on its /// own, so a leader whose read hangs stalls its waiters at most that long. + /// + /// As with [`Self::member_channels`], a read answers its own request but + /// is cached only if no invalidation for its community ran while it read. async fn open_channels( &self, community_id: CommunityId, + read: impl std::future::Future< + Output = Result< + buzz_db::ReadAt, + buzz_db::DbError, + >, + >, ) -> Result, buzz_db::DbError> { let fresh = || { self.open_channels_cache @@ -2745,15 +2872,16 @@ impl AppState { "absent" }; metrics::counter!("buzz_open_channels_cache_misses_total", "reason" => reason).increment(1); - let read = self - .db - .get_listed_open_channel_ids_read_at(community_id) - .await?; + let load = self.open_channels_loads.begin(&community_id); + let read = read.await?; let open = Arc::new(OpenChannels { - ids: read.value, + ids: read.value.implicit, + named_only: read.value.named_only, read_at: read.read_at, }); - self.open_channels_cache.insert(community_id, open.clone()); + self.open_channels_loads.publish(&community_id, load, || { + self.open_channels_cache.insert(community_id, open.clone()); + }); Ok(open) } @@ -2768,6 +2896,23 @@ impl AppState { self.restriction_cache.seed(key, state); } + /// Seeds a fresh member-channels entry for `key` without touching the + /// database. + #[cfg(test)] + pub(crate) fn seed_member_channels( + &self, + key: (CommunityId, Vec), + set: buzz_db::channel_members::ChannelSet, + ) { + self.member_channels_cache.insert( + key, + MemberChannels { + set: Arc::new(set), + read_at: Instant::now(), + }, + ); + } + /// Seeds both accessible-channel caches so `pubkey` reads exactly /// `channels`, with no open channels, without touching the database. #[cfg(test)] @@ -2777,12 +2922,18 @@ impl AppState { pubkey: Vec, channels: Vec, ) { - self.member_channels_cache - .insert((community_id, pubkey), channels); + self.seed_member_channels( + (community_id, pubkey), + buzz_db::channel_members::ChannelSet { + implicit: channels, + named_only: Vec::new(), + }, + ); self.open_channels_cache.insert( community_id, Arc::new(OpenChannels { ids: Vec::new(), + named_only: Vec::new(), read_at: Instant::now(), }), ); @@ -3985,7 +4136,14 @@ pub(crate) mod tests { behind_held_connection(&pool, wait, misses, || { let reader = Arc::clone(&state); - async move { reader.open_channels(community).await } + async move { + reader + .open_channels( + community, + reader.db.get_listed_open_channels_read_at(community), + ) + .await + } }) .await .into_iter() @@ -4137,7 +4295,14 @@ pub(crate) mod tests { (0..n) .map(|_| { let state = Arc::clone(&state); - tokio::spawn(async move { state.open_channels(community).await }) + tokio::spawn(async move { + state + .open_channels( + community, + state.db.get_listed_open_channels_read_at(community), + ) + .await + }) }) .collect::>() }; @@ -4292,6 +4457,7 @@ pub(crate) mod tests { community, Arc::new(OpenChannels { ids: stale.ids.clone(), + named_only: stale.named_only.clone(), read_at, }), ); @@ -4299,9 +4465,7 @@ pub(crate) mod tests { // A cached reader and a fresh stamp keep the control off the // database and the clock, however slowly the steps above ran. let control = reader(); - reader_pod - .member_channels_cache - .insert((community, control.clone()), Vec::new()); + reader_pod.seed_member_channels((community, control.clone()), Default::default()); restamp(Instant::now()); assert!( grants(control, channel).await, @@ -4574,13 +4738,270 @@ pub(crate) mod tests { assert_eq!( state .member_channels_cache - .get(&(community_b, pubkey.clone())), + .get(&(community_b, pubkey.clone())) + .map(|member| member.set.implicit.clone()), Some(channels_b), "A's cache drop must not evict B's accessible-channel entry" ); assert!(state.open_channels_cache.get(&community_b).is_some()); } + /// A read result whose connection was checked out now. + fn read_now(value: T) -> buzz_db::ReadAt { + buzz_db::ReadAt { + value, + read_at: Instant::now(), + } + } + + /// Yields until a refill of `key` is in flight in `fence`. + async fn until_loading(fence: &crate::load_fence::LoadFence, key: &K) + where + K: std::hash::Hash + Eq + Clone + Send + Sync + 'static, + { + for _ in 0..1_000 { + if fence.is_loading(key) { + return; + } + tokio::task::yield_now().await; + } + panic!("the refill never started"); + } + + /// A member-channels read that straddles an invalidation of its key, + /// per user or community-wide, answers its own request but is not + /// cached, so a removal is not undone by a read that began before it. A + /// read with no invalidation is cached. + /// Mutation: publish without checking the load token, or drop the token + /// invalidation from either path → RED. + #[tokio::test] + async fn a_member_read_that_straddles_an_invalidation_is_not_cached() { + use buzz_db::channel_members::ChannelSet; + let state = test_state().await; + let community = CommunityId::from_uuid(Uuid::from_u128(0xAAAA)); + let pubkey = vec![7u8; 32]; + let key = (community, pubkey.clone()); + let revoked = Uuid::from_u128(1); + let stale = ChannelSet { + implicit: Vec::new(), + named_only: vec![(revoked, "system".to_owned())], + }; + let invalidations: [&dyn Fn(); 2] = [ + &|| state.invalidate_membership_local(community, revoked, &pubkey), + &|| state.invalidate_all_accessible_channels_local(community), + ]; + for (path, invalidate) in invalidations.into_iter().enumerate() { + let (release, held) = tokio::sync::oneshot::channel::<()>(); + let read = { + let stale = stale.clone(); + async move { + held.await.ok(); + Ok(read_now(stale)) + } + }; + let task = { + let state = state.clone(); + let key = key.clone(); + tokio::spawn(async move { state.member_channels(key, read).await }) + }; + until_loading(&state.member_channels_loads, &key).await; + invalidate(); + release.send(()).expect("read is waiting"); + let answered = task.await.expect("join").expect("read"); + assert_eq!( + *answered, stale, + "path {path}: the read answers its request" + ); + assert!( + state.member_channels_cache.get(&key).is_none(), + "path {path}: a read that straddles an invalidation is not cached" + ); + } + let fresh = ChannelSet::default(); + state + .member_channels(key.clone(), async { Ok(read_now(ChannelSet::default())) }) + .await + .expect("read"); + assert_eq!( + state + .member_channels_cache + .get(&key) + .map(|member| (*member.set).clone()), + Some(fresh), + "a read with no invalidation is cached" + ); + } + + /// Overlapping member reads for one key share a load token, so the first + /// to finish is cached even while a later miss is still reading. Main + /// cached every completed read; a newer miss must not stop an older one + /// from warming the cache under a slow writer. + /// Mutation: give each refill its own token in `LoadFence::begin` → RED. + #[tokio::test] + async fn overlapping_member_reads_cache_the_first_to_finish() { + use buzz_db::channel_members::ChannelSet; + let state = test_state().await; + let key = ( + CommunityId::from_uuid(Uuid::from_u128(0xAAAC)), + vec![7u8; 32], + ); + let first = ChannelSet { + implicit: Vec::new(), + named_only: vec![(Uuid::from_u128(1), "system".to_owned())], + }; + let (release_a, held_a) = tokio::sync::oneshot::channel::<()>(); + let a = { + let state = state.clone(); + let key = key.clone(); + let first = first.clone(); + tokio::spawn(async move { + state + .member_channels(key, async move { + held_a.await.ok(); + Ok(read_now(first)) + }) + .await + }) + }; + until_loading(&state.member_channels_loads, &key).await; + let (started_b, b_started) = tokio::sync::oneshot::channel::<()>(); + let b = { + let state = state.clone(); + let key = key.clone(); + tokio::spawn(async move { + state + .member_channels(key, async move { + started_b.send(()).ok(); + std::future::pending::<()>().await; + Ok(read_now(ChannelSet::default())) + }) + .await + }) + }; + b_started.await.expect("B is reading"); + release_a.send(()).expect("A is waiting"); + let answered = a.await.expect("join").expect("read"); + assert_eq!(*answered, first, "A answers its request"); + assert_eq!( + state + .member_channels_cache + .get(&key) + .map(|member| (*member.set).clone()), + Some(first.clone()), + "the first overlapping read to finish is cached" + ); + b.abort(); + let served = state + .member_channels(key.clone(), async { Ok(read_now(ChannelSet::default())) }) + .await + .expect("read"); + assert_eq!(*served, first, "the next lookup is a hit on A's set"); + } + + /// A member snapshot is dated from its read's connection checkout, not + /// from its insert: one already [`MEMBER_CHANNELS_MAX_AGE`] old when it + /// is published is not served to the next lookup, so a slow read cannot + /// stretch a missed peer invalidation past that bound. + /// Mutation: drop the `read_at` age check on hits → RED. + #[tokio::test] + async fn a_member_snapshot_ages_from_its_read_not_its_insert() { + use buzz_db::channel_members::ChannelSet; + let state = test_state().await; + let key = ( + CommunityId::from_uuid(Uuid::from_u128(0xAAAB)), + vec![7u8; 32], + ); + let old = ChannelSet { + implicit: vec![Uuid::from_u128(1)], + named_only: Vec::new(), + }; + let aged = buzz_db::ReadAt { + value: old.clone(), + read_at: Instant::now() + .checked_sub(MEMBER_CHANNELS_MAX_AGE) + .expect("the monotonic clock is older than the max age"), + }; + state + .member_channels(key.clone(), async { Ok(aged) }) + .await + .expect("read"); + let next = state + .member_channels(key.clone(), async { Ok(read_now(ChannelSet::default())) }) + .await + .expect("read"); + assert_eq!( + *next, + ChannelSet::default(), + "a snapshot past its age at publication is read again" + ); + let again = state + .member_channels(key, async { Ok(read_now(old)) }) + .await + .expect("read"); + assert_eq!( + *again, + ChannelSet::default(), + "control: a fresh snapshot is served from the cache" + ); + } + + /// An open-set read that straddles its community's invalidation (an + /// open channel made private on this pod) answers its own request but + /// is not cached, so the next request reads again instead of using the + /// old snapshot. A read with no invalidation is cached. + /// Mutation: publish the open set without checking its load token, or + /// drop the token invalidation → RED. + #[tokio::test] + async fn an_open_read_that_straddles_an_invalidation_is_not_cached() { + use buzz_db::channel_members::ChannelSet; + let state = test_state().await; + let community = CommunityId::from_uuid(Uuid::from_u128(0xBBBB)); + let revoked = Uuid::from_u128(1); + let stale = ChannelSet { + implicit: vec![revoked], + named_only: vec![(Uuid::from_u128(2), "system".to_owned())], + }; + let (release, held) = tokio::sync::oneshot::channel::<()>(); + let task = { + let state = state.clone(); + tokio::spawn(async move { + state + .open_channels(community, async move { + held.await.ok(); + Ok(read_now(stale)) + }) + .await + }) + }; + until_loading(&state.open_channels_loads, &community).await; + state.invalidate_all_accessible_channels_local(community); + release.send(()).expect("read is waiting"); + let answered = task.await.expect("join").expect("read"); + assert_eq!(answered.ids, [revoked], "the read answers its request"); + + let next = state + .open_channels(community, async { Ok(read_now(ChannelSet::default())) }) + .await + .expect("read"); + assert!( + next.ids.is_empty() && next.named_only.is_empty(), + "a later request reads again instead of using the straddling snapshot" + ); + let again = state + .open_channels(community, async { + Ok(read_now(ChannelSet { + implicit: vec![revoked], + named_only: Vec::new(), + })) + }) + .await + .expect("read"); + assert!( + Arc::ptr_eq(&again, &next), + "control: a read with no invalidation is cached" + ); + } + #[tokio::test] async fn accessible_channels_join_member_and_open_halves() { let state = test_state().await; @@ -4592,6 +5013,7 @@ pub(crate) mod tests { community, Arc::new(OpenChannels { ids: vec![both, open], + named_only: Vec::new(), read_at: Instant::now(), }), ); @@ -4604,9 +5026,7 @@ pub(crate) mod tests { // Another reader shares the community's open half. let other = vec![8u8; 32]; - state - .member_channels_cache - .insert((community, other.clone()), vec![]); + state.seed_member_channels((community, other.clone()), Default::default()); let ids = state .get_accessible_channel_ids_cached(community, &other) .await @@ -4629,7 +5049,14 @@ pub(crate) mod tests { (0..8) .map(|_| { let state = Arc::clone(state); - tokio::spawn(async move { state.open_channels(community).await }) + tokio::spawn(async move { + state + .open_channels( + community, + state.db.get_listed_open_channels_read_at(community), + ) + .await + }) }) .collect::>() }; @@ -4645,6 +5072,7 @@ pub(crate) mod tests { community, Arc::new(OpenChannels { ids: vec![open], + named_only: Vec::new(), read_at: Instant::now(), }), ); @@ -4796,7 +5224,8 @@ pub(crate) mod tests { assert_eq!( state .member_channels_cache - .get(&(community_b, pubkey.clone())), + .get(&(community_b, pubkey.clone())) + .map(|member| member.set.implicit.clone()), Some(vec![channel_id]) ); assert!(state.open_channels_cache.get(&community_b).is_some()); diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index 170344edac..193799c3a0 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -422,6 +422,10 @@ run_unit_tests() { community_active::tests::invalidation_fences_an_in_flight_fill_and_its_waiters \ community_active::tests::errors_are_not_cached \ state::tests::concurrent_open_channel_misses_share_the_in_flight_read \ + state::tests::a_member_read_that_straddles_an_invalidation_is_not_cached \ + state::tests::a_member_snapshot_ages_from_its_read_not_its_insert \ + state::tests::overlapping_member_reads_cache_the_first_to_finish \ + state::tests::an_open_read_that_straddles_an_invalidation_is_not_cached \ state::tests::concurrent_restriction_and_host_misses_share_the_in_flight_read \ tenant::tests::app_state_resolver_serves_fresh_cached_hosts_only \ tenant::tests::an_overlong_host_fails_closed_before_the_resolver \