Files
buzz/crates/buzz-pubsub/src/subscriber.rs
Logan Johnson 30e1fa47fb fix(relay): fence pending subscriptions on close or replacement (#2382)
## Summary

A REQ handler runs as a spawned task and can pause in its access checks.
Before this change it took its subscription ID only when it registered.
So:

- `REQ x`, then `CLOSE x` while the REQ was still in its access checks:
the relay sent `CLOSED x`, and then the REQ registered `x` anyway and
sent events and `EOSE` under an ID the client had closed.
- `REQ x` (A), then a newer `REQ x` (B): if A finished its checks after
B registered, A replaced B, or A's refusal retired B and sent a `CLOSED`
the client could not tell from B failing.

Now the read loop admits each REQ and sync REQ, in arrival order, before
it spawns the handler: the newest request owns the ID from the moment it
arrives. A `CLOSE` or a newer same-ID request fences an older one that
is still pending. A fenced request does not register, and does not send
`NOTICE`, `CLOSED`, `EVENT` or `EOSE` for the ID.

This builds on the owner token and lifecycle lock that #8522 added. That
PR fenced output after registration; this one moves the token to
admission, so the same fence also covers the time before registration.

The pubsub retain no longer waits on a full subscriber command queue.
Callers hold a connection's lifecycle lock while they retain. A retain
past a full queue now leaves a coalesced wake-up, and the subscriber
subscribes every retained topic it is missing. A retain that fits in the
queue leaves no wake-up, so first retains do not each make the
subscriber rescan the map.

## Behavior

- `close::admit` runs in the read loop before spawn. It records the
request's token in the connection's subscription map, with a flag that
says whether the request has claimed yet. It also applies the
subscription limit, which moves there from the handlers.
- Claims (`claim_admitted_live`, `claim_admitted_search`, the sync
claim) register only while the request still owns its token.
- Refusals after admission go through `close_if_owner`. The two REQ
refusals that also send a `NOTICE` send it in the same critical section.
- Refusals before admission (rate limit, admission quota) still retire
the old holder, as before.
- The old holder stays registered until the newer request claims or is
refused, as before.
- A channel-access eviction that removes an old holder while a newer
same-ID request is still pending retires only the old holder. It sends
no `CLOSED` for the ID, because the client already replaced that holder,
and the newer request still claims.

Client-visible changes to the subscription limit:

- The limit is checked on arrival, before scope, auth and filter checks.
On a full connection, a REQ for a new ID that would also fail those
checks now gets `CLOSED "error: too many subscriptions"` instead of the
other refusal.
- Requests still in their access checks count toward the limit.

## Scope

Live fan-out does not check the token. A same-ID request that has
arrived but not yet claimed does not stop live events to the old holder.
That path is unchanged here.

If a handler panics before it claims, its token stays in the map until a
`CLOSE`, a same-ID REQ, or the disconnect removes it. Until then it
counts toward the subscription limit.

## Testing

- `close_fences_a_req_whose_handler_has_not_run` (REQ and sync REQ):
`REQ x` then `CLOSE x` before the handler runs gives only `CLOSED x` and
no registration.
- `only_the_newest_same_id_req_answers`: of two same-ID REQs, only the
newer one answers.
- `superseded_or_closed_requests_cannot_claim`: an older request cannot
claim after a newer one, and a closed request cannot claim or close.
- `revoke_of_a_replaced_holder_spares_the_pending_replacement`: a revoke
of the old holder sends no `CLOSED`, keeps the pending request's token,
and the pending request then claims its own channel.
- `queue_full_retain_does_not_wait_and_schedules_reconciliation`
(pubsub).
- `live_subscriber_recovers_a_dropped_subscribe_hint` (pubsub, requires
Redis): it runs the real subscriber on a live link and drops a topic's
subscribe hint with a full queue. The topic is still delivered without a
reconnect and without `Confirm`. The same holds after the topic is
released, unsubscribed and retained again.
- Mutations: with no owner check in `close_owned`, both connection tests
fail. With no owner check in `claim_admitted_live`, the claim test
fails. With no `replaced` check in the eviction, the revoke test fails.
With no reconcile arm in the subscriber, or no `notify_one` in
`retain_topic`, the Redis subscriber test fails.
- CI: the four new relay tests and the full-queue pubsub test are added
to `just test-unit` and `scripts/run-tests.sh`. The Redis subscriber
test runs in a new Redis-backed backend-integration step.
- `cargo test -p buzz-relay --lib` (with `--skip config::tests`, which
hangs locally when run in one process), `cargo test -p buzz-pubsub --
--include-ignored` against a local Redis, `cargo clippy -p buzz-relay -p
buzz-pubsub --all-targets -- -D warnings`, `cargo fmt --all -- --check`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 14:16:48 -05:00

264 lines
9.5 KiB
Rust

//! Redis pub/sub subscriber — fans out messages to local WS connections via broadcast.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use futures_util::StreamExt;
use nostr::JsonUtil;
use tokio::sync::{broadcast, mpsc, oneshot, watch, Mutex, Notify};
use crate::topic::EventTopicKey;
use crate::{ChannelEvent, LinkState};
/// Initial reconnect backoff (1 second).
const BACKOFF_INITIAL_SECS: u64 = 1;
/// Maximum reconnect backoff (30 seconds).
const BACKOFF_MAX_SECS: u64 = 30;
/// Local desired topic refcounts, keyed by fully scoped Redis topic.
pub(crate) type DesiredTopics = Arc<Mutex<HashMap<EventTopicKey, usize>>>;
/// Commands sent from relay subscription registration/removal to the Redis
/// pub/sub task.
#[derive(Debug)]
pub(crate) enum SubscriptionCommand {
/// Ensure the topic is subscribed on the current Redis pub/sub connection.
Subscribe(EventTopicKey),
/// Unsubscribe only if the desired refcount is still zero when processed.
UnsubscribeIfIdle(EventTopicKey),
/// Subscribe if needed, then answer with the link epoch on which the
/// server has confirmed the subscription.
Confirm(EventTopicKey, oneshot::Sender<u64>),
}
/// Record a possible loss of messages: the epoch advances, so every reader
/// that started on the old epoch can tell.
fn mark_loss(link: &watch::Sender<LinkState>, up: bool) {
link.send_modify(|state| {
state.epoch += 1;
state.up = up;
});
}
/// Runs a dynamically scoped subscriber and forwards events to broadcast.
///
/// The desired refcount map is the source of truth. On every reconnect, this
/// task snapshots topics with count > 0 and subscribes to those exact Redis
/// channels before processing messages.
pub(crate) async fn run_subscriber(
redis_url: String,
broadcast_tx: broadcast::Sender<ChannelEvent>,
desired_topics: DesiredTopics,
mut subscription_rx: mpsc::Receiver<SubscriptionCommand>,
subscription_changed: Arc<Notify>,
link: watch::Sender<LinkState>,
) {
let mut backoff_secs = BACKOFF_INITIAL_SECS;
loop {
let result = connect_and_subscribe(
&redis_url,
&broadcast_tx,
desired_topics.clone(),
&mut subscription_rx,
&subscription_changed,
&link,
)
.await;
if link.borrow().up {
// Messages published while the link is down are not replayed.
mark_loss(&link, false);
}
match result {
Ok(()) => {
// Stream ended cleanly (Redis returned None). The connection was
// established and ran successfully, so reset backoff to the initial
// value — a brief Redis restart should reconnect quickly.
backoff_secs = BACKOFF_INITIAL_SECS;
tracing::warn!("Redis pub/sub stream ended (clean disconnect) — reconnecting in {backoff_secs}s");
}
Err(e) => {
tracing::error!("Redis pub/sub error: {e} — reconnecting in {backoff_secs}s");
}
}
tokio::time::sleep(Duration::from_secs(backoff_secs)).await;
backoff_secs = (backoff_secs * 2).min(BACKOFF_MAX_SECS);
tracing::info!("Attempting to reconnect to Redis pub/sub...");
}
}
/// Establish a Redis pub/sub connection, subscribe to the current desired-topic
/// snapshot, and run the fan-out / command loop until the connection ends.
async fn connect_and_subscribe(
redis_url: &str,
broadcast_tx: &broadcast::Sender<ChannelEvent>,
desired_topics: DesiredTopics,
subscription_rx: &mut mpsc::Receiver<SubscriptionCommand>,
subscription_changed: &Notify,
link: &watch::Sender<LinkState>,
) -> Result<(), redis::RedisError> {
let client = redis::Client::open(redis_url)?;
let conn = client.get_async_pubsub().await?;
let (mut sink, mut stream) = conn.split();
let mut active_topics = HashSet::new();
let initial_topics: Vec<EventTopicKey> = {
let desired = desired_topics.lock().await;
desired
.iter()
.filter_map(|(topic, count)| (*count > 0).then_some(*topic))
.collect()
};
for topic in initial_topics {
let channel = topic.redis_channel();
sink.subscribe(&channel).await?;
active_topics.insert(channel);
}
tracing::info!(
topic_count = active_topics.len(),
"Redis pub/sub subscriber connected with dynamic scoped subscriptions"
);
mark_loss(link, true);
loop {
tokio::select! {
() = subscription_changed.notified() => {
// Retains signal this besides their best-effort queue hint.
// Re-read the source of truth so a hint lost to a full queue
// cannot leave the live connection missing a topic.
for topic in missing_desired_topics(&desired_topics, &active_topics).await {
let channel = topic.redis_channel();
sink.subscribe(&channel).await?;
active_topics.insert(channel);
}
}
Some(command) = subscription_rx.recv() => {
match command {
SubscriptionCommand::Subscribe(topic) => {
let channel = topic.redis_channel();
if active_topics.insert(channel.clone()) {
sink.subscribe(&channel).await?;
}
}
SubscriptionCommand::Confirm(topic, reply) => {
let channel = topic.redis_channel();
if !active_topics.contains(&channel) {
sink.subscribe(&channel).await?;
active_topics.insert(channel);
}
let _ = reply.send(link.borrow().epoch);
}
SubscriptionCommand::UnsubscribeIfIdle(topic) => {
if desired_refcount(&desired_topics, topic).await == 0 {
let channel = topic.redis_channel();
if active_topics.remove(&channel) {
sink.unsubscribe(&channel).await?;
}
}
}
}
}
msg = stream.next() => {
let Some(msg) = msg else {
// Stream returned None — Redis connection closed.
return Ok(());
};
let payload: String = match msg.get_payload() {
Ok(p) => p,
Err(e) => {
tracing::warn!("Failed to get pub/sub message payload: {e}");
mark_loss(link, true);
continue;
}
};
let channel_name = msg.get_channel_name();
let topic_key = match EventTopicKey::parse_redis_channel(channel_name) {
Ok(topic_key) => topic_key,
Err(_) => {
tracing::warn!("Received pub/sub message on unexpected channel: {channel_name}");
continue;
}
};
let event = match nostr::Event::from_json(&payload) {
Ok(e) => e,
Err(e) => {
tracing::warn!("Failed to deserialize event from pub/sub: {e}");
mark_loss(link, true);
continue;
}
};
let channel_event = ChannelEvent {
community_id: topic_key.community_id,
topic: topic_key.topic,
event,
};
if let Err(_e) = broadcast_tx.send(channel_event) {
tracing::trace!(topic = %channel_name, "No broadcast receivers for topic — message dropped");
}
}
else => {
// Command channel closed and stream ended; let the reconnect loop retry.
return Ok(());
}
}
}
}
/// Retained topics the live connection has not subscribed yet.
pub(crate) async fn missing_desired_topics(
desired_topics: &DesiredTopics,
active_topics: &HashSet<String>,
) -> Vec<EventTopicKey> {
desired_topics
.lock()
.await
.iter()
.filter_map(|(topic, count)| {
(*count > 0 && !active_topics.contains(&topic.redis_channel())).then_some(*topic)
})
.collect()
}
async fn desired_refcount(desired_topics: &DesiredTopics, topic: EventTopicKey) -> usize {
desired_topics
.lock()
.await
.get(&topic)
.copied()
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
use buzz_core::{CommunityId, TenantContext};
use uuid::Uuid;
fn topic(id: u128) -> EventTopicKey {
let ctx = TenantContext::resolved(CommunityId::from_uuid(Uuid::from_u128(id)), "test");
EventTopicKey::from_context(&ctx, crate::EventTopic::Global)
}
#[tokio::test]
async fn desired_refcount_returns_zero_for_absent_topic() {
let desired = Arc::new(Mutex::new(HashMap::new()));
assert_eq!(desired_refcount(&desired, topic(1)).await, 0);
}
#[tokio::test]
async fn desired_refcount_reads_present_topic() {
let desired = Arc::new(Mutex::new(HashMap::from([(topic(1), 3)])));
assert_eq!(desired_refcount(&desired, topic(1)).await, 3);
}
}