| 1 | use crate::approval_log::ApprovalReceipt; |
| 2 | use anyhow::{Context as _, Result, bail}; |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | #[derive(Clone)] |
| 6 | pub struct NativeApprovalPublication(Arc<PublicationState>); |
| 7 | |
| 8 | struct PublicationState { |
| 9 | tool_id: String, |
| 10 | state: parking_lot::Mutex<PublicationValue>, |
| 11 | changed: tokio::sync::watch::Sender<u64>, |
| 12 | } |
| 13 | |
| 14 | #[derive(Default)] |
| 15 | struct PublicationValue { |
| 16 | bound: bool, |
| 17 | timeout: Option<std::time::Duration>, |
| 18 | receipt: Option<Result<ApprovalReceipt, String>>, |
| 19 | publication: Option<Result<(), String>>, |
| 20 | #[cfg(any(test, feature = "test-support"))] |
| 21 | mock_controls: Option<( |
| 22 | tokio_util::sync::CancellationToken, |
| 23 | Option<tokio::time::Instant>, |
| 24 | )>, |
| 25 | } |
| 26 | |
| 27 | pub(crate) struct ApprovalProducer { |
| 28 | source: NativeApprovalPublication, |
| 29 | current: Option<Arc<parking_lot::Mutex<Option<NativeApprovalPublication>>>>, |
| 30 | } |
| 31 | |
| 32 | pub(crate) struct ApprovalPublicationBinding { |
| 33 | source: NativeApprovalPublication, |
| 34 | } |
| 35 | |
| 36 | impl std::fmt::Debug for NativeApprovalPublication { |
| 37 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 38 | formatter.write_str("NativeApprovalPublication(held Core approval)") |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl NativeApprovalPublication { |
| 43 | pub(crate) fn new(tool_id: &str) -> (Self, ApprovalProducer) { |
| 44 | let (changed, _) = tokio::sync::watch::channel(0); |
| 45 | let source = Self(Arc::new(PublicationState { |
| 46 | tool_id: tool_id.to_owned(), |
| 47 | state: parking_lot::Mutex::new(PublicationValue::default()), |
| 48 | changed, |
| 49 | })); |
| 50 | let producer = ApprovalProducer { |
| 51 | source: source.clone(), |
| 52 | current: None, |
| 53 | }; |
| 54 | (source, producer) |
| 55 | } |
| 56 | |
| 57 | pub(crate) fn same_request(&self, other: &Self) -> bool { |
| 58 | Arc::ptr_eq(&self.0, &other.0) |
| 59 | } |
| 60 | |
| 61 | pub(crate) fn is_for(&self, tool_id: &str) -> bool { |
| 62 | self.0.tool_id == tool_id |
| 63 | } |
| 64 | |
| 65 | pub(crate) fn bind(&self, tool_id: &str) -> Result<ApprovalPublicationBinding> { |
| 66 | anyhow::ensure!( |
| 67 | self.0.tool_id == tool_id, |
| 68 | "Core approval source identity changed" |
| 69 | ); |
| 70 | let mut state = self.0.state.lock(); |
| 71 | anyhow::ensure!( |
| 72 | !state.bound, |
| 73 | "Core approval already has its publication owner" |
| 74 | ); |
| 75 | anyhow::ensure!( |
| 76 | match state.receipt.as_ref() { |
| 77 | None => true, |
| 78 | Some(Ok(ApprovalReceipt::Decided { outcome, .. })) => matches!( |
| 79 | outcome, |
| 80 | crate::approval_log::ApprovalOutcome::Denied |
| 81 | | crate::approval_log::ApprovalOutcome::Timeout |
| 82 | | crate::approval_log::ApprovalOutcome::Cancelled |
| 83 | | crate::approval_log::ApprovalOutcome::Unavailable |
| 84 | ), |
| 85 | _ => false, |
| 86 | }, |
| 87 | "Core approval already settled before publication binding" |
| 88 | ); |
| 89 | state.bound = true; |
| 90 | Ok(ApprovalPublicationBinding { |
| 91 | source: self.clone(), |
| 92 | }) |
| 93 | } |
| 94 | |
| 95 | pub(crate) fn set_timeout(&self, timeout: Option<std::time::Duration>) { |
| 96 | self.0.state.lock().timeout = timeout; |
| 97 | } |
| 98 | |
| 99 | pub(crate) fn timeout_seconds(&self) -> Option<u64> { |
| 100 | self.0.state.lock().timeout.map(|timeout| timeout.as_secs()) |
| 101 | } |
| 102 | |
| 103 | fn changed(&self) { |
| 104 | self.0 |
| 105 | .changed |
| 106 | .send_modify(|epoch| *epoch = epoch.saturating_add(1)); |
| 107 | } |
| 108 | |
| 109 | pub(crate) async fn actual(&self) -> Result<ApprovalReceipt> { |
| 110 | let mut changed = self.0.changed.subscribe(); |
| 111 | loop { |
| 112 | if let Some(receipt) = self.0.state.lock().receipt.clone() { |
| 113 | return receipt.map_err(anyhow::Error::msg); |
| 114 | } |
| 115 | changed |
| 116 | .changed() |
| 117 | .await |
| 118 | .context("Core approval outcome channel closed")?; |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub(crate) async fn published(&self) -> Result<ApprovalReceipt> { |
| 123 | let mut changed = self.0.changed.subscribe(); |
| 124 | loop { |
| 125 | let (receipt, publication, bound) = { |
| 126 | let state = self.0.state.lock(); |
| 127 | ( |
| 128 | state.receipt.clone(), |
| 129 | state.publication.clone(), |
| 130 | state.bound, |
| 131 | ) |
| 132 | }; |
| 133 | if let Some(Err(error)) = receipt.as_ref() { |
| 134 | bail!("Core approval outcome is unconfirmed: {error}"); |
| 135 | } |
| 136 | if let Some(Err(error)) = publication.as_ref() { |
| 137 | bail!("Core approval publication is unconfirmed: {error}"); |
| 138 | } |
| 139 | if let Some(receipt) = receipt { |
| 140 | let receipt = receipt.map_err(anyhow::Error::msg)?; |
| 141 | if !bound || matches!(publication, Some(Ok(()))) { |
| 142 | return Ok(receipt); |
| 143 | } |
| 144 | } |
| 145 | changed |
| 146 | .changed() |
| 147 | .await |
| 148 | .context("Core approval publication channel closed")?; |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | pub(crate) async fn commit(&self, receipt: ApprovalReceipt) -> Result<()> { |
| 153 | anyhow::ensure!( |
| 154 | receipt.approval_id() == self.0.tool_id, |
| 155 | "Core approval receipt identity changed" |
| 156 | ); |
| 157 | { |
| 158 | let mut state = self.0.state.lock(); |
| 159 | anyhow::ensure!( |
| 160 | state.receipt.is_none(), |
| 161 | "Core approval already has its winning receipt" |
| 162 | ); |
| 163 | state.receipt = Some(Ok(receipt)); |
| 164 | } |
| 165 | self.changed(); |
| 166 | self.published().await?; |
| 167 | Ok(()) |
| 168 | } |
| 169 | |
| 170 | #[cfg(any(test, feature = "test-support"))] |
| 171 | pub(crate) fn set_mock_controls( |
| 172 | &self, |
| 173 | cancel: tokio_util::sync::CancellationToken, |
| 174 | timeout: Option<std::time::Duration>, |
| 175 | ) { |
| 176 | let mut state = self.0.state.lock(); |
| 177 | state.timeout = timeout; |
| 178 | state.mock_controls = Some(( |
| 179 | cancel, |
| 180 | timeout.map(|timeout| tokio::time::Instant::now() + timeout), |
| 181 | )); |
| 182 | } |
| 183 | |
| 184 | #[cfg(any(test, feature = "test-support"))] |
| 185 | pub(crate) fn commit_mock_outcome(&self, receipt: ApprovalReceipt) -> Result<bool> { |
| 186 | anyhow::ensure!( |
| 187 | receipt.approval_id() == self.0.tool_id, |
| 188 | "mock Core approval identity changed" |
| 189 | ); |
| 190 | let mut state = self.0.state.lock(); |
| 191 | if state.receipt.is_some() { |
| 192 | return Ok(false); |
| 193 | } |
| 194 | let receipt = match state.mock_controls.as_ref() { |
| 195 | Some((cancel, _)) if cancel.is_cancelled() => { |
| 196 | crate::approval_log::ApprovalReceipt::decided_with( |
| 197 | &self.0.tool_id, |
| 198 | crate::approval_log::ApprovalOutcome::Cancelled, |
| 199 | Some(crate::approval_log::ApprovalDecider::Host), |
| 200 | ) |
| 201 | } |
| 202 | Some((_, Some(deadline))) if tokio::time::Instant::now() >= *deadline => { |
| 203 | crate::approval_log::ApprovalReceipt::decided_with( |
| 204 | &self.0.tool_id, |
| 205 | crate::approval_log::ApprovalOutcome::Timeout, |
| 206 | None, |
| 207 | ) |
| 208 | } |
| 209 | _ => receipt, |
| 210 | }; |
| 211 | state.receipt = Some(Ok(receipt)); |
| 212 | drop(state); |
| 213 | self.changed(); |
| 214 | Ok(true) |
| 215 | } |
| 216 | |
| 217 | pub(crate) fn acknowledge(&self, result: Result<(), String>) -> Result<()> { |
| 218 | let mut state = self.0.state.lock(); |
| 219 | if result.is_ok() { |
| 220 | anyhow::ensure!( |
| 221 | matches!(state.receipt.as_ref(), Some(Ok(_))), |
| 222 | "Core approval receipt is not committed" |
| 223 | ); |
| 224 | } |
| 225 | if let Some(previous) = state.publication.as_ref() { |
| 226 | return previous.clone().map_err(anyhow::Error::msg); |
| 227 | } |
| 228 | state.publication = Some(result); |
| 229 | drop(state); |
| 230 | self.changed(); |
| 231 | Ok(()) |
| 232 | } |
| 233 | |
| 234 | pub(crate) fn fail_native(&self, error: String) { |
| 235 | let mut state = self.0.state.lock(); |
| 236 | if state.receipt.is_none() { |
| 237 | state.receipt = Some(Err(error)); |
| 238 | } |
| 239 | drop(state); |
| 240 | self.changed(); |
| 241 | } |
| 242 | |
| 243 | fn close(&self) { |
| 244 | let mut state = self.0.state.lock(); |
| 245 | if state.receipt.is_none() { |
| 246 | state.receipt = Some(Err( |
| 247 | "Core approval ended without a confirmed durable outcome".into(), |
| 248 | )); |
| 249 | } |
| 250 | if state.bound && state.publication.is_none() { |
| 251 | state.publication = Some(Err( |
| 252 | "Core approval publication owner ended before acknowledgement".into(), |
| 253 | )); |
| 254 | } |
| 255 | drop(state); |
| 256 | self.changed(); |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | impl ApprovalProducer { |
| 261 | pub(crate) fn install( |
| 262 | &mut self, |
| 263 | current: Arc<parking_lot::Mutex<Option<NativeApprovalPublication>>>, |
| 264 | ) -> Result<()> { |
| 265 | let mut slot = current.lock(); |
| 266 | anyhow::ensure!(slot.is_none(), "Core already has a current approval waiter"); |
| 267 | *slot = Some(self.source.clone()); |
| 268 | drop(slot); |
| 269 | self.current = Some(current); |
| 270 | Ok(()) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | impl Drop for ApprovalProducer { |
| 275 | fn drop(&mut self) { |
| 276 | self.source.close(); |
| 277 | if let Some(current) = self.current.as_ref() { |
| 278 | let mut slot = current.lock(); |
| 279 | if slot |
| 280 | .as_ref() |
| 281 | .is_some_and(|source| source.same_request(&self.source)) |
| 282 | { |
| 283 | *slot = None; |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | impl Drop for ApprovalPublicationBinding { |
| 290 | fn drop(&mut self) { |
| 291 | let _ = self.source.acknowledge(Err( |
| 292 | "Runtime approval projection ended before durable acknowledgement".into(), |
| 293 | )); |
| 294 | } |
| 295 | } |
| 296 |