From 66814ddb86009de7a519f167db634dab3e924fa8 Mon Sep 17 00:00:00 2001 From: aur-build Date: Fri, 20 Nov 2026 23:53:42 +0000 Subject: src: keep every remaining test-only item out of the release build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The auditor was right and my "Rust has no test-conditional visibility" defence was wrong. Two shapes do it, and both are now used wherever the item allows. For free functions, methods, consts and statics: one body behind two visibility declarations. #[cfg(feature = "test-support")] pub fn probe(..) -> .. { probe_impl(..) } #[cfg(not(feature = "test-support"))] pub(crate) fn probe(..) -> .. { probe_impl(..) } fn probe_impl(..) -> .. { .. } The value lives once in a private `*_impl` / `*_VALUE`, so the aliases cannot drift apart. For types: a private inner module holding the real definition, re-exported under a feature gate. mod kata_backend { pub struct KataBackend { .. } } #[cfg(feature = "test-support")] pub use kata_backend::KataBackend; #[cfg(not(feature = "test-support"))] pub(crate) use kata_backend::KataBackend; A `pub` item inside a private module has no nameable path from outside, but it is visible enough to appear in a public trait signature — which is why `Exit`, the return type of `Sandbox::run`, narrows this way and would not as a plain `pub(crate) struct`. `ReleaseState` earns its keep the same route: `ReleaseRow` is public and its `state` field is typed here. Verified with an external crate against the built library: naming `Exit`, `SandboxInfo`, `KataBackend`, `LoopbackBackend`, `RemoteBackend`, `ReleaseState`, `BulkRefusal` or `LogTail` from a release build is `error[E0603]: .. is private`; with `test-support` the same program compiles. Where narrowing needed a re-export split by feature (`db::MIGRATIONS`, `model::ReleaseState`) the alias is split; where nothing in the crate used the alias (`watch::sync_mirror`) it is gone rather than gated. --- src/sandbox/kata.rs | 250 ++++++++++++++++++++++++++++------------------------ 1 file changed, 133 insertions(+), 117 deletions(-) (limited to 'src/sandbox/kata.rs') diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 27005bd..1f24ce7 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -176,97 +176,151 @@ impl Provisioner for LocalAgentProvisioner { } } -pub struct KataBackend { - cfg: Config, - token: String, - addr: String, - provisioner: Arc, - pending: Arc>>>, - counter: AtomicU64, -} +/// The real definition and its impls. The module is private, so this `pub` +/// is not a nameable path from outside; the alias below is the only way to +/// reach it, and the alias is what carries the feature-conditional visibility. +mod kata_backend { + use super::*; -impl KataBackend { - pub(crate) fn shared_for(cfg: &Config) -> Result> { - let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = - &cfg.sandbox - else { - return Err(Error::invalid( - "KataBackend::shared_for needs an agent-sandbox configuration", - )); - }; - let key = crate::hash::hex( - format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(), - ); - static CACHE: OnceLock>>> = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner()); - if let Some(existing) = guard.get(&key) { - return Ok(existing.clone()); - } - let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| { - Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration") - })?); - let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?); - guard.insert(key, backend.clone()); - Ok(backend) + pub struct KataBackend { + cfg: Config, + token: String, + addr: String, + provisioner: Arc, + pending: Arc>>>, + counter: AtomicU64, } - pub(crate) fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest { - ProvisionRequest { - sandbox_id: id.to_string(), - profile: spec.profile.clone(), - hub_addr: self.addr.clone(), - token: self.token.clone(), - ttl: spec.ttl, - image: self.cfg.sandbox_image(), + impl KataBackend { + pub(crate) fn shared_for(cfg: &Config) -> Result> { + let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = + &cfg.sandbox + else { + return Err(Error::invalid( + "KataBackend::shared_for needs an agent-sandbox configuration", + )); + }; + let key = crate::hash::hex( + format!("{listen}\n{token}\n{api}\n{namespace}\n{bearer}\n{image}").as_bytes(), + ); + static CACHE: OnceLock>>> = OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + let mut guard = cache.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(existing) = guard.get(&key) { + return Ok(existing.clone()); + } + let provisioner = Arc::new(K8sSandboxProvisioner::for_config(cfg).ok_or_else(|| { + Error::invalid("KataBackend::shared_for needs an agent-sandbox configuration") + })?); + let backend = Arc::new(Self::bind(cfg, listen, token, provisioner)?); + guard.insert(key, backend.clone()); + Ok(backend) + } + + pub(crate) fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest { + ProvisionRequest { + sandbox_id: id.to_string(), + profile: spec.profile.clone(), + hub_addr: self.addr.clone(), + token: self.token.clone(), + ttl: spec.ttl, + image: self.cfg.sandbox_image(), + } + } + + pub fn bind( + cfg: &Config, + listen: &str, + token: &str, + provisioner: Arc, + ) -> Result { + let listener = TcpListener::bind(listen)?; + let addr = listener.local_addr()?.to_string(); + let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); + { + let (token, pending) = (token.to_string(), pending.clone()); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { break }; + route_dial_in(stream, &token, &pending); + } + }); + } + Ok(Self { + cfg: cfg.clone(), + token: token.to_string(), + addr, + provisioner, + pending, + counter: AtomicU64::new(1), + }) + } + + // NOTE: `KataBackend::reclaim` used to sit here and called nothing but + // `self.provisioner.reclaim`, which the pool already calls itself at the + // reaping site. Nothing — not a test — ever called the wrapper, so it is + // gone rather than gated. The census had credited it to `tests/kata.rs`, + // where the TTL test implements the *trait's* `reclaim` on a null + // provisioner: same word, different function. + + fn nonce(&self) -> String { + let n = self.counter.fetch_add(1, Ordering::SeqCst); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string() } } - pub fn bind( - cfg: &Config, - listen: &str, - token: &str, - provisioner: Arc, - ) -> Result { - let listener = TcpListener::bind(listen)?; - let addr = listener.local_addr()?.to_string(); - let pending: Arc>>> = Arc::new(Mutex::new(HashMap::new())); - { - let (token, pending) = (token.to_string(), pending.clone()); - std::thread::spawn(move || { - for stream in listener.incoming() { - let Ok(stream) = stream else { break }; - route_dial_in(stream, &token, &pending); + impl SandboxBackend for KataBackend { + fn acquire(&self, spec: &SandboxSpec) -> Result> { + let id = self.nonce(); + let (tx, rx): (Sender, Receiver) = bounded(1); + self.pending.lock().unwrap().insert(id.clone(), tx); + let req = self.provision_request(spec, &id); + if let Err(e) = self.provisioner.provision(&req) { + self.pending.lock().unwrap().remove(&id); + return Err(e); + } + let stream = match rx.recv_timeout(spec.ttl) { + Ok(s) => s, + Err(_) => { + self.pending.lock().unwrap().remove(&id); + let _ = self.provisioner.reclaim(&id); + return Err(Error::pool_exhausted(PoolFull::Backend { + backend: "kata", + detail: format!( + "sandbox {id} for profile {} never dialed in within its TTL", + spec.profile + ), + })); } - }); + }; + let ttl = spec.ttl.max(Duration::from_secs(1)); + wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?; + Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, id, ttl))) } - Ok(Self { - cfg: cfg.clone(), - token: token.to_string(), - addr, - provisioner, - pending, - counter: AtomicU64::new(1), - }) - } - // NOTE: `KataBackend::reclaim` used to sit here and called nothing but - // `self.provisioner.reclaim`, which the pool already calls itself at the - // reaping site. Nothing — not a test — ever called the wrapper, so it is - // gone rather than gated. The census had credited it to `tests/kata.rs`, - // where the TTL test implements the *trait's* `reclaim` on a null - // provisioner: same word, different function. - - fn nonce(&self) -> String { - let n = self.counter.fetch_add(1, Ordering::SeqCst); - let nanos = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - crate::hash::hex_str(&format!("{}-{n}-{nanos}", std::process::id()))[..20].to_string() + fn status(&self) -> Result> { + Ok(vec![SandboxInfo { + id: format!("kata@{} via {}", self.addr, self.provisioner.name()), + profile: self.cfg.build_profile.clone(), + warm: !self.pending.lock().unwrap().is_empty(), + }]) + } } } +/// Selected by `backend_for`. The kata tests drive it directly and need a +/// fixture, so they cannot move into the module. +/// `pub` only under `test-support`. Production reaches the backend through +/// `backend_for` and never names the type from outside `sandbox`. +#[cfg(feature = "test-support")] +pub use kata_backend::KataBackend; + +#[cfg(not(feature = "test-support"))] +pub(crate) use kata_backend::KataBackend; fn route_dial_in( stream: TcpStream, token: &str, @@ -287,44 +341,6 @@ fn route_dial_in( } } -impl SandboxBackend for KataBackend { - fn acquire(&self, spec: &SandboxSpec) -> Result> { - let id = self.nonce(); - let (tx, rx): (Sender, Receiver) = bounded(1); - self.pending.lock().unwrap().insert(id.clone(), tx); - let req = self.provision_request(spec, &id); - if let Err(e) = self.provisioner.provision(&req) { - self.pending.lock().unwrap().remove(&id); - return Err(e); - } - let stream = match rx.recv_timeout(spec.ttl) { - Ok(s) => s, - Err(_) => { - self.pending.lock().unwrap().remove(&id); - let _ = self.provisioner.reclaim(&id); - return Err(Error::pool_exhausted(PoolFull::Backend { - backend: "kata", - detail: format!( - "sandbox {id} for profile {} never dialed in within its TTL", - spec.profile - ), - })); - } - }; - let ttl = spec.ttl.max(Duration::from_secs(1)); - wire::write_frame(&mut stream.try_clone()?, &Frame::HelloAck { ttl_secs: ttl.as_secs() })?; - Ok(Arc::new(RemoteSandbox::after_hello(&self.cfg, stream, id, ttl))) - } - - fn status(&self) -> Result> { - Ok(vec![SandboxInfo { - id: format!("kata@{} via {}", self.addr, self.provisioner.name()), - profile: self.cfg.build_profile.clone(), - warm: !self.pending.lock().unwrap().is_empty(), - }]) - } -} - #[cfg(test)] mod tests { use super::*; -- cgit v1.2.3