Skip to main content

kaspa_notify/subscription/
mod.rs

1use crate::{error::Result, events::EventType, notification::Notification, scope::Scope, subscription::context::SubscriptionContext};
2use borsh::{BorshDeserialize, BorshSerialize};
3use serde::{Deserialize, Serialize};
4use std::fmt::Display;
5use std::ops::Deref;
6use std::{
7    any::Any,
8    fmt::Debug,
9    hash::{Hash, Hasher},
10    sync::Arc,
11};
12
13pub mod array;
14pub mod compounded;
15pub mod context;
16pub mod single;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
19#[borsh(use_discriminant = true)]
20pub enum Command {
21    Start = 0,
22    Stop = 1,
23}
24
25impl Display for Command {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        let label = match self {
28            Command::Start => "start",
29            Command::Stop => "stop",
30        };
31        write!(f, "{label}")
32    }
33}
34
35impl From<Command> for i32 {
36    fn from(item: Command) -> Self {
37        item as i32
38    }
39}
40
41impl From<i32> for Command {
42    // We make this conversion infallible by falling back to Start from any unexpected value.
43    fn from(item: i32) -> Self {
44        if item == 1 { Command::Stop } else { Command::Start }
45    }
46}
47
48/// Defines how an incoming UtxosChanged mutation must be propagated upwards
49#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
50pub enum UtxosChangedMutationPolicy {
51    /// Mutation granularity defined at address level
52    #[default]
53    AddressSet,
54
55    /// Mutation granularity reduced to all or nothing
56    Wildcard,
57}
58
59#[derive(Clone, Copy, Default, Debug)]
60pub struct MutationPolicies {
61    pub utxo_changed: UtxosChangedMutationPolicy,
62}
63
64impl MutationPolicies {
65    pub fn new(utxo_changed: UtxosChangedMutationPolicy) -> Self {
66        Self { utxo_changed }
67    }
68}
69
70/// A subscription mutation formed by a start/stop command and
71/// a notification scope.
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct Mutation {
74    pub command: Command,
75    pub scope: Scope,
76}
77
78impl Mutation {
79    pub fn new(command: Command, scope: Scope) -> Self {
80        Self { command, scope }
81    }
82
83    #[inline(always)]
84    pub fn active(&self) -> bool {
85        self.command == Command::Start
86    }
87
88    #[inline(always)]
89    pub fn event_type(&self) -> EventType {
90        (&self.scope).into()
91    }
92}
93
94pub trait Subscription {
95    fn event_type(&self) -> EventType;
96    fn active(&self) -> bool;
97    fn scope(&self, context: &SubscriptionContext) -> Scope;
98}
99
100pub trait Compounded: Subscription + AsAny + DynEq + CompoundedClone + Debug + Send + Sync {
101    fn compound(&mut self, mutation: Mutation, context: &SubscriptionContext) -> Option<Mutation>;
102}
103
104impl PartialEq for dyn Compounded {
105    fn eq(&self, other: &dyn Compounded) -> bool {
106        DynEq::dyn_eq(self, other.as_any())
107    }
108}
109impl Eq for dyn Compounded {}
110
111pub type CompoundedSubscription = Box<dyn Compounded>;
112
113/// The result of applying a [`Mutation`] to a [`DynSubscription`]
114pub struct MutationOutcome {
115    /// Optional new mutated subscription state
116    pub mutated: Option<DynSubscription>,
117
118    /// Mutations applied to the [`DynSubscription`]
119    pub mutations: Vec<Mutation>,
120}
121
122impl MutationOutcome {
123    pub fn new() -> Self {
124        Self { mutated: None, mutations: vec![] }
125    }
126
127    pub fn with_mutations(mutations: Vec<Mutation>) -> Self {
128        Self { mutated: None, mutations }
129    }
130
131    pub fn with_mutated(mutated: DynSubscription, mutations: Vec<Mutation>) -> Self {
132        Self { mutated: Some(mutated), mutations }
133    }
134
135    /// Updates `target` to the mutated state if any, otherwise leave `target` as is.
136    pub fn apply_to(self, target: &mut DynSubscription) -> Self {
137        if let Some(ref mutated) = self.mutated {
138            *target = mutated.clone();
139        }
140        self
141    }
142
143    #[inline(always)]
144    pub fn has_new_state(&self) -> bool {
145        self.mutated.is_some()
146    }
147
148    #[inline(always)]
149    pub fn has_changes(&self) -> bool {
150        self.has_new_state() || !self.mutations.is_empty()
151    }
152}
153
154impl Default for MutationOutcome {
155    fn default() -> Self {
156        Self::new()
157    }
158}
159
160/// A single subscription (as opposed to a compounded one)
161pub trait Single: Subscription + AsAny + DynHash + DynEq + Debug + Send + Sync {
162    /// Applies a [`Mutation`] to a single subscription.
163    ///
164    /// On success, returns both an optional new state and the mutations, if any, resulting of the process.
165    ///
166    /// Implementation guidelines:
167    ///
168    /// - If the processing of the mutation yields no change, the returned outcome must have no new state and no mutations
169    ///   otherwise the outcome should contain both a new state (see next point for exception) and some mutations.
170    /// - If the subscription has inner mutability and its current state and incoming mutation do allow an inner mutation,
171    ///   the outcome new state must be empty.
172    fn apply_mutation(
173        &self,
174        arc_self: &Arc<dyn Single>,
175        mutation: Mutation,
176        policies: MutationPolicies,
177        context: &SubscriptionContext,
178    ) -> Result<MutationOutcome>;
179}
180
181pub trait MutateSingle: Deref<Target = dyn Single> {
182    /// Applies a [`Mutation`] to a single subscription.
183    ///
184    /// On success, updates `self` to the new state if any and returns both the optional new state and the mutations
185    /// resulting of the process as a [`MutationOutcome`].
186    fn mutate(&mut self, mutation: Mutation, policies: MutationPolicies, context: &SubscriptionContext) -> Result<MutationOutcome>;
187}
188
189impl MutateSingle for Arc<dyn Single> {
190    fn mutate(&mut self, mutation: Mutation, policies: MutationPolicies, context: &SubscriptionContext) -> Result<MutationOutcome> {
191        let outcome = self.apply_mutation(self, mutation, policies, context)?.apply_to(self);
192        Ok(outcome)
193    }
194}
195
196pub trait BroadcastingSingle: Deref<Target = dyn Single> {
197    /// Returns the broadcasting instance of the subscription.
198    ///
199    /// This is used for grouping all the wildcard UtxosChanged subscriptions under
200    /// the same unique instance in the broadcaster plans, allowing message optimizations
201    /// during broadcasting of the notifications.
202    fn broadcasting(self, context: &SubscriptionContext) -> DynSubscription;
203}
204
205impl Hash for dyn Single {
206    fn hash<H: Hasher>(&self, state: &mut H) {
207        self.dyn_hash(state);
208    }
209}
210impl PartialEq for dyn Single {
211    fn eq(&self, other: &dyn Single) -> bool {
212        DynEq::dyn_eq(self, other.as_any())
213    }
214}
215impl Eq for dyn Single {}
216
217pub type DynSubscription = Arc<dyn Single>;
218
219pub trait AsAny {
220    fn as_any(&self) -> &dyn Any;
221}
222impl<T: Any> AsAny for T {
223    fn as_any(&self) -> &dyn Any {
224        self
225    }
226}
227
228pub trait DynHash {
229    fn dyn_hash(&self, state: &mut dyn Hasher);
230}
231impl<H: Hash + ?Sized> DynHash for H {
232    fn dyn_hash(&self, mut state: &mut dyn Hasher) {
233        self.hash(&mut state);
234    }
235}
236
237pub trait DynEq {
238    fn dyn_eq(&self, other: &dyn Any) -> bool;
239}
240impl<T: Eq + Any> DynEq for T {
241    fn dyn_eq(&self, other: &dyn Any) -> bool {
242        if let Some(other) = other.downcast_ref::<Self>() { self == other } else { false }
243    }
244}
245
246pub trait CompoundedClone {
247    fn clone_box(&self) -> Box<dyn Compounded>;
248}
249
250impl<T> CompoundedClone for T
251where
252    T: 'static + Compounded + Clone,
253{
254    fn clone_box(&self) -> Box<dyn Compounded> {
255        Box::new(self.clone())
256    }
257}
258
259pub trait ApplyTo {
260    fn apply_to<N: Notification>(&self, notification: &N) -> Option<N>;
261}