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
152/// One receive with adapter-owned storage admitted before dequeue. Rejected admission leaves both
153/// the queued notification and its delivery sequence unchanged.
154#[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
180/// An idle listener independent of the query session that created it. Close every retained handle before replacing a database file.
181pub 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    /// No database read, SQL execution or blocking receive is performed by this poll.
192    pub fn poll(&self) -> Result<Poll<Option<NotificationEvent>>, NotificationSubscriptionError> {
193        self.inbox.poll()
194    }
195    /// Receive without the caller's transaction or SQL timeout. Timeout leaves this listener registered.
196    pub fn wait(
197        &self,
198        timeout: Duration,
199    ) -> Result<NotificationWait, NotificationSubscriptionError> {
200        self.inbox.wait(timeout)
201    }
202    /// Poll with fallible destination admission under the inbox lock. `prepare` runs at most once,
203    /// only for a present event, and must not reenter this inbox or Engine. It may reserve storage;
204    /// it must not invoke host callbacks. Failure or unwinding preserves the event and sequence.
205    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    /// Wait with the same admission contract as [`Self::poll_with`]. Timeout and closure do not
212    /// invoke `prepare`; all ordinary native receive and retained-failure semantics remain intact.
213    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    /// 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.
221    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    /// Preserve the exact effective SQL role selected at registration, including its incarnation.
230    pub fn role_identity(&self) -> uqa_core::catalog_role::RoleIdentity {
231        self.authorization.current().identity()
232    }
233    /// 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.
234    pub fn stop_delivery(&self) {
235        self.inbox.close();
236    }
237    /// Stop delivery and wake a blocked receiver before releasing only this listener's retained resources. Concurrent callers wait for that same cleanup to complete.
238    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    /// 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.
253    ///
254    /// 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.
255    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    /// 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.
268    ///
269    /// 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.
270    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    /// 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.
282    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    /// 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.
300    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}