uqa_engine/notifications/
subscription.rs1use parking_lot::Mutex;
10use std::{
11 collections::HashSet,
12 error::Error,
13 fmt,
14 sync::{Arc, Weak},
15 task::Poll,
16 time::Duration,
17};
18use uqa_core::notifications::{NotificationEvent, NotificationFailureKind, NotificationIdentity};
19use uqa_sql::catalog::roles::session::SessionAuthorization;
20use uqa_storage::{PersistentStorageBackend, PersistentStorageProvider};
21
22use super::{inbox::SubscriptionInbox, registration, NotificationHubOwner};
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct NotificationSubscriptionOptions {
29 pub max_active_subscriptions: usize,
30 pub max_channels: usize,
31 pub max_queued_notifications: usize,
32 pub max_queued_bytes: usize,
33 pub max_registry_entries_per_poll: usize,
34}
35
36impl NotificationSubscriptionOptions {
37 pub(super) fn validate(self) -> Result<(), NotificationSubscriptionError> {
38 if self.max_active_subscriptions == 0
39 || self.max_channels == 0
40 || self.max_queued_notifications == 0
41 || self.max_queued_bytes == 0
42 || self.max_registry_entries_per_poll == 0
43 {
44 return Err(NotificationSubscriptionError::new(
45 NotificationFailureKind::InvalidRequest,
46 ));
47 }
48 Ok(())
49 }
50}
51
52pub struct NotificationSubscriptionPermit {
54 hub: Weak<NotificationHubOwner>,
55 admission: Arc<registration::SubscriptionAdmission>,
56 options: NotificationSubscriptionOptions,
57}
58
59impl fmt::Debug for NotificationSubscriptionPermit {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.debug_struct("NotificationSubscriptionPermit")
62 .finish_non_exhaustive()
63 }
64}
65
66fn validate_channels(
67 channels: &[&str],
68 options: NotificationSubscriptionOptions,
69 cancellation: &uqa_core::CancellationToken,
70) -> Result<(), NotificationSubscriptionError> {
71 options.validate()?;
72 registration::check(cancellation)?;
73 if channels.is_empty() || channels.len() > options.max_channels {
74 return Err(NotificationSubscriptionError::new(
75 NotificationFailureKind::InvalidRequest,
76 ));
77 }
78 let mut seen = HashSet::new();
79 seen.try_reserve(channels.len()).map_err(|error| {
80 NotificationSubscriptionError::with_source(NotificationFailureKind::Capacity, error)
81 })?;
82 for channel in channels {
83 registration::check(cancellation)?;
84 if channel.contains('\0')
85 || super::validate_channel(channel).is_err()
86 || !seen.insert(*channel)
87 {
88 return Err(NotificationSubscriptionError::new(
89 NotificationFailureKind::InvalidRequest,
90 ));
91 }
92 }
93 registration::check(cancellation)
94}
95
96#[derive(Clone)]
98pub struct NotificationSubscriptionError {
99 kind: NotificationFailureKind,
100 original: Option<Arc<dyn Error + Send + Sync>>,
101}
102
103impl NotificationSubscriptionError {
104 pub(super) fn new(kind: NotificationFailureKind) -> Self {
105 Self {
106 kind,
107 original: None,
108 }
109 }
110 pub(super) fn with_source(
111 kind: NotificationFailureKind,
112 error: impl Error + Send + Sync + 'static,
113 ) -> Self {
114 Self {
115 kind,
116 original: Some(Arc::new(error)),
117 }
118 }
119 pub fn kind(&self) -> NotificationFailureKind {
120 self.kind
121 }
122 pub fn code(&self) -> &'static str {
123 self.kind.code()
124 }
125 pub fn original_error(&self) -> Option<&(dyn Error + Send + Sync + 'static)> {
127 self.original.as_deref()
128 }
129}
130impl fmt::Debug for NotificationSubscriptionError {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 f.debug_struct("NotificationSubscriptionError")
133 .field("kind", &self.kind)
134 .finish_non_exhaustive()
135 }
136}
137impl fmt::Display for NotificationSubscriptionError {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.write_str(self.code())
140 }
141}
142impl Error for NotificationSubscriptionError {}
143
144#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum NotificationWait {
147 Event(NotificationEvent),
148 TimedOut,
149 Closed,
150}
151
152pub(super) struct ListenerResources {
153 pub(super) hub: Arc<NotificationHubOwner>,
154 pub(super) session_id: u64,
155 pub(super) locks: Arc<crate::row_locks::RowLockManager>,
156 pub(super) _provider: Option<Arc<dyn PersistentStorageProvider>>,
157 pub(super) _backend: Option<Arc<dyn PersistentStorageBackend>>,
158 pub(super) _admission: Arc<registration::SubscriptionAdmission>,
159}
160
161impl Drop for ListenerResources {
162 fn drop(&mut self) {
163 self.hub.retire_subscription(self.session_id);
164 self.locks.release_session(self.session_id);
165 }
166}
167
168pub struct NotificationSubscription {
170 pub(super) inbox: Arc<SubscriptionInbox>,
171 pub(super) resources: Mutex<Option<ListenerResources>>,
172 pub(super) authorization: SessionAuthorization,
173}
174
175impl NotificationSubscription {
176 pub fn identity(&self) -> &NotificationIdentity {
177 self.inbox.identity()
178 }
179 pub fn poll(&self) -> Result<Poll<Option<NotificationEvent>>, NotificationSubscriptionError> {
181 self.inbox.poll()
182 }
183 pub fn wait(
185 &self,
186 timeout: Duration,
187 ) -> Result<NotificationWait, NotificationSubscriptionError> {
188 self.inbox.wait(timeout)
189 }
190 pub async fn next_event(
192 &self,
193 ) -> Result<Option<NotificationEvent>, NotificationSubscriptionError> {
194 self.inbox.wait_async().await
195 }
196 pub fn is_closed(&self) -> bool {
197 self.inbox.is_closed()
198 }
199 pub fn role_identity(&self) -> uqa_core::catalog_role::RoleIdentity {
201 self.authorization.current().identity()
202 }
203 pub fn stop_delivery(&self) {
205 self.inbox.close();
206 }
207 pub fn close(&self) {
209 self.stop_delivery();
210 let mut resources = self.resources.lock();
211 drop(resources.take());
212 }
213}
214
215impl Drop for NotificationSubscription {
216 fn drop(&mut self) {
217 self.close();
218 }
219}
220
221impl crate::Engine {
222 pub fn subscribe_notifications(
226 &self,
227 channels: &[&str],
228 options: NotificationSubscriptionOptions,
229 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
230 self.subscribe_notifications_with_cancellation(
231 channels,
232 options,
233 &uqa_core::CancellationToken::new(),
234 )
235 }
236
237 pub fn subscribe_notifications_with_cancellation(
241 &self,
242 channels: &[&str],
243 options: NotificationSubscriptionOptions,
244 cancellation: &uqa_core::CancellationToken,
245 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
246 validate_channels(channels, options, cancellation)?;
247 let permit = self.reserve_notification_subscription(options, cancellation)?;
248 self.register_notification_subscription(channels, permit, cancellation)
249 }
250
251 pub fn reserve_notification_subscription(
253 &self,
254 options: NotificationSubscriptionOptions,
255 cancellation: &uqa_core::CancellationToken,
256 ) -> Result<NotificationSubscriptionPermit, NotificationSubscriptionError> {
257 options.validate()?;
258 let admission = self
259 .notification_hub
260 .admissions
261 .reserve(options.max_active_subscriptions, cancellation)?;
262 Ok(NotificationSubscriptionPermit {
263 hub: Arc::downgrade(&self.notification_hub),
264 admission,
265 options,
266 })
267 }
268
269 pub fn subscribe_notifications_with_permit(
271 &self,
272 channels: &[&str],
273 permit: NotificationSubscriptionPermit,
274 cancellation: &uqa_core::CancellationToken,
275 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
276 if !Weak::ptr_eq(&permit.hub, &Arc::downgrade(&self.notification_hub)) {
277 return Err(NotificationSubscriptionError::new(
278 NotificationFailureKind::InvalidRequest,
279 ));
280 }
281 validate_channels(channels, permit.options, cancellation)?;
282 self.register_notification_subscription(channels, permit, cancellation)
283 }
284
285 fn register_notification_subscription(
286 &self,
287 channels: &[&str],
288 permit: NotificationSubscriptionPermit,
289 cancellation: &uqa_core::CancellationToken,
290 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
291 let _statement = self
292 .runtime
293 .statement_gate
294 .lock_with_cancellation(cancellation)
295 .map_err(|error| registration::failure(error.into()))?;
296 self.prepare_notification_recovery_with_cancellation(Some(cancellation))
297 .map_err(registration::failure)?;
298 let authorization = registration::read(&self.session.state, cancellation)
299 .map_err(registration::failure)?
300 .authorization
301 .clone();
302 let mut bytes = [0u8; 16];
303 getrandom::fill(&mut bytes).map_err(|error| {
304 NotificationSubscriptionError::with_source(
305 NotificationFailureKind::SourceUnavailable,
306 std::io::Error::other(error.to_string()),
307 )
308 })?;
309 bytes[6] = (bytes[6] & 0x0f) | 0x40;
310 bytes[8] = (bytes[8] & 0x3f) | 0x80;
311 let identity = NotificationIdentity {
312 epoch: uqa_core::notifications::NotificationEpoch::from_bytes(bytes)
313 .expect("version and variant set above"),
314 request_id: None,
315 };
316 let session_id = self.row_locks.allocate_session();
317 let inbox = SubscriptionInbox::new(identity, permit.options);
318 self.notification_hub.register_subscription(
319 session_id,
320 self.backend_process_id(),
321 channels
322 .iter()
323 .map(|channel| (*channel).to_owned())
324 .collect(),
325 &inbox,
326 cancellation,
327 )?;
328 Ok(NotificationSubscription {
329 inbox,
330 resources: Mutex::new(Some(ListenerResources {
331 hub: self.notification_hub.clone(),
332 session_id,
333 locks: self.row_locks.clone(),
334 _provider: self.storage.provider.clone(),
335 _backend: self.storage.backend.clone(),
336 _admission: permit.admission,
337 })),
338 authorization,
339 })
340 }
341}