cdk_common/pub_sub/mod.rs
1//! Publish–subscribe pattern.
2//!
3//! This is a generic implementation for
4//! [NUT-17](<https://github.com/cashubtc/nuts/blob/main/17.md>) with a type
5//! agnostic Publish-subscribe manager.
6//!
7//! The manager has a method for subscribers to subscribe to events with a
8//! generic type that must be converted to a vector of indexes.
9//!
10//! Events are also generic that should implement the `Indexable` trait.
11use std::fmt::Debug;
12use std::ops::Deref;
13use std::str::FromStr;
14
15use serde::{Deserialize, Serialize};
16
17pub mod index;
18
19/// Default size of the remove channel
20pub const DEFAULT_REMOVE_SIZE: usize = 10_000;
21
22/// Default channel size for subscription buffering
23pub const DEFAULT_CHANNEL_SIZE: usize = 10;
24
25#[async_trait::async_trait]
26/// On New Subscription trait
27///
28/// This trait is optional and it is used to notify the application when a new
29/// subscription is created. This is useful when the application needs to send
30/// the initial state to the subscriber upon subscription
31pub trait OnNewSubscription {
32 /// Index type
33 type Index;
34 /// Subscription event type
35 type Event;
36
37 /// Called when a new subscription is created
38 async fn on_new_subscription(
39 &self,
40 request: &[&Self::Index],
41 ) -> Result<Vec<Self::Event>, String>;
42}
43
44/// Subscription Id wrapper
45///
46/// This is the place to add some sane default (like a max length) to the
47/// subscription ID
48#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
49pub struct SubId(String);
50
51impl From<&str> for SubId {
52 fn from(s: &str) -> Self {
53 Self(s.to_string())
54 }
55}
56
57impl From<String> for SubId {
58 fn from(s: String) -> Self {
59 Self(s)
60 }
61}
62
63impl FromStr for SubId {
64 type Err = ();
65
66 fn from_str(s: &str) -> Result<Self, Self::Err> {
67 Ok(Self(s.to_string()))
68 }
69}
70
71impl Deref for SubId {
72 type Target = String;
73
74 fn deref(&self) -> &Self::Target {
75 &self.0
76 }
77}