Skip to main content

useceleris_client/
channel.rs

1use std::collections::{HashSet, VecDeque};
2use std::fmt;
3use std::sync::{Arc, Mutex, MutexGuard, Weak};
4use std::time::{Duration, SystemTime};
5
6use tokio::runtime::Handle;
7use tokio::sync::{Notify, oneshot, watch};
8use tokio::task::JoinHandle;
9use tokio::time::{Instant, sleep, sleep_until, timeout};
10use tokio_tungstenite::tungstenite::Bytes;
11
12use crate::client::ClientConfiguration;
13use crate::command_queue::{CommandQueue, InterestKind, QueuedPublish};
14use crate::connection::{ConnectionState, WebSocket, closed_before_sent};
15use crate::connection_url::credential_url;
16use crate::constants::{CLOSE_BUDGET, DEFAULT_SEGMENT_ID, RETRY_BUDGET_RESET};
17use crate::credentials::{CredentialReason, CredentialRequest, validate_credentials};
18use crate::encode::{SegmentCommand, encode_presence_list, encode_publish};
19use crate::errors::{CelerisError, configuration_error, failure};
20use crate::events::{ChannelEventHandler, EventQueue, Listeners};
21use crate::identifiers::identifier_rule;
22use crate::ordered_map::OrderedMap;
23use crate::reconnect::{replay_lookback, retry_delay};
24use crate::segment::{Segment, Subscription};
25use crate::values::{ChannelState, PresencePage, RecoveryEvent};
26
27/// One WebSocket connection. Every segment of the channel is multiplexed over
28/// it; another `Channel`, even for the same reference, is another connection
29/// (SEG-01). Obtain one with [`Client::channel`](crate::Client::channel).
30///
31/// A `Channel` is cheap to clone, and every clone is the same channel. Close
32/// it when done: dropping every handle also stops its connection, without the
33/// closing handshake.
34#[derive(Clone)]
35pub struct Channel {
36    pub(crate) shared: Arc<ChannelShared>,
37} // end struct Channel
38
39impl fmt::Debug for Channel {
40    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41        formatter
42            .debug_struct("Channel")
43            .field("reference", &self.shared.reference)
44            .field("state", &self.state())
45            .finish()
46    } // end method fmt
47} // end impl Debug for Channel
48
49impl Channel {
50    pub(crate) fn new(client: Arc<ClientConfiguration>, reference: &str) -> Channel {
51        let shared = Arc::new_cyclic(|this| ChannelShared {
52            client: Arc::clone(&client),
53            reference: reference.to_owned(),
54            inner: Mutex::new(ChannelInner::new(this.clone(), Arc::clone(&client))),
55            idle: Notify::new(),
56            closed: watch::Sender::new(false),
57        });
58
59        Channel { shared }
60    } // end fn new
61
62    /// The channel reference that this channel connects to.
63    pub fn reference(&self) -> &str {
64        &self.shared.reference
65    } // end method reference
66
67    /// The current state. It may change as soon as it is read.
68    pub fn state(&self) -> ChannelState {
69        self.shared.lock().state
70    } // end method state
71
72    /// The handler for channel-wide listeners.
73    pub fn events(&self) -> ChannelEventHandler {
74        ChannelEventHandler {
75            channel: Arc::clone(&self.shared),
76        }
77    } // end method events
78
79    /// A handle for the segment with the given id. It does no network work,
80    /// and any number of handles for one segment share its subscriptions and
81    /// listeners. It fails with [`CelerisError::Configuration`] for an id that
82    /// is empty or contains CR or LF.
83    pub fn segment(&self, segment_id: &str) -> Result<Segment, CelerisError> {
84        if let Some(rule) = identifier_rule(segment_id) {
85            return Err(configuration_error("segment ID", &[failure("", rule)]));
86        }
87
88        Ok(Segment::new(Arc::clone(&self.shared), segment_id))
89    } // end method segment
90
91    /// A handle for the segment that every connection joins automatically
92    /// (SEG-01).
93    pub fn default_segment(&self) -> Segment {
94        Segment::new(Arc::clone(&self.shared), DEFAULT_SEGMENT_ID)
95    } // end method default_segment
96
97    /// Opens the connection. It returns once the WebSocket is established and
98    /// the held subscriptions are queued to be restored ahead of any publish,
99    /// or fails without a retry: only a connection that was up recovers
100    /// automatically.
101    ///
102    /// It fails with [`CelerisError::OperationInProgress`] while connecting,
103    /// connected or reconnecting, and with [`CelerisError::NotConnected`] once
104    /// the channel is closing or closed. A failed attempt leaves the channel
105    /// [`ChannelState::Failed`], from which `connect` may be called again.
106    /// Dropping the returned future abandons the attempt and leaves the channel
107    /// failed.
108    pub async fn connect(&self) -> Result<(), CelerisError> {
109        let channel = &self.shared;
110
111        let generation = {
112            let mut inner = channel.lock();
113            inner.runtime.get_or_insert_with(Handle::current);
114
115            match inner.state {
116                ChannelState::Connecting | ChannelState::Connected | ChannelState::Reconnecting => {
117                    return Err(CelerisError::OperationInProgress(format!(
118                        "Connect was already called; the channel is {}.",
119                        inner.state
120                    )));
121                }
122                ChannelState::Closing | ChannelState::Closed => return Err(closed_channel()),
123                ChannelState::Idle | ChannelState::Failed => {}
124            }
125
126            inner.generation += 1;
127            inner.retries_used = 0;
128            inner.outage = None;
129            inner.deduplication.clear();
130            inner.queue_state_change(ChannelState::Connecting);
131            inner.generation
132        };
133
134        channel.dispatch_events();
135
136        let abandoned = AbandonConnect {
137            channel: Some(Arc::clone(channel)),
138            generation,
139        };
140
141        let result = channel
142            .establish_connection(generation, CredentialReason::Initial, 0)
143            .await;
144
145        abandoned.disarm();
146
147        if result.is_err() {
148            channel.lock().fail_initial_connect(generation);
149        }
150
151        channel.dispatch_events();
152
153        result
154    } // end method connect
155
156    /// Closes the connection and every segment handle with it. It is terminal
157    /// and idempotent, and returns within about five seconds even when the
158    /// server does not answer. Publishes and presence queries that still wait
159    /// fail with [`CelerisError::Cancelled`].
160    pub async fn close(&self) {
161        let channel = &self.shared;
162
163        let closing = {
164            let mut inner = channel.lock();
165            inner.runtime.get_or_insert_with(Handle::current);
166            inner.begin_close()
167        };
168
169        let CloseStart::Started(closing) = closing else {
170            let mut closed = channel.closed.subscribe();
171            let _ = closed.wait_for(|closed| *closed).await;
172
173            return;
174        };
175
176        channel.dispatch_events();
177
178        if let Some(ClosingConnection { id, writer }) = closing {
179            // The writer flushes what it holds, then performs the closing
180            // handshake, within the budget.
181            if let Some(mut writer) = writer
182                && timeout(CLOSE_BUDGET, &mut writer).await.is_err()
183            {
184                writer.abort();
185            }
186
187            channel.lock().discard_connection(id, &closed_before_sent());
188        }
189
190        channel.lock().queue_state_change(ChannelState::Closed);
191        channel.closed.send_replace(true);
192        channel.dispatch_events();
193    } // end method close
194} // end impl Channel
195
196/// What a call to close found.
197enum CloseStart {
198    AlreadyStarted,
199
200    /// This call closes, and finishes the connection that it detached.
201    Started(Option<ClosingConnection>),
202} // end enum CloseStart
203
204/// A connection that flushes and closes, and its writer.
205struct ClosingConnection {
206    id: u64,
207    writer: Option<JoinHandle<()>>,
208} // end struct ClosingConnection
209
210/// Fails the initial attempt when the caller drops the future of `connect`.
211struct AbandonConnect {
212    channel: Option<Arc<ChannelShared>>,
213    generation: u64,
214} // end struct AbandonConnect
215
216impl AbandonConnect {
217    /// The attempt finished, so nothing is abandoned.
218    fn disarm(mut self) {
219        self.channel = None;
220    } // end method disarm
221} // end impl AbandonConnect
222
223impl Drop for AbandonConnect {
224    fn drop(&mut self) {
225        let Some(channel) = self.channel.take() else {
226            return;
227        };
228
229        let mut inner = channel.lock();
230
231        if inner.generation == self.generation {
232            // Dropping the sender cancels the attempt in flight.
233            inner.attempt_cancel = None;
234        }
235
236        inner.fail_initial_connect(self.generation);
237        drop(inner);
238        channel.dispatch_events();
239    } // end method drop
240} // end impl Drop for AbandonConnect
241
242fn closed_channel() -> CelerisError {
243    CelerisError::NotConnected(
244        "Channel is closed; create a new one with Client::channel.".to_owned(),
245    )
246} // end fn closed_channel
247
248fn cancelled_attempt() -> CelerisError {
249    CelerisError::Cancelled(
250        "Connection attempt cancelled: the channel was closed or a newer attempt started."
251            .to_owned(),
252    )
253} // end fn cancelled_attempt
254
255/// What every handle of one channel shares.
256pub(crate) struct ChannelShared {
257    pub(crate) client: Arc<ClientConfiguration>,
258    pub(crate) reference: String,
259    inner: Mutex<ChannelInner>,
260
261    /// Signalled whenever the event queue becomes quiet.
262    pub(crate) idle: Notify,
263
264    /// Becomes `true` when close finishes.
265    closed: watch::Sender<bool>,
266} // end struct ChannelShared
267
268impl ChannelShared {
269    /// The channel's one lock. It guards all of the channel's state and is
270    /// never held while user code runs or while the socket blocks. A listener
271    /// that panics never holds it, so the lock is used even if poisoned.
272    pub(crate) fn lock(&self) -> MutexGuard<'_, ChannelInner> {
273        self.inner
274            .lock()
275            .unwrap_or_else(|poisoned| poisoned.into_inner())
276    } // end method lock
277} // end impl ChannelShared
278
279/// A pending timer. Its token tells a firing timer whether it is still the
280/// current one, since a timer can fire just as it is stopped.
281pub(crate) struct Timer {
282    pub(crate) token: u64,
283    task: JoinHandle<()>,
284} // end struct Timer
285
286impl Timer {
287    pub(crate) fn stop(self) {
288        self.task.abort();
289    } // end method stop
290} // end impl Timer
291
292/// When the connection dropped: a monotonic instant measures the outage, and
293/// the wall clock goes to the credential provider.
294#[derive(Clone, Copy)]
295struct Outage {
296    started: Instant,
297    wall: SystemTime,
298} // end struct Outage
299
300pub(crate) struct PendingPresence {
301    request_id: String,
302    result: oneshot::Sender<Result<PresencePage, CelerisError>>,
303    timer: Timer,
304} // end struct PendingPresence
305
306/// The channel's state, guarded by its lock.
307pub(crate) struct ChannelInner {
308    pub(crate) this: Weak<ChannelShared>,
309    pub(crate) client: Arc<ClientConfiguration>,
310
311    /// The runtime that the first connect or close ran on. Tasks and listener
312    /// deliveries run on it.
313    pub(crate) runtime: Option<Handle>,
314
315    pub(crate) state: ChannelState,
316    pub(crate) generation: u64,
317
318    /// The current connection and any connection that still closes.
319    pub(crate) connections: Vec<ConnectionState>,
320    pub(crate) current_connection: Option<u64>,
321    pub(crate) last_connection_id: u64,
322
323    retries_used: u32,
324    retry_timer: Option<Timer>,
325    connected_at: Instant,
326    outage: Option<Outage>,
327
328    /// Cancels the attempt in flight when dropped.
329    attempt_cancel: Option<oneshot::Sender<()>>,
330
331    close_started: bool,
332
333    pub(crate) queue: CommandQueue,
334    deduplication: DeduplicationWindow,
335
336    message_interests: OrderedMap<usize>,
337    presence_interests: OrderedMap<usize>,
338
339    /// Issues presence query request ids. Kept per channel rather than per
340    /// socket, so an id is never reused across reconnects (QUERY-01).
341    presence_request_count: u64,
342    pending_presence: Option<PendingPresence>,
343
344    pub(crate) listeners: Listeners,
345    pub(crate) events: EventQueue,
346
347    last_timer_token: u64,
348} // end struct ChannelInner
349
350impl ChannelInner {
351    fn new(this: Weak<ChannelShared>, client: Arc<ClientConfiguration>) -> ChannelInner {
352        ChannelInner {
353            this,
354            client,
355            runtime: None,
356            state: ChannelState::Idle,
357            generation: 0,
358            connections: Vec::new(),
359            current_connection: None,
360            last_connection_id: 0,
361            retries_used: 0,
362            retry_timer: None,
363            connected_at: Instant::now(),
364            outage: None,
365            attempt_cancel: None,
366            close_started: false,
367            queue: CommandQueue::default(),
368            deduplication: DeduplicationWindow::default(),
369            message_interests: OrderedMap::default(),
370            presence_interests: OrderedMap::default(),
371            presence_request_count: 0,
372            pending_presence: None,
373            listeners: Listeners::default(),
374            events: EventQueue::default(),
375            last_timer_token: 0,
376        }
377    } // end fn new
378
379    /// The runtime of the first connect or close. Everything that needs it
380    /// runs only after one of them.
381    pub(crate) fn runtime(&self) -> Handle {
382        self.runtime
383            .clone()
384            .expect("the channel's runtime is known once it connects or closes")
385    } // end method runtime
386
387    /// Starts a timer that calls `fire` with its token, then delivers the
388    /// events that `fire` queued.
389    pub(crate) fn start_timer(
390        &mut self,
391        delay: Duration,
392        fire: fn(&Arc<ChannelShared>, u64),
393    ) -> Timer {
394        self.last_timer_token += 1;
395        let token = self.last_timer_token;
396        let channel = self.this.clone();
397
398        let task = self.runtime().spawn(async move {
399            sleep(delay).await;
400
401            if let Some(channel) = channel.upgrade() {
402                fire(&channel, token);
403                channel.dispatch_events();
404            }
405        });
406
407        Timer { token, task }
408    } // end method start_timer
409
410    /// Starts closing: everything that waits is cancelled, and the current
411    /// connection, if any, is asked to flush and close.
412    fn begin_close(&mut self) -> CloseStart {
413        if self.close_started {
414            return CloseStart::AlreadyStarted;
415        }
416
417        self.close_started = true;
418        self.reject_pending_presence(CelerisError::Cancelled(
419            "Channel closed while the presence query was pending.".to_owned(),
420        ));
421        self.generation += 1;
422        self.stop_retry_timer();
423
424        // Dropping the sender cancels the attempt in flight.
425        self.attempt_cancel = None;
426        self.reset_queue(&closed_before_sent());
427
428        let closing = self.current_connection.take().and_then(|id| {
429            let connection = self.connection_mut(id)?;
430            connection.begin_closing();
431
432            Some(ClosingConnection {
433                id,
434                writer: connection.writer.take(),
435            })
436        });
437
438        self.queue_state_change(ChannelState::Closing);
439
440        CloseStart::Started(closing)
441    } // end method begin_close
442
443    fn stop_retry_timer(&mut self) {
444        if let Some(timer) = self.retry_timer.take() {
445            timer.stop();
446        }
447    } // end method stop_retry_timer
448
449    /// Marks the initial attempt of `generation` as failed, unless a close or a
450    /// newer attempt overtook it.
451    fn fail_initial_connect(&mut self, generation: u64) {
452        if generation == self.generation {
453            self.generation += 1;
454            self.queue_state_change(ChannelState::Failed);
455        }
456    } // end method fail_initial_connect
457
458    /// Starts recovery when the channel's own socket closed or failed, and
459    /// reports if that queued events.
460    pub(crate) fn receive_socket_failure(&mut self, id: u64) -> bool {
461        if self.current_connection != Some(id) {
462            return false;
463        }
464
465        self.enter_reconnecting(Instant::now());
466
467        true
468    } // end method receive_socket_failure
469
470    /// Starts recovery when the heartbeat found the channel's own socket dead,
471    /// and reports if that queued events. The outage began when the server
472    /// was last heard from, so the replay lookback covers what was published
473    /// during the silence.
474    pub(crate) fn heartbeat_failure(&mut self, id: u64) -> bool {
475        if self.current_connection != Some(id) {
476            return false;
477        }
478
479        let last_heard = self
480            .connection(id)
481            .map_or_else(Instant::now, |connection| connection.heartbeat.last_heard);
482
483        self.enter_reconnecting(last_heard);
484
485        true
486    } // end method heartbeat_failure
487
488    /// Starts recovery from an outage that began at `outage_start`.
489    fn enter_reconnecting(&mut self, outage_start: Instant) {
490        self.reject_pending_presence(connection_lost_during_query());
491        self.drop_queue_connection();
492
493        let now = Instant::now();
494
495        if now.duration_since(self.connected_at) >= RETRY_BUDGET_RESET {
496            self.retries_used = 0;
497        }
498
499        // The wall clock moves back by the same span as the monotonic one.
500        let elapsed = now.duration_since(outage_start);
501
502        self.outage = Some(Outage {
503            started: outage_start,
504            wall: SystemTime::now() - elapsed,
505        });
506
507        if let Some(id) = self.current_connection {
508            let unwritten = self
509                .connection_mut(id)
510                .map(ConnectionState::take_unwritten)
511                .unwrap_or_default();
512
513            self.put_back(unwritten);
514            self.discard_connection(id, &closed_before_sent());
515        }
516
517        self.queue_state_change(ChannelState::Reconnecting);
518        self.schedule_retry();
519    } // end method enter_reconnecting
520
521    fn schedule_retry(&mut self) {
522        let delay = retry_delay(self.retries_used, (self.client.random)());
523        self.retry_timer = Some(self.start_timer(delay, ChannelShared::retry_elapsed));
524    } // end method schedule_retry
525
526    fn fail_terminal(&mut self, error: CelerisError) {
527        self.reject_pending_presence(connection_lost_during_query());
528        self.reset_queue(&error);
529        self.generation += 1;
530        self.stop_retry_timer();
531        self.queue_error(error);
532        self.queue_state_change(ChannelState::Failed);
533    } // end method fail_terminal
534
535    pub(crate) fn interests(&self, kind: InterestKind) -> &OrderedMap<usize> {
536        match kind {
537            InterestKind::Message => &self.message_interests,
538            InterestKind::Presence => &self.presence_interests,
539        }
540    } // end method interests
541
542    fn interests_mut(&mut self, kind: InterestKind) -> &mut OrderedMap<usize> {
543        match kind {
544            InterestKind::Message => &mut self.message_interests,
545            InterestKind::Presence => &mut self.presence_interests,
546        }
547    } // end method interests_mut
548
549    /// Counts one interest; the first registration queues a sync of the
550    /// segment's subscription.
551    pub(crate) fn add_interest(
552        &mut self,
553        kind: InterestKind,
554        segment_id: &str,
555    ) -> Result<(), CelerisError> {
556        if matches!(self.state, ChannelState::Closing | ChannelState::Closed) {
557            return Err(closed_channel());
558        }
559
560        let count = self.interests(kind).get(segment_id).copied().unwrap_or(0);
561        self.interests_mut(kind).set(segment_id, count + 1);
562
563        if count == 0 {
564            self.queue_interest_sync(kind, segment_id);
565        }
566
567        Ok(())
568    } // end method add_interest
569
570    /// Releases one interest; the last cancellation queues a sync of the
571    /// segment's subscription.
572    pub(crate) fn release_interest(&mut self, kind: InterestKind, segment_id: &str) {
573        let count = self.interests(kind).get(segment_id).copied().unwrap_or(0);
574
575        if count > 1 {
576            self.interests_mut(kind).set(segment_id, count - 1);
577
578            return;
579        }
580
581        self.interests_mut(kind).remove(segment_id);
582        self.queue_interest_sync(kind, segment_id);
583    } // end method release_interest
584
585    /// Does nothing without a socket: installing one syncs every held
586    /// interest, and it holds no subscription to drop.
587    fn queue_interest_sync(&mut self, kind: InterestKind, segment_id: &str) {
588        if self.current_connection.is_some() {
589            self.queue_interest(kind, segment_id);
590        }
591    } // end method queue_interest_sync
592
593    /// Names the command that brings the server in line with the segment's
594    /// interest as it stands now, or `None` when none is needed. Subscriptions
595    /// are synced as state, so a resend is always safe.
596    pub(crate) fn interest_command(
597        &self,
598        kind: InterestKind,
599        segment_id: &str,
600    ) -> Option<SegmentCommand> {
601        let held = self.interests(kind).get(segment_id).is_some();
602
603        match kind {
604            // Presence applies to every segment, the default one included: the
605            // server's connect-time join grants message membership only.
606            InterestKind::Presence if held => Some(SegmentCommand::PresenceSubscribe),
607            InterestKind::Presence => Some(SegmentCommand::PresenceUnsubscribe),
608
609            // The server joins the default segment on connect and never leaves
610            // it.
611            InterestKind::Message if segment_id == DEFAULT_SEGMENT_ID => None,
612
613            // Watching presence is not membership, so it never holds the
614            // segment.
615            InterestKind::Message if held => Some(SegmentCommand::Subscribe),
616            InterestKind::Message => Some(SegmentCommand::Unsubscribe),
617        }
618    } // end method interest_command
619
620    fn take_pending_presence(&mut self) -> Option<PendingPresence> {
621        let pending = self.pending_presence.take()?;
622        pending.timer.task.abort();
623
624        Some(pending)
625    } // end method take_pending_presence
626
627    pub(crate) fn reject_pending_presence(&mut self, error: CelerisError) {
628        if let Some(pending) = self.take_pending_presence() {
629            let _ = pending.result.send(Err(error));
630        }
631    } // end method reject_pending_presence
632
633    /// Settles the pending query whose request id is `request_id`. A reply for
634    /// any other id answers a query that already failed, so it is dropped.
635    pub(crate) fn settle_pending_presence(
636        &mut self,
637        request_id: &str,
638        result: Result<PresencePage, CelerisError>,
639    ) {
640        let pending_matches = self
641            .pending_presence
642            .as_ref()
643            .is_some_and(|pending| pending.request_id == request_id);
644
645        if pending_matches && let Some(pending) = self.take_pending_presence() {
646            let _ = pending.result.send(result);
647        }
648    } // end method settle_pending_presence
649
650    /// Records a delivered id. Returns `false` for an id already in the window.
651    pub(crate) fn record_delivery(&mut self, message_id: &str) -> bool {
652        self.deduplication
653            .record_if_new(message_id, self.client.deduplication_window_size)
654    } // end method record_delivery
655} // end impl ChannelInner
656
657fn connection_lost_during_query() -> CelerisError {
658    CelerisError::Transport(
659        "Connection lost during the presence query; query again once the channel reconnects."
660            .to_owned(),
661    )
662} // end fn connection_lost_during_query
663
664impl ChannelShared {
665    /// Runs one attempt: fresh credentials, the handshake, then installing the
666    /// socket. On success the channel is connected and, for a reconnect, the
667    /// recovery event is queued, all before any received message is routed.
668    async fn establish_connection(
669        self: &Arc<Self>,
670        generation: u64,
671        reason: CredentialReason,
672        retry_index: u32,
673    ) -> Result<(), CelerisError> {
674        let reconnect = matches!(reason, CredentialReason::Reconnect { .. });
675
676        let deadline_span = if reconnect {
677            self.client.reconnect_timeout
678        } else {
679            self.client.connect_timeout
680        };
681
682        let deadline = Instant::now() + deadline_span;
683        let (cancel, cancelled) = oneshot::channel();
684
685        {
686            let mut inner = self.lock();
687
688            if generation != inner.generation {
689                return Err(cancelled_attempt());
690            }
691
692            inner.attempt_cancel = Some(cancel);
693        }
694
695        let request = CredentialRequest {
696            channel_reference: self.reference.clone(),
697            reason,
698        };
699
700        let opened = tokio::select! {
701            biased;
702            _ = cancelled => Err(cancelled_attempt()),
703            () = sleep_until(deadline) => Err(CelerisError::Timeout(format!(
704                "Connection attempt timed out after {} ms.",
705                deadline_span.as_millis()
706            ))),
707            opened = self.open_socket(request) => opened,
708        };
709
710        let mut inner = self.lock();
711        inner.attempt_cancel = None;
712        let socket = opened?;
713
714        if generation != inner.generation {
715            return Err(cancelled_attempt());
716        }
717
718        inner.install_connection(socket);
719        inner.connected_at = Instant::now();
720        inner.outage = None;
721
722        // Restoration goes through the queue, so it waits for writer room and
723        // reaches the server before the publishes that waited for this socket.
724        inner.restore_interests();
725        inner.queue_state_change(ChannelState::Connected);
726
727        if reconnect {
728            let recovery = RecoveryEvent {
729                retry_index,
730                possible_gaps: true,
731                possible_duplicates: true,
732            };
733
734            inner.queue_event(
735                |listeners| Some(&listeners.recoveries),
736                move |listener| listener(&recovery),
737                true,
738            );
739        }
740
741        Ok(())
742    } // end method establish_connection
743
744    /// Acquires credentials and performs the handshake. Every failure maps to
745    /// fixed text: a provider's error and the dialer's error, which quotes the
746    /// credential URL, are never passed on.
747    async fn open_socket(&self, request: CredentialRequest) -> Result<WebSocket, CelerisError> {
748        // A task of its own contains a provider's panic; aborting it when this
749        // future is dropped cancels the provider.
750        let mut provider = AbortOnDrop(tokio::spawn(
751            self.client.credential_provider.provide(request),
752        ));
753
754        let credentials = match (&mut provider.0).await {
755            Ok(Ok(credentials)) => credentials,
756            Ok(Err(_)) | Err(_) => {
757                return Err(CelerisError::Transport(
758                    "Credential acquisition failed: the credential provider returned an error or panicked."
759                        .to_owned(),
760                ));
761            }
762        };
763
764        validate_credentials(&credentials)?;
765
766        let url = credential_url(&self.client.base_url, &self.reference, &credentials);
767
768        (self.client.dial)(url).await.map_err(|()| {
769            CelerisError::Transport(
770                "WebSocket handshake failed: the server refused the connection or could not be reached. Check the base URL, the credentials and the channel reference."
771                    .to_owned(),
772            )
773        })
774    } // end method open_socket
775
776    /// The retry delay is over: run the next reconnect attempt.
777    fn retry_elapsed(self: &Arc<Self>, token: u64) {
778        let generation = {
779            let mut inner = self.lock();
780
781            if !inner
782                .retry_timer
783                .as_ref()
784                .is_some_and(|timer| timer.token == token)
785            {
786                return;
787            }
788
789            inner.retry_timer = None;
790            inner.generation
791        };
792
793        tokio::spawn(Arc::clone(self).run_reconnect_attempt(generation));
794    } // end method retry_elapsed
795
796    async fn run_reconnect_attempt(self: Arc<Self>, generation: u64) {
797        let (retry_index, reason) = {
798            let inner = self.lock();
799
800            let Some(outage) = inner.outage.filter(|_| generation == inner.generation) else {
801                return;
802            };
803
804            let reason = CredentialReason::Reconnect {
805                disconnected_at: outage.wall,
806                replay_lookback: replay_lookback(outage.started.elapsed()),
807            };
808
809            (inner.retries_used, reason)
810        };
811
812        let result = self
813            .establish_connection(generation, reason, retry_index)
814            .await;
815
816        if let Err(error) = result {
817            let mut inner = self.lock();
818
819            if generation == inner.generation {
820                if matches!(error, CelerisError::Transport(_) | CelerisError::Timeout(_)) {
821                    inner.retries_used += 1;
822
823                    if inner.retries_used >= self.client.maximum_reconnect_attempts {
824                        inner.fail_terminal(error);
825                    } else {
826                        inner.schedule_retry();
827                    }
828                } else {
829                    inner.fail_terminal(error);
830                }
831            }
832        }
833
834        self.dispatch_events();
835    } // end method run_reconnect_attempt
836
837    pub(crate) fn subscribe(
838        self: &Arc<Self>,
839        kind: InterestKind,
840        segment_id: &str,
841    ) -> Result<Subscription, CelerisError> {
842        self.lock().add_interest(kind, segment_id)?;
843
844        Ok(Subscription::new(Arc::clone(self), kind, segment_id))
845    } // end method subscribe
846
847    pub(crate) async fn publish(
848        self: &Arc<Self>,
849        segment_id: &str,
850        payload: &[u8],
851        message_id: &str,
852    ) -> Result<(), CelerisError> {
853        // Encoding copies up to 2 MiB, so it happens without the lock. Its
854        // failure is still reported in the reference's order, after the
855        // connection check.
856        let encoded = encode_publish(segment_id, Some(message_id), payload);
857
858        let (publish, result) = {
859            let mut inner = self.lock();
860
861            // While reconnecting the publish waits in the queue for the next
862            // socket (QUEUE-01).
863            let connected =
864                inner.state == ChannelState::Connected && inner.current_connection.is_some();
865
866            if !connected && inner.state != ChannelState::Reconnecting {
867                return Err(CelerisError::NotConnected(format!(
868                    "Channel is not connected; it is {}.",
869                    inner.state
870                )));
871            }
872
873            inner.queue_publish(segment_id, message_id, encoded?)?
874        };
875
876        // Dropping this future takes the publish back; once it settled, that
877        // does nothing.
878        let _withdraw = WithdrawPublish {
879            channel: Arc::clone(self),
880            publish,
881        };
882
883        result.await.unwrap_or_else(|_| Err(closed_before_sent()))
884    } // end method publish
885
886    /// Settles a publish whose caller stopped waiting. A rate limit can requeue
887    /// a publish still in the writer, so it may have a copy queued and copies
888    /// in the writer at once: every copy not yet written is taken back. No
889    /// later rate limit resends it.
890    fn cancel_publish(&self, publish: &Arc<QueuedPublish>) {
891        let mut inner = self.lock();
892
893        if publish.is_settled() {
894            return;
895        }
896
897        let connection_id = publish.connection();
898        let withdrawn = inner.withdraw_publish(publish);
899
900        let (removed, writing) = connection_id
901            .and_then(|id| inner.connection_mut(id))
902            .map_or((false, false), |connection| {
903                connection.remove_publish(publish)
904            });
905
906        if writing {
907            publish.settle(Err(CelerisError::DeliveryUnknown(
908                "The publish was dropped while the socket was writing it, so it may or may not have been sent."
909                    .to_owned(),
910            )));
911        } else if withdrawn || removed {
912            publish.settle(Err(CelerisError::Cancelled(
913                "The publish was dropped before it was sent.".to_owned(),
914            )));
915        } else {
916            return;
917        }
918
919        inner.forget_publish(publish);
920
921        // The room taken back from the writer may let a waiting command through.
922        if removed && connection_id == inner.current_connection {
923            inner.drain();
924        }
925    } // end method cancel_publish
926
927    pub(crate) async fn query_presence(
928        self: &Arc<Self>,
929        segment_id: &str,
930        page: i32,
931        per_page: i32,
932    ) -> Result<PresencePage, CelerisError> {
933        let (request_id, result) = {
934            let mut inner = self.lock();
935
936            let connection_id = match inner.current_connection {
937                Some(id) if inner.state == ChannelState::Connected => id,
938                _ => {
939                    return Err(CelerisError::NotConnected(format!(
940                        "Channel is not connected; it is {}.",
941                        inner.state
942                    )));
943                }
944            };
945
946            if inner.pending_presence.is_some() {
947                return Err(CelerisError::OperationInProgress(
948                    "A presence query is already in flight; wait for it to settle before starting another."
949                        .to_owned(),
950                ));
951            }
952
953            inner.presence_request_count += 1;
954            let request_id = inner.presence_request_count.to_string();
955            let data: Bytes = encode_presence_list(segment_id, page, per_page, &request_id)?;
956
957            // A query that the writer refuses fails without taking the slot.
958            inner.send_now(connection_id, data)?;
959
960            // A timed-out or dropped query frees its slot and leaves the
961            // connection alone: a late reply carries the old request id and is
962            // dropped.
963            let (sender, receiver) = oneshot::channel();
964            let timer = inner.start_timer(
965                self.client.presence_query_timeout,
966                ChannelShared::presence_timed_out,
967            );
968
969            inner.pending_presence = Some(PendingPresence {
970                request_id: request_id.clone(),
971                result: sender,
972                timer,
973            });
974
975            (request_id, receiver)
976        };
977
978        // Dropping this future frees the slot; once the query settled, that
979        // does nothing.
980        let _abandon = AbandonPresenceQuery {
981            channel: Arc::clone(self),
982            request_id,
983        };
984
985        result
986            .await
987            .unwrap_or_else(|_| Err(connection_lost_during_query()))
988    } // end method query_presence
989
990    fn presence_timed_out(self: &Arc<Self>, token: u64) {
991        let mut inner = self.lock();
992
993        let current = inner
994            .pending_presence
995            .as_ref()
996            .is_some_and(|pending| pending.timer.token == token);
997
998        if current {
999            let error = CelerisError::Timeout(format!(
1000                "Presence query timed out after {} ms.",
1001                self.client.presence_query_timeout.as_millis()
1002            ));
1003
1004            inner.reject_pending_presence(error);
1005        }
1006    } // end method presence_timed_out
1007} // end impl ChannelShared
1008
1009/// Takes back a publish when the caller drops the future of `publish`.
1010struct WithdrawPublish {
1011    channel: Arc<ChannelShared>,
1012    publish: Arc<QueuedPublish>,
1013} // end struct WithdrawPublish
1014
1015impl Drop for WithdrawPublish {
1016    fn drop(&mut self) {
1017        self.channel.cancel_publish(&self.publish);
1018    } // end method drop
1019} // end impl Drop for WithdrawPublish
1020
1021/// Frees the query slot when the caller drops the future of a presence query.
1022struct AbandonPresenceQuery {
1023    channel: Arc<ChannelShared>,
1024    request_id: String,
1025} // end struct AbandonPresenceQuery
1026
1027impl Drop for AbandonPresenceQuery {
1028    fn drop(&mut self) {
1029        let mut inner = self.channel.lock();
1030        let cancelled = CelerisError::Cancelled("The presence query was dropped.".to_owned());
1031        inner.settle_pending_presence(&self.request_id, Err(cancelled));
1032    } // end method drop
1033} // end impl Drop for AbandonPresenceQuery
1034
1035/// Aborts a task when dropped.
1036struct AbortOnDrop<Output>(JoinHandle<Output>);
1037
1038impl<Output> Drop for AbortOnDrop<Output> {
1039    fn drop(&mut self) {
1040        self.0.abort();
1041    } // end method drop
1042} // end impl Drop for AbortOnDrop
1043
1044/// Remembers the most recently delivered message ids, a window of them. It
1045/// survives reconnects, which absorbs replay duplicates, and clears on connect
1046/// (REV-01).
1047#[derive(Default)]
1048struct DeduplicationWindow {
1049    identifiers: HashSet<String>,
1050    order: VecDeque<String>,
1051} // end struct DeduplicationWindow
1052
1053impl DeduplicationWindow {
1054    /// Returns `false` for an id already in the window. A new one is recorded,
1055    /// and the oldest leaves once the window holds `limit` ids.
1056    fn record_if_new(&mut self, identifier: &str, limit: usize) -> bool {
1057        if self.identifiers.contains(identifier) {
1058            return false;
1059        }
1060
1061        self.identifiers.insert(identifier.to_owned());
1062        self.order.push_back(identifier.to_owned());
1063
1064        if self.order.len() > limit
1065            && let Some(oldest) = self.order.pop_front()
1066        {
1067            self.identifiers.remove(&oldest);
1068        }
1069
1070        true
1071    } // end method record_if_new
1072
1073    fn clear(&mut self) {
1074        self.identifiers.clear();
1075        self.order.clear();
1076    } // end method clear
1077} // end impl DeduplicationWindow