Skip to main content

uqa_engine/notifications/
sql_session.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Optional bounded output for LISTEN on the existing SQL session.
8
9use super::{
10    inbox::SubscriptionInbox, Engine, NotificationSubscriptionError,
11    NotificationSubscriptionOptions, SQLError, SQLNotification,
12};
13use uqa_core::notifications::{NotificationEpoch, NotificationFailureKind, NotificationIdentity};
14
15/// Opt-in bounds for the SQL session's own LISTEN queue. Overflow is terminal and explicit.
16/// Queue bytes include string capacities, queue slots and transient prepared batches.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub struct SQLNotificationOptions {
19    pub max_channels: usize,
20    pub max_queued_notifications: usize,
21    pub max_queued_bytes: usize,
22    pub max_registry_entries_per_poll: usize,
23}
24
25impl Engine {
26    /// Configure bounded LISTEN delivery once, before opening a transaction or listening.
27    /// This does not create another session, change channels or execute SQL. The adapter
28    /// must use `try_take_sql_notifications` and close this session on a terminal error.
29    pub fn configure_sql_notifications(
30        &self,
31        options: SQLNotificationOptions,
32    ) -> Result<(), NotificationSubscriptionError> {
33        let options = NotificationSubscriptionOptions {
34            max_active_subscriptions: 1,
35            max_channels: options.max_channels,
36            max_queued_notifications: options.max_queued_notifications,
37            max_queued_bytes: options.max_queued_bytes,
38            max_registry_entries_per_poll: options.max_registry_entries_per_poll,
39        };
40        options.validate()?;
41        let _statement = self
42            .runtime
43            .statement_gate
44            .lock_with_cancellation(&self.runtime.cancellation)
45            .map_err(|error| {
46                NotificationSubscriptionError::with_source(
47                    NotificationFailureKind::Cancelled,
48                    error,
49                )
50            })?;
51        let mut selected = self.runtime.bounded_sql_notifications.lock();
52        if selected.is_some()
53            || self.transaction_depth() != 0
54            || !self.listening_channels().is_empty()
55            || !self.runtime.notifications.lock().is_empty()
56        {
57            return Err(NotificationSubscriptionError::new(
58                NotificationFailureKind::InvalidRequest,
59            ));
60        }
61        let mut bytes = [0_u8; 16];
62        getrandom::fill(&mut bytes).map_err(|error| {
63            NotificationSubscriptionError::with_source(
64                NotificationFailureKind::SourceUnavailable,
65                std::io::Error::other(error.to_string()),
66            )
67        })?;
68        bytes[6] = (bytes[6] & 0x0f) | 0x40;
69        bytes[8] = (bytes[8] & 0x3f) | 0x80;
70        *selected = Some(SubscriptionInbox::new(
71            NotificationIdentity {
72                epoch: NotificationEpoch::from_bytes(bytes).expect("set UUID version and variant"),
73                request_id: None,
74            },
75            options,
76        ));
77        Ok(())
78    }
79
80    /// Synchronize committed messages and atomically drain the same SQL session's inbox.
81    /// Transactional LISTEN, UNLISTEN, NOTIFY and savepoint semantics remain unchanged.
82    /// An overflow or source failure remains terminal; no lost message is called success.
83    pub fn try_take_sql_notifications(&self) -> Result<Vec<SQLNotification>, SQLError> {
84        if self.transaction_depth() != 0 {
85            return Ok(Vec::new());
86        }
87        self.poll_sql_notifications()?;
88        let bounded = self.runtime.bounded_sql_notifications.lock().clone();
89        if let Some(inbox) = bounded {
90            return inbox.take_sql().map_err(|error| sql_failure(&error));
91        }
92        Ok(self.runtime.notifications.lock().drain(..).collect())
93    }
94
95    pub(super) fn validate_sql_notification_channels(
96        &self,
97        channels: &[String],
98    ) -> Result<(), SQLError> {
99        if self
100            .runtime
101            .bounded_sql_notifications
102            .lock()
103            .as_ref()
104            .is_some_and(|inbox| channels.len() > inbox.options.max_channels)
105        {
106            return Err(SQLError::Routine {
107                sqlstate: "54000".into(),
108                message: "SQL notification channel limit exceeded".into(),
109            });
110        }
111        Ok(())
112    }
113}
114
115pub(super) fn sql_failure(error: &NotificationSubscriptionError) -> SQLError {
116    SQLError::Internal(error.code().into())
117}
118
119impl SubscriptionInbox {
120    pub(in crate::notifications) fn pending_count(
121        &self,
122    ) -> Result<usize, NotificationSubscriptionError> {
123        let state = self.state.lock();
124        if let Some(error) = &state.failure {
125            return Err(error.clone());
126        }
127        Ok(state.queue.len())
128    }
129    pub(in crate::notifications) fn take_sql(
130        &self,
131    ) -> Result<Vec<SQLNotification>, NotificationSubscriptionError> {
132        let mut state = self.state.lock();
133        if let Some(error) = &state.failure {
134            return Err(error.clone());
135        }
136        let mut result = Vec::with_capacity(state.queue.len());
137        while let Some(value) = state.queue.pop_front() {
138            result.push(value.value);
139        }
140        Ok(result)
141    }
142    pub(in crate::notifications) fn wait_ready(
143        &self,
144        timeout: std::time::Duration,
145    ) -> Result<bool, NotificationSubscriptionError> {
146        let started = std::time::Instant::now();
147        let mut state = self.state.lock();
148        loop {
149            if let Some(error) = &state.failure {
150                return Err(error.clone());
151            }
152            if !state.queue.is_empty() {
153                return Ok(true);
154            }
155            if state.closed {
156                return Ok(false);
157            }
158            let remaining = timeout.saturating_sub(started.elapsed());
159            if remaining.is_zero() {
160                return Ok(false);
161            }
162            #[cfg(test)]
163            if let Some(started) = self.sql_wait_started.lock().take() {
164                let _ = started.send(());
165            }
166            self.wake.wait_for(&mut state, remaining);
167        }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use std::{sync::Arc, time::Duration};
175
176    #[test]
177    fn sql_wait_releases_configuration_ownership_before_parking_the_inbox() {
178        let engine = Arc::new(Engine::new());
179        engine
180            .configure_sql_notifications(SQLNotificationOptions {
181                max_channels: 1,
182                max_queued_notifications: 2,
183                max_queued_bytes: 65_536,
184                max_registry_entries_per_poll: 2,
185            })
186            .unwrap();
187        engine.sql("LISTEN events", &[]).unwrap();
188        let inbox = engine
189            .runtime
190            .bounded_sql_notifications
191            .lock()
192            .clone()
193            .unwrap();
194        let (started, boundary) = std::sync::mpsc::channel();
195        *inbox.sql_wait_started.lock() = Some(started);
196        let waiting = engine.clone();
197        let task =
198            std::thread::spawn(move || waiting.wait_for_sql_notifications(Duration::from_secs(15)));
199        boundary.recv_timeout(Duration::from_secs(15)).unwrap();
200        let released = engine
201            .runtime
202            .bounded_sql_notifications
203            .try_lock()
204            .is_some();
205        if !released {
206            inbox.close();
207            let _ = task.join();
208            panic!("notification wait retained the configuration lock");
209        }
210        engine.sql("NOTIFY events, 'ready'", &[]).unwrap();
211        assert!(task.join().unwrap().unwrap());
212        assert_eq!(
213            engine.try_take_sql_notifications().unwrap()[0].payload,
214            "ready"
215        );
216    }
217}