uqa_execution/row_locks/
temporary_roles.rs1use super::{CrossAttachment, RowLockManager};
10use std::collections::BTreeSet;
11use uqa_core::CancellationToken;
12use uqa_sql::SQLError;
13
14#[cfg(test)]
15mod tests;
16
17pub(crate) const MAX_TEMPORARY_ROLE_REFERENCES: u32 = 8192;
18
19pub(super) fn reference_limit_error() -> SQLError {
20 SQLError::Routine {
21 sqlstate: "53200".into(),
22 message: "temporary role dependency capacity exhausted".into(),
23 }
24}
25
26pub struct TemporaryRolePublication<'a> {
27 manager: &'a RowLockManager,
28 session: u64,
29 before: BTreeSet<u32>,
30 after: Option<BTreeSet<u32>>,
31}
32
33impl TemporaryRolePublication<'_> {
34 pub fn commit(mut self) {
35 if let Some(after) = self.after.take() {
36 self.manager.finish_temporary_roles(self.session, after);
37 }
38 }
39}
40
41impl Drop for TemporaryRolePublication<'_> {
42 fn drop(&mut self) {
43 if self.after.is_some() {
44 self.manager
45 .finish_temporary_roles(self.session, std::mem::take(&mut self.before));
46 }
47 }
48}
49
50impl RowLockManager {
51 pub fn has_temporary_role_references(&self, session: u64) -> bool {
52 self.temporary_roles.lock().contains_key(&session)
53 }
54
55 pub fn prepare_temporary_roles<'a>(
56 &'a self,
57 session: u64,
58 roles: BTreeSet<u32>,
59 cancel: &CancellationToken,
60 ) -> Result<TemporaryRolePublication<'a>, SQLError> {
61 if roles.len() > MAX_TEMPORARY_ROLE_REFERENCES as usize {
62 return Err(reference_limit_error());
63 }
64 let mut state = self.temporary_roles.lock();
65 if state
66 .get(&session)
67 .is_some_and(|existing| *existing == roles)
68 || (roles.is_empty() && !state.contains_key(&session))
69 {
70 return Ok(TemporaryRolePublication {
71 manager: self,
72 session,
73 before: BTreeSet::new(),
74 after: None,
75 });
76 }
77 let before = state.get(&session).cloned().unwrap_or_default();
78 let additions = roles.difference(&before).copied().collect::<Vec<_>>();
79 let count = state.values().map(BTreeSet::len).sum::<usize>();
80 if count.saturating_add(additions.len()) > MAX_TEMPORARY_ROLE_REFERENCES as usize {
81 return Err(reference_limit_error());
82 }
83 match self.cross.as_ref() {
84 Some(CrossAttachment::Active(coordinator)) => {
85 for (index, role) in additions.iter().enumerate() {
86 if let Err(error) = coordinator.retain_temporary_role(session, *role, cancel) {
87 for added in &additions[..index] {
88 coordinator.release_temporary_role(session, *added);
89 }
90 return Err(error);
91 }
92 }
93 }
94 Some(CrossAttachment::Unavailable(reason)) => {
95 return Err(SQLError::Internal(format!(
96 "cross-process temporary role dependencies are unavailable: {reason}"
97 )))
98 }
99 None => cancel.check()?,
100 }
101 state.entry(session).or_default().extend(additions);
102 Ok(TemporaryRolePublication {
103 manager: self,
104 session,
105 before,
106 after: Some(roles),
107 })
108 }
109
110 fn finish_temporary_roles(&self, session: u64, roles: BTreeSet<u32>) {
111 let mut state = self.temporary_roles.lock();
112 if let Some(previous) = state.get(&session) {
113 if let Some(CrossAttachment::Active(coordinator)) = self.cross.as_ref() {
114 for removed in previous.difference(&roles) {
115 coordinator.release_temporary_role(session, *removed);
116 }
117 }
118 }
119 if roles.is_empty() {
120 state.remove(&session);
121 } else {
122 state.insert(session, roles);
123 }
124 }
125
126 pub fn close_temporary_roles(&self, session: u64) {
127 self.finish_temporary_roles(session, BTreeSet::new());
128 }
129
130 pub fn peer_temporary_role_reference(
131 &self,
132 session: u64,
133 role: u32,
134 cancel: &CancellationToken,
135 ) -> Result<bool, SQLError> {
136 if self
137 .temporary_roles
138 .lock()
139 .iter()
140 .any(|(owner, roles)| *owner != session && roles.contains(&role))
141 {
142 return Ok(true);
143 }
144 match self.cross.as_ref() {
145 Some(CrossAttachment::Active(coordinator)) => {
146 coordinator.foreign_temporary_role_reference(role, cancel)
147 }
148 Some(CrossAttachment::Unavailable(reason)) => Err(SQLError::Internal(format!(
149 "cross-process temporary role dependencies are unavailable: {reason}"
150 ))),
151 None => Ok(false),
152 }
153 }
154}