-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathproxies.rs
More file actions
91 lines (78 loc) · 2.67 KB
/
proxies.rs
File metadata and controls
91 lines (78 loc) · 2.67 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
86
87
88
89
90
91
use crate::node::interface_proxy::function_caller::FunctionCaller;
use crate::node::interface_proxy::types::{MethodMap, MethodsType, ProxiesType};
use crate::node::util::helpers::ResultType;
use lazy_static::lazy_static;
use napi::Env;
use rand::RngCore;
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard};
type DaemonProxiesType = HashMap<usize, (MethodsType, FunctionCaller)>;
lazy_static! {
static ref PROXIES: Mutex<ProxiesType> = Mutex::new(HashMap::new());
static ref DAEMON_PROXIES: Mutex<DaemonProxiesType> = Mutex::new(HashMap::new());
}
pub(in crate::node::interface_proxy) fn get_proxies<'a>() -> MutexGuard<'a, ProxiesType> {
PROXIES.lock().unwrap()
}
pub(in crate::node::interface_proxy) fn get_daemon_proxies<'a>() -> MutexGuard<'a, DaemonProxiesType>
{
DAEMON_PROXIES.lock().unwrap()
}
pub(in crate::node::interface_proxy) fn generate_proxy_id(
proxies: &MutexGuard<ProxiesType>,
daemon_proxies: &MutexGuard<DaemonProxiesType>,
) -> usize {
let mut rng = rand::rng();
let mut id: usize = rng.next_u32() as usize;
while proxies.contains_key(&id) || daemon_proxies.contains_key(&id) {
id = rng.next_u32() as usize;
}
id
}
pub(in crate::node::interface_proxy) fn find_methods_by_id(
id: usize,
proxies: &MutexGuard<ProxiesType>,
daemon_proxies: &MutexGuard<DaemonProxiesType>,
) -> ResultType<MethodMap> {
if let Some(methods) = proxies.get(&id) {
Ok(methods.lock().unwrap().clone())
} else if let Some((methods, _)) = daemon_proxies.get(&id) {
Ok(methods.lock().unwrap().clone())
} else {
Err(format!("No proxy with the id {} exists", id).into())
}
}
pub(in crate::node::interface_proxy) fn remove_proxy(
id: usize,
keep_as_daemon: bool,
proxies: &mut MutexGuard<ProxiesType>,
daemon_proxies: &mut MutexGuard<DaemonProxiesType>,
function_caller: Option<FunctionCaller>,
) {
let removed = proxies.remove(&id);
if !keep_as_daemon {
return;
}
if let Some(caller) = function_caller {
if caller.is_alive() {
if let Some(methods) = removed {
daemon_proxies.insert(id, (methods, caller));
}
}
}
}
pub fn interface_proxy_exists() -> bool {
!PROXIES.lock().unwrap().is_empty() || !DAEMON_PROXIES.lock().unwrap().is_empty()
}
/// Clears the list of daemon proxies.
#[napi]
#[allow(unused)]
pub fn clear_daemon_proxies(env: Env) -> napi::Result<()> {
let mut proxies = DAEMON_PROXIES.lock().unwrap();
for (_, (methods, function_caller)) in proxies.iter_mut() {
function_caller.destroy(Some(env))?;
methods.lock().unwrap().clear();
}
proxies.clear();
Ok(())
}