Skip to main content

uqa_engine/notifications/
subscription.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Independent listener ownership over the original notification hub and provider.
8
9use 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/// Explicit limits for an owned listener. No deployment capacity is inferred from SQL `work_mem`.
25///
26/// Registrations and retained listeners share every admitted handle's active-subscription ceiling. Admission cannot weaken a stricter ceiling retained by another pending registration or live handle. Queue bytes include string capacities, queue slots and transient prepared-delivery buffers; provider caches and the returned application's owned events are separate resources.
27#[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
52/// One non-cloneable reservation against the original hub's pending/live limit. Reserve before submitting registration to a runtime queue; dropping an unused permit releases capacity without provider I/O. A permit does not retain the Engine or register any channels.
53pub 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/// A stable failure category with an original cause available only through explicit inspection.
97#[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    /// Inspect the original local failure explicitly; it can contain private provider diagnostics.
126    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/// A bounded wait ending with one value, elapsed receive time, or explicit closure.
145#[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
168/// An idle listener independent of the query session that created it. Close every retained handle before replacing a database file.
169pub 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    /// No database read, SQL execution or blocking receive is performed by this poll.
180    pub fn poll(&self) -> Result<Poll<Option<NotificationEvent>>, NotificationSubscriptionError> {
181        self.inbox.poll()
182    }
183    /// Receive without the caller's transaction or SQL timeout. Timeout leaves this listener registered.
184    pub fn wait(
185        &self,
186        timeout: Duration,
187    ) -> Result<NotificationWait, NotificationSubscriptionError> {
188        self.inbox.wait(timeout)
189    }
190    /// Receive without blocking a thread or requiring a particular async runtime. At most one asynchronous receive may be pending; another returns `InvalidRequest`. Dropping a pending receive releases its wake slot without consuming an event or closing the listener.
191    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    /// Preserve the exact effective SQL role selected at registration, including its incarnation.
200    pub fn role_identity(&self) -> uqa_core::catalog_role::RoleIdentity {
201        self.authorization.current().identity()
202    }
203    /// End delivery and wake receivers without provider I/O. Runtime adapters must still call `close` off their event-loop worker and wait for it to finish; this signal retains registration resources and admission until that cleanup completes.
204    pub fn stop_delivery(&self) {
205        self.inbox.close();
206    }
207    /// Stop delivery and wake a blocked receiver before releasing only this listener's retained resources. Concurrent callers wait for that same cleanup to complete.
208    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    /// Register one independent idle listener before returning a ready handle. Channels are exact, unique, nonempty UTF-8 names of at most 63 bytes; no identifier folding or truncation is performed. The caller's transaction and low-level SQL listener remain independent.
223    ///
224    /// Registration and close can perform native provider I/O. Runtime adapters must run them outside their event-loop worker. Polling never performs I/O; a wait timeout does not unsubscribe.
225    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    /// Register with independent caller cancellation through statement, hub and native registry waits. A pending registration already owns subscription capacity. Cancellation before the committed registration boundary returns `Cancelled` without publishing a partial listener; successful readiness wins a simultaneous cancellation race.
238    ///
239    /// The signal applies to registration only. After readiness the handle retains its independent lifetime until close/drop. Native file opening and provider-session construction already in progress remain synchronous; this method does not establish an operating-system I/O deadline.
240    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    /// Reserve the original hub's shared pending/live allowance without waiting on Engine or provider gates. Runtime adapters must retain this Engine separately and obtain the permit before submitting work. The cancellation token applies to this reservation call; the consuming registration accepts its own retained signal.
252    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    /// Consume one pre-submission reservation on its original hub. The permit fixes every limit and cannot be reused or transferred to another database identity. Invalid input, cancellation or failure releases it; readiness transfers that same permit to the listener through completed cleanup.
270    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}