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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
//! Component managing [`TransitableState`].
use std::{
cell::{Cell, RefCell},
rc::Rc,
time::Duration,
};
use futures::{
FutureExt as _, StreamExt as _, future, future::Either,
stream::LocalBoxStream,
};
use medea_reactive::{Processed, ProgressableCell};
use super::TransitableState;
use crate::{
peer::media::transitable_state::{
InStable, InTransition, media_exchange_state, mute_state,
},
platform,
utils::{ResettableDelayHandle, resettable_delay_for},
};
/// [`TransitableStateController`] for the [`mute_state`].
pub type MuteStateController =
TransitableStateController<mute_state::Stable, mute_state::Transition>;
/// [`TransitableStateController`] for the [`media_exchange_state`].
pub type MediaExchangeStateController = TransitableStateController<
media_exchange_state::Stable,
media_exchange_state::Transition,
>;
/// Component managing all kinds of [`TransitableState`].
#[derive(Debug)]
pub struct TransitableStateController<S, T> {
/// Actual [`TransitableState`].
state: ProgressableCell<TransitableState<S, T>>,
/// Timeout of the [`TransitableStateController::state`] transition.
timeout_handle: RefCell<Option<ResettableDelayHandle>>,
/// Indicator whether [`TransitableStateController::timeout_handle`]'s
/// timeout is stopped.
is_transition_timeout_stopped: Cell<bool>,
}
impl<S, T> TransitableStateController<S, T>
where
S: InStable<Transition = T> + Into<TransitableState<S, T>> + 'static,
T: InTransition<Stable = S> + Into<TransitableState<S, T>> + 'static,
{
/// Timeout for the current state to transit into the desired one.
const TRANSITION_TIMEOUT: Duration = {
#[cfg(not(feature = "mockable"))]
{
Duration::from_secs(10)
}
#[cfg(feature = "mockable")]
{
Duration::from_millis(500)
}
};
/// Returns new [`TransitableStateController`] with the provided
/// stable state.
#[must_use]
pub fn new(state: S) -> Rc<Self> {
let this = Rc::new(Self {
state: ProgressableCell::new(state.into()),
timeout_handle: RefCell::new(None),
is_transition_timeout_stopped: Cell::new(false),
});
Rc::clone(&this).spawn();
this
}
/// Spawns all the required [`Stream`] listeners for this
/// [`TransitableStateController`].
///
/// [`Stream`]: futures::Stream
fn spawn(self: Rc<Self>) {
// We don't care about initial state, be cause transceiver is inactive
// at that moment.
let mut state_changes = self.state.subscribe().skip(1);
let weak_self = Rc::downgrade(&self);
platform::spawn(async move {
while let Some(state) = state_changes.next().await {
let (state, _guard) = state.into_parts();
if let Some(this) = weak_self.upgrade() {
if let TransitableState::Transition(_) = state {
let weak_this = Rc::downgrade(&this);
platform::spawn(async move {
let mut states = this.state.subscribe().skip(1);
let (timeout, timeout_handle) =
resettable_delay_for(
Self::TRANSITION_TIMEOUT,
this.is_transition_timeout_stopped.get(),
);
drop(
this.timeout_handle
.borrow_mut()
.replace(timeout_handle),
);
match future::select(
states.next(),
Box::pin(timeout),
)
.await
{
Either::Left(_) => (),
Either::Right(_) => {
#[expect( // false positive
clippy::shadow_unrelated,
reason = "actually related"
)]
if let Some(this) = weak_this.upgrade() {
let stable = this
.state
.get()
.cancel_transition();
this.state.set(stable);
}
}
}
});
}
} else {
break;
}
}
});
}
/// Returns [`Stream`] into which the [`TransitableState::Stable`] updates
/// will be emitted.
///
/// [`Stream`]: futures::Stream
pub fn subscribe_stable(&self) -> LocalBoxStream<'static, S> {
self.state
.subscribe()
.filter_map(async |s| {
let (s, _guard) = s.into_parts();
if let TransitableState::Stable(stable) = s {
Some(stable)
} else {
None
}
})
.boxed_local()
}
/// Returns [`Stream`] into which the [`TransitableState::Transition`]
/// updates will be emitted.
///
/// [`Stream`]: futures::Stream
pub fn subscribe_transition(&self) -> LocalBoxStream<'static, T> {
self.state
.subscribe()
.filter_map(async |s| {
let (s, _guard) = s.into_parts();
if let TransitableState::Transition(transition) = s {
Some(transition)
} else {
None
}
})
.boxed_local()
}
/// Stops disable/enable timeout of this [`TransitableStateController`].
pub fn stop_transition_timeout(&self) {
self.is_transition_timeout_stopped.set(true);
if let Some(timer) = &*self.timeout_handle.borrow() {
timer.stop();
}
}
/// Resets disable/enable timeout of this [`TransitableStateController`].
pub fn reset_transition_timeout(&self) {
self.is_transition_timeout_stopped.set(false);
if let Some(timer) = &*self.timeout_handle.borrow() {
timer.reset();
}
}
/// Returns current [`TransitableStateController::state`].
#[must_use]
pub fn state(&self) -> TransitableState<S, T> {
self.state.get()
}
/// Starts transition of the [`TransitableStateController::state`] to the
/// provided one.
pub fn transition_to(&self, desired_state: S) {
let current_state = self.state.get();
self.state.set(current_state.transition_to(desired_state));
}
/// Returns [`Future`] which will be resolved when state of this
/// [`TransitableStateController`] will be [`TransitableState::Stable`] or
/// the [`TransitableStateController`] is dropped.
///
/// Succeeds if [`TransitableStateController`]'s state transits into the
/// `desired_state` or the [`TransitableStateController`] is dropped.
///
/// # Errors
///
/// With an approved stable [`MediaState`] if transition to the
/// `desired_state` cannot be made.
///
/// [`MediaState`]: super::MediaState
pub fn when_media_state_stable(
&self,
desired_state: S,
) -> future::LocalBoxFuture<'static, Result<(), S>> {
let mut states = self.state.subscribe();
async move {
while let Some(state) = states.next().await {
let (state, _guard) = state.into_parts();
match state {
TransitableState::Transition(_) => {}
TransitableState::Stable(s) => {
return if s == desired_state {
Ok(())
} else {
Err(s)
};
}
}
}
Ok(())
}
.boxed_local()
}
/// Returns [`Processed`] that will be resolved once all the underlying data
/// updates are processed by all subscribers.
pub fn when_processed(&self) -> Processed<'static> {
self.state.when_all_processed()
}
/// Returns [`Future`] which will be resolved once [`TransitableState`] is
/// transited to the [`TransitableState::Stable`].
pub fn when_stabilized(self: Rc<Self>) -> Processed<'static, ()> {
Processed::new(Box::new(move || {
let stable = self.subscribe_stable();
Box::pin(async move {
stable.fuse().select_next_some().map(drop).await;
})
}))
}
/// Updates [`TransitableStateController::state`].
pub(in super::super) fn update(&self, new_state: S) {
let current_state = self.state.get();
let state_update = match current_state {
TransitableState::Stable(_) => new_state.into(),
TransitableState::Transition(t) => {
if t.intended() == new_state {
new_state.into()
} else {
t.set_inner(new_state).into()
}
}
};
self.state.set(state_update);
}
}
impl MuteStateController {
/// Indicates whether [`TransitableStateController`]'s mute state is in
/// [`mute_state::Stable::Muted`].
#[must_use]
pub fn muted(&self) -> bool {
self.state.get() == mute_state::Stable::Muted.into()
}
/// Indicates whether [`TransitableStateController`]'s mute state is in
/// [`mute_state::Stable::Unmuted`].
#[must_use]
pub fn unmuted(&self) -> bool {
self.state.get() == mute_state::Stable::Unmuted.into()
}
}
impl MediaExchangeStateController {
/// Indicates whether [`TransitableStateController`]'s media exchange state
/// is in [`media_exchange_state::Stable::Disabled`].
#[must_use]
pub fn disabled(&self) -> bool {
self.state.get() == media_exchange_state::Stable::Disabled.into()
}
/// Indicates whether [`TransitableStateController`]'s media exchange state
/// is in [`media_exchange_state::Stable::Enabled`].
#[must_use]
pub fn enabled(&self) -> bool {
self.state.get() == media_exchange_state::Stable::Enabled.into()
}
}