1use super::event_loop::EventLoop;
5use super::{ClientErrorKind, ConnectionError, Scheduler, Timer};
6use crate::json::{Object, Value, number};
7use crate::protocol::{ErrorBody, FailureCause};
8use std::cell::{Cell, RefCell};
9use std::rc::{Rc, Weak};
10
11#[derive(Clone, Debug, PartialEq)]
13pub(crate) enum State {
14 Initializing,
15 Disconnected(ConnectionError),
16 Connecting {
17 attempt: u32,
18 disconnect_at: f64,
19 reason: Option<ConnectionError>,
20 },
21 Connected,
22 NeedsAuth(ConnectionError),
23 Error(ConnectionError),
24 Closed(ConnectionError),
25}
26
27impl State {
28 pub(crate) fn status(&self) -> ConnectionStatus {
29 match self {
30 State::Initializing => ConnectionStatus::Initializing,
31 State::Disconnected(_) => ConnectionStatus::Disconnected,
32 State::Connecting { .. } => ConnectionStatus::Connecting,
33 State::Connected => ConnectionStatus::Connected,
34 State::NeedsAuth(_) => ConnectionStatus::NeedsAuth,
35 State::Error(_) => ConnectionStatus::Error,
36 State::Closed(_) => ConnectionStatus::Closed,
37 }
38 }
39
40 pub(crate) fn is_terminal(&self) -> bool {
42 matches!(self, State::NeedsAuth(_) | State::Error(_))
43 }
44}
45
46type Subscriber = Rc<dyn Fn(&State)>;
47type Waiter = (Box<dyn Fn() -> bool>, Box<dyn FnOnce(State)>);
48
49pub(crate) struct ConnectionManager {
50 me: Weak<ConnectionManager>,
51 state: RefCell<State>,
52 disconnect_timeout: f64,
53 timeout_check_interval: f64,
54 scheduler: Rc<dyn Scheduler>,
55 event_loop: Weak<EventLoop>,
56 subscribers: RefCell<Vec<(u64, Subscriber)>>,
57 next_subscriber_id: Cell<u64>,
58 state_waiters: RefCell<Vec<Waiter>>,
59 connect_requested: Cell<bool>,
60 connect_request_waiters: RefCell<Vec<Box<dyn FnOnce()>>>,
61 connecting_started_at: Cell<Option<f64>>,
62 timeout_timer: RefCell<Option<Box<dyn Timer>>>,
63 last_timeout_check_at: Cell<f64>,
64}
65
66impl ConnectionManager {
67 pub(crate) fn new(
68 disconnect_timeout: f64,
69 scheduler: Rc<dyn Scheduler>,
70 event_loop: Weak<EventLoop>,
71 ) -> Rc<Self> {
72 let now = scheduler.now();
73 Rc::new_cyclic(|me| ConnectionManager {
74 me: me.clone(),
75 state: RefCell::new(State::Initializing),
76 disconnect_timeout,
77 timeout_check_interval: 1000.0,
78 scheduler,
79 event_loop,
80 subscribers: RefCell::default(),
81 next_subscriber_id: Cell::new(0),
82 state_waiters: RefCell::default(),
83 connect_requested: Cell::new(false),
84 connect_request_waiters: RefCell::default(),
85 connecting_started_at: Cell::new(None),
86 timeout_timer: RefCell::new(None),
87 last_timeout_check_at: Cell::new(now),
88 })
89 }
90
91 pub(crate) fn state(&self) -> State {
92 self.state.borrow().clone()
93 }
94
95 pub(crate) fn status(&self) -> ConnectionStatus {
96 self.state.borrow().status()
97 }
98
99 pub(crate) fn is(&self, status: ConnectionStatus) -> bool {
100 self.status() == status
101 }
102
103 pub(crate) fn is_in_terminal_state(&self) -> bool {
104 self.state.borrow().is_terminal()
105 }
106
107 pub(crate) fn should_continue_run_loop(&self) -> bool {
108 !self.is(ConnectionStatus::Closed)
109 }
110
111 fn microtask(&self, task: impl FnOnce() + 'static) {
112 if let Some(l) = self.event_loop.upgrade() {
113 l.microtask(task);
114 }
115 }
116
117 pub(crate) fn subscribe(&self, listener: impl Fn(&State) + 'static) -> Box<dyn Fn()> {
119 let id = self.next_subscriber_id.get();
120 self.next_subscriber_id.set(id + 1);
121 self.subscribers.borrow_mut().push((id, Rc::new(listener)));
122 let me = self.me.clone();
123 Box::new(move || {
124 if let Some(me) = me.upgrade() {
125 me.subscribers.borrow_mut().retain(|(i, _)| *i != id);
126 }
127 })
128 }
129
130 pub(crate) fn on_next_state_change(
135 &self,
136 is_current: impl Fn() -> bool + 'static,
137 waiter: impl FnOnce(State) + 'static,
138 ) {
139 let mut w = self.state_waiters.borrow_mut();
140 w.retain(|(current, _)| current());
141 w.push((Box::new(is_current), Box::new(waiter)));
142 }
143
144 pub(crate) fn request_connect(&self) {
145 if self.connect_requested.replace(true) {
146 return;
147 }
148 let waiters = std::mem::take(&mut *self.connect_request_waiters.borrow_mut());
149 for w in waiters {
150 self.microtask(w);
151 }
152 }
153
154 pub(crate) fn on_connect_request(&self, waiter: impl FnOnce() + 'static) {
157 if self.connect_requested.get() {
158 self.microtask(waiter);
159 } else {
160 self.connect_request_waiters
161 .borrow_mut()
162 .push(Box::new(waiter));
163 }
164 }
165
166 pub(crate) fn resume_from_connect_request(&self) -> bool {
168 if !self.is_in_terminal_state() || !self.connect_requested.replace(false) {
169 return false;
170 }
171 self.connecting(None);
172 true
173 }
174
175 pub(crate) fn initialized(&self) {
177 if !matches!(*self.state.borrow(), State::Initializing) {
178 return;
179 }
180 let now = self.scheduler.now();
181 self.connecting_started_at.set(Some(now));
182 self.set(State::Connecting {
183 attempt: 0,
184 disconnect_at: now + self.disconnect_timeout,
185 reason: None,
186 });
187 self.maybe_start_timeout_interval();
188 self.publish();
189 }
190
191 pub(crate) fn connecting(&self, reason: Option<ConnectionError>) {
192 let state = self.state();
193 let mut hidden_disconnect = false;
194 match &state {
195 State::Closed(_) => return,
196 State::Disconnected(r) => {
197 if r.client_kind() != Some(ClientErrorKind::Hidden) {
198 return;
199 }
200 hidden_disconnect = true;
201 }
202 _ => {}
203 }
204 let now = self.scheduler.now();
205 if hidden_disconnect {
206 self.connecting_started_at.set(None);
207 }
208 if let State::Connecting {
209 attempt,
210 disconnect_at,
211 ..
212 } = state
213 {
214 self.set(State::Connecting {
215 attempt: attempt + 1,
216 disconnect_at,
217 reason,
218 });
219 self.maybe_start_timeout_interval();
220 self.publish();
221 return;
222 }
223 let started = self.connecting_started_at.get().unwrap_or(now);
224 self.connecting_started_at.set(Some(started));
225 self.set(State::Connecting {
226 attempt: 1,
227 disconnect_at: started + self.disconnect_timeout,
228 reason,
229 });
230 self.maybe_start_timeout_interval();
231 self.publish();
232 }
233
234 pub(crate) fn connected(&self) {
235 if matches!(*self.state.borrow(), State::Closed(_) | State::Connected) {
236 return;
237 }
238 self.connecting_started_at.set(None);
239 self.maybe_stop_timeout_interval();
240 self.set(State::Connected);
241 self.publish();
242 }
243
244 pub(crate) fn disconnected(&self, reason: ConnectionError) {
245 match *self.state.borrow() {
246 State::Closed(_) | State::Disconnected(_) => return,
247 State::Connected => self.connecting_started_at.set(None),
248 _ => {}
249 }
250 self.maybe_stop_timeout_interval();
251 self.set(State::Disconnected(reason));
252 self.publish();
253 }
254
255 pub(crate) fn needs_auth(&self, reason: ConnectionError) {
256 if matches!(*self.state.borrow(), State::Closed(_) | State::NeedsAuth(_)) {
257 return;
258 }
259 self.connecting_started_at.set(None);
260 self.maybe_stop_timeout_interval();
261 self.set(State::NeedsAuth(reason));
262 self.publish();
263 }
264
265 pub(crate) fn error(&self, reason: ConnectionError) {
266 if matches!(*self.state.borrow(), State::Closed(_) | State::Error(_)) {
267 return;
268 }
269 self.connecting_started_at.set(None);
270 self.maybe_stop_timeout_interval();
271 self.set(State::Error(reason));
272 self.publish();
273 }
274
275 pub(crate) fn closed(&self) {
276 if matches!(*self.state.borrow(), State::Closed(_)) {
277 return;
278 }
279 self.connecting_started_at.set(None);
280 self.maybe_stop_timeout_interval();
281 self.set(State::Closed(ConnectionError::client(
282 ClientErrorKind::ClientClosed,
283 "Zero was explicitly closed by calling zero.close()",
284 )));
285 self.publish();
286 self.subscribers.borrow_mut().clear();
287 self.resolve_state_waiters();
288 }
289
290 fn set(&self, state: State) {
291 *self.state.borrow_mut() = state;
292 }
293
294 fn publish(&self) {
295 let state = self.state();
296 let subscribers: Vec<Subscriber> = self
297 .subscribers
298 .borrow()
299 .iter()
300 .map(|(_, s)| s.clone())
301 .collect();
302 for s in subscribers {
303 s(&state);
304 }
305 self.resolve_state_waiters();
306 }
307
308 fn resolve_state_waiters(&self) {
309 let state = self.state();
310 let waiters = std::mem::take(&mut *self.state_waiters.borrow_mut());
311 for (_, w) in waiters {
312 let state = state.clone();
313 self.microtask(move || w(state));
314 }
315 }
316
317 fn credit_frozen_time(&self) {
320 let now = self.scheduler.now();
321 let elapsed = now - self.last_timeout_check_at.get();
322 self.last_timeout_check_at.set(now);
323 if elapsed <= 2.0 * self.timeout_check_interval {
324 return;
325 }
326 if let Some(started) = self.connecting_started_at.get() {
327 self.connecting_started_at.set(Some(started + elapsed));
328 }
329 let mut state = self.state.borrow_mut();
330 if let State::Connecting { disconnect_at, .. } = &mut *state {
331 *disconnect_at += elapsed;
332 }
333 }
334
335 fn check_timeout(&self) {
336 let State::Connecting { disconnect_at, .. } = self.state() else {
337 return;
338 };
339 if self.scheduler.now() >= disconnect_at {
340 self.disconnected(ConnectionError::client(
341 ClientErrorKind::Offline,
342 format!(
343 "Zero was unable to connect for {} seconds and was disconnected",
344 number::format((self.disconnect_timeout / 1000.0).floor())
345 ),
346 ));
347 }
348 }
349
350 fn maybe_start_timeout_interval(&self) {
351 if self.timeout_timer.borrow().is_some() {
352 return;
353 }
354 self.last_timeout_check_at.set(self.scheduler.now());
355 let me = self.me.clone();
356 let timer = self.scheduler.schedule_repeating(
357 self.timeout_check_interval,
358 Box::new(move || {
359 if let Some(me) = me.upgrade() {
360 me.credit_frozen_time();
361 me.check_timeout();
362 }
363 }),
364 );
365 *self.timeout_timer.borrow_mut() = Some(timer);
366 }
367
368 fn maybe_stop_timeout_interval(&self) {
369 if let Some(t) = self.timeout_timer.borrow_mut().take() {
370 t.cancel();
371 }
372 }
373}
374
375crate::ast::string_enum!(
376 ConnectionStatus {
378 Initializing = "initializing",
379 Disconnected = "disconnected",
380 Connecting = "connecting",
381 Connected = "connected",
382 NeedsAuth = "needs-auth",
383 Error = "error",
384 Closed = "closed",
385 }
386);
387
388#[derive(Clone, Debug, PartialEq)]
391pub enum ConnectionState {
392 Initializing,
394 Disconnected {
396 reason: String,
398 },
399 Connecting {
401 reason: Option<String>,
403 },
404 Connected,
406 NeedsAuth(NeedsAuthReason),
409 Error {
412 reason: String,
414 },
415 Closed {
417 reason: String,
419 },
420}
421
422impl ConnectionState {
423 pub fn status(&self) -> ConnectionStatus {
425 match self {
426 ConnectionState::Initializing => ConnectionStatus::Initializing,
427 ConnectionState::Disconnected { .. } => ConnectionStatus::Disconnected,
428 ConnectionState::Connecting { .. } => ConnectionStatus::Connecting,
429 ConnectionState::Connected => ConnectionStatus::Connected,
430 ConnectionState::NeedsAuth(_) => ConnectionStatus::NeedsAuth,
431 ConnectionState::Error { .. } => ConnectionStatus::Error,
432 ConnectionState::Closed { .. } => ConnectionStatus::Closed,
433 }
434 }
435
436 pub(crate) fn of(state: &State) -> ConnectionState {
437 match state {
438 State::Initializing => ConnectionState::Initializing,
439 State::Closed(r) => ConnectionState::Closed {
440 reason: r.message().to_owned(),
441 },
442 State::Connected => ConnectionState::Connected,
443 State::Connecting { reason, .. } => ConnectionState::Connecting {
444 reason: reason
445 .as_ref()
446 .map(|r| r.message().to_owned())
447 .filter(|m| !m.is_empty()),
448 },
449 State::Disconnected(r) => ConnectionState::Disconnected {
450 reason: r.message().to_owned(),
451 },
452 State::Error(r) => ConnectionState::Error {
453 reason: r.message().to_owned(),
454 },
455 State::NeedsAuth(r) => ConnectionState::NeedsAuth(NeedsAuthReason::of(r)),
456 }
457 }
458
459 pub fn to_json(&self) -> Value {
461 let mut o = Object::new();
462 o.insert("name", Value::from(self.status().as_str()));
463 match self {
464 ConnectionState::Initializing | ConnectionState::Connected => {}
465 ConnectionState::Connecting { reason } => {
466 if let Some(r) = reason {
467 o.insert("reason", Value::from(r.as_str()));
468 }
469 }
470 ConnectionState::Disconnected { reason }
471 | ConnectionState::Error { reason }
472 | ConnectionState::Closed { reason } => {
473 o.insert("reason", Value::from(reason.as_str()));
474 }
475 ConnectionState::NeedsAuth(r) => {
476 o.insert("reason", r.to_json());
477 }
478 }
479 Value::Object(o)
480 }
481}
482
483#[derive(Clone, Debug, PartialEq)]
485pub enum NeedsAuthReason {
486 Mutate {
488 status: f64,
490 body: Option<String>,
492 },
493 Query {
495 status: f64,
497 body: Option<String>,
499 },
500 ZeroCache {
502 reason: String,
504 },
505}
506
507impl NeedsAuthReason {
508 fn of(error: &ConnectionError) -> NeedsAuthReason {
509 if let ConnectionError::Server(body) = error {
510 let http = |cause: &FailureCause| match cause {
511 FailureCause::Http {
512 status,
513 body_preview,
514 } => Some((*status, body_preview.clone().filter(|b| !b.is_empty()))),
515 _ => None,
516 };
517 match &**body {
518 ErrorBody::PushFailed { cause, .. } => {
519 if let Some((status, body)) = http(cause) {
520 return NeedsAuthReason::Mutate { status, body };
521 }
522 }
523 ErrorBody::TransformFailed { cause, .. } => {
524 if let Some((status, body)) = http(cause) {
525 return NeedsAuthReason::Query { status, body };
526 }
527 }
528 _ => {}
529 }
530 }
531 NeedsAuthReason::ZeroCache {
532 reason: error.message().to_owned(),
533 }
534 }
535
536 pub fn to_json(&self) -> Value {
538 let mut o = Object::new();
539 match self {
540 NeedsAuthReason::Mutate { status, body } | NeedsAuthReason::Query { status, body } => {
541 let ty = if matches!(self, NeedsAuthReason::Mutate { .. }) {
542 "mutate"
543 } else {
544 "query"
545 };
546 o.insert("type", Value::from(ty));
547 o.insert("status", Value::from(*status));
548 if let Some(b) = body {
549 o.insert("body", Value::from(b.as_str()));
550 }
551 }
552 NeedsAuthReason::ZeroCache { reason } => {
553 o.insert("type", Value::from("zero-cache"));
554 o.insert("reason", Value::from(reason.as_str()));
555 }
556 }
557 Value::Object(o)
558 }
559}