Skip to main content

useceleris_client/
segment.rs

1use std::fmt;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, Ordering};
4
5use crate::channel::ChannelShared;
6use crate::command_queue::InterestKind;
7use crate::errors::CelerisError;
8use crate::events::{ListenerLocation, MessageListener, PresenceListener, Registration};
9use crate::random::generate_message_id;
10use crate::values::{MessageMetadata, PresenceEvent, PresencePage};
11
12/// A handle for one segment of a channel. It holds only its id:
13/// subscriptions, listeners and the connection belong to the channel, so any
14/// number of handles for one segment share them. Obtain one with
15/// [`Channel::segment`](crate::Channel::segment) or
16/// [`Channel::default_segment`](crate::Channel::default_segment).
17#[derive(Clone)]
18pub struct Segment {
19    channel: Arc<ChannelShared>,
20    segment_id: String,
21} // end struct Segment
22
23impl fmt::Debug for Segment {
24    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
25        formatter
26            .debug_struct("Segment")
27            .field("segment_id", &self.segment_id)
28            .finish()
29    } // end method fmt
30} // end impl Debug for Segment
31
32impl Segment {
33    pub(crate) fn new(channel: Arc<ChannelShared>, segment_id: &str) -> Segment {
34        Segment {
35            channel,
36            segment_id: segment_id.to_owned(),
37        }
38    } // end fn new
39
40    /// The segment's id.
41    pub fn id(&self) -> &str {
42        &self.segment_id
43    } // end method id
44
45    /// Registers interest in the segment's messages. The first interest in a
46    /// segment subscribes it, and it stays subscribed until every interest is
47    /// cancelled; subscriptions are restored after every reconnect. The
48    /// default segment is joined automatically and never subscribed or
49    /// unsubscribed.
50    ///
51    /// A subscription needs read access to the segment. No acknowledgement
52    /// exists: a denial arrives later, as a `PermissionDeniedError`, through
53    /// [`ChannelEventHandler::on_error`](crate::ChannelEventHandler::on_error).
54    /// It fails with [`CelerisError::NotConnected`] once the channel is closing
55    /// or closed.
56    pub fn subscribe(&self) -> Result<Subscription, CelerisError> {
57        self.channel
58            .subscribe(InterestKind::Message, &self.segment_id)
59    } // end method subscribe
60
61    /// Registers interest in the segment's presence joins and leaves. Watching
62    /// presence is not membership: it delivers no messages, and the watcher is
63    /// not itself announced or listed.
64    pub fn subscribe_presence(&self) -> Result<Subscription, CelerisError> {
65        self.channel
66            .subscribe(InterestKind::Presence, &self.segment_id)
67    } // end method subscribe_presence
68
69    /// Registers a listener for the segment's deliveries. Each message id is
70    /// delivered once within a bounded window (REV-01).
71    pub fn on_message(
72        &self,
73        listener: impl Fn(&[u8], &MessageMetadata) + Send + Sync + 'static,
74    ) -> Registration {
75        let listener: Arc<MessageListener> = Arc::new(listener);
76        let segment_id = self.segment_id.clone();
77
78        self.channel.register(
79            ListenerLocation::SegmentMessage(self.segment_id.clone()),
80            move |listeners| listeners.segment_messages.entry(segment_id).or_default(),
81            listener,
82        )
83    } // end method on_message
84
85    /// Registers a listener for joins and leaves. Events arrive only while a
86    /// presence subscription is held: the server sends them to presence
87    /// subscribers alone (PRES-01).
88    pub fn on_presence(
89        &self,
90        listener: impl Fn(&PresenceEvent) + Send + Sync + 'static,
91    ) -> Registration {
92        let listener: Arc<PresenceListener> = Arc::new(listener);
93        let segment_id = self.segment_id.clone();
94
95        self.channel.register(
96            ListenerLocation::Presence(self.segment_id.clone()),
97            move |listeners| listeners.presence.entry(segment_id).or_default(),
98            listener,
99        )
100    } // end method on_presence
101
102    /// Sends `payload` to the segment with a generated message id. It returns
103    /// once the socket accepted the bytes. That is not receipt, delivery or
104    /// durability: the protocol has no acknowledgements.
105    ///
106    /// A publish needs write access and does not join the segment. To receive
107    /// from the segment, your own publishes included, call
108    /// [`subscribe`](Segment::subscribe).
109    ///
110    /// While the channel reconnects, the publish waits in the queue and is sent
111    /// after the reconnect, once the restored subscriptions have gone out. It
112    /// then fails with the error that
113    /// [`on_error`](crate::ChannelEventHandler::on_error) reports if recovery
114    /// stops in [`Failed`](crate::ChannelState::Failed), and with
115    /// [`CelerisError::Cancelled`] if the channel closes.
116    ///
117    /// It fails with [`CelerisError::NotConnected`] before the first connect,
118    /// while connecting, and once failed or closed; with
119    /// [`CelerisError::Backpressure`] when the publish queue (64 by default) is
120    /// already full; and with [`CelerisError::DeliveryUnknown`] when the socket
121    /// failed during the write, which is never resent. The plan's cap counts
122    /// the whole encoded command, not only the payload. A publish over it
123    /// still succeeds here and is refused afterwards with a
124    /// `MessageSizeLimitError` through `on_error`.
125    ///
126    /// Dropping the returned future takes the publish back if the socket has
127    /// not started to write it.
128    pub async fn publish(&self, payload: impl AsRef<[u8]>) -> Result<(), CelerisError> {
129        let message_id = generate_message_id();
130
131        self.channel
132            .publish(&self.segment_id, payload.as_ref(), &message_id)
133            .await
134    } // end method publish
135
136    /// [`Segment::publish`] with your own message id. Receivers drop a repeated
137    /// id within their deduplication window, so reuse an id only to resend the
138    /// same message.
139    pub async fn publish_with_message_id(
140        &self,
141        payload: impl AsRef<[u8]>,
142        message_id: &str,
143    ) -> Result<(), CelerisError> {
144        self.channel
145            .publish(&self.segment_id, payload.as_ref(), message_id)
146            .await
147    } // end method publish_with_message_id
148
149    /// One page of the segment's presence. One query may be in flight per
150    /// channel; it fails with [`CelerisError::OperationInProgress`] while
151    /// another is pending, and with [`CelerisError::Timeout`] after the
152    /// presence query timeout. `page` starts at 1, and `per_page` is 1 to 100.
153    ///
154    /// Dropping the returned future frees the query slot.
155    pub async fn presence_list(
156        &self,
157        page: i32,
158        per_page: i32,
159    ) -> Result<PresencePage, CelerisError> {
160        self.channel
161            .query_presence(&self.segment_id, page, per_page)
162            .await
163    } // end method presence_list
164} // end impl Segment
165
166/// One registered interest. Cancel it when done; dropping it keeps the
167/// interest.
168pub struct Subscription {
169    channel: Arc<ChannelShared>,
170    kind: InterestKind,
171    segment_id: String,
172    cancelled: AtomicBool,
173} // end struct Subscription
174
175impl fmt::Debug for Subscription {
176    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
177        formatter
178            .debug_struct("Subscription")
179            .field("segment_id", &self.segment_id)
180            .field("presence", &(self.kind == InterestKind::Presence))
181            .finish()
182    } // end method fmt
183} // end impl Debug for Subscription
184
185impl Subscription {
186    pub(crate) fn new(
187        channel: Arc<ChannelShared>,
188        kind: InterestKind,
189        segment_id: &str,
190    ) -> Subscription {
191        Subscription {
192            channel,
193            kind,
194            segment_id: segment_id.to_owned(),
195            cancelled: AtomicBool::new(false),
196        }
197    } // end fn new
198
199    /// Releases the interest at once. Cancelling the last message interest
200    /// unsubscribes the segment, and cancelling the last presence interest
201    /// stops its presence events; neither affects the other. Calling `cancel`
202    /// again does nothing.
203    pub fn cancel(&self) {
204        if self.cancelled.swap(true, Ordering::SeqCst) {
205            return;
206        }
207
208        self.channel
209            .lock()
210            .release_interest(self.kind, &self.segment_id);
211    } // end method cancel
212} // end impl Subscription