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
152#[derive(Debug)]
155pub enum NotificationReceive<T> {
156 Event {
157 event: NotificationEvent,
158 admitted: T,
159 },
160 TimedOut,
161 Closed,
162}
163
164pub(super) struct ListenerResources {
165 pub(super) hub: Arc<NotificationHubOwner>,
166 pub(super) session_id: u64,
167 pub(super) locks: Arc<crate::row_locks::RowLockManager>,
168 pub(super) _provider: Option<Arc<dyn PersistentStorageProvider>>,
169 pub(super) _backend: Option<Arc<dyn PersistentStorageBackend>>,
170 pub(super) _admission: Arc<registration::SubscriptionAdmission>,
171}
172
173impl Drop for ListenerResources {
174 fn drop(&mut self) {
175 self.hub.retire_subscription(self.session_id);
176 self.locks.release_session(self.session_id);
177 }
178}
179
180pub struct NotificationSubscription {
182 pub(super) inbox: Arc<SubscriptionInbox>,
183 pub(super) resources: Mutex<Option<ListenerResources>>,
184 pub(super) authorization: SessionAuthorization,
185}
186
187impl NotificationSubscription {
188 pub fn identity(&self) -> &NotificationIdentity {
189 self.inbox.identity()
190 }
191 pub fn poll(&self) -> Result<Poll<Option<NotificationEvent>>, NotificationSubscriptionError> {
193 self.inbox.poll()
194 }
195 pub fn wait(
197 &self,
198 timeout: Duration,
199 ) -> Result<NotificationWait, NotificationSubscriptionError> {
200 self.inbox.wait(timeout)
201 }
202 pub fn poll_with<T, E: From<NotificationSubscriptionError>>(
206 &self,
207 prepare: impl FnOnce(&uqa_core::notifications::SQLNotification) -> Result<T, E>,
208 ) -> Result<NotificationReceive<T>, E> {
209 self.inbox.poll_with(prepare)
210 }
211 pub fn wait_with<T, E: From<NotificationSubscriptionError>>(
214 &self,
215 timeout: Duration,
216 prepare: impl FnOnce(&uqa_core::notifications::SQLNotification) -> Result<T, E>,
217 ) -> Result<NotificationReceive<T>, E> {
218 self.inbox.wait_with(timeout, prepare)
219 }
220 pub async fn next_event(
222 &self,
223 ) -> Result<Option<NotificationEvent>, NotificationSubscriptionError> {
224 self.inbox.wait_async().await
225 }
226 pub fn is_closed(&self) -> bool {
227 self.inbox.is_closed()
228 }
229 pub fn role_identity(&self) -> uqa_core::catalog_role::RoleIdentity {
231 self.authorization.current().identity()
232 }
233 pub fn stop_delivery(&self) {
235 self.inbox.close();
236 }
237 pub fn close(&self) {
239 self.stop_delivery();
240 let mut resources = self.resources.lock();
241 drop(resources.take());
242 }
243}
244
245impl Drop for NotificationSubscription {
246 fn drop(&mut self) {
247 self.close();
248 }
249}
250
251impl crate::Engine {
252 pub fn subscribe_notifications(
256 &self,
257 channels: &[&str],
258 options: NotificationSubscriptionOptions,
259 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
260 self.subscribe_notifications_with_cancellation(
261 channels,
262 options,
263 &uqa_core::CancellationToken::new(),
264 )
265 }
266
267 pub fn subscribe_notifications_with_cancellation(
271 &self,
272 channels: &[&str],
273 options: NotificationSubscriptionOptions,
274 cancellation: &uqa_core::CancellationToken,
275 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
276 validate_channels(channels, options, cancellation)?;
277 let permit = self.reserve_notification_subscription(options, cancellation)?;
278 self.register_notification_subscription(channels, permit, cancellation)
279 }
280
281 pub fn reserve_notification_subscription(
283 &self,
284 options: NotificationSubscriptionOptions,
285 cancellation: &uqa_core::CancellationToken,
286 ) -> Result<NotificationSubscriptionPermit, NotificationSubscriptionError> {
287 options.validate()?;
288 let admission = self
289 .notification_hub
290 .admissions
291 .reserve(options.max_active_subscriptions, cancellation)?;
292 Ok(NotificationSubscriptionPermit {
293 hub: Arc::downgrade(&self.notification_hub),
294 admission,
295 options,
296 })
297 }
298
299 pub fn subscribe_notifications_with_permit(
301 &self,
302 channels: &[&str],
303 permit: NotificationSubscriptionPermit,
304 cancellation: &uqa_core::CancellationToken,
305 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
306 if !Weak::ptr_eq(&permit.hub, &Arc::downgrade(&self.notification_hub)) {
307 return Err(NotificationSubscriptionError::new(
308 NotificationFailureKind::InvalidRequest,
309 ));
310 }
311 validate_channels(channels, permit.options, cancellation)?;
312 self.register_notification_subscription(channels, permit, cancellation)
313 }
314
315 fn register_notification_subscription(
316 &self,
317 channels: &[&str],
318 permit: NotificationSubscriptionPermit,
319 cancellation: &uqa_core::CancellationToken,
320 ) -> Result<NotificationSubscription, NotificationSubscriptionError> {
321 let _statement = self
322 .runtime
323 .statement_gate
324 .lock_with_cancellation(cancellation)
325 .map_err(|error| registration::failure(error.into()))?;
326 self.prepare_notification_recovery_with_cancellation(Some(cancellation))
327 .map_err(registration::failure)?;
328 let authorization = registration::read(&self.session.state, cancellation)
329 .map_err(registration::failure)?
330 .authorization
331 .clone();
332 let mut bytes = [0u8; 16];
333 getrandom::fill(&mut bytes).map_err(|error| {
334 NotificationSubscriptionError::with_source(
335 NotificationFailureKind::SourceUnavailable,
336 std::io::Error::other(error.to_string()),
337 )
338 })?;
339 bytes[6] = (bytes[6] & 0x0f) | 0x40;
340 bytes[8] = (bytes[8] & 0x3f) | 0x80;
341 let identity = NotificationIdentity {
342 epoch: uqa_core::notifications::NotificationEpoch::from_bytes(bytes)
343 .expect("version and variant set above"),
344 request_id: None,
345 };
346 let session_id = self.row_locks.allocate_session();
347 let inbox = SubscriptionInbox::new(identity, permit.options);
348 self.notification_hub.register_subscription(
349 session_id,
350 self.backend_process_id(),
351 channels
352 .iter()
353 .map(|channel| (*channel).to_owned())
354 .collect(),
355 &inbox,
356 cancellation,
357 )?;
358 Ok(NotificationSubscription {
359 inbox,
360 resources: Mutex::new(Some(ListenerResources {
361 hub: self.notification_hub.clone(),
362 session_id,
363 locks: self.row_locks.clone(),
364 _provider: self.storage.provider.clone(),
365 _backend: self.storage.backend.clone(),
366 _admission: permit.admission,
367 })),
368 authorization,
369 })
370 }
371}