mirror of
https://github.com/block/buzz.git
synced 2026-11-07 09:52:03 +00:00
## Summary - send desktop presence heartbeats every 60 seconds instead of every 30 seconds - extend presence TTL from 90 to 180 seconds to preserve the existing three-heartbeat expiry window - add mutation-sensitive tests that pin the one-minute / three-window timing contract - update presence documentation to match This halves steady-state **desktop** presence `SET` + `PUBLISH` traffic while retaining tolerance for two missed heartbeats. Mobile already uses a 60-second heartbeat, so the fleet-wide reduction depends on desktop's share of connected clients. ## Rollout order Deploy the relay TTL increase before shipping the desktop heartbeat change. Old desktop + new relay is safe; new desktop + old relay leaves only a 90-second TTL on a 60-second cadence and can flap after one missed heartbeat. ## Verification At initial live-test commit `00816e233b187bc5ba12c667d675ed050a8cc1c9`: - isolated clean-room relay built from the exact SHA against fresh Postgres, Redis, and MinIO - live Redis `MONITOR` observed kind-20001 writes as `SET ... EX 180`, global `PUBLISH`, and clean-disconnect / explicit-offline `DEL` - normal workflows passed: channel create/update/archive/unarchive; message send/get/reply/thread/search; archived-channel write rejection and resumed write after unarchive At follow-up commit `bf38a8c5c96f196ff8ee46e48d4141ee7811f186`: - `pnpm -C desktop test` — 3829 passed - `pnpm -C desktop typecheck` - `cargo test -p buzz-pubsub` — 24 passed, 11 Redis-dependent tests ignored - mutation probes fail when the server TTL changes to `999999` or the desktop heartbeat changes back to 30 seconds - `git diff --check` The pre-push suite's relevant checks passed, but its unrelated Tauri clippy step fails on current `origin/main`: `desktop/src-tauri/src/linux_media.rs` has three dead-code warnings on macOS. This PR does not modify that file, so the branch was pushed after independently running the suites above. ## Buzz context Originating channel: `buzz-redis-cluster-mode` (`f4e36d32-afdb-447f-8c87-ab003e069d18`) --------- Signed-off-by: npub1t2tgm7d8f995uqvmnm8h88sg3wnpp9a5xysjf6dg3tjmgt3ltulqdp8ehr <5a968df9a7494b4e019b9ecf739e088ba61097b4312124e9a88ae5b42e3f5f3e@buzz.block.builderlab.xyz> Co-authored-by: npub1t2tgm7d8f995uqvmnm8h88sg3wnpp9a5xysjf6dg3tjmgt3ltulqdp8ehr <5a968df9a7494b4e019b9ecf739e088ba61097b4312124e9a88ae5b42e3f5f3e@buzz.block.builderlab.xyz>
216 lines
6.5 KiB
Rust
216 lines
6.5 KiB
Rust
//! Presence tracking — online/away status with TTL.
|
|
//!
|
|
//! Stored as `SET buzz:{community}:presence:{pubkey_hex} "online" EX 180`.
|
|
//! TTL is 3x the 60s heartbeat interval so a single missed heartbeat doesn't
|
|
//! cause presence flap. Clean disconnect deletes immediately.
|
|
|
|
use buzz_core::TenantContext;
|
|
use deadpool_redis::Pool;
|
|
use nostr::PublicKey;
|
|
use std::collections::HashMap;
|
|
|
|
use crate::error::PubSubError;
|
|
use crate::topic::BUZZ_PREFIX;
|
|
|
|
/// 3x the 60s heartbeat — single missed heartbeat won't cause presence flap.
|
|
pub const PRESENCE_TTL_SECS: u64 = 180;
|
|
|
|
/// Returns the Redis key for the presence entry of `pubkey` under `ctx`.
|
|
pub fn presence_key(ctx: &TenantContext, pubkey: &PublicKey) -> String {
|
|
format!(
|
|
"{BUZZ_PREFIX}:{}:presence:{}",
|
|
ctx.community(),
|
|
pubkey.to_hex()
|
|
)
|
|
}
|
|
|
|
/// Sets presence status for `pubkey` with a [`PRESENCE_TTL_SECS`]-second TTL.
|
|
pub async fn set_presence(
|
|
pool: &Pool,
|
|
ctx: &TenantContext,
|
|
pubkey: &PublicKey,
|
|
status: &str,
|
|
) -> Result<(), PubSubError> {
|
|
let mut conn = pool.get().await?;
|
|
let key = presence_key(ctx, pubkey);
|
|
redis::cmd("SET")
|
|
.arg(&key)
|
|
.arg(status)
|
|
.arg("EX")
|
|
.arg(PRESENCE_TTL_SECS)
|
|
.query_async::<()>(&mut conn)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Removes the presence entry for `pubkey`. Call on clean disconnect.
|
|
pub async fn clear_presence(
|
|
pool: &Pool,
|
|
ctx: &TenantContext,
|
|
pubkey: &PublicKey,
|
|
) -> Result<(), PubSubError> {
|
|
let mut conn = pool.get().await?;
|
|
let key = presence_key(ctx, pubkey);
|
|
redis::cmd("DEL")
|
|
.arg(&key)
|
|
.query_async::<()>(&mut conn)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Returns the current presence status for `pubkey`, or `None` if not set or expired.
|
|
pub async fn get_presence(
|
|
pool: &Pool,
|
|
ctx: &TenantContext,
|
|
pubkey: &PublicKey,
|
|
) -> Result<Option<String>, PubSubError> {
|
|
let mut conn = pool.get().await?;
|
|
let key = presence_key(ctx, pubkey);
|
|
let value: Option<String> = redis::cmd("GET").arg(&key).query_async(&mut conn).await?;
|
|
Ok(value)
|
|
}
|
|
|
|
/// Returns `pubkey_hex → status` for all currently-set keys.
|
|
pub async fn get_presence_bulk(
|
|
pool: &Pool,
|
|
ctx: &TenantContext,
|
|
pubkeys: &[PublicKey],
|
|
) -> Result<HashMap<String, String>, PubSubError> {
|
|
if pubkeys.is_empty() {
|
|
return Ok(HashMap::new());
|
|
}
|
|
let mut conn = pool.get().await?;
|
|
let keys: Vec<String> = pubkeys
|
|
.iter()
|
|
.map(|pubkey| presence_key(ctx, pubkey))
|
|
.collect();
|
|
let values: Vec<Option<String>> = redis::cmd("MGET").arg(&keys).query_async(&mut conn).await?;
|
|
let result = pubkeys
|
|
.iter()
|
|
.zip(values.iter())
|
|
.filter_map(|(pk, v)| v.as_ref().map(|s| (pk.to_hex(), s.clone())))
|
|
.collect();
|
|
Ok(result)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::test_util::make_test_pool;
|
|
use buzz_core::{CommunityId, TenantContext};
|
|
use nostr::Keys;
|
|
use uuid::Uuid;
|
|
|
|
fn make_pubkey() -> PublicKey {
|
|
Keys::generate().public_key()
|
|
}
|
|
|
|
fn ctx(id: u128, host: &str) -> TenantContext {
|
|
TenantContext::resolved(CommunityId::from_uuid(Uuid::from_u128(id)), host)
|
|
}
|
|
|
|
#[test]
|
|
fn presence_ttl_is_three_one_minute_heartbeat_windows() {
|
|
assert_eq!(PRESENCE_TTL_SECS, 180);
|
|
assert_eq!(PRESENCE_TTL_SECS, 3 * 60);
|
|
}
|
|
|
|
#[test]
|
|
fn test_presence_key_format() {
|
|
let pubkey = make_pubkey();
|
|
let ctx = ctx(0xaaaa, "a.example");
|
|
let key = presence_key(&ctx, &pubkey);
|
|
let prefix = format!("buzz:{}:presence:", ctx.community());
|
|
assert!(key.starts_with(&prefix));
|
|
let hex_part = key.strip_prefix(&prefix).unwrap();
|
|
assert_eq!(hex_part.len(), 64);
|
|
assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
|
|
}
|
|
|
|
#[test]
|
|
fn same_pubkey_in_two_communities_has_different_presence_keys() {
|
|
let pubkey = make_pubkey();
|
|
let community_a = ctx(0xaaaa, "a.example");
|
|
let community_b = ctx(0xbbbb, "b.example");
|
|
|
|
assert_ne!(
|
|
presence_key(&community_a, &pubkey),
|
|
presence_key(&community_b, &pubkey)
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Redis"]
|
|
async fn test_presence_set_and_get() {
|
|
let pool = make_test_pool();
|
|
let pubkey = make_pubkey();
|
|
let ctx = ctx(0xaaaa, "a.example");
|
|
|
|
let status = get_presence(&pool, &ctx, &pubkey).await.unwrap();
|
|
assert!(status.is_none());
|
|
|
|
set_presence(&pool, &ctx, &pubkey, "online").await.unwrap();
|
|
let status = get_presence(&pool, &ctx, &pubkey).await.unwrap();
|
|
assert_eq!(status.as_deref(), Some("online"));
|
|
|
|
set_presence(&pool, &ctx, &pubkey, "away").await.unwrap();
|
|
let status = get_presence(&pool, &ctx, &pubkey).await.unwrap();
|
|
assert_eq!(status.as_deref(), Some("away"));
|
|
|
|
clear_presence(&pool, &ctx, &pubkey).await.unwrap();
|
|
let status = get_presence(&pool, &ctx, &pubkey).await.unwrap();
|
|
assert!(status.is_none());
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Redis"]
|
|
async fn test_presence_bulk() {
|
|
let pool = make_test_pool();
|
|
let pk1 = make_pubkey();
|
|
let pk2 = make_pubkey();
|
|
let pk3 = make_pubkey();
|
|
let ctx = ctx(0xaaaa, "a.example");
|
|
|
|
set_presence(&pool, &ctx, &pk1, "online").await.unwrap();
|
|
set_presence(&pool, &ctx, &pk2, "away").await.unwrap();
|
|
|
|
let result = get_presence_bulk(&pool, &ctx, &[pk1, pk2, pk3])
|
|
.await
|
|
.unwrap();
|
|
|
|
assert_eq!(
|
|
result.get(&pk1.to_hex()).map(|s| s.as_str()),
|
|
Some("online")
|
|
);
|
|
assert_eq!(result.get(&pk2.to_hex()).map(|s| s.as_str()), Some("away"));
|
|
assert!(!result.contains_key(&pk3.to_hex()));
|
|
|
|
clear_presence(&pool, &ctx, &pk1).await.unwrap();
|
|
clear_presence(&pool, &ctx, &pk2).await.unwrap();
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Redis"]
|
|
async fn test_presence_ttl() {
|
|
let pool = make_test_pool();
|
|
let pubkey = make_pubkey();
|
|
let ctx = ctx(0xaaaa, "a.example");
|
|
|
|
set_presence(&pool, &ctx, &pubkey, "online").await.unwrap();
|
|
|
|
let mut conn = pool.get().await.unwrap();
|
|
let ttl: i64 = redis::cmd("TTL")
|
|
.arg(presence_key(&ctx, &pubkey))
|
|
.query_async(&mut conn)
|
|
.await
|
|
.unwrap();
|
|
|
|
assert!(
|
|
ttl > 0 && ttl <= PRESENCE_TTL_SECS as i64,
|
|
"TTL should be 1-{PRESENCE_TTL_SECS}s, got {ttl}"
|
|
);
|
|
|
|
clear_presence(&pool, &ctx, &pubkey).await.unwrap();
|
|
}
|
|
}
|