hyperstack_sdk/
subscription.rs1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5pub struct Subscription {
6 pub view: String,
7 #[serde(skip_serializing_if = "Option::is_none")]
8 pub key: Option<String>,
9 #[serde(skip_serializing_if = "Option::is_none")]
10 pub partition: Option<String>,
11 #[serde(skip_serializing_if = "Option::is_none")]
12 pub filters: Option<HashMap<String, String>>,
13}
14
15impl Subscription {
16 pub fn new(view: impl Into<String>) -> Self {
17 Self {
18 view: view.into(),
19 key: None,
20 partition: None,
21 filters: None,
22 }
23 }
24
25 pub fn with_key(mut self, key: impl Into<String>) -> Self {
26 self.key = Some(key.into());
27 self
28 }
29
30 pub fn with_filters(mut self, filters: HashMap<String, String>) -> Self {
31 self.filters = Some(filters);
32 self
33 }
34
35 pub fn sub_key(&self) -> String {
36 let filters_str = self
37 .filters
38 .as_ref()
39 .map(|f| serde_json::to_string(f).unwrap_or_default())
40 .unwrap_or_default();
41 format!(
42 "{}:{}:{}:{}",
43 self.view,
44 self.key.as_deref().unwrap_or("*"),
45 self.partition.as_deref().unwrap_or(""),
46 filters_str
47 )
48 }
49}
50
51#[derive(Debug, Default)]
52pub struct SubscriptionRegistry {
53 subscriptions: HashMap<String, Subscription>,
54}
55
56impl SubscriptionRegistry {
57 pub fn new() -> Self {
58 Self::default()
59 }
60
61 pub fn add(&mut self, sub: Subscription) {
62 let key = sub.sub_key();
63 self.subscriptions.insert(key, sub);
64 }
65
66 pub fn remove(&mut self, sub: &Subscription) {
67 let key = sub.sub_key();
68 self.subscriptions.remove(&key);
69 }
70
71 pub fn contains(&self, sub: &Subscription) -> bool {
72 let key = sub.sub_key();
73 self.subscriptions.contains_key(&key)
74 }
75
76 pub fn all(&self) -> Vec<Subscription> {
77 self.subscriptions.values().cloned().collect()
78 }
79
80 #[allow(dead_code)]
81 pub fn clear(&mut self) {
82 self.subscriptions.clear();
83 }
84}