use serde::{Deserialize, Serialize};
use tokio::sync::broadcast::{self, Receiver, Sender};
use crate::error::{Result, SkybaseError};
use crate::index::store::RecordRow;
pub const DEFAULT_BROADCAST_CAPACITY: usize = 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChangeNotification {
Upsert(RecordRow),
Delete {
uri: String,
did: String,
collection: String,
rkey: String,
},
}
impl ChangeNotification {
#[must_use]
pub fn uri(&self) -> &str {
match self {
Self::Upsert(row) => &row.uri,
Self::Delete { uri, .. } => uri.as_str(),
}
}
#[must_use]
pub fn did(&self) -> &str {
match self {
Self::Upsert(row) => &row.did,
Self::Delete { did, .. } => did.as_str(),
}
}
#[must_use]
pub fn collection(&self) -> &str {
match self {
Self::Upsert(row) => &row.collection,
Self::Delete { collection, .. } => collection.as_str(),
}
}
#[must_use]
pub fn rkey(&self) -> &str {
match self {
Self::Upsert(row) => &row.rkey,
Self::Delete { rkey, .. } => rkey.as_str(),
}
}
#[must_use]
pub fn is_upsert(&self) -> bool {
matches!(self, Self::Upsert(_))
}
#[must_use]
pub fn is_delete(&self) -> bool {
matches!(self, Self::Delete { .. })
}
#[must_use]
pub fn record(&self) -> Option<&RecordRow> {
match self {
Self::Upsert(row) => Some(row),
Self::Delete { .. } => None,
}
}
#[must_use]
pub fn matches_collection(&self, collection: &str) -> bool {
self.collection() == collection
}
#[must_use]
pub fn matches_did(&self, did: &str) -> bool {
self.did() == did
}
}
#[derive(Clone, Debug)]
pub struct BroadcastBus {
sender: Sender<ChangeNotification>,
}
impl Default for BroadcastBus {
fn default() -> Self {
let (sender, _rx) = broadcast::channel(DEFAULT_BROADCAST_CAPACITY);
Self { sender }
}
}
pub const MAX_BROADCAST_CAPACITY: usize = 65_536;
impl BroadcastBus {
pub fn new(capacity: usize) -> Result<Self> {
if capacity == 0 || capacity > MAX_BROADCAST_CAPACITY {
return Err(SkybaseError::Config(format!(
"Broadcast bus capacity must be between 1 and {MAX_BROADCAST_CAPACITY}, got {capacity}"
)));
}
let (sender, _rx) = broadcast::channel(capacity);
Ok(Self { sender })
}
#[must_use]
pub fn subscribe(&self) -> Receiver<ChangeNotification> {
self.sender.subscribe()
}
pub fn publish(&self, notification: ChangeNotification) -> usize {
self.sender.send(notification).unwrap_or_default()
}
pub fn publish_upsert(&self, row: RecordRow) -> usize {
self.publish(ChangeNotification::Upsert(row))
}
pub fn publish_delete(
&self,
uri: impl Into<String>,
did: impl Into<String>,
collection: impl Into<String>,
rkey: impl Into<String>,
) -> usize {
self.publish(ChangeNotification::Delete {
uri: uri.into(),
did: did.into(),
collection: collection.into(),
rkey: rkey.into(),
})
}
#[must_use]
pub fn receiver_count(&self) -> usize {
self.sender.receiver_count()
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, missing_docs)]
mod tests {
use super::*;
fn sample_record_row(rkey: &str) -> RecordRow {
RecordRow {
uri: format!("at://did:plc:test/app.bsky.feed.post/{rkey}"),
cid: "bafyreitestcid".to_string(),
did: "did:plc:test".to_string(),
collection: "app.bsky.feed.post".to_string(),
rkey: rkey.to_string(),
record_json: serde_json::json!({ "text": "hello skybase" }),
indexed_at: 1_700_000_000,
is_deleted: false,
}
}
#[test]
fn test_zero_capacity_error() {
let bus_res = BroadcastBus::new(0);
assert!(matches!(bus_res, Err(SkybaseError::Config(_))));
}
#[test]
fn test_zero_subscriber_delivery() {
let bus = BroadcastBus::new(16).unwrap();
assert_eq!(bus.receiver_count(), 0);
let row = sample_record_row("post1");
let delivered = bus.publish_upsert(row);
assert_eq!(
delivered, 0,
"Zero active subscribers must return 0 without panicking"
);
}
#[tokio::test]
async fn test_single_subscriber_delivery() {
let bus = BroadcastBus::new(16).unwrap();
let mut rx = bus.subscribe();
assert_eq!(bus.receiver_count(), 1);
let row = sample_record_row("post1");
let delivered = bus.publish_upsert(row.clone());
assert_eq!(delivered, 1);
let event = rx.recv().await.unwrap();
assert_eq!(event, ChangeNotification::Upsert(row.clone()));
assert_eq!(event.uri(), "at://did:plc:test/app.bsky.feed.post/post1");
assert_eq!(event.did(), "did:plc:test");
assert_eq!(event.collection(), "app.bsky.feed.post");
assert_eq!(event.rkey(), "post1");
assert!(event.is_upsert());
assert!(!event.is_delete());
assert_eq!(event.record(), Some(&row));
assert!(event.matches_collection("app.bsky.feed.post"));
assert!(!event.matches_collection("app.bsky.graph.follow"));
assert!(event.matches_did("did:plc:test"));
assert!(!event.matches_did("did:plc:other"));
}
#[tokio::test]
async fn test_multi_subscriber_fanout() {
let bus = BroadcastBus::new(16).unwrap();
let mut rx1 = bus.subscribe();
let mut rx2 = bus.subscribe();
let mut rx3 = bus.subscribe();
assert_eq!(bus.receiver_count(), 3);
let delivered = bus.publish_delete(
"at://did:plc:test/app.bsky.feed.post/del1",
"did:plc:test",
"app.bsky.feed.post",
"del1",
);
assert_eq!(delivered, 3);
for rx in [&mut rx1, &mut rx2, &mut rx3] {
let event = rx.recv().await.unwrap();
assert_eq!(
event,
ChangeNotification::Delete {
uri: "at://did:plc:test/app.bsky.feed.post/del1".to_string(),
did: "did:plc:test".to_string(),
collection: "app.bsky.feed.post".to_string(),
rkey: "del1".to_string(),
}
);
assert!(event.is_delete());
assert!(!event.is_upsert());
assert_eq!(event.record(), None);
}
}
#[tokio::test]
async fn test_lagged_receiver_non_blocking() {
let bus = BroadcastBus::new(4).unwrap();
let mut slow_rx = bus.subscribe();
for i in 0..8 {
let row = sample_record_row(&format!("key_{i}"));
bus.publish_upsert(row);
}
match slow_rx.recv().await {
Err(broadcast::error::RecvError::Lagged(skipped)) => {
assert_eq!(skipped, 4, "Must indicate 4 messages were skipped");
}
other => panic!("Expected RecvError::Lagged, got {other:?}"),
}
let next_event = slow_rx.recv().await.unwrap();
assert_eq!(next_event.rkey(), "key_4");
}
#[tokio::test]
async fn test_closed_on_drop() {
let bus = BroadcastBus::new(8).unwrap();
let mut rx = bus.subscribe();
drop(bus);
let result = rx.recv().await;
assert_eq!(result, Err(broadcast::error::RecvError::Closed));
}
#[test]
fn test_change_notification_serde_roundtrip() {
let row = sample_record_row("test_serde");
let notif = ChangeNotification::Upsert(row);
let serialized = serde_json::to_string(¬if).unwrap();
let deserialized: ChangeNotification = serde_json::from_str(&serialized).unwrap();
assert_eq!(notif, deserialized);
}
}