Skip to main content

uqa_storage_sqlite/notifications/
scan.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Finite, borrowed registry reads with consumer-owned retention and cancellation.
8
9use std::{num::NonZeroUsize, ops::ControlFlow};
10
11use uqa_storage::{
12    notifications::{NotificationQueueEntryRef, NotificationQueueScan},
13    read_control::StorageReadControl,
14    StorageBackendResult,
15};
16
17use super::control;
18
19use super::{nonnegative_u64, registry_error, sqlite_integer, NotificationRegistryTransaction};
20
21impl NotificationRegistryTransaction {
22    /// Visit at most `max_entries` ordered rows without materializing their strings or a result vector. The consumer must admit any copies under its own queue limits before retaining them. Existing `SQLite` connection/cache memory remains owned by the registry.
23    ///
24    /// `Continue` accepts the current row and advances the returned resume boundary; `Break` declines it and stops without advancing past it. `visited` includes a declined row. This method never changes a listener cursor or commits a transaction. Consumer errors and cancellation stop the scan; an error grants no cursor advancement.
25    pub fn visit_entries_from(
26        &self,
27        from_sequence: u64,
28        max_entries: NonZeroUsize,
29        control: &StorageReadControl,
30        visit: &mut dyn FnMut(
31            NotificationQueueEntryRef<'_>,
32        ) -> StorageBackendResult<ControlFlow<()>>,
33    ) -> StorageBackendResult<NotificationQueueScan> {
34        let _operation =
35            control::operation_with(&self.connection, self.control.as_ref(), Some(control))?;
36        control.check()?;
37        let mut statement = self
38            .connection
39            .prepare_cached(
40                "SELECT sequence, process_id, channel, payload FROM queue_entries WHERE sequence >= ?1 ORDER BY sequence LIMIT ?2",
41            )
42            .map_err(|error| registry_error("prepare queue scan", &error))?;
43        let mut rows = statement
44            .query(rusqlite::params![
45                sqlite_integer(from_sequence, "scan sequence")?,
46                i64::try_from(max_entries.get()).unwrap_or(i64::MAX),
47            ])
48            .map_err(|error| registry_error("scan queue entries", &error))?;
49        let mut progress = NotificationQueueScan {
50            visited: 0,
51            next_sequence: from_sequence,
52            exhausted: false,
53        };
54        while progress.visited < max_entries.get() {
55            control.check()?;
56            let Some(row) = rows
57                .next()
58                .map_err(|error| registry_error("read queue entry", &error))?
59            else {
60                control.check()?;
61                progress.exhausted = true;
62                return Ok(progress);
63            };
64            let entry = read_entry(row)?;
65            control.check()?;
66            progress.visited += 1;
67            let accepted = visit(entry)?;
68            control.check()?;
69            if accepted.is_break() {
70                return Ok(progress);
71            }
72            // SQLite INTEGER bounds make this addition safe without saturating or skipping a value.
73            progress.next_sequence = entry.sequence + 1;
74        }
75        Ok(progress)
76    }
77}
78
79fn read_entry<'row>(
80    row: &'row rusqlite::Row<'_>,
81) -> StorageBackendResult<NotificationQueueEntryRef<'row>> {
82    let sequence = row
83        .get::<_, i64>(0)
84        .map_err(|error| registry_error("read queue entry sequence", &error))?;
85    let process_id = row
86        .get(1)
87        .map_err(|error| registry_error("read queue entry process identifier", &error))?;
88    let channel = row
89        .get_ref(2)
90        .and_then(|value| value.as_str().map_err(rusqlite::Error::from))
91        .map_err(|error| registry_error("read queue entry channel", &error))?;
92    let payload = row
93        .get_ref(3)
94        .and_then(|value| value.as_str().map_err(rusqlite::Error::from))
95        .map_err(|error| registry_error("read queue entry payload", &error))?;
96    Ok(NotificationQueueEntryRef {
97        sequence: nonnegative_u64(sequence, "entry sequence")?,
98        process_id,
99        channel,
100        payload,
101    })
102}