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` or `try_take_sql_notification_with` and close
29    /// this session on a terminal error.
30    pub fn configure_sql_notifications(
31        &self,
32        options: SQLNotificationOptions,
33    ) -> Result<(), NotificationSubscriptionError> {
34        let options = NotificationSubscriptionOptions {
35            max_active_subscriptions: 1,
36            max_channels: options.max_channels,
37            max_queued_notifications: options.max_queued_notifications,
38            max_queued_bytes: options.max_queued_bytes,
39            max_registry_entries_per_poll: options.max_registry_entries_per_poll,
40        };
41        options.validate()?;
42        let _statement = self
43            .runtime
44            .statement_gate
45            .lock_with_cancellation(&self.runtime.cancellation)
46            .map_err(|error| {
47                NotificationSubscriptionError::with_source(
48                    NotificationFailureKind::Cancelled,
49                    error,
50                )
51            })?;
52        let mut selected = self.runtime.bounded_sql_notifications.lock();
53        if selected.is_some()
54            || self.transaction_depth() != 0
55            || !self.listening_channels().is_empty()
56            || !self.runtime.notifications.lock().is_empty()
57        {
58            return Err(NotificationSubscriptionError::new(
59                NotificationFailureKind::InvalidRequest,
60            ));
61        }
62        let mut bytes = [0_u8; 16];
63        getrandom::fill(&mut bytes).map_err(|error| {
64            NotificationSubscriptionError::with_source(
65                NotificationFailureKind::SourceUnavailable,
66                std::io::Error::other(error.to_string()),
67            )
68        })?;
69        bytes[6] = (bytes[6] & 0x0f) | 0x40;
70        bytes[8] = (bytes[8] & 0x3f) | 0x80;
71        *selected = Some(SubscriptionInbox::new(
72            NotificationIdentity {
73                epoch: NotificationEpoch::from_bytes(bytes).expect("set UUID version and variant"),
74                request_id: None,
75            },
76            options,
77        ));
78        Ok(())
79    }
80
81    /// Synchronize committed messages and atomically drain the same SQL session's inbox.
82    /// Transactional LISTEN, UNLISTEN, NOTIFY and savepoint semantics remain unchanged.
83    /// An overflow or source failure remains terminal; no lost message is called success.
84    pub fn try_take_sql_notifications(&self) -> Result<Vec<SQLNotification>, SQLError> {
85        if self.transaction_depth() != 0 {
86            return Ok(Vec::new());
87        }
88        self.poll_sql_notifications()?;
89        let bounded = self.runtime.bounded_sql_notifications.lock().clone();
90        if let Some(inbox) = bounded {
91            return inbox.take_sql().map_err(|error| sql_failure(&error));
92        }
93        Ok(self.runtime.notifications.lock().drain(..).collect())
94    }
95
96    /// Receive one event from a configured bounded SQL LISTEN inbox, admitting its destination
97    /// before dequeue. The ordinary SQL transaction deferral and cross-process synchronization
98    /// remain native. `prepare` follows `NotificationSubscription::poll_with`'s no-reentry contract.
99    /// A source failure remains terminal in this inbox; admission failures do not consume it.
100    pub fn try_take_sql_notification_with<T, E>(
101        &self,
102        prepare: impl FnOnce(&SQLNotification) -> Result<T, E>,
103    ) -> Result<super::NotificationReceive<T>, E>
104    where
105        E: From<NotificationSubscriptionError>,
106    {
107        let inbox = self
108            .runtime
109            .bounded_sql_notifications
110            .lock()
111            .clone()
112            .ok_or_else(|| {
113                NotificationSubscriptionError::new(NotificationFailureKind::InvalidRequest)
114            })?;
115        if self.transaction_depth() != 0 {
116            return Ok(super::NotificationReceive::TimedOut);
117        }
118        // Preserve a previously retained source/overflow failure before performing more I/O.
119        inbox.pending_count()?;
120        if let Err(error) = self.poll_sql_notifications() {
121            // Synchronization may already have installed the original structured failure.
122            inbox.pending_count()?;
123            let failure = NotificationSubscriptionError::with_source(
124                NotificationFailureKind::SourceUnavailable,
125                error,
126            );
127            inbox.fail(failure.clone());
128            return Err(failure.into());
129        }
130        inbox.poll_with(prepare)
131    }
132
133    pub(super) fn validate_sql_notification_channels(
134        &self,
135        channels: &[String],
136    ) -> Result<(), SQLError> {
137        if self
138            .runtime
139            .bounded_sql_notifications
140            .lock()
141            .as_ref()
142            .is_some_and(|inbox| channels.len() > inbox.options.max_channels)
143        {
144            return Err(SQLError::Routine {
145                sqlstate: "54000".into(),
146                message: "SQL notification channel limit exceeded".into(),
147            });
148        }
149        Ok(())
150    }
151}
152
153pub(super) fn sql_failure(error: &NotificationSubscriptionError) -> SQLError {
154    SQLError::Internal(error.code().into())
155}
156
157impl SubscriptionInbox {
158    pub(in crate::notifications) fn pending_count(
159        &self,
160    ) -> Result<usize, NotificationSubscriptionError> {
161        let state = self.state.lock();
162        if let Some(error) = &state.failure {
163            return Err(error.clone());
164        }
165        Ok(state.queue.len())
166    }
167    pub(in crate::notifications) fn take_sql(
168        &self,
169    ) -> Result<Vec<SQLNotification>, NotificationSubscriptionError> {
170        let mut state = self.state.lock();
171        if let Some(error) = &state.failure {
172            return Err(error.clone());
173        }
174        let mut result = Vec::with_capacity(state.queue.len());
175        while let Some(value) = state.queue.pop_front() {
176            result.push(value.value);
177        }
178        Ok(result)
179    }
180    pub(in crate::notifications) fn wait_ready(
181        &self,
182        timeout: std::time::Duration,
183    ) -> Result<bool, NotificationSubscriptionError> {
184        let started = std::time::Instant::now();
185        let mut state = self.state.lock();
186        loop {
187            if let Some(error) = &state.failure {
188                return Err(error.clone());
189            }
190            if !state.queue.is_empty() {
191                return Ok(true);
192            }
193            if state.closed {
194                return Ok(false);
195            }
196            let remaining = timeout.saturating_sub(started.elapsed());
197            if remaining.is_zero() {
198                return Ok(false);
199            }
200            #[cfg(test)]
201            if let Some(started) = self.sql_wait_started.lock().take() {
202                let _ = started.send(());
203            }
204            self.wake.wait_for(&mut state, remaining);
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212    use std::{sync::Arc, time::Duration};
213
214    #[test]
215    fn admitted_sql_receive_keeps_deferred_delivery_and_failed_destination() {
216        use super::super::NotificationReceive;
217        use uqa_core::notifications::NotificationEvent;
218        let engine = Engine::new();
219        engine
220            .configure_sql_notifications(SQLNotificationOptions {
221                max_channels: 1,
222                max_queued_notifications: 2,
223                max_queued_bytes: 4096,
224                max_registry_entries_per_poll: 2,
225            })
226            .unwrap();
227        engine
228            .sql("LISTEN events; BEGIN; NOTIFY events, 'committed'", &[])
229            .unwrap();
230        assert!(matches!(
231            engine.try_take_sql_notification_with::<(), NotificationSubscriptionError>(|_| panic!(
232                "transaction defers delivery"
233            )),
234            Ok(NotificationReceive::TimedOut)
235        ));
236        engine.sql("COMMIT", &[]).unwrap();
237        assert_eq!(
238            engine
239                .try_take_sql_notification_with::<(), _>(|_| {
240                    Err(NotificationSubscriptionError::new(
241                        NotificationFailureKind::Capacity,
242                    ))
243                })
244                .unwrap_err()
245                .kind(),
246            NotificationFailureKind::Capacity
247        );
248        let NotificationReceive::Event {
249            event:
250                NotificationEvent::Notification {
251                    sequence,
252                    notification,
253                    ..
254                },
255            ..
256        } = engine
257            .try_take_sql_notification_with(|_| Ok::<_, NotificationSubscriptionError>(()))
258            .unwrap()
259        else {
260            panic!("original notification")
261        };
262        assert_eq!(sequence, 1);
263        assert_eq!(notification.payload, "committed");
264        engine
265            .sql("BEGIN; NOTIFY events, 'abandoned'; ROLLBACK", &[])
266            .unwrap();
267        assert!(matches!(
268            engine.try_take_sql_notification_with::<(), NotificationSubscriptionError>(|_| panic!(
269                "rollback removes delivery"
270            )),
271            Ok(NotificationReceive::TimedOut)
272        ));
273        engine
274            .sql(
275                "NOTIFY events, 'one'; NOTIFY events, 'two'; NOTIFY events, 'overflow'",
276                &[],
277            )
278            .unwrap();
279        for _ in 0..2 {
280            assert_eq!(
281                engine
282                    .try_take_sql_notification_with::<(), NotificationSubscriptionError>(
283                        |_| panic!("terminal error precedes admission")
284                    )
285                    .unwrap_err()
286                    .kind(),
287                NotificationFailureKind::Backpressure
288            );
289        }
290    }
291
292    #[test]
293    fn sql_wait_releases_configuration_ownership_before_parking_the_inbox() {
294        let engine = Arc::new(Engine::new());
295        engine
296            .configure_sql_notifications(SQLNotificationOptions {
297                max_channels: 1,
298                max_queued_notifications: 2,
299                max_queued_bytes: 65_536,
300                max_registry_entries_per_poll: 2,
301            })
302            .unwrap();
303        engine.sql("LISTEN events", &[]).unwrap();
304        let inbox = engine
305            .runtime
306            .bounded_sql_notifications
307            .lock()
308            .clone()
309            .unwrap();
310        let (started, boundary) = std::sync::mpsc::channel();
311        *inbox.sql_wait_started.lock() = Some(started);
312        let waiting = engine.clone();
313        let task =
314            std::thread::spawn(move || waiting.wait_for_sql_notifications(Duration::from_secs(15)));
315        boundary.recv_timeout(Duration::from_secs(15)).unwrap();
316        let released = engine
317            .runtime
318            .bounded_sql_notifications
319            .try_lock()
320            .is_some();
321        if !released {
322            inbox.close();
323            let _ = task.join();
324            panic!("notification wait retained the configuration lock");
325        }
326        engine.sql("NOTIFY events, 'ready'", &[]).unwrap();
327        assert!(task.join().unwrap().unwrap());
328        assert_eq!(
329            engine.try_take_sql_notifications().unwrap()[0].payload,
330            "ready"
331        );
332    }
333}