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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! `Simulcrypt`: the registry of CAS channels and EMMG listeners.
use std::{
collections::HashMap,
sync::{
Arc,
Mutex,
atomic::{
AtomicU32,
Ordering,
},
},
};
use crate::{
cas::CasEntry,
config::{
CasConfig,
ServiceConfig,
},
emmg::EmmgListeners,
error::Error,
event::{
CasStatus,
EmmgPortStatus,
},
lock_ext::MutexExt,
service::Service,
};
/// Cheap copyable reference to a CAS channel; survives reconnects.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct CasRef(u32);
/// Process registry: CAS channels and open services. Cheap to clone (an `Arc` inside), can be
/// passed freely to several tasks.
#[derive(Clone)]
pub struct Simulcrypt {
inner: Arc<Inner>,
}
impl Default for Simulcrypt {
fn default() -> Self {
Self::new()
}
}
pub struct Inner {
next_cas_id: AtomicU32,
cas_by_config_id: Mutex<HashMap<String, CasRef>>,
cas: Mutex<HashMap<CasRef, Arc<CasEntry>>>,
emmg: EmmgListeners,
/// Serializes CW group changes and CAS updates and removals. Without a single point, two
/// concurrent `open_service` calls overlapping different `(CasRef, ecm_pid)` pairs of two
/// different existing groups, or `open_service` racing `Drop`, could disagree on which
/// group owns which pair.
pub topology: Mutex<()>,
}
impl Inner {
pub fn cas_entry(&self, cas_ref: CasRef) -> Result<Arc<CasEntry>, Error> {
self.cas
.lock_or_recover()
.get(&cas_ref)
.cloned()
.ok_or(Error::UnknownCas)
}
/// See [`Simulcrypt::remove_cas`]. The caller holds `topology`.
fn remove_cas(&self, cas: CasRef) -> Result<(), Error> {
let entry = self
.cas
.lock_or_recover()
.remove(&cas)
.ok_or(Error::UnknownCas)?;
self.cas_by_config_id
.lock_or_recover()
.retain(|_, cas_ref| *cas_ref != cas);
entry.detach(&self.emmg, cas);
Ok(())
}
}
impl Simulcrypt {
/// Tasks are spawned on the current tokio runtime.
#[must_use]
pub fn new() -> Self {
Self {
inner: Arc::new(Inner {
next_cas_id: AtomicU32::new(0),
cas_by_config_id: Mutex::new(HashMap::new()),
cas: Mutex::new(HashMap::new()),
emmg: EmmgListeners::default(),
topology: Mutex::new(()),
}),
}
}
/// Registers a CAS and connects to its ECMG. A repeated call with the same `id` applies the new
/// settings to that CAS and returns its `CasRef`: open services keep running, the ECMG
/// connection restarts if its settings changed, the EMMG channel moves if its port or
/// `channel_id` changed, and [`EmmgConfig::udp`](crate::EmmgConfig::udp) turned on binds UDP on
/// the port. Identical settings change nothing.
///
/// # Errors
///
/// If `cfg.emmg` is set, returns `Err` when the TCP listening socket (or the UDP one with
/// [`EmmgConfig::udp`](crate::EmmgConfig::udp)) cannot be bound, or `cfg.ecmg.channel_id` is
/// already taken by another CAS channel on the same EMMG port. A failed update leaves the
/// CAS unchanged.
pub fn add_cas(&self, cfg: CasConfig) -> Result<CasRef, Error> {
let _topology = self.inner.topology.lock_or_recover();
let existing = self
.inner
.cas_by_config_id
.lock_or_recover()
.get(&cfg.id)
.copied();
if let Some(cas_ref) = existing {
self.inner
.cas_entry(cas_ref)?
.update(&self.inner.emmg, cas_ref, cfg)?;
return Ok(cas_ref);
}
let emmg = match &cfg.emmg {
Some(emmg) => Some(self.inner.emmg.register(&cfg, emmg)?),
None => None,
};
let cas_ref = CasRef(self.inner.next_cas_id.fetch_add(1, Ordering::Relaxed));
let config_id = cfg.id.clone();
let entry = CasEntry::new(cfg, emmg);
self.inner
.cas
.lock_or_recover()
.insert(cas_ref, Arc::clone(&entry));
self.inner
.cas_by_config_id
.lock_or_recover()
.insert(config_id, cas_ref);
entry.ensure_running(cas_ref);
Ok(cas_ref)
}
/// Removes a CAS: closes its ECMG channel and its EMMG channel, and detaches its streams from
/// open services, which keep running on their other CAS. The EMMG listener closes with the
/// last CAS on its port.
///
/// # Errors
///
/// Returns `Err` if `cas` is not registered in this `Simulcrypt`.
pub fn remove_cas(&self, cas: CasRef) -> Result<(), Error> {
let _topology = self.inner.topology.lock_or_recover();
self.inner.remove_cas(cas)
}
/// Removes every CAS (see [`Self::remove_cas`]): all ECMG connections and EMMG listeners are
/// closed.
pub fn close(&self) {
let _topology = self.inner.topology.lock_or_recover();
let all: Vec<CasRef> = self.inner.cas.lock_or_recover().keys().copied().collect();
for cas in all {
let _ = self.inner.remove_cas(cas);
}
}
/// Opens a service: allocates `stream_id`s and brings up missing connections. If at least one
/// `(CasRef, ecm_pid)` pair already belongs to a live CW group, the new handle joins it (and
/// brings along any still unused pairs from its `cas`); if the requested pairs overlap TWO
/// different live groups at once, the conflict cannot be resolved.
///
/// # Errors
///
/// Returns `Err` if `cfg.cas` is empty, `cfg.crypto_period` does not fit into the 16-bit
/// protocol field, any `CasRef` in `cfg.cas` is not registered in this `Simulcrypt`, a
/// requested `(CasRef, ecm_pid)` pair overlaps two different live CW groups, the live group
/// found uses a different `crypto_period`, or a channel that has to be brought back up
/// after becoming empty failed to re-register its EMMG channel.
pub fn open_service(&self, cfg: &ServiceConfig) -> Result<Service, Error> {
Service::open(&self.inner, cfg)
}
/// State of every CAS channel and its streams: diagnostics and monitoring.
#[must_use]
pub fn status(&self) -> Vec<CasStatus> {
let entries: Vec<_> = self
.inner
.cas
.lock_or_recover()
.iter()
.map(|(cas, entry)| (*cas, Arc::clone(entry)))
.collect();
entries
.into_iter()
.map(|(cas, entry)| entry.status(cas))
.collect()
}
/// Internal state of a CAS, for in-crate tests.
#[cfg(test)]
pub fn entry(&self, cas: CasRef) -> Arc<CasEntry> {
self.inner.cas_entry(cas).expect("registered CAS")
}
/// State of every EMMG listener, one per port.
#[must_use]
pub fn emmg_status(&self) -> Vec<EmmgPortStatus> {
self.inner.emmg.status()
}
}