Skip to main content

uqa_execution/row_locks/
change_gate.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Scoped row-change snapshot and publication gates.
8
9use super::{
10    change_gate_claim, ByteClaim, CrossAttachment, Duration, Instant, RowChangeBaseline,
11    RowLockManager, RwLockReadGuard, RwLockWriteGuard, SQLError, CHANGE_GATE_SESSION,
12    CHANGE_GATE_WAIT_LIMIT, WAIT_SLICE,
13};
14
15pub struct RowChangeSnapshot<'manager> {
16    manager: &'manager RowLockManager,
17    cross_claim: Option<ByteClaim>,
18    _local: RwLockReadGuard<'manager, ()>,
19}
20
21/// Serializes writers' final preparation without preventing readers from pinning committed snapshots.
22pub struct RowChangePreparation<'manager> {
23    manager: &'manager RowLockManager,
24    cross_claim: Option<ByteClaim>,
25    _local: RwLockWriteGuard<'manager, ()>,
26}
27
28pub struct RowChangePublication<'manager> {
29    manager: &'manager RowLockManager,
30    cross_claim: Option<ByteClaim>,
31    _local: RwLockWriteGuard<'manager, ()>,
32}
33
34impl RowChangeSnapshot<'_> {
35    pub fn baseline(&self) -> Result<RowChangeBaseline, SQLError> {
36        let epoch = self.manager.current_change_epoch();
37        let (cross_sequence, retention) = match self.manager.cross.as_ref() {
38            Some(CrossAttachment::Active(coordinator)) => {
39                let (sequence, lease) = coordinator
40                    .pin_change_sequence()
41                    .map_err(SQLError::Internal)?;
42                (sequence, Some(lease))
43            }
44            _ => (0, None),
45        };
46        Ok(RowChangeBaseline {
47            epoch,
48            cross_sequence,
49            _retention: retention,
50            _manager: self.manager.baseline_owner.upgrade(),
51        })
52    }
53}
54
55impl Drop for RowChangeSnapshot<'_> {
56    fn drop(&mut self) {
57        if let (Some(CrossAttachment::Active(coordinator)), Some(claim)) =
58            (self.manager.cross.as_ref(), self.cross_claim)
59        {
60            coordinator.release(CHANGE_GATE_SESSION, &[claim]);
61        }
62    }
63}
64
65impl Drop for RowChangePreparation<'_> {
66    fn drop(&mut self) {
67        if let (Some(CrossAttachment::Active(coordinator)), Some(claim)) =
68            (self.manager.cross.as_ref(), self.cross_claim)
69        {
70            coordinator.release(CHANGE_GATE_SESSION, &[claim]);
71        }
72    }
73}
74
75impl Drop for RowChangePublication<'_> {
76    fn drop(&mut self) {
77        if let (Some(CrossAttachment::Active(coordinator)), Some(claim)) =
78            (self.manager.cross.as_ref(), self.cross_claim)
79        {
80            coordinator.release(CHANGE_GATE_SESSION, &[claim]);
81        }
82    }
83}
84
85impl RowLockManager {
86    fn acquire_change_gate_claim(
87        &self,
88        claim: ByteClaim,
89        cancel: &uqa_core::CancellationToken,
90        deadline: Instant,
91    ) -> Result<Option<ByteClaim>, SQLError> {
92        let Some(CrossAttachment::Active(coordinator)) = self.cross.as_ref() else {
93            return Ok(None);
94        };
95        loop {
96            cancel.check()?;
97            if let Ok(()) = coordinator
98                .try_claim(CHANGE_GATE_SESSION, &[claim])
99                .map_err(SQLError::Internal)?
100            {
101                return Ok(Some(claim));
102            }
103            if Instant::now() >= deadline {
104                return Err(change_gate_timeout());
105            }
106            std::thread::sleep(Duration::from_millis(1));
107        }
108    }
109
110    /// Serialize writer preparation through final publication. Snapshot readers do not acquire this guard. Acquire it before the snapshot/publication gate and release it after metadata publication.
111    pub fn begin_change_preparation(
112        &self,
113        cancel: &uqa_core::CancellationToken,
114    ) -> Result<RowChangePreparation<'_>, SQLError> {
115        let deadline = Instant::now() + CHANGE_GATE_WAIT_LIMIT;
116        let local = loop {
117            cancel.check()?;
118            let remaining = deadline.saturating_duration_since(Instant::now());
119            if remaining.is_zero() {
120                return Err(change_gate_timeout());
121            }
122            if let Some(local) = self
123                .change_preparation
124                .try_write_for(remaining.min(WAIT_SLICE))
125            {
126                break local;
127            }
128        };
129        let cross_claim = self.acquire_change_gate_claim(
130            super::cross_process::change_preparation_claim(),
131            cancel,
132            deadline,
133        )?;
134        Ok(RowChangePreparation {
135            manager: self,
136            cross_claim,
137            _local: local,
138        })
139    }
140
141    /// Hold the shared commit/snapshot gate while a storage snapshot is pinned and its row-change baseline is captured.
142    pub fn begin_change_snapshot(
143        &self,
144        cancel: &uqa_core::CancellationToken,
145    ) -> Result<RowChangeSnapshot<'_>, SQLError> {
146        let deadline = Instant::now() + CHANGE_GATE_WAIT_LIMIT;
147        let local = loop {
148            cancel.check()?;
149            let remaining = deadline.saturating_duration_since(Instant::now());
150            if remaining.is_zero() {
151                return Err(change_gate_timeout());
152            }
153            if let Some(local) = self.change_gate.try_read_for(remaining.min(WAIT_SLICE)) {
154                break local;
155            }
156        };
157        let cross_claim =
158            self.acquire_change_gate_claim(change_gate_claim(false), cancel, deadline)?;
159        Ok(RowChangeSnapshot {
160            manager: self,
161            cross_claim,
162            _local: local,
163        })
164    }
165
166    /// Hold the exclusive commit/snapshot gate from immediately before the backend commit through publication of its row-change metadata.
167    pub fn begin_change_publication(
168        &self,
169        cancel: &uqa_core::CancellationToken,
170    ) -> Result<RowChangePublication<'_>, SQLError> {
171        let deadline = Instant::now() + CHANGE_GATE_WAIT_LIMIT;
172        let local = loop {
173            cancel.check()?;
174            let remaining = deadline.saturating_duration_since(Instant::now());
175            if remaining.is_zero() {
176                return Err(change_gate_timeout());
177            }
178            if let Some(local) = self.change_gate.try_write_for(remaining.min(WAIT_SLICE)) {
179                break local;
180            }
181        };
182        let cross_claim =
183            self.acquire_change_gate_claim(change_gate_claim(true), cancel, deadline)?;
184        Ok(RowChangePublication {
185            manager: self,
186            cross_claim,
187            _local: local,
188        })
189    }
190}
191
192pub(super) fn change_gate_timeout() -> SQLError {
193    SQLError::Routine {
194        sqlstate: "55P03".into(),
195        message: format!(
196            "timed out after {} seconds waiting for cross-process row-change coordination",
197            CHANGE_GATE_WAIT_LIMIT.as_secs()
198        ),
199    }
200}