1use crate::client::{
7 LogLevel, LogSink, Scheduler, SocketConnection, SocketEvents, SocketFactory, SocketMessage,
8 Timer, timer_delay,
9};
10use std::cell::{Cell, RefCell};
11use std::rc::{Rc, Weak};
12
13enum Action {
14 Once(Option<Box<dyn FnOnce()>>),
15 Repeat(Option<Box<dyn FnMut()>>),
16}
17
18struct ManualTimer {
19 sequence: u64,
20 due: Cell<f64>,
21 interval: Option<f64>,
22 action: RefCell<Action>,
23 cancelled: Cell<bool>,
24}
25
26struct TimerHandle(Rc<ManualTimer>);
27
28impl Timer for TimerHandle {
29 fn cancel(&self) {
30 self.0.cancelled.set(true);
31 }
32}
33
34pub struct ManualScheduler {
40 now: Cell<f64>,
41 monotonic_now: Cell<f64>,
42 timers: RefCell<Vec<Rc<ManualTimer>>>,
43 checkpoints: RefCell<Vec<Box<dyn FnOnce()>>>,
44 next_sequence: Cell<u64>,
45}
46
47impl ManualScheduler {
48 pub fn new(now: f64) -> Rc<Self> {
50 Rc::new(ManualScheduler {
51 now: Cell::new(now),
52 monotonic_now: Cell::new(0.0),
53 timers: RefCell::default(),
54 checkpoints: RefCell::default(),
55 next_sequence: Cell::new(0),
56 })
57 }
58
59 fn add(&self, due: f64, interval: Option<f64>, action: Action) -> Box<dyn Timer> {
60 let sequence = self.next_sequence.get() + 1;
61 self.next_sequence.set(sequence);
62 let timer = Rc::new(ManualTimer {
63 sequence,
64 due: Cell::new(due),
65 interval,
66 action: RefCell::new(action),
67 cancelled: Cell::new(false),
68 });
69 self.timers.borrow_mut().push(timer.clone());
70 Box::new(TimerHandle(timer))
71 }
72
73 pub fn run_checkpoints(&self) {
75 loop {
76 let next = {
77 let mut c = self.checkpoints.borrow_mut();
78 if c.is_empty() {
79 break;
80 }
81 c.remove(0)
82 };
83 next();
84 }
85 }
86
87 pub fn pending_timers(&self) -> usize {
89 self.timers
90 .borrow()
91 .iter()
92 .filter(|t| !t.cancelled.get())
93 .count()
94 }
95
96 fn next_due(&self, limit: f64) -> Option<Rc<ManualTimer>> {
97 self.run_checkpoints();
98 let mut timers = self.timers.borrow_mut();
99 timers.retain(|t| !t.cancelled.get());
100 let mut best: Option<&Rc<ManualTimer>> = None;
101 for t in timers.iter() {
102 if t.due.get() > limit {
103 continue;
104 }
105 if let Some(b) = best
106 && (b.due.get(), b.sequence) <= (t.due.get(), t.sequence)
107 {
108 continue;
109 }
110 best = Some(t);
111 }
112 best.cloned()
113 }
114
115 fn fire(&self, timer: &ManualTimer) {
116 let elapsed = timer.due.get() - self.monotonic_now.get();
117 if elapsed > 0.0 {
118 self.monotonic_now.set(timer.due.get());
119 self.now.set(self.now.get() + elapsed);
120 }
121 match timer.interval {
122 Some(interval) => timer.due.set(timer.due.get() + interval),
123 None => timer.cancelled.set(true),
124 }
125 let taken = match &mut *timer.action.borrow_mut() {
126 Action::Once(f) => f.take().map(|f| Action::Once(Some(f))),
127 Action::Repeat(f) => f.take().map(|f| Action::Repeat(Some(f))),
128 };
129 match taken {
130 Some(Action::Once(Some(f))) => f(),
131 Some(Action::Repeat(Some(mut f))) => {
132 f();
133 *timer.action.borrow_mut() = Action::Repeat(Some(f));
134 }
135 _ => {}
136 }
137 }
138
139 pub fn advance(&self, ms: f64) {
142 let target = self.monotonic_now.get() + ms;
143 while let Some(timer) = self.next_due(target) {
144 self.fire(&timer);
145 }
146 self.now
147 .set(self.now.get() + target - self.monotonic_now.get());
148 self.monotonic_now.set(target);
149 }
150
151 pub fn run_due_timers(&self) {
154 let mut count = 0;
155 while let Some(timer) = self.next_due(self.monotonic_now.get()) {
156 self.fire(&timer);
157 count += 1;
158 assert!(count < 100_000, "Timers keep scheduling timers");
159 }
160 }
161}
162
163impl Scheduler for ManualScheduler {
164 fn now(&self) -> f64 {
165 self.now.get()
166 }
167
168 fn monotonic_now(&self) -> f64 {
169 self.monotonic_now.get()
170 }
171
172 fn schedule(&self, ms: f64, action: Box<dyn FnOnce()>) -> Box<dyn Timer> {
173 self.add(
174 self.monotonic_now.get() + timer_delay(ms),
175 None,
176 Action::Once(Some(action)),
177 )
178 }
179
180 fn schedule_repeating(&self, ms: f64, action: Box<dyn FnMut()>) -> Box<dyn Timer> {
181 let interval = timer_delay(ms).max(1.0);
182 self.add(
183 self.monotonic_now.get() + interval,
184 Some(interval),
185 Action::Repeat(Some(action)),
186 )
187 }
188
189 fn checkpoint(&self, action: Box<dyn FnOnce()>) {
192 self.checkpoints.borrow_mut().push(action);
193 }
194}
195
196#[derive(Default)]
200pub struct MockSocketFactory {
201 sockets: RefCell<Vec<Rc<MockSocket>>>,
202}
203
204impl MockSocketFactory {
205 pub fn new() -> Rc<Self> {
207 Rc::default()
208 }
209
210 pub fn sockets(&self) -> Vec<Rc<MockSocket>> {
212 self.sockets.borrow().clone()
213 }
214}
215
216impl SocketFactory for MockSocketFactory {
217 fn open(
218 &self,
219 url: &str,
220 sec_protocol: Option<&str>,
221 events: Rc<dyn SocketEvents>,
222 ) -> Box<dyn SocketConnection> {
223 let socket = Rc::new(MockSocket {
224 url: url.to_owned(),
225 sec_protocol: sec_protocol.map(str::to_owned),
226 messages: RefCell::default(),
227 closed: Cell::new(false),
228 close_code: Cell::new(None),
229 events: RefCell::new(Rc::downgrade(&events)),
230 });
231 self.sockets.borrow_mut().push(socket.clone());
232 Box::new(MockConnection(socket))
233 }
234}
235
236struct MockConnection(Rc<MockSocket>);
237
238impl SocketConnection for MockConnection {
239 fn send(&self, text: &str) {
240 self.0.messages.borrow_mut().push(text.to_owned());
241 }
242
243 fn close(&self, code: Option<u16>) {
244 self.0.closed.set(true);
245 self.0.close_code.set(code);
246 }
247}
248
249pub struct MockSocket {
252 pub url: String,
254 pub sec_protocol: Option<String>,
256 messages: RefCell<Vec<String>>,
257 closed: Cell<bool>,
258 close_code: Cell<Option<u16>>,
259 events: RefCell<Weak<dyn SocketEvents>>,
260}
261
262impl MockSocket {
263 pub fn messages(&self) -> Vec<String> {
265 self.messages.borrow().clone()
266 }
267
268 pub fn closed(&self) -> bool {
270 self.closed.get()
271 }
272
273 pub fn close_code(&self) -> Option<u16> {
275 self.close_code.get()
276 }
277
278 fn events(&self) -> Option<Rc<dyn SocketEvents>> {
279 self.events.borrow().upgrade()
280 }
281
282 pub fn receive(&self, message: SocketMessage) {
284 if let Some(e) = self.events() {
285 e.did_receive(message);
286 }
287 }
288
289 pub fn receive_text(&self, text: &str) {
291 self.receive(SocketMessage::Text(text.to_owned()));
292 }
293
294 pub fn server_close(&self, code: u16, reason: &str, was_clean: bool) {
296 if let Some(e) = self.events() {
297 e.did_close(code, reason, was_clean);
298 }
299 }
300
301 pub fn open(&self) {
303 if let Some(e) = self.events() {
304 e.did_open();
305 }
306 }
307}
308
309#[derive(Default)]
311pub struct RecordingLogSink {
312 entries: RefCell<Vec<(LogLevel, String)>>,
313}
314
315impl RecordingLogSink {
316 pub fn entries(&self) -> Vec<(LogLevel, String)> {
318 self.entries.borrow().clone()
319 }
320}
321
322impl LogSink for RecordingLogSink {
323 fn log(&self, level: LogLevel, message: &str, _context: &[(String, String)]) {
324 self.entries.borrow_mut().push((level, message.to_owned()));
325 }
326}