use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use crate::proto::meta::KEY_SUBSCRIPTION_ID;
use crate::proto::{JsonRpcNotification, RequestKey};
#[derive(Debug, Clone)]
pub struct Subscription {
pub token: CancellationToken,
pub client_cancelled: Arc<AtomicBool>,
}
#[derive(Debug, Default)]
pub struct Registry {
entries: Mutex<HashMap<RequestKey, Subscription>>,
}
impl Registry {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn register(&self, key: RequestKey) -> Subscription {
let subscription = Subscription {
token: CancellationToken::new(),
client_cancelled: Arc::new(AtomicBool::new(false)),
};
self.lock().insert(key, subscription.clone());
subscription
}
pub fn remove(&self, key: &RequestKey) {
self.lock().remove(key);
}
pub fn cancel_by_client(&self, key: &RequestKey) -> bool {
match self.lock().remove(key) {
Some(subscription) => {
subscription.client_cancelled.store(true, Ordering::SeqCst);
subscription.token.cancel();
true
}
None => false,
}
}
pub fn cancel_all(&self) {
for (_, subscription) in self.lock().drain() {
subscription.token.cancel();
}
}
pub fn len(&self) -> usize {
self.lock().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<RequestKey, Subscription>> {
self.entries.lock().unwrap_or_else(|poisoned| {
tracing::warn!("Subscription registry lock was poisoned; recovering.");
poisoned.into_inner()
})
}
}
#[must_use]
pub fn honoured_filter(_requested: Option<&Value>) -> Value {
serde_json::json!({})
}
#[must_use]
pub fn acknowledgement(key: &RequestKey, requested: Option<&Value>) -> JsonRpcNotification {
JsonRpcNotification::new(
"notifications/subscriptions/acknowledged",
serde_json::json!({
"_meta": { KEY_SUBSCRIPTION_ID: key.to_value() },
"notifications": honoured_filter(requested),
}),
)
}
#[must_use]
pub fn teardown_notification(key: &RequestKey) -> JsonRpcNotification {
JsonRpcNotification::new(
"notifications/cancelled",
serde_json::json!({
"requestId": key.to_value(),
"reason": "Server shutting down",
}),
)
}
#[must_use]
pub fn graceful_closure_payload(key: &RequestKey) -> Value {
serde_json::json!({ "_meta": { KEY_SUBSCRIPTION_ID: key.to_value() } })
}
#[cfg(test)]
mod tests {
use super::*;
fn key(n: i64) -> RequestKey {
RequestKey::Num(n)
}
#[test]
fn acknowledgement_carries_the_subscription_id_and_an_empty_filter() {
let ack = acknowledgement(
&key(1),
Some(&serde_json::json!({ "toolsListChanged": true })),
);
assert_eq!(ack.method, "notifications/subscriptions/acknowledged");
let params = ack.params.unwrap();
assert_eq!(params["_meta"][KEY_SUBSCRIPTION_ID], 1);
assert_eq!(params["notifications"], serde_json::json!({}));
}
#[test]
fn client_cancellation_is_flagged_as_such() {
let registry = Registry::new();
let subscription = registry.register(key(1));
assert!(registry.cancel_by_client(&key(1)));
assert!(subscription.token.is_cancelled());
assert!(subscription.client_cancelled.load(Ordering::SeqCst));
assert!(registry.is_empty());
}
#[test]
fn server_teardown_is_not_flagged_as_client_cancellation() {
let registry = Registry::new();
let subscription = registry.register(key(1));
registry.cancel_all();
assert!(subscription.token.is_cancelled());
assert!(!subscription.client_cancelled.load(Ordering::SeqCst));
}
#[test]
fn cancelling_an_unknown_subscription_is_ignored() {
let registry = Registry::new();
assert!(!registry.cancel_by_client(&key(7)));
}
#[test]
fn teardown_messages_reference_the_subscription() {
let notification = teardown_notification(&key(3));
assert_eq!(notification.method, "notifications/cancelled");
assert_eq!(notification.params.unwrap()["requestId"], 3);
let payload = graceful_closure_payload(&key(3));
assert_eq!(payload["_meta"][KEY_SUBSCRIPTION_ID], 3);
}
}