| 1 | //! One process-wide publication gate for verified facts, status and reader generation. |
| 2 | //! Fetchers capture a settings ticket before work; stale settings cannot publish or |
| 3 | //! write their cache after a newer disable or source change has been admitted. |
| 4 | |
| 5 | use std::collections::BTreeMap; |
| 6 | use std::sync::{Arc, LazyLock, RwLock}; |
| 7 | |
| 8 | use super::provenance::{CloudFactsState, CloudFactsStatus}; |
| 9 | use super::registry::{AdmittedRegistry, REGISTRY_SCHEMA}; |
| 10 | use super::scope::ScopedFacts; |
| 11 | |
| 12 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 13 | pub struct OverlayTicket { |
| 14 | epoch: u64, |
| 15 | source_identity: String, |
| 16 | } |
| 17 | |
| 18 | #[derive(Debug, Clone, Default)] |
| 19 | pub struct OverlaySnapshot { |
| 20 | pub generation: u64, |
| 21 | pub fetched_at: Option<u64>, |
| 22 | pub facts: Option<Arc<ScopedFacts>>, |
| 23 | pub status: CloudFactsStatus, |
| 24 | } |
| 25 | |
| 26 | #[derive(Default)] |
| 27 | struct State { |
| 28 | epoch: u64, |
| 29 | enabled: bool, |
| 30 | source_identity: String, |
| 31 | highest_seen: BTreeMap<String, u64>, |
| 32 | snapshot: OverlaySnapshot, |
| 33 | registry: Option<Arc<AdmittedRegistry>>, |
| 34 | } |
| 35 | |
| 36 | static STATE: LazyLock<RwLock<State>> = LazyLock::new(|| RwLock::new(State::default())); |
| 37 | |
| 38 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 39 | pub enum DefaultSource { |
| 40 | Compiled, |
| 41 | CloudFacts { facts_version: u64 }, |
| 42 | } |
| 43 | |
| 44 | #[must_use] |
| 45 | pub fn hard_disabled() -> bool { |
| 46 | std::env::var("CODEWHALE_DISABLE_CLOUD_FACTS").is_ok_and(|value| { |
| 47 | matches!( |
| 48 | value.trim().to_ascii_lowercase().as_str(), |
| 49 | "1" | "true" | "yes" | "on" |
| 50 | ) |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | fn disable(state: &mut State) { |
| 55 | if state.enabled |
| 56 | || state.snapshot.facts.is_some() |
| 57 | || state.registry.is_some() |
| 58 | || state.snapshot.status.state != CloudFactsState::Off |
| 59 | { |
| 60 | state.epoch = state.epoch.saturating_add(1); |
| 61 | state.snapshot.generation = state.snapshot.generation.saturating_add(1); |
| 62 | } |
| 63 | state.enabled = false; |
| 64 | state.snapshot.facts = None; |
| 65 | state.snapshot.status = CloudFactsStatus::default(); |
| 66 | state.registry = None; |
| 67 | } |
| 68 | |
| 69 | fn admits(state: &mut State, ticket: &OverlayTicket) -> bool { |
| 70 | if hard_disabled() { |
| 71 | disable(state); |
| 72 | } |
| 73 | state.enabled && ticket.epoch == state.epoch && ticket.source_identity == state.source_identity |
| 74 | } |
| 75 | |
| 76 | /// Admit effective settings synchronously. Refreshes must use `current_ticket` |
| 77 | /// instead: an old settings object must never implicitly re-enable this layer. |
| 78 | pub fn configure(enabled: bool, source_identity: &str) -> Option<OverlayTicket> { |
| 79 | let mut state = STATE.write().ok()?; |
| 80 | if !enabled || hard_disabled() { |
| 81 | disable(&mut state); |
| 82 | return None; |
| 83 | } |
| 84 | if !state.enabled || state.source_identity != source_identity { |
| 85 | state.epoch = state.epoch.saturating_add(1); |
| 86 | state.snapshot.generation = state.snapshot.generation.saturating_add(1); |
| 87 | state.snapshot.facts = None; |
| 88 | state.registry = None; |
| 89 | state.snapshot.status = CloudFactsStatus { |
| 90 | state: CloudFactsState::BundledOnly, |
| 91 | ..Default::default() |
| 92 | }; |
| 93 | state.source_identity = source_identity.to_string(); |
| 94 | state.enabled = true; |
| 95 | } |
| 96 | Some(OverlayTicket { |
| 97 | epoch: state.epoch, |
| 98 | source_identity: state.source_identity.clone(), |
| 99 | }) |
| 100 | } |
| 101 | |
| 102 | /// Accepted in-process rollback floors survive settings and trust changes. |
| 103 | #[must_use] |
| 104 | pub fn highest_seen(channel: &str) -> Option<u64> { |
| 105 | STATE.read().ok()?.highest_seen.get(channel).copied() |
| 106 | } |
| 107 | |
| 108 | #[must_use] |
| 109 | pub fn current_ticket(source_identity: &str) -> Option<OverlayTicket> { |
| 110 | let mut state = STATE.write().ok()?; |
| 111 | if hard_disabled() { |
| 112 | disable(&mut state); |
| 113 | } |
| 114 | (state.enabled && state.source_identity == source_identity).then(|| OverlayTicket { |
| 115 | epoch: state.epoch, |
| 116 | source_identity: state.source_identity.clone(), |
| 117 | }) |
| 118 | } |
| 119 | |
| 120 | #[must_use] |
| 121 | pub fn is_current(ticket: &OverlayTicket) -> bool { |
| 122 | STATE |
| 123 | .write() |
| 124 | .is_ok_and(|mut state| admits(&mut state, ticket)) |
| 125 | } |
| 126 | |
| 127 | pub fn publish( |
| 128 | ticket: &OverlayTicket, |
| 129 | facts: Option<ScopedFacts>, |
| 130 | status: CloudFactsStatus, |
| 131 | ) -> bool { |
| 132 | publish_with(ticket, facts, status, || {}) |
| 133 | } |
| 134 | |
| 135 | /// The callback may save/delete the bounded cache but must not reenter this |
| 136 | /// module. Its write and the state publication share the disable/source gate. |
| 137 | pub fn publish_with( |
| 138 | ticket: &OverlayTicket, |
| 139 | facts: Option<ScopedFacts>, |
| 140 | status: CloudFactsStatus, |
| 141 | before_publish: impl FnOnce(), |
| 142 | ) -> bool { |
| 143 | let Ok(mut state) = STATE.write() else { |
| 144 | return false; |
| 145 | }; |
| 146 | if !admits(&mut state, ticket) { |
| 147 | return false; |
| 148 | } |
| 149 | if let Some(facts) = &facts { |
| 150 | if state |
| 151 | .highest_seen |
| 152 | .get(&facts.channel) |
| 153 | .is_some_and(|version| facts.facts_version < *version) |
| 154 | { |
| 155 | return false; |
| 156 | } |
| 157 | state |
| 158 | .highest_seen |
| 159 | .insert(facts.channel.clone(), facts.facts_version); |
| 160 | } |
| 161 | before_publish(); |
| 162 | state.snapshot.fetched_at = if facts.is_none() { |
| 163 | None |
| 164 | } else { |
| 165 | match &status.state { |
| 166 | CloudFactsState::Verified { fetched_at, .. } => Some(*fetched_at), |
| 167 | _ => state.snapshot.fetched_at, |
| 168 | } |
| 169 | }; |
| 170 | state.snapshot.facts = facts.map(Arc::new); |
| 171 | state.snapshot.status = status; |
| 172 | state.snapshot.generation = state.snapshot.generation.saturating_add(1); |
| 173 | true |
| 174 | } |
| 175 | |
| 176 | pub fn publish_registry( |
| 177 | ticket: &OverlayTicket, |
| 178 | registry: Option<Arc<AdmittedRegistry>>, |
| 179 | before_publish: impl FnOnce(Option<u64>), |
| 180 | ) -> bool { |
| 181 | let Ok(mut state) = STATE.write() else { |
| 182 | return false; |
| 183 | }; |
| 184 | if !admits(&mut state, ticket) { |
| 185 | return false; |
| 186 | } |
| 187 | if let Some(registry) = ®istry { |
| 188 | if state |
| 189 | .highest_seen |
| 190 | .get(REGISTRY_SCHEMA) |
| 191 | .is_some_and(|revision| registry.revision < *revision) |
| 192 | { |
| 193 | return false; |
| 194 | } |
| 195 | state |
| 196 | .highest_seen |
| 197 | .insert(REGISTRY_SCHEMA.to_string(), registry.revision); |
| 198 | } |
| 199 | before_publish(state.highest_seen.get(REGISTRY_SCHEMA).copied()); |
| 200 | if state.registry.is_some() || registry.is_some() { |
| 201 | state.snapshot.generation = state.snapshot.generation.saturating_add(1); |
| 202 | } |
| 203 | state.registry = registry; |
| 204 | true |
| 205 | } |
| 206 | |
| 207 | #[must_use] |
| 208 | pub fn pulled_registry() -> Option<Arc<AdmittedRegistry>> { |
| 209 | pulled_registry_at(crate::catalog::now_unix()) |
| 210 | } |
| 211 | |
| 212 | #[must_use] |
| 213 | pub fn pulled_registry_at(now: u64) -> Option<Arc<AdmittedRegistry>> { |
| 214 | if let Ok(state) = STATE.read() { |
| 215 | let Some(registry) = &state.registry else { |
| 216 | return None; |
| 217 | }; |
| 218 | if !hard_disabled() && !registry.is_expired_at(now) { |
| 219 | return Some(Arc::clone(registry)); |
| 220 | } |
| 221 | } |
| 222 | let mut state = STATE.write().ok()?; |
| 223 | if hard_disabled() { |
| 224 | disable(&mut state); |
| 225 | return None; |
| 226 | } |
| 227 | if state |
| 228 | .registry |
| 229 | .as_ref() |
| 230 | .is_some_and(|registry| registry.is_expired_at(now)) |
| 231 | { |
| 232 | state.registry = None; |
| 233 | state.snapshot.generation = state.snapshot.generation.saturating_add(1); |
| 234 | } |
| 235 | state.registry.clone() |
| 236 | } |
| 237 | |
| 238 | fn snapshot_at(now: u64) -> OverlaySnapshot { |
| 239 | let Ok(mut state) = STATE.write() else { |
| 240 | return OverlaySnapshot::default(); |
| 241 | }; |
| 242 | if hard_disabled() { |
| 243 | disable(&mut state); |
| 244 | } |
| 245 | if state |
| 246 | .registry |
| 247 | .as_ref() |
| 248 | .is_some_and(|registry| registry.is_expired_at(now)) |
| 249 | { |
| 250 | state.registry = None; |
| 251 | state.snapshot.generation = state.snapshot.generation.saturating_add(1); |
| 252 | } |
| 253 | if state |
| 254 | .snapshot |
| 255 | .facts |
| 256 | .as_ref() |
| 257 | .is_some_and(|facts| !facts.is_current_at(now)) |
| 258 | { |
| 259 | state.snapshot.facts = None; |
| 260 | state.snapshot.generation = state.snapshot.generation.saturating_add(1); |
| 261 | if let CloudFactsState::Verified { stale, .. } = &mut state.snapshot.status.state { |
| 262 | *stale = true; |
| 263 | } |
| 264 | } |
| 265 | state.snapshot.clone() |
| 266 | } |
| 267 | |
| 268 | #[must_use] |
| 269 | pub fn snapshot() -> OverlaySnapshot { |
| 270 | snapshot_at(crate::catalog::now_unix()) |
| 271 | } |
| 272 | |
| 273 | #[must_use] |
| 274 | pub fn overlay() -> Option<Arc<ScopedFacts>> { |
| 275 | snapshot().facts |
| 276 | } |
| 277 | |
| 278 | #[must_use] |
| 279 | pub fn status() -> CloudFactsStatus { |
| 280 | snapshot().status |
| 281 | } |
| 282 | |
| 283 | #[must_use] |
| 284 | pub fn is_verified() -> bool { |
| 285 | overlay().is_some() |
| 286 | } |
| 287 | |
| 288 | #[must_use] |
| 289 | pub fn cloud_default_model(provider: &str) -> Option<(String, DefaultSource)> { |
| 290 | if let Some(overlay) = overlay() |
| 291 | && let Some(model) = overlay |
| 292 | .provider_defaults |
| 293 | .get(provider) |
| 294 | .and_then(|d| d.default_model.clone()) |
| 295 | { |
| 296 | return Some(( |
| 297 | model, |
| 298 | DefaultSource::CloudFacts { |
| 299 | facts_version: overlay.facts_version, |
| 300 | }, |
| 301 | )); |
| 302 | } |
| 303 | let reg = pulled_registry()?; |
| 304 | let model = reg.compiled.provider_defaults.get(provider)?.clone(); |
| 305 | Some(( |
| 306 | model, |
| 307 | DefaultSource::CloudFacts { |
| 308 | facts_version: reg.revision, |
| 309 | }, |
| 310 | )) |
| 311 | } |
| 312 | |
| 313 | /// Cloud defaults are a floor for official hosted endpoints, never an override |
| 314 | /// for named compatible routes, local machines, or a Codex account roster. |
| 315 | #[must_use] |
| 316 | pub fn cloud_default_model_for_route( |
| 317 | provider: crate::ProviderKind, |
| 318 | base_url: &str, |
| 319 | ) -> Option<(String, DefaultSource)> { |
| 320 | if matches!( |
| 321 | provider, |
| 322 | crate::ProviderKind::Custom |
| 323 | | crate::ProviderKind::Ollama |
| 324 | | crate::ProviderKind::Sglang |
| 325 | | crate::ProviderKind::Vllm |
| 326 | | crate::ProviderKind::OpenaiCodex |
| 327 | ) || !super::scope::base_url_allowed(provider.as_str(), base_url) |
| 328 | { |
| 329 | return None; |
| 330 | } |
| 331 | cloud_default_model(provider.as_str()) |
| 332 | } |
| 333 | |
| 334 | #[must_use] |
| 335 | pub fn cloud_default_base_url(provider: &str) -> Option<(String, DefaultSource)> { |
| 336 | let overlay = overlay()?; |
| 337 | let url = overlay.provider_defaults.get(provider)?.base_url.clone()?; |
| 338 | Some(( |
| 339 | url, |
| 340 | DefaultSource::CloudFacts { |
| 341 | facts_version: overlay.facts_version, |
| 342 | }, |
| 343 | )) |
| 344 | } |
| 345 | |
| 346 | pub fn clear() { |
| 347 | if let Ok(mut state) = STATE.write() { |
| 348 | disable(&mut state); |
| 349 | } |
| 350 | } |
| 351 |