forked from StellarRouter/StellarRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate.rs
More file actions
85 lines (75 loc) · 2.56 KB
/
Copy pathstate.rs
File metadata and controls
85 lines (75 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use dashmap::DashMap;
use std::sync::Arc;
use tokio::sync::broadcast;
use crate::{
auth::AuthConfig,
rpc::{FeeConfig, SorobanRpcClient},
types::TransactionStatusEvent,
};
/// Capacity of the broadcast channel used for WebSocket status events.
pub const BROADCAST_CHANNEL_CAPACITY: usize = 1000;
#[derive(Clone)]
pub struct AppState {
pub rpc: SorobanRpcClient,
#[allow(dead_code)]
pub execution_contract_id: String,
pub router_core_contract_id: String,
#[allow(dead_code)]
pub auth_config: AuthConfig,
pub tx_status_tx: broadcast::Sender<TransactionStatusEvent>,
pub tx_subscribers: Arc<DashMap<String, usize>>,
}
impl AppState {
pub fn new(
rpc_url: String,
execution_contract_id: String,
router_core_contract_id: String,
auth_config: AuthConfig,
fee_config: FeeConfig,
) -> Self {
let (tx_status_tx, _) = broadcast::channel(BROADCAST_CHANNEL_CAPACITY);
Self {
rpc: SorobanRpcClient::new(rpc_url, Some(router_core_contract_id.clone()), fee_config),
execution_contract_id,
router_core_contract_id,
auth_config,
tx_status_tx,
tx_subscribers: Arc::new(DashMap::new()),
}
}
/// Send a [`TransactionStatusEvent`] to all active WebSocket subscribers.
///
/// The return value is ignored: a send error simply means no receivers are
/// currently listening, which is not a fatal condition.
pub fn broadcast_status(&self, event: TransactionStatusEvent) {
let _ = self.tx_status_tx.send(event);
}
/// Returns the fixed capacity of the broadcast channel.
pub fn broadcast_channel_capacity(&self) -> usize {
BROADCAST_CHANNEL_CAPACITY
}
/// Returns the total number of active subscriptions across all tx IDs.
pub fn active_subscriptions(&self) -> usize {
self.tx_subscribers.iter().map(|e| *e.value()).sum()
}
/// Returns the number of distinct tx IDs currently being tracked.
pub fn unique_tx_ids(&self) -> usize {
self.tx_subscribers.len()
}
pub fn add_subscriber(&self, tx_id: String) {
self.tx_subscribers
.entry(tx_id)
.and_modify(|count| *count += 1)
.or_insert(1);
}
pub fn remove_subscriber(&self, tx_id: &str) {
if let Some(mut entry) = self.tx_subscribers.get_mut(tx_id) {
if *entry > 1 {
*entry -= 1;
} else {
drop(entry);
self.tx_subscribers.remove(tx_id);
}
}
}
}