Skip to main content

uqa_engine/
notifications.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Transactional SQL asynchronous-notification coordination.
8
9mod completion;
10#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
11mod cross_process;
12mod hub;
13mod inbox;
14mod sql_session;
15pub(crate) use inbox::SubscriptionInbox as SQLNotificationInbox;
16pub use sql_session::SQLNotificationOptions;
17mod owner;
18mod registration;
19mod session_policy;
20mod subscription;
21
22pub(crate) use owner::NotificationHubOwner;
23#[cfg(test)]
24pub(crate) use registration::gate_waited;
25
26pub use subscription::{
27    NotificationReceive, NotificationSubscription, NotificationSubscriptionError,
28    NotificationSubscriptionOptions, NotificationSubscriptionPermit, NotificationWait,
29};
30
31#[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
32mod cross_process {
33    use std::sync::Arc;
34    use uqa_sql::SQLError;
35    use uqa_storage::{
36        notifications::{NotificationPublication, PendingNotification},
37        read_control::StorageReadControl,
38        PersistentStorageBackend,
39    };
40
41    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42    pub(super) struct CrossProcessQueueState {
43        pub(super) next_sequence: u64,
44        pub(super) head_position: u64,
45    }
46
47    #[derive(Clone, Debug, PartialEq, Eq)]
48    pub(super) struct CrossProcessQueueEntry {
49        pub(super) sequence: u64,
50        pub(super) process_id: i32,
51        pub(super) channel: String,
52        pub(super) payload: String,
53    }
54
55    #[derive(Clone, Debug, PartialEq, Eq)]
56    pub(super) struct CrossProcessListenerRow {
57        pub(super) owner_id: [u8; 16],
58        pub(super) session_id: u64,
59        pub(super) process_id: i32,
60        pub(super) wake_port: u16,
61        pub(super) channels: Vec<String>,
62        pub(super) transaction_open: bool,
63        pub(super) next_sequence: u64,
64        pub(super) position: u64,
65    }
66
67    pub(super) struct ListenerLease {
68        owner_id: [u8; 16],
69    }
70
71    impl ListenerLease {
72        pub(super) const fn owner_id(&self) -> [u8; 16] {
73            self.owner_id
74        }
75    }
76
77    pub(super) struct CrossProcessRegistryTransaction;
78
79    impl CrossProcessRegistryTransaction {
80        pub(super) fn suspend_publication(
81            &mut self,
82            _publication: &uqa_storage::notifications::NotificationPublication,
83            _owner: [u8; 16],
84        ) -> Result<(), SQLError> {
85            Err(unsupported())
86        }
87        pub(super) fn resume_publication(
88            &mut self,
89            _publication: &uqa_storage::notifications::NotificationPublication,
90            _owner: [u8; 16],
91            _control: &StorageReadControl,
92        ) -> Result<bool, SQLError> {
93            Err(unsupported())
94        }
95        pub(super) fn prepare_publication(
96            &mut self,
97            _process_id: i32,
98            _pending: &[PendingNotification],
99            _listener: Option<&CrossProcessListenerRow>,
100            _control: &StorageReadControl,
101        ) -> Result<NotificationPublication, SQLError> {
102            Err(unsupported())
103        }
104        pub(super) const fn pending_acknowledgement(&self) -> Option<[u8; 32]> {
105            None
106        }
107        pub(super) fn queue_state(&self) -> Result<CrossProcessQueueState, SQLError> {
108            Err(unsupported())
109        }
110
111        pub(super) fn entries_from(
112            &self,
113            _from_sequence: u64,
114        ) -> Result<Vec<CrossProcessQueueEntry>, SQLError> {
115            Err(unsupported())
116        }
117
118        pub(super) fn delete_entries_before(&self, _sequence: u64) -> Result<(), SQLError> {
119            Err(unsupported())
120        }
121
122        pub(super) fn visit_entries_from(
123            &self,
124            _from_sequence: u64,
125            _max_entries: std::num::NonZeroUsize,
126            _control: &StorageReadControl,
127            _visit: &mut dyn FnMut(
128                uqa_storage::notifications::NotificationQueueEntryRef<'_>,
129            )
130                -> uqa_storage::StorageBackendResult<std::ops::ControlFlow<()>>,
131        ) -> Result<uqa_storage::notifications::NotificationQueueScan, SQLError> {
132            Err(unsupported())
133        }
134
135        pub(super) fn listener_metadata_after(
136            &self,
137            _after: Option<uqa_storage::notifications::NotificationListenerKey>,
138        ) -> Result<Option<uqa_storage::notifications::NotificationListenerMetadata>, SQLError>
139        {
140            Err(unsupported())
141        }
142
143        pub(super) fn listener(
144            &self,
145            _key: uqa_storage::notifications::NotificationListenerKey,
146            _max_channels: Option<usize>,
147        ) -> Result<Option<CrossProcessListenerRow>, SQLError> {
148            Err(unsupported())
149        }
150
151        pub(super) fn save_listener(
152            &self,
153            _listener: &CrossProcessListenerRow,
154        ) -> Result<(), SQLError> {
155            Err(unsupported())
156        }
157
158        pub(super) fn drop_listener(
159            &self,
160            _owner_id: [u8; 16],
161            _session_id: u64,
162        ) -> Result<(), SQLError> {
163            Err(unsupported())
164        }
165
166        pub(super) fn commit(self) -> Result<(), SQLError> {
167            Err(unsupported())
168        }
169        pub(super) fn commit_with_control(
170            self,
171            _control: &StorageReadControl,
172        ) -> Result<(), SQLError> {
173            Err(unsupported())
174        }
175    }
176
177    pub(super) struct CrossProcessCoordinator;
178
179    impl CrossProcessCoordinator {
180        pub(super) fn begin_publication_transaction(
181            &self,
182            _control: &StorageReadControl,
183            _resume: Option<(
184                &uqa_storage::notifications::NotificationPublication,
185                [u8; 16],
186            )>,
187        ) -> Result<CrossProcessRegistryTransaction, SQLError> {
188            Err(unsupported())
189        }
190        pub(super) fn initialize_recovery_with_cancellation(
191            &self,
192            _backend: &Arc<dyn PersistentStorageBackend>,
193            _control: &StorageReadControl,
194            _cancellation: Option<&uqa_core::CancellationToken>,
195        ) -> Result<(), SQLError> {
196            Err(unsupported())
197        }
198        pub(super) fn recovery_control(&self) -> Result<StorageReadControl, SQLError> {
199            Err(unsupported())
200        }
201        pub(super) fn recovery_control_with_cancellation(
202            &self,
203            _cancellation: Option<&uqa_core::CancellationToken>,
204        ) -> Result<StorageReadControl, SQLError> {
205            Err(unsupported())
206        }
207        pub(super) const fn recovery_initialized(&self) -> bool {
208            false
209        }
210        pub(super) fn poll_needed(&self, _local_owners: &[[u8; 16]]) -> Result<bool, SQLError> {
211            Err(unsupported())
212        }
213        pub(super) fn begin_registry_transaction(
214            &self,
215        ) -> Result<CrossProcessRegistryTransaction, SQLError> {
216            Err(unsupported())
217        }
218        pub(super) fn begin_registry_transaction_with_cancellation(
219            &self,
220            _cancellation: Option<&uqa_core::CancellationToken>,
221        ) -> Result<CrossProcessRegistryTransaction, SQLError> {
222            Err(unsupported())
223        }
224
225        pub(super) fn create_listener_lease(&self) -> Result<ListenerLease, SQLError> {
226            Err(unsupported())
227        }
228
229        pub(super) fn listener_is_alive(
230            &self,
231            _owner_id: [u8; 16],
232            _local_owner_ids: &[[u8; 16]],
233        ) -> Result<bool, SQLError> {
234            Err(unsupported())
235        }
236
237        pub(super) const fn wake_port(&self) -> u16 {
238            0
239        }
240
241        pub(super) fn wake(_ports: impl IntoIterator<Item = u16>) {}
242    }
243
244    fn unsupported() -> SQLError {
245        SQLError::Internal(
246            "cross-process asynchronous notifications are unavailable on this target".into(),
247        )
248    }
249}
250
251use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
252use std::sync::{Arc, OnceLock, Weak};
253use std::time::{Duration, Instant};
254
255use crate::Engine;
256use cross_process::{
257    CrossProcessCoordinator, CrossProcessListenerRow, CrossProcessQueueState,
258    CrossProcessRegistryTransaction, ListenerLease,
259};
260use parking_lot::{Condvar, Mutex, MutexGuard};
261pub use uqa_core::notifications::SQLNotification;
262use uqa_sql::{SQLError, SQLNotice};
263pub(crate) use uqa_storage::notifications::PendingNotification;
264#[cfg(test)]
265use uqa_storage::notifications::NOTIFICATION_QUEUE_PAGE_BYTES;
266use uqa_storage::notifications::{
267    notification_end_position, notifications_fit_queue, queue_page, MAX_NOTIFICATION_CHANNEL_BYTES,
268    MAX_NOTIFICATION_PAYLOAD_BYTES, MAX_NOTIFICATION_QUEUE_PAGES,
269};
270
271const NOTIFICATION_QUEUE_WARNING_INTERVAL: Duration = Duration::from_secs(5);
272
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub(crate) enum PendingListenAction {
275    Listen(String),
276    Unlisten(String),
277    UnlistenAll,
278}
279
280impl PendingListenAction {
281    fn apply(&self, channels: &mut Vec<String>) {
282        match self {
283            Self::Listen(channel) if !channels.contains(channel) => channels.push(channel.clone()),
284            Self::Listen(_) => {}
285            Self::Unlisten(channel) => channels.retain(|candidate| candidate != channel),
286            Self::UnlistenAll => channels.clear(),
287        }
288    }
289}
290
291#[derive(Clone)]
292struct CommittedNotification {
293    sequence: u64,
294    process_id: i32,
295    channel: String,
296    payload: String,
297}
298
299struct NotificationListener {
300    process_id: i32,
301    channels: Vec<String>,
302    queue: Weak<Mutex<VecDeque<SQLNotification>>>,
303    wake: Weak<Condvar>,
304    subscription: Option<Weak<inbox::SubscriptionInbox>>,
305    next_sequence: u64,
306    position: u64,
307    transaction_open: bool,
308    lease: Option<ListenerLease>,
309}
310
311struct NotificationSessionCommit<'a> {
312    session_id: u64,
313    process_id: i32,
314    channels: Vec<String>,
315    queue: &'a Arc<Mutex<VecDeque<SQLNotification>>>,
316    subscription: Option<Arc<inbox::SubscriptionInbox>>,
317    wake: &'a Arc<Condvar>,
318    notices: &'a Arc<uqa_execution::query::NoticeQueue>,
319    pending: &'a [PendingNotification],
320}
321
322enum PreparedDelivery {
323    Session {
324        session_id: u64,
325        notifications: Vec<SQLNotification>,
326    },
327    Subscription(inbox::PreparedNotifications),
328}
329
330pub(super) struct CrossNotificationCommit {
331    registry: Option<CrossProcessRegistryTransaction>,
332    new_lease: Option<ListenerLease>,
333    publisher_lease: Option<ListenerLease>,
334    publication_applied: bool,
335    publication: Option<uqa_storage::notifications::NotificationPublication>,
336    previous_publication: Option<[u8; 32]>,
337    wake_ports: uqa_storage::notifications::NotificationWakePorts,
338    warning: Option<SQLNotice>,
339}
340
341#[derive(Clone, Copy)]
342struct CrossNotificationRequest<'a> {
343    session_id: u64,
344    process_id: i32,
345    channels: &'a [String],
346    pending: &'a [PendingNotification],
347    control: &'a uqa_storage::read_control::StorageReadControl,
348    durable_publication: bool,
349}
350
351struct PreparedCrossSubscription {
352    new_lease: Option<ListenerLease>,
353    listeners: uqa_storage::notifications::NotificationListenerSummary,
354    subscription: Option<CrossProcessListenerRow>,
355}
356
357#[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
358struct CrossProcessState {
359    database_path: std::path::PathBuf,
360    encryption_key: Option<uqa_storage::StorageEncryptionKey>,
361    registry: Mutex<Option<uqa_storage_sqlite::notifications::NotificationRegistry>>,
362    hub: Weak<NotificationHub>,
363    coordinator: Mutex<Option<Arc<CrossProcessCoordinator>>>,
364}
365
366#[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
367struct CrossProcessState;
368
369impl CrossProcessState {
370    #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
371    fn initialized_coordinator(&self) -> Option<Arc<CrossProcessCoordinator>> {
372        self.coordinator.lock().clone()
373    }
374
375    #[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
376    fn initialized_coordinator(&self) -> Option<Arc<CrossProcessCoordinator>> {
377        None
378    }
379
380    #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
381    fn registry(
382        &self,
383    ) -> Result<uqa_storage_sqlite::notifications::NotificationRegistry, SQLError> {
384        self.registry_with_cancellation(None)
385    }
386
387    #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
388    fn registry_with_cancellation(
389        &self,
390        cancellation: Option<&uqa_core::CancellationToken>,
391    ) -> Result<uqa_storage_sqlite::notifications::NotificationRegistry, SQLError> {
392        let mut initialized = registration::lock(&self.registry, cancellation)?;
393        if let Some(registry) = initialized.as_ref() {
394            return Ok(registry.clone());
395        }
396        let registry =
397            cross_process::open_registry(&self.database_path, self.encryption_key.as_ref())
398                .map_err(SQLError::Internal)?;
399        *initialized = Some(registry.clone());
400        Ok(registry)
401    }
402
403    #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
404    fn allocate_backend_process_id(&self) -> Result<i32, SQLError> {
405        CrossProcessCoordinator::allocate_backend_process_id(&self.registry()?)
406    }
407
408    #[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
409    fn allocate_backend_process_id(&self) -> Result<i32, SQLError> {
410        Err(SQLError::Internal(
411            "cross-process backend process identifiers are unavailable on this target".into(),
412        ))
413    }
414
415    #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
416    fn coordinator(&self) -> Result<Arc<CrossProcessCoordinator>, SQLError> {
417        self.coordinator_with_cancellation(None)
418    }
419
420    #[cfg(any(windows, all(unix, not(target_os = "emscripten"))))]
421    fn coordinator_with_cancellation(
422        &self,
423        cancellation: Option<&uqa_core::CancellationToken>,
424    ) -> Result<Arc<CrossProcessCoordinator>, SQLError> {
425        let mut initialized = registration::lock(&self.coordinator, cancellation)?;
426        if let Some(coordinator) = initialized.as_ref() {
427            return Ok(Arc::clone(coordinator));
428        }
429        let (coordinator, listener) = CrossProcessCoordinator::open(
430            &self.database_path,
431            self.registry_with_cancellation(cancellation)?,
432        )
433        .map_err(SQLError::Internal)?;
434        let coordinator = Arc::new(coordinator);
435        coordinator
436            .start_worker(listener, self.hub.clone())
437            .map_err(SQLError::Internal)?;
438        *initialized = Some(Arc::clone(&coordinator));
439        Ok(coordinator)
440    }
441
442    #[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
443    fn coordinator(&self) -> Result<Arc<CrossProcessCoordinator>, SQLError> {
444        self.coordinator_with_cancellation(None)
445    }
446
447    #[cfg(not(any(windows, all(unix, not(target_os = "emscripten")))))]
448    fn coordinator_with_cancellation(
449        &self,
450        _cancellation: Option<&uqa_core::CancellationToken>,
451    ) -> Result<Arc<CrossProcessCoordinator>, SQLError> {
452        Err(SQLError::Internal(
453            "cross-process asynchronous notifications are unavailable on this target".into(),
454        ))
455    }
456}
457
458pub(super) struct NotificationCommitGuard<'a> {
459    _gate: MutexGuard<'a, ()>,
460    cross: Option<Box<CrossNotificationCommit>>,
461}
462
463impl NotificationCommitGuard<'_> {
464    pub(super) fn retain(mut self) -> (Option<Box<CrossNotificationCommit>>, Result<(), SQLError>) {
465        let suspended = self.cross.as_mut().map_or(Ok(()), |prepared| {
466            if !prepared.publication_applied {
467                if let (Some(registry), Some(publication)) =
468                    (prepared.registry.as_mut(), prepared.publication.as_ref())
469                {
470                    let owner = prepared
471                        .publisher_lease
472                        .as_ref()
473                        .ok_or_else(|| {
474                            SQLError::Internal(
475                                "retained notification has no publication lease".into(),
476                            )
477                        })?
478                        .owner_id();
479                    registry.suspend_publication(publication, owner)?;
480                }
481            }
482            prepared.registry.take();
483            Ok(())
484        });
485        (self.cross, suspended)
486    }
487}
488
489#[derive(Default)]
490struct NotificationHubState {
491    listeners: BTreeMap<u64, NotificationListener>,
492    entries: VecDeque<CommittedNotification>,
493    next_sequence: u64,
494    head_position: u64,
495    last_queue_warning: Option<Instant>,
496    /// Cross-process synchronizations whose delivery commit failed; each failure fails every local subscription.
497    delivery_failures: u64,
498    last_delivery_failure: Option<SQLError>,
499}
500
501pub(crate) struct NotificationHub {
502    admissions: registration::SubscriptionAdmissions,
503    commit_gate: Mutex<()>,
504    state: Mutex<NotificationHubState>,
505    max_queue_pages: u64,
506    cross: Option<CrossProcessState>,
507    cross_error: Mutex<Option<String>>,
508    /// Runs between a cross-process publication and the committing session's own synchronization.
509    #[cfg(test)]
510    after_publication: Mutex<Option<AfterPublication>>,
511}
512
513#[cfg(test)]
514type AfterPublication = Box<dyn FnOnce(&NotificationHub) + Send>;
515
516impl Default for NotificationHub {
517    fn default() -> Self {
518        Self {
519            admissions: registration::SubscriptionAdmissions::default(),
520            commit_gate: Mutex::new(()),
521            state: Mutex::new(NotificationHubState::default()),
522            max_queue_pages: MAX_NOTIFICATION_QUEUE_PAGES,
523            cross: None,
524            cross_error: Mutex::new(None),
525            #[cfg(test)]
526            after_publication: Mutex::new(None),
527        }
528    }
529}
530
531fn append_notification(
532    state: &mut NotificationHubState,
533    process_id: i32,
534    notification: &PendingNotification,
535) {
536    let end_position = notification_end_position(state.head_position, notification);
537    let sequence = state.next_sequence;
538    state.entries.push_back(CommittedNotification {
539        sequence,
540        process_id,
541        channel: notification.channel.clone(),
542        payload: notification.payload.clone(),
543    });
544    state.next_sequence = state.next_sequence.saturating_add(1);
545    state.head_position = end_position;
546}
547
548fn projected_tail_position(
549    state: &NotificationHubState,
550    session_id: u64,
551    final_channels: &[String],
552) -> u64 {
553    state
554        .listeners
555        .iter()
556        .filter_map(|(listener_id, listener)| {
557            (*listener_id != session_id || !final_channels.is_empty()).then_some(listener.position)
558        })
559        .min()
560        .unwrap_or(state.head_position)
561}
562
563/// The warning `PostgreSQL`'s `asyncQueueFillWarning` reports once the queue is at least half full (`usage` is the filled fraction): the process `blocker` is a listener whose position holds back the oldest entries.
564fn queue_fill_warning(usage: f64, blocker: i32) -> SQLNotice {
565    SQLNotice::warning(format!("NOTIFY queue is {:.0}% full", usage * 100.0))
566        .with_detail(format!(
567            "The server process with PID {blocker} is among those with the oldest transactions."
568        ))
569        .with_hint(
570            "The NOTIFY queue cannot be emptied until that process ends its current transaction.",
571        )
572}
573
574fn queue_usage(state: &NotificationHubState, max_queue_pages: u64) -> f64 {
575    let tail = state
576        .listeners
577        .values()
578        .map(|listener| listener.position)
579        .min()
580        .unwrap_or(state.head_position);
581    let pages = queue_page(state.head_position).saturating_sub(queue_page(tail));
582    pages as f64 / max_queue_pages as f64
583}
584
585fn validate_channel(channel: &str) -> Result<(), SQLError> {
586    if channel.is_empty() {
587        return Err(SQLError::Routine {
588            sqlstate: "22023".into(),
589            message: "channel name cannot be empty".into(),
590        });
591    }
592    if channel.len() >= MAX_NOTIFICATION_CHANNEL_BYTES {
593        return Err(SQLError::Routine {
594            sqlstate: "22023".into(),
595            message: "channel name too long".into(),
596        });
597    }
598    Ok(())
599}
600
601#[derive(Clone, Debug, PartialEq, Eq, Hash)]
602enum NotificationHubIdentity {
603    Durable(uqa_storage::PersistentStorageIdentity),
604    Provider(usize),
605}
606
607static DATABASE_NOTIFICATION_HUBS: OnceLock<
608    Mutex<HashMap<NotificationHubIdentity, Weak<NotificationHubOwner>>>,
609> = OnceLock::new();
610
611#[derive(Default)]
612struct BackendProcessIdRegistry {
613    active: BTreeSet<i32>,
614    next: i32,
615}
616
617static BACKEND_PROCESS_IDS: OnceLock<Mutex<BackendProcessIdRegistry>> = OnceLock::new();
618
619pub(crate) fn allocate_backend_process_id() -> i32 {
620    let registry = BACKEND_PROCESS_IDS.get_or_init(|| {
621        Mutex::new(BackendProcessIdRegistry {
622            active: BTreeSet::new(),
623            next: 1,
624        })
625    });
626    let mut registry = registry.lock();
627    for _ in 0..i32::MAX {
628        let candidate = registry.next;
629        registry.next = registry.next.checked_add(1).unwrap_or(1);
630        if registry.active.insert(candidate) {
631            return candidate;
632        }
633    }
634    panic!("exhausted positive backend process identifiers");
635}
636
637pub(crate) fn release_backend_process_id(process_id: i32) {
638    if let Some(registry) = BACKEND_PROCESS_IDS.get() {
639        registry.lock().active.remove(&process_id);
640    }
641}
642
643pub(crate) fn shared_provider_notification_hub(
644    identity: Option<uqa_storage::PersistentStorageIdentity>,
645    provider: &Arc<dyn uqa_storage::PersistentStorageProvider>,
646) -> Arc<NotificationHubOwner> {
647    shared_notification_hub(
648        identity,
649        NotificationHubIdentity::Provider(Arc::as_ptr(provider).cast::<()>() as usize),
650        provider.auxiliary_encryption_key(),
651    )
652}
653
654pub(crate) fn shared_backend_notification_hub(
655    identity: Option<uqa_storage::PersistentStorageIdentity>,
656    backend: &Arc<dyn uqa_storage::PersistentStorageBackend>,
657) -> Arc<NotificationHubOwner> {
658    shared_notification_hub(
659        identity,
660        NotificationHubIdentity::Provider(Arc::as_ptr(backend).cast::<()>() as usize),
661        backend.auxiliary_encryption_key(),
662    )
663}
664
665fn shared_notification_hub(
666    identity: Option<uqa_storage::PersistentStorageIdentity>,
667    fallback: NotificationHubIdentity,
668    encryption_key: Option<uqa_storage::StorageEncryptionKey>,
669) -> Arc<NotificationHubOwner> {
670    let identity = identity.map_or(fallback, NotificationHubIdentity::Durable);
671    let registry = DATABASE_NOTIFICATION_HUBS.get_or_init(|| Mutex::new(HashMap::new()));
672    let mut registry = registry.lock();
673    registry.retain(|_, hub| hub.strong_count() != 0);
674    if let Some(hub) = registry.get(&identity).and_then(Weak::upgrade) {
675        return hub;
676    }
677    let hub = match &identity {
678        NotificationHubIdentity::Durable(uqa_storage::PersistentStorageIdentity::File(path)) => {
679            NotificationHub::for_database_file(path, encryption_key)
680        }
681        _ => Arc::new(NotificationHub::default()),
682    };
683    let hub = Arc::new(NotificationHubOwner::new(hub));
684    registry.insert(identity, Arc::downgrade(&hub));
685    hub
686}
687
688impl Engine {
689    pub(crate) fn listen(&self, channel: &str) -> Result<(), SQLError> {
690        validate_channel(channel)?;
691        self.pending_listen_action(PendingListenAction::Listen(channel.to_string()))
692    }
693
694    pub(crate) fn unlisten(&self, channel: Option<&str>) -> Result<(), SQLError> {
695        let action = match channel {
696            Some(channel) => {
697                validate_channel(channel)?;
698                PendingListenAction::Unlisten(channel.to_string())
699            }
700            None => PendingListenAction::UnlistenAll,
701        };
702        self.pending_listen_action(action)
703    }
704
705    fn pending_listen_action(&self, action: PendingListenAction) -> Result<(), SQLError> {
706        let mut stack = self.session.transactions.lock();
707        let frame = stack.last_mut().ok_or_else(|| {
708            SQLError::Internal("LISTEN state changed without a transaction frame".into())
709        })?;
710        frame.pending_listen_actions.push(action);
711        Ok(())
712    }
713
714    pub(crate) fn notify(&self, channel: &str, payload: &str) -> Result<(), SQLError> {
715        validate_channel(channel)?;
716        if payload.len() >= MAX_NOTIFICATION_PAYLOAD_BYTES {
717            return Err(SQLError::Routine {
718                sqlstate: "22023".into(),
719                message: "payload string too long".into(),
720            });
721        }
722        let notification = PendingNotification {
723            channel: channel.to_string(),
724            payload: payload.to_string(),
725        };
726        let mut stack = self.session.transactions.lock();
727        let frame = stack.last_mut().ok_or_else(|| {
728            SQLError::Internal("NOTIFY executed without a transaction frame".into())
729        })?;
730        if !frame.pending_notifications.contains(&notification) {
731            frame.pending_notifications.push(notification);
732        }
733        Ok(())
734    }
735
736    pub(super) fn begin_notification_transaction(&self) -> Result<(), SQLError> {
737        self.notification_hub.begin_transaction(self.session_id)
738    }
739
740    pub(super) fn rollback_notification_state(&self) -> Result<(), SQLError> {
741        self.notification_hub.rollback_session(self.session_id)
742    }
743
744    pub(crate) fn clear_notification_listener_without_transaction(&self) -> Result<(), SQLError> {
745        self.notification_hub.replace_idle_session(
746            self.session_id,
747            self.backend_process_id(),
748            Vec::new(),
749            &self.runtime.notifications,
750            &self.runtime.notification_wake,
751            &self.runtime.notices,
752        )?;
753        self.session.state.write().listened_channels.clear();
754        Ok(())
755    }
756
757    /// PostgreSQL-compatible backend process identifier for this logical SQL session.
758    #[must_use]
759    pub fn backend_process_id(&self) -> i32 {
760        self.session
761            .backend_process_id
762            .load(std::sync::atomic::Ordering::Acquire)
763    }
764
765    pub(crate) fn listening_channels(&self) -> Vec<String> {
766        self.session.state.read().listened_channels.clone()
767    }
768
769    pub(crate) fn notification_queue_usage(&self) -> Result<f64, SQLError> {
770        self.prepare_notification_recovery()?;
771        self.notification_hub.usage()
772    }
773
774    /// Pull committed cross-process messages into this session without draining them.
775    pub fn poll_sql_notifications(&self) -> Result<usize, SQLError> {
776        if self.transaction_depth() != 0 {
777            return Ok(0);
778        }
779        self.notification_hub
780            .try_synchronize_cross_process_session(Some((self.session_id, false)))?;
781        if let Some(error) = self.notification_hub.cross_error.lock().take() {
782            return Err(SQLError::Internal(error));
783        }
784        let bounded = self.runtime.bounded_sql_notifications.lock().clone();
785        if let Some(inbox) = bounded {
786            return inbox
787                .pending_count()
788                .map_err(|error| sql_session::sql_failure(&error));
789        }
790        Ok(self.runtime.notifications.lock().len())
791    }
792
793    /// Wait until at least one committed notification is ready for this idle SQL session or the timeout elapses.
794    pub fn wait_for_sql_notifications(&self, timeout: Duration) -> Result<bool, SQLError> {
795        if self.transaction_depth() != 0 {
796            return Ok(false);
797        }
798        let started = Instant::now();
799        loop {
800            if self.poll_sql_notifications()? != 0 {
801                return Ok(true);
802            }
803            let elapsed = started.elapsed();
804            if elapsed >= timeout {
805                return Ok(false);
806            }
807            let bounded = self.runtime.bounded_sql_notifications.lock().clone();
808            if let Some(inbox) = bounded {
809                return inbox
810                    .wait_ready(timeout.saturating_sub(elapsed))
811                    .map_err(|error| sql_session::sql_failure(&error));
812            }
813            let mut notifications = self.runtime.notifications.lock();
814            if !notifications.is_empty() {
815                return Ok(true);
816            }
817            self.runtime
818                .notification_wake
819                .wait_for(&mut notifications, timeout.saturating_sub(elapsed));
820        }
821    }
822
823    /// Drain committed notifications available to this SQL session. Notifications received during a transaction remain queued until that transaction ends.
824    pub fn take_sql_notifications(&self) -> Vec<SQLNotification> {
825        if self.transaction_depth() != 0 {
826            return Vec::new();
827        }
828        let bounded = self.runtime.bounded_sql_notifications.lock().clone();
829        if let Some(inbox) = bounded {
830            // The checked API preserves the terminal error for a bounded adapter.
831            return inbox.take_sql().unwrap_or_default();
832        }
833        self.runtime.notifications.lock().drain(..).collect()
834    }
835}
836
837impl crate::TransactionFrame {
838    fn final_listened_channels(&self, current: &[String]) -> Vec<String> {
839        let mut channels = current.to_vec();
840        for action in &self.pending_listen_actions {
841            action.apply(&mut channels);
842        }
843        channels
844    }
845
846    pub(super) fn merge_pending_listen_actions(&mut self, pending: Vec<PendingListenAction>) {
847        self.pending_listen_actions.extend(pending);
848    }
849
850    pub(super) fn merge_pending_notifications(&mut self, pending: Vec<PendingNotification>) {
851        for notification in pending {
852            if !self.pending_notifications.contains(&notification) {
853                self.pending_notifications.push(notification);
854            }
855        }
856    }
857
858    pub(super) fn restore_pending_notification_savepoint(&mut self, position: usize) {
859        self.pending_listen_actions = self.savepoints[position].pending_listen_actions.clone();
860        self.pending_notifications = self.savepoints[position].pending_notifications.clone();
861    }
862}
863
864#[cfg(test)]
865mod recovery_tests;
866
867#[cfg(test)]
868mod tests {
869    use super::*;
870
871    #[test]
872    fn queue_warning_identifies_the_oldest_transaction_and_is_throttled() {
873        let queue = Arc::new(Mutex::new(VecDeque::new()));
874        let wake = Arc::new(Condvar::new());
875        let mut state = NotificationHubState {
876            head_position: NOTIFICATION_QUEUE_PAGE_BYTES,
877            ..NotificationHubState::default()
878        };
879        state.listeners.insert(
880            7,
881            NotificationListener {
882                process_id: 42,
883                channels: vec!["events".into()],
884                queue: Arc::downgrade(&queue),
885                wake: Arc::downgrade(&wake),
886                subscription: None,
887                next_sequence: 0,
888                position: 0,
889                transaction_open: true,
890                lease: None,
891            },
892        );
893        let hub = NotificationHub {
894            admissions: registration::SubscriptionAdmissions::default(),
895            commit_gate: Mutex::new(()),
896            state: Mutex::new(NotificationHubState::default()),
897            max_queue_pages: 1,
898            cross: None,
899            cross_error: Mutex::new(None),
900            #[cfg(test)]
901            after_publication: Mutex::new(None),
902        };
903        assert_eq!(
904            hub.queue_warning(&mut state),
905            Some(
906                SQLNotice::warning("NOTIFY queue is 100% full")
907                    .with_detail(
908                        "The server process with PID 42 is among those with the oldest transactions."
909                    )
910                    .with_hint(
911                        "The NOTIFY queue cannot be emptied until that process ends its current transaction."
912                    )
913            )
914        );
915        assert!(hub.queue_warning(&mut state).is_none());
916    }
917}