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/db/mod.rs | 8 +- src/db/model/mod.rs | 6 +- src/db/model/state.rs | 31 ++++-- src/http/sse.rs | 156 +++++++++++++++--------------- src/review/approve.rs | 2 + src/sandbox/kata.rs | 250 ++++++++++++++++++++++++++---------------------- src/sandbox/loopback.rs | 25 ++++- src/sandbox/remote.rs | 31 +++++- src/watch/upstream.rs | 2 + 9 files changed, 303 insertions(+), 208 deletions(-) (limited to 'src') diff --git a/src/db/mod.rs b/src/db/mod.rs index 1266d9e..e8a97b4 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -36,11 +36,17 @@ pub(crate) use model::json_or; pub use model::{ BUILD_STEPS, BuildState, CandidateRow, CandidateState, - Identity, Recipe, ReleaseRow, ReleaseState, + Identity, Recipe, ReleaseRow, SourceDigest, SourceEntry, StageBCacheRow, StepState, SubscriptionState, UpstreamPin, WorldMember, candidate_kind, notice_kind, }; +/// `ReleaseState` is a column type on the release row. Nothing outside `db` +/// names it, so the alias out of `db` exists only for the test tier. +#[cfg(feature = "test-support")] +pub use model::ReleaseState; +#[cfg(not(feature = "test-support"))] +pub(crate) use model::ReleaseState; pub use audit::{AuditEntry, audit, audit_in, audit_system, list_audit}; pub use invariants::approved_but_unbuilt; #[cfg(feature = "test-support")] diff --git a/src/db/model/mod.rs b/src/db/model/mod.rs index 827ce5e..ba97073 100644 --- a/src/db/model/mod.rs +++ b/src/db/model/mod.rs @@ -208,7 +208,11 @@ mod state; pub(crate) use state::StateEnum; pub use build_state::{BUILD_STEPS, BuildState, StepState}; -pub use state::{CandidateState, ReleaseState, SubscriptionState, candidate_kind, notice_kind}; +pub use state::{CandidateState, SubscriptionState, candidate_kind, notice_kind}; +#[cfg(feature = "test-support")] +pub use state::ReleaseState; +#[cfg(not(feature = "test-support"))] +pub(crate) use state::ReleaseState; #[cfg(test)] mod tests { diff --git a/src/db/model/state.rs b/src/db/model/state.rs index f773f5b..dcc9b84 100644 --- a/src/db/model/state.rs +++ b/src/db/model/state.rs @@ -73,14 +73,33 @@ pub mod candidate_kind { pub const FIRST_INTRODUCTION: &str = "first_introduction"; } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ReleaseState { - Published, - Withdrawn, - FailedUnbuilt, +/// The real definition. 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 release_state { + use super::*; + + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] + #[serde(rename_all = "snake_case")] + pub enum ReleaseState { + Published, + Withdrawn, + FailedUnbuilt, + } } +/// The state column of a release row. `ReleaseRow` is public and its `state` field is typed here, so the type stays reachable in a release build only through this alias. +/// +/// `pub` only under `test-support`. Production reaches the type +/// through its own module and never names it from outside; the +/// outside reader that needs the name is a test. +#[cfg(feature = "test-support")] +pub use release_state::ReleaseState; + +#[cfg(not(feature = "test-support"))] +pub(crate) use release_state::ReleaseState; + impl ReleaseState { const ALL: &'static [ReleaseState] = &[ ReleaseState::Published, diff --git a/src/http/sse.rs b/src/http/sse.rs index 98e9282..03e09ff 100644 --- a/src/http/sse.rs +++ b/src/http/sse.rs @@ -13,9 +13,11 @@ const POLL: Duration = Duration::from_millis(200); /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod log_tail { + use super::*; + pub struct LogTail { path: PathBuf, - build_id: String, + pub build_id: String, db: crate::db::Db, offset: u64, out: std::collections::VecDeque, @@ -23,101 +25,103 @@ mod log_tail { since_keepalive: Duration, ended: bool, } -} - -/// The SSE tail handle. The live test that names it drives a real server, so it cannot move into the module. -/// -/// `pub` only under `test-support`. Production reaches the type -/// through its own module and never names it from outside; the -/// outside reader that needs the name is a test. -#[cfg(feature = "test-support")] -pub use log_tail::LogTail; - -#[cfg(not(feature = "test-support"))] -pub(crate) use log_tail::LogTail; -impl LogTail { - pub fn new(cfg: &crate::config::Config, db: crate::db::Db, build_id: &str) -> Self { - Self { - path: cfg.build_log_path(build_id), - build_id: build_id.to_string(), - db, - offset: 0, - out: std::collections::VecDeque::new(), - started: Instant::now(), - since_keepalive: Duration::ZERO, - ended: false, + impl LogTail { + pub fn new(cfg: &crate::config::Config, db: crate::db::Db, build_id: &str) -> Self { + Self { + path: cfg.build_log_path(build_id), + build_id: build_id.to_string(), + db, + offset: 0, + out: std::collections::VecDeque::new(), + started: Instant::now(), + since_keepalive: Duration::ZERO, + ended: false, + } } - } - fn terminal(&self) -> bool { - match builds::get(&self.db, &self.build_id) { - Ok(Some(b)) => b.state.is_terminal(), - Ok(None) => true, - Err(_) => false, + fn terminal(&self) -> bool { + match builds::get(&self.db, &self.build_id) { + Ok(Some(b)) => b.state.is_terminal(), + Ok(None) => true, + Err(_) => false, + } } - } - fn pump(&mut self) { - let (bytes, grew) = read_from(&self.path, self.offset); - if grew { - self.offset += bytes.len() as u64; - for line in String::from_utf8_lossy(&bytes).lines() { - self.out.extend(format!("data: {line}\n\n").as_bytes()); + fn pump(&mut self) { + let (bytes, grew) = read_from(&self.path, self.offset); + if grew { + self.offset += bytes.len() as u64; + for line in String::from_utf8_lossy(&bytes).lines() { + self.out.extend(format!("data: {line}\n\n").as_bytes()); + } + self.since_keepalive = Duration::ZERO; } - self.since_keepalive = Duration::ZERO; } - } - fn finish(&mut self) { - if self.ended { - return; + fn finish(&mut self) { + if self.ended { + return; + } + self.ended = true; + self.out.extend(b"event: end\ndata: done\n\n"); } - self.ended = true; - self.out.extend(b"event: end\ndata: done\n\n"); } -} -impl Read for LogTail { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - loop { - if !self.out.is_empty() { - let n = buf.len().min(self.out.len()); - for (i, b) in self.out.drain(..n).enumerate() { - buf[i] = b; + impl Read for LogTail { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + loop { + if !self.out.is_empty() { + let n = buf.len().min(self.out.len()); + for (i, b) in self.out.drain(..n).enumerate() { + buf[i] = b; + } + return Ok(n); + } + if self.ended { + return Ok(0); } - return Ok(n); - } - if self.ended { - return Ok(0); - } - self.pump(); - if !self.out.is_empty() { - continue; - } - if self.terminal() { - // One more pump in case the last lines landed with the state - // change; a race here would silently drop the end of a log. self.pump(); - if self.out.is_empty() { + if !self.out.is_empty() { + continue; + } + if self.terminal() { + // One more pump in case the last lines landed with the state + // change; a race here would silently drop the end of a log. + self.pump(); + if self.out.is_empty() { + self.finish(); + } + continue; + } + if self.started.elapsed() > MAX_LIFETIME { self.finish(); + continue; + } + crate::time::sleep(POLL); + self.since_keepalive += POLL; + if self.since_keepalive >= KEEPALIVE { + self.since_keepalive = Duration::ZERO; + self.out.extend(b": keepalive\n\n"); } - continue; - } - if self.started.elapsed() > MAX_LIFETIME { - self.finish(); - continue; - } - crate::time::sleep(POLL); - self.since_keepalive += POLL; - if self.since_keepalive >= KEEPALIVE { - self.since_keepalive = Duration::ZERO; - self.out.extend(b": keepalive\n\n"); } } } } +/// The SSE tail handle. The live test that names it drives a real server, so it cannot move into the module. +/// +/// `pub` only under `test-support`. Production reaches the type +/// through its own module and never names it from outside; the +/// outside reader that needs the name is a test. +#[cfg(feature = "test-support")] +pub use log_tail::LogTail; + +#[cfg(not(feature = "test-support"))] +pub(crate) use log_tail::LogTail; + + + fn read_from(path: &Path, offset: u64) -> (Vec, bool) { let mut f = match std::fs::File::open(path) { Ok(f) => f, diff --git a/src/review/approve.rs b/src/review/approve.rs index f277ac5..f116a92 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -156,6 +156,8 @@ pub enum BulkOutcome { /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod bulk_refusal { + use super::*; + #[derive(Debug, thiserror::Error)] pub enum BulkRefusal { #[error("high risk: confirm it individually")] 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::*; diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 7847fdc..9629206 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -7,10 +7,31 @@ use crate::config::Config; use crate::error::{Error, Result}; use crate::sandbox::{Cmd, Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; -pub struct LoopbackBackend { - cfg: Config, +/// The real definition. 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 loopback_backend { + use super::*; + // `pub` fields inside a private module are not nameable from + // outside; they stay readable by the impls below. + + pub struct LoopbackBackend { + pub cfg: Config, + } } +/// The default backend, built by `backend_for`. A failure test builds one to inject a fault. +/// +/// `pub` only under `test-support`. Production reaches the type +/// through its own module and never names it from outside; the +/// outside reader that needs the name is a test. +#[cfg(feature = "test-support")] +pub use loopback_backend::LoopbackBackend; + +#[cfg(not(feature = "test-support"))] +pub(crate) use loopback_backend::LoopbackBackend; + impl LoopbackBackend { pub fn new(cfg: &Config) -> Self { Self { cfg: cfg.clone() } diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index c648843..6d369e2 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -9,13 +9,34 @@ use crate::error::{Error, Result}; use crate::sandbox::wire::{self, Frame}; use crate::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; -pub struct RemoteBackend { - cfg: Config, - token: String, - addr: String, - queue: Receiver, +/// The real definition. 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 remote_backend { + use super::*; + // `pub` fields inside a private module are not nameable from + // outside; they stay readable by the impls below. + + pub struct RemoteBackend { + pub cfg: Config, + pub token: String, + pub addr: String, + pub queue: Receiver, + } } +/// The remote backend, built by `backend_for`. A fixture test builds one to drive the agent protocol. +/// +/// `pub` only under `test-support`. Production reaches the type +/// through its own module and never names it from outside; the +/// outside reader that needs the name is a test. +#[cfg(feature = "test-support")] +pub use remote_backend::RemoteBackend; + +#[cfg(not(feature = "test-support"))] +pub(crate) use remote_backend::RemoteBackend; + impl RemoteBackend { pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result { let bound = super::bound_listener(addr, token)?; diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs index 888a5ed..0845440 100644 --- a/src/watch/upstream.rs +++ b/src/watch/upstream.rs @@ -148,6 +148,8 @@ static SLOT_LOCK: Mutex<()> = Mutex::new(()); /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod stage_b_slot { + use super::*; + pub struct StageBSlot(()); impl StageBSlot { -- cgit v1.2.3