Skip to main content

uqa_storage_sqlite/
notifications.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Physical notification registry transactions and encrypted connection ownership.
8
9mod publication;
10mod reservations;
11mod schema;
12#[cfg(test)]
13mod tests;
14
15use crate::{ManagedConnection, SQLiteConnectionLease};
16use rusqlite::params;
17use std::{path::Path, time::Duration};
18use uqa_storage::{
19    notifications::{NotificationListenerRow, NotificationQueueEntry, NotificationQueueState},
20    StorageBackendError, StorageBackendResult, StorageEncryptionKey,
21};
22
23const REGISTRY_BUSY_TIMEOUT: Duration = Duration::from_secs(30);
24
25#[derive(Clone)]
26pub struct NotificationRegistry {
27    connection: ManagedConnection,
28}
29
30impl NotificationRegistry {
31    pub fn open(path: &Path, key: Option<&StorageEncryptionKey>) -> StorageBackendResult<Self> {
32        schema::open_registry(path, key)
33            .map(|connection| Self { connection })
34            .map_err(StorageBackendError::Other)
35    }
36
37    pub fn begin(&self) -> StorageBackendResult<NotificationRegistryTransaction> {
38        open_registry_transaction(&self.connection)
39    }
40}
41
42pub struct NotificationRegistryTransaction {
43    connection: SQLiteConnectionLease,
44    finished: bool,
45    poisoned: bool,
46    pending_acknowledgement: Option<[u8; 32]>,
47    preparing: bool,
48}
49
50impl NotificationRegistryTransaction {
51    pub const fn pending_acknowledgement(&self) -> Option<[u8; 32]> {
52        self.pending_acknowledgement
53    }
54
55    pub fn allocate_backend_process_id(&self) -> Result<i32, StorageBackendError> {
56        let next = self
57            .connection
58            .query_row(
59                "SELECT next_process_id FROM backend_process_id_state WHERE singleton = 1",
60                [],
61                |row| row.get::<_, i64>(0),
62            )
63            .map_err(|error| registry_error("load backend process identifier", &error))?;
64        let process_id = i32::try_from(next).map_err(|_| {
65            StorageBackendError::Other(
66                "exhausted positive cross-process backend process identifiers".into(),
67            )
68        })?;
69        if process_id <= 0 {
70            return Err(StorageBackendError::Other(format!(
71                "corrupt asynchronous notification backend process identifier {process_id}"
72            )));
73        }
74        self.connection
75            .execute(
76                "UPDATE backend_process_id_state SET next_process_id = ?1 WHERE singleton = 1",
77                params![next + 1],
78            )
79            .map_err(|error| registry_error("advance backend process identifier", &error))?;
80        Ok(process_id)
81    }
82
83    pub fn queue_state(&self) -> Result<NotificationQueueState, StorageBackendError> {
84        self.connection
85            .query_row(
86                "SELECT next_sequence, head_position FROM queue_state WHERE singleton = 1",
87                [],
88                |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)),
89            )
90            .map_err(|error| registry_error("load queue state", &error))
91            .and_then(|(next_sequence, head_position)| {
92                Ok(NotificationQueueState {
93                    next_sequence: nonnegative_u64(next_sequence, "queue sequence")?,
94                    head_position: nonnegative_u64(head_position, "queue position")?,
95                })
96            })
97    }
98
99    pub fn save_queue_state(
100        &self,
101        state: NotificationQueueState,
102    ) -> Result<(), StorageBackendError> {
103        self.connection
104            .execute(
105                "UPDATE queue_state SET next_sequence = ?1, head_position = ?2 WHERE singleton = 1",
106                params![
107                    sqlite_integer(state.next_sequence, "queue sequence")?,
108                    sqlite_integer(state.head_position, "queue position")?,
109                ],
110            )
111            .map_err(|error| registry_error("save queue state", &error))?;
112        Ok(())
113    }
114
115    pub fn append_entries(
116        &self,
117        entries: &[NotificationQueueEntry],
118    ) -> Result<(), StorageBackendError> {
119        let mut statement = self
120            .connection
121            .prepare_cached(
122                "INSERT INTO queue_entries (sequence, process_id, channel, payload) VALUES (?1, ?2, ?3, ?4)",
123            )
124            .map_err(|error| registry_error("prepare queue append", &error))?;
125        for entry in entries {
126            statement
127                .execute(params![
128                    sqlite_integer(entry.sequence, "entry sequence")?,
129                    entry.process_id,
130                    entry.channel,
131                    entry.payload,
132                ])
133                .map_err(|error| registry_error("append queue entry", &error))?;
134        }
135        Ok(())
136    }
137
138    pub fn entries_from(
139        &self,
140        from_sequence: u64,
141    ) -> Result<Vec<NotificationQueueEntry>, StorageBackendError> {
142        let mut statement = self
143            .connection
144            .prepare_cached(
145                "SELECT sequence, process_id, channel, payload FROM queue_entries WHERE sequence >= ?1 ORDER BY sequence",
146            )
147            .map_err(|error| registry_error("prepare queue scan", &error))?;
148        let rows = statement
149            .query_map(
150                params![sqlite_integer(from_sequence, "scan sequence")?],
151                |row| {
152                    Ok((
153                        row.get::<_, i64>(0)?,
154                        row.get::<_, i32>(1)?,
155                        row.get::<_, String>(2)?,
156                        row.get::<_, String>(3)?,
157                    ))
158                },
159            )
160            .map_err(|error| registry_error("scan queue entries", &error))?;
161        rows.map(|row| {
162            let (sequence, process_id, channel, payload) =
163                row.map_err(|error| registry_error("read queue entry", &error))?;
164            Ok(NotificationQueueEntry {
165                sequence: nonnegative_u64(sequence, "entry sequence")?,
166                process_id,
167                channel,
168                payload,
169            })
170        })
171        .collect()
172    }
173
174    pub fn delete_entries_before(&self, sequence: u64) -> Result<(), StorageBackendError> {
175        self.connection
176            .execute(
177                "DELETE FROM queue_entries WHERE sequence < ?1",
178                params![sqlite_integer(sequence, "cleanup sequence")?],
179            )
180            .map_err(|error| registry_error("clean queue entries", &error))?;
181        Ok(())
182    }
183
184    pub fn listeners(&self) -> Result<Vec<NotificationListenerRow>, StorageBackendError> {
185        let mut statement = self
186            .connection
187            .prepare_cached(
188                "SELECT owner_id, session_id, process_id, wake_port, channels_json, transaction_open, next_sequence, position FROM listeners ORDER BY owner_id, session_id",
189            )
190            .map_err(|error| registry_error("prepare listener scan", &error))?;
191        let rows = statement
192            .query_map([], |row| {
193                Ok((
194                    row.get::<_, Vec<u8>>(0)?,
195                    row.get::<_, Vec<u8>>(1)?,
196                    row.get::<_, i32>(2)?,
197                    row.get::<_, i64>(3)?,
198                    row.get::<_, String>(4)?,
199                    row.get::<_, bool>(5)?,
200                    row.get::<_, i64>(6)?,
201                    row.get::<_, i64>(7)?,
202                ))
203            })
204            .map_err(|error| registry_error("scan listeners", &error))?;
205        rows.map(|row| {
206            let (
207                owner_id,
208                session_id,
209                process_id,
210                wake_port,
211                channels_json,
212                transaction_open,
213                next_sequence,
214                position,
215            ) = row.map_err(|error| registry_error("read listener", &error))?;
216            Ok(NotificationListenerRow {
217                owner_id: fixed_bytes(owner_id, "owner identity")?,
218                session_id: u64::from_be_bytes(fixed_bytes(session_id, "session identity")?),
219                process_id,
220                wake_port: u16::try_from(wake_port).map_err(|_| {
221                    StorageBackendError::Other(format!(
222                        "corrupt asynchronous notification wake port {wake_port}"
223                    ))
224                })?,
225                channels: serde_json::from_str(&channels_json).map_err(|error| {
226                    StorageBackendError::Other(format!(
227                        "decode asynchronous notification listener channels: {error}"
228                    ))
229                })?,
230                transaction_open,
231                next_sequence: nonnegative_u64(next_sequence, "listener sequence")?,
232                position: nonnegative_u64(position, "listener position")?,
233            })
234        })
235        .collect()
236    }
237
238    pub fn save_listener(
239        &self,
240        listener: &NotificationListenerRow,
241    ) -> Result<(), StorageBackendError> {
242        let channels_json = serde_json::to_string(&listener.channels).map_err(|error| {
243            StorageBackendError::Other(format!(
244                "encode asynchronous notification listener channels: {error}"
245            ))
246        })?;
247        self.connection
248            .execute(
249                "INSERT INTO listeners (owner_id, session_id, process_id, wake_port, channels_json, transaction_open, next_sequence, position) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) ON CONFLICT(owner_id, session_id) DO UPDATE SET process_id = excluded.process_id, wake_port = excluded.wake_port, channels_json = excluded.channels_json, transaction_open = excluded.transaction_open, next_sequence = excluded.next_sequence, position = excluded.position",
250                params![
251                    listener.owner_id.as_slice(),
252                    listener.session_id.to_be_bytes().as_slice(),
253                    listener.process_id,
254                    i64::from(listener.wake_port),
255                    channels_json,
256                    listener.transaction_open,
257                    sqlite_integer(listener.next_sequence, "listener sequence")?,
258                    sqlite_integer(listener.position, "listener position")?,
259                ],
260            )
261            .map_err(|error| registry_error("save listener", &error))?;
262        Ok(())
263    }
264
265    pub fn drop_listener(
266        &self,
267        owner_id: [u8; 16],
268        session_id: u64,
269    ) -> Result<(), StorageBackendError> {
270        self.connection
271            .execute(
272                "DELETE FROM listeners WHERE owner_id = ?1 AND session_id = ?2",
273                params![owner_id.as_slice(), session_id.to_be_bytes().as_slice()],
274            )
275            .map_err(|error| registry_error("remove listener", &error))?;
276        Ok(())
277    }
278
279    pub fn commit(mut self) -> Result<(), StorageBackendError> {
280        if self.poisoned {
281            return Err(StorageBackendError::Other(
282                "cannot commit notification registry after failed publication rollback".into(),
283            ));
284        }
285        self.connection
286            .execute_batch("COMMIT")
287            .map_err(|error| registry_error("commit registry transaction", &error))?;
288        self.finished = true;
289        Ok(())
290    }
291}
292
293impl Drop for NotificationRegistryTransaction {
294    fn drop(&mut self) {
295        if !self.finished {
296            let _ = self.connection.execute_batch("ROLLBACK");
297        }
298    }
299}
300
301fn registry_error(action: &str, error: &rusqlite::Error) -> StorageBackendError {
302    StorageBackendError::Other(format!(
303        "{action} in asynchronous notification registry: {error}"
304    ))
305}
306
307fn open_registry_transaction(
308    registry: &ManagedConnection,
309) -> Result<NotificationRegistryTransaction, StorageBackendError> {
310    let connection = registry.lease_connection().map_err(|error| {
311        StorageBackendError::Other(format!(
312            "lease asynchronous notification registry connection: {error}"
313        ))
314    })?;
315    schema::register_writer(&connection).map_err(StorageBackendError::Other)?;
316    connection
317        .busy_timeout(REGISTRY_BUSY_TIMEOUT)
318        .map_err(|error| registry_error("set registry busy timeout", &error))?;
319    connection
320        .pragma_update(None, "secure_delete", true)
321        .map_err(|error| registry_error("enable registry secure deletion", &error))?;
322    connection
323        .execute_batch("BEGIN IMMEDIATE")
324        .map_err(|error| registry_error("begin registry transaction", &error))?;
325    let transaction = NotificationRegistryTransaction {
326        connection,
327        finished: false,
328        poisoned: false,
329        pending_acknowledgement: None,
330        preparing: false,
331    };
332    schema::validate_writer(&transaction.connection).map_err(StorageBackendError::Other)?;
333    Ok(transaction)
334}
335
336fn sqlite_integer(value: u64, label: &str) -> Result<i64, StorageBackendError> {
337    i64::try_from(value).map_err(|_| {
338        StorageBackendError::Other(format!(
339            "asynchronous notification {label} {value} exceeds SQLite INTEGER"
340        ))
341    })
342}
343
344fn nonnegative_u64(value: i64, label: &str) -> Result<u64, StorageBackendError> {
345    u64::try_from(value).map_err(|_| {
346        StorageBackendError::Other(format!("corrupt asynchronous notification {label} {value}"))
347    })
348}
349
350fn fixed_bytes<const N: usize>(
351    bytes: Vec<u8>,
352    label: &str,
353) -> Result<[u8; N], StorageBackendError> {
354    let length = bytes.len();
355    bytes.try_into().map_err(|_| {
356        StorageBackendError::Other(format!(
357            "corrupt asynchronous notification {label} has {length} bytes"
358        ))
359    })
360}