Skip to main content

engenho_controllers/
service_router.rs

1//! R11 — Service IP routing primitive.
2//!
3//! The substrate has Service + Endpoints objects + matching Pods
4//! since R9.6; before R11 nothing actually routed traffic from a
5//! Service's `ClusterIP` to the backing Pods. R11 ships the typed
6//! routing surface + a backend trait.
7//!
8//! ## Architecture
9//!
10//! ```text
11//! ServiceRoutingController (Controller impl)
12//!     reads: Service + Endpoints from StoreMesh
13//!     emits: RouteTable
14//!         → pluggable ServiceRouter backend:
15//!             - FakeRouter (tests; tracks routes in BTreeMap)
16//!             - IptablesRouter (Linux production; shells out to iptables)
17//!             - IpvsRouter (Linux production, scalable; future R11.5)
18//! ```
19//!
20//! ## Reconcile rule
21//!
22//! 1. List Services + Endpoints from the store.
23//! 2. For each pair (service, endpoints), compute the typed
24//!    [`ServiceRoute`]: `ClusterIP` + per-port (proto, port, `target_port`)
25//!    + the set of healthy Pod IPs from Endpoints.subsets.
26//! 3. Diff against the backend's current table. Add/remove routes
27//!    to converge.
28//! 4. Idempotent — re-running with the same state is a no-op.
29//!
30//! ## Datapath scope (HONEST — the macOS-VM packet-install is a typed
31//!    deferral, NOT a silent gap)
32//!
33//! Three layers compose the kube-proxy datapath; engenho ships them at
34//! different maturities and is explicit about which:
35//!
36//!   1. **VIP allocation** — DONE (`crate::cluster_ip`): a Service gets a
37//!      real `ClusterIP`, so a route HAS a VIP to key on (before this the
38//!      VIP was `None` and every route degenerate).
39//!   2. **Desired-rule computation** — DONE (this module): the controller
40//!      resolves Service+Endpoints → typed [`ServiceRoute`]s, and the
41//!      [`IptablesRouter`]/[`IpvsRouter`] backends render the EXACT
42//!      `KUBE-SVC`/`KUBE-SEP` chain hierarchy (resp. ipvs virtual-server
43//!      table) kube-proxy installs — fully unit-tested via pure
44//!      `render_script`.
45//!   3. **Packet-routing INSTALL** — the actual `iptables-restore` /
46//!      `ipvsadm` apply on the node. On the bootstrap macOS topology the
47//!      engenho host process runs on Darwin while pods run in a podman
48//!      Linux VM, so the host cannot install the Linux VIP datapath the
49//!      way a Linux node would. The controller's backend selection is a
50//!      typed decision ([`DatapathInstall`]): `Computed` (default off-Linux
51//!      — routes are computed + observable via a [`FakeRouter`], but no
52//!      kernel rule is installed) vs `Installed` (Linux node — the
53//!      iptables/ipvs backend applies the rules). A `Computed` install is
54//!      NOT a silent skip: it is the named, fail-safe state the same way
55//!      the webhook caBundle deferral is — real progress (correct allocator
56//!      + correct computed rules + `EndpointSlice`) awaiting a Linux node for
57//!      the final kernel apply.
58
59use std::collections::{BTreeMap, BTreeSet};
60use std::sync::Arc;
61
62use async_trait::async_trait;
63use engenho_store::StoreMesh;
64use serde::{Deserialize, Serialize};
65use thiserror::Error;
66use tokio::sync::Mutex;
67
68use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
69use crate::effect::Effect;
70use crate::error::ControllerError;
71use crate::reads::{DeclaresReads, Reads, gvk};
72
73/// A single routing entry — one ClusterIP:port → set of pod backends.
74#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
75pub struct ServiceRoute {
76    /// `namespace/name` identifier — stable across edits.
77    pub service_id: String,
78    /// Cluster-IP allocated for the service. Empty = headless.
79    pub cluster_ip: String,
80    /// Port mapping (each Service can expose multiple ports).
81    pub ports: Vec<PortMap>,
82    /// Sorted set of backend Pod IPs ready to receive traffic.
83    pub endpoints: BTreeSet<String>,
84}
85
86/// Per-port service-to-pod mapping.
87#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
88pub struct PortMap {
89    /// Operator-facing port name (e.g. "http").
90    pub name: String,
91    /// Service-side port (the `ClusterIP` listens here).
92    pub service_port: u16,
93    /// Pod-side port (Endpoints subsets each have this).
94    pub target_port: u16,
95    /// Protocol; defaults to "TCP".
96    pub protocol: String,
97}
98
99/// Errors a `ServiceRouter` backend may return.
100#[derive(Debug, Clone, Error)]
101pub enum RouterError {
102    /// Backend (iptables / ipvs) returned a non-zero exit.
103    #[error("backend: {0}")]
104    Backend(String),
105    /// Invalid route shape (e.g. empty `service_id`).
106    #[error("invalid route: {0}")]
107    InvalidRoute(String),
108}
109
110engenho_substrate::impl_error_kind! {
111    RouterError {
112        (Backend(_)) => "backend",
113        (InvalidRoute(_)) => "invalid_route",
114    }
115}
116
117/// The datapath-install maturity a [`ServiceRouter`] backend provides —
118/// the typed name for "did we COMPUTE the rules, or did we INSTALL them in
119/// the kernel?" This makes the macOS-VM packet-install deferral a typed
120/// value, never a silent gap.
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
122pub enum DatapathInstall {
123    /// Routes are computed + tracked + observable, but NO kernel rule is
124    /// installed. The fail-safe state on a topology where the host cannot
125    /// install the Linux VIP datapath (e.g. engenho on Darwin with pods in
126    /// a podman Linux VM). Correct allocator + correct computed rules,
127    /// awaiting a Linux node for the kernel apply.
128    Computed,
129    /// The backend installs the VIP datapath in the node's kernel
130    /// (iptables / ipvs / eBPF) — a real Linux node.
131    Installed,
132}
133
134/// Pluggable routing backend trait. Implementations apply +
135/// remove routes on the local host (iptables, ipvs, ebpf, fake).
136#[async_trait]
137pub trait ServiceRouter: Send + Sync {
138    /// Stable backend name.
139    fn name(&self) -> &'static str;
140
141    /// The datapath-install maturity this backend provides. `Computed`
142    /// (`FakeRouter` / off-Linux topology) ⇒ routes are computed + tracked
143    /// but no kernel rule is installed; `Installed` (iptables / ipvs on a
144    /// Linux node) ⇒ the VIP datapath is applied. Defaults to `Installed`
145    /// (the kernel backends); the `FakeRouter` overrides to `Computed`.
146    fn datapath(&self) -> DatapathInstall {
147        DatapathInstall::Installed
148    }
149
150    /// Install / refresh a route. Idempotent — if the route is
151    /// already installed identically, this is a no-op.
152    ///
153    /// # Errors
154    ///
155    /// Returns [`RouterError::Backend`] if the host refuses the rule.
156    async fn upsert(&self, route: &ServiceRoute) -> Result<(), RouterError>;
157
158    /// Remove an existing route by `service_id`.
159    ///
160    /// # Errors
161    ///
162    /// [`RouterError::Backend`] on host failure.
163    async fn remove(&self, service_id: &str) -> Result<(), RouterError>;
164
165    /// Currently-installed routes (for diff + reconcile).
166    ///
167    /// # Errors
168    ///
169    /// [`RouterError::Backend`] on backend inspection failure.
170    async fn list(&self) -> Result<BTreeMap<String, ServiceRoute>, RouterError>;
171
172    /// Make the installed routes exactly `desired`, returning how many
173    /// routes changed. The default upserts what differs and removes what is
174    /// no longer desired; a backend that owns a shared table (iptables'
175    /// `KUBE-SERVICES`) rewrites it whole instead.
176    ///
177    /// # Errors
178    ///
179    /// [`RouterError::Backend`] on host failure.
180    async fn sync(&self, desired: &BTreeMap<String, ServiceRoute>) -> Result<usize, RouterError> {
181        let installed = self.list().await?;
182        let mut changed = 0;
183        for (id, route) in desired {
184            if installed.get(id) != Some(route) {
185                self.upsert(route).await?;
186                changed += 1;
187            }
188        }
189        for id in installed.keys() {
190            if !desired.contains_key(id) {
191                self.remove(id).await?;
192                changed += 1;
193            }
194        }
195        Ok(changed)
196    }
197}
198
199// =================================================================
200// FakeRouter — deterministic in-memory backend for tests
201// =================================================================
202
203/// Test backend. Tracks routes in a `BTreeMap` + records every
204/// upsert/remove call for assertion in tests.
205#[derive(Default, Clone)]
206pub struct FakeRouter {
207    inner: Arc<Mutex<FakeRouterState>>,
208}
209
210#[derive(Default)]
211struct FakeRouterState {
212    routes: BTreeMap<String, ServiceRoute>,
213    events: Vec<FakeRouterEvent>,
214}
215
216/// Per-call event log entry for tests.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub enum FakeRouterEvent {
219    /// `upsert(service_id)` was invoked.
220    Upsert(String),
221    /// `remove(service_id)` was invoked.
222    Remove(String),
223}
224
225impl FakeRouter {
226    /// Fresh empty backend.
227    #[must_use]
228    pub fn new() -> Self {
229        Self::default()
230    }
231
232    /// Snapshot of recorded events.
233    pub async fn events(&self) -> Vec<FakeRouterEvent> {
234        self.inner.lock().await.events.clone()
235    }
236
237    /// Current route count.
238    pub async fn route_count(&self) -> usize {
239        self.inner.lock().await.routes.len()
240    }
241}
242
243#[async_trait]
244impl ServiceRouter for FakeRouter {
245    fn name(&self) -> &'static str {
246        "fake"
247    }
248
249    fn datapath(&self) -> DatapathInstall {
250        // Computes + tracks routes; installs nothing in the kernel. This is
251        // ALSO the honest default backend on the macOS-VM topology where the
252        // host can't install the Linux VIP datapath — routes are computed +
253        // observable, the kernel apply awaits a Linux node.
254        DatapathInstall::Computed
255    }
256
257    async fn upsert(&self, route: &ServiceRoute) -> Result<(), RouterError> {
258        if route.service_id.is_empty() {
259            return Err(RouterError::InvalidRoute("empty service_id".into()));
260        }
261        let mut state = self.inner.lock().await;
262        state.routes.insert(route.service_id.clone(), route.clone());
263        state
264            .events
265            .push(FakeRouterEvent::Upsert(route.service_id.clone()));
266        Ok(())
267    }
268
269    async fn remove(&self, service_id: &str) -> Result<(), RouterError> {
270        let mut state = self.inner.lock().await;
271        state.routes.remove(service_id);
272        state
273            .events
274            .push(FakeRouterEvent::Remove(service_id.to_string()));
275        Ok(())
276    }
277
278    async fn list(&self) -> Result<BTreeMap<String, ServiceRoute>, RouterError> {
279        Ok(self.inner.lock().await.routes.clone())
280    }
281}
282
283// =================================================================
284// IptablesRouter — Linux production backend (R11b)
285// =================================================================
286
287/// Production `ServiceRouter` for Linux nodes. Renders the desired
288/// state as iptables rules + applies them via `iptables-restore`.
289///
290/// Per the org's NO SHELL rule, this is the ONE acceptable
291/// shell-out site for `ServiceRouter` — the integration boundary
292/// itself, not orchestration glue.
293///
294/// ## Approach
295///
296/// Each `upsert` builds a fully-formed iptables-restore script
297/// for the `KUBE-SERVICES` + `KUBE-SVC-{hash}` + `KUBE-SEP-{hash}`
298/// chain hierarchy + pipes it to `iptables-restore --noflush`.
299/// The same idempotent rule structure kube-proxy's iptables mode
300/// uses. Removal flushes the relevant chains.
301///
302/// In-memory tracking of installed routes (so `list` returns the
303/// authoritative state without re-parsing iptables-save output).
304#[derive(Clone)]
305pub struct IptablesRouter {
306    /// Binary path; default `iptables-restore`.
307    binary: String,
308    /// The `iptables` control binary (check / create / delete a single
309    /// rule). `iptables-restore` cannot express "append only if absent",
310    /// which is the whole of [`ensure_root_chain`](IptablesRouter::ensure_root_chain).
311    control_binary: String,
312    inner: Arc<Mutex<IptablesState>>,
313}
314
315#[derive(Default)]
316struct IptablesState {
317    /// Routes the router has installed.
318    routes: BTreeMap<String, ServiceRoute>,
319    /// Whether this process has rewritten the root chain yet. Until it has,
320    /// the chain may hold a previous process's jumps, so the first sync runs
321    /// even when no route changed.
322    synced: bool,
323}
324
325impl Default for IptablesRouter {
326    fn default() -> Self {
327        Self::new()
328    }
329}
330
331impl IptablesRouter {
332    /// New router using `iptables-restore` from `$PATH`.
333    #[must_use]
334    pub fn new() -> Self {
335        Self::with_binary("iptables-restore")
336    }
337
338    /// New router with an explicit binary path. Useful for testing
339    /// against `iptables-legacy-restore` or for shimming in CI.
340    #[must_use]
341    pub fn with_binary(binary: impl Into<String>) -> Self {
342        let binary = binary.into();
343        let control = Self::control_binary_for(&binary);
344        Self::with_binaries(binary, control)
345    }
346
347    /// New router with both binaries named explicitly.
348    #[must_use]
349    pub fn with_binaries(binary: impl Into<String>, control_binary: impl Into<String>) -> Self {
350        Self {
351            binary: binary.into(),
352            control_binary: control_binary.into(),
353            inner: Arc::new(Mutex::new(IptablesState::default())),
354        }
355    }
356
357    /// `iptables-restore` -> `iptables`, preserving any directory and any
358    /// variant prefix (`iptables-legacy-restore` -> `iptables-legacy`), so a
359    /// node pinned to the legacy backend does not get its rules checked
360    /// through the nft one. Pure — unit-assertable.
361    #[must_use]
362    pub fn control_binary_for(restore_binary: &str) -> String {
363        restore_binary
364            .strip_suffix("-restore")
365            .unwrap_or(restore_binary)
366            .to_string()
367    }
368
369    /// Render the iptables-restore script for one route. Pure —
370    /// no I/O. Test helper exposed publicly so callers can inspect
371    /// what the router would emit.
372    ///
373    /// Built as a typed [`engenho_types::egress::IptablesScript`] +
374    /// rendered through its `Display` chokepoint (★★ TYPED EMISSION —
375    /// no `format!()` of iptables syntax).
376    #[must_use]
377    pub fn render_script(route: &ServiceRoute) -> String {
378        let one = [(route.service_id.clone(), route.clone())]
379            .into_iter()
380            .collect();
381        Self::render_sync_script(&one, &BTreeMap::new())
382    }
383
384    fn port_key(route: &ServiceRoute, port: &PortMap) -> String {
385        let mut key = route.service_id.clone();
386        key.push('/');
387        key.push_str(&port.protocol.to_lowercase());
388        key.push('/');
389        key.push_str(&port.service_port.to_string());
390        key
391    }
392
393    fn svc_chain(route: &ServiceRoute, port: &PortMap) -> String {
394        chain_name("KUBE-SVC", &Self::port_key(route, port))
395    }
396
397    fn sep_chain(route: &ServiceRoute, port: &PortMap, pod_ip: &str) -> String {
398        let mut key = Self::port_key(route, port);
399        key.push('/');
400        key.push_str(pod_ip);
401        chain_name("KUBE-SEP", &key)
402    }
403
404    /// Every chain `route` owns: one `KUBE-SVC` per port and one
405    /// `KUBE-SEP` per port and endpoint.
406    #[must_use]
407    pub fn chains_of(route: &ServiceRoute) -> BTreeSet<String> {
408        let mut out = BTreeSet::new();
409        for port in &route.ports {
410            out.insert(Self::svc_chain(route, port));
411            for pod_ip in &route.endpoints {
412                out.insert(Self::sep_chain(route, port, pod_ip));
413            }
414        }
415        out
416    }
417
418    /// The whole nat datapath for `desired`, as kube-proxy writes it: the
419    /// root chain is declared (so `iptables-restore --noflush` flushes and
420    /// refills it), every desired chain is declared and filled, and every
421    /// chain only `installed` owned is flushed and deleted. A Service whose
422    /// address moved or that was deleted therefore leaves no jump behind,
423    /// and each port has its own chains, so a port only ever reaches its
424    /// own target port.
425    #[must_use]
426    pub fn render_sync_script(
427        desired: &BTreeMap<String, ServiceRoute>,
428        installed: &BTreeMap<String, ServiceRoute>,
429    ) -> String {
430        use engenho_types::egress::IptablesScript;
431        let mut script = IptablesScript::new();
432        script.table("nat").chain(Self::ROOT_CHAIN);
433        let mut kept = BTreeSet::new();
434        for route in desired.values() {
435            for port in &route.ports {
436                let proto = port.protocol.to_lowercase();
437                let chain_svc = Self::svc_chain(route, port);
438                script.chain(&chain_svc);
439                kept.insert(chain_svc.clone());
440                script.jump_to_service_chain(
441                    &route.cluster_ip,
442                    &proto,
443                    port.service_port,
444                    &chain_svc,
445                );
446                for (i, pod_ip) in route.endpoints.iter().enumerate() {
447                    let chain_ep = Self::sep_chain(route, port, pod_ip);
448                    script.chain(&chain_ep);
449                    kept.insert(chain_ep.clone());
450                    let remaining = route.endpoints.len() - i;
451                    let probability = 1.0 / (remaining as f64);
452                    script.statistic_jump(&chain_svc, probability, &chain_ep);
453                    script.dnat(&chain_ep, &proto, pod_ip, port.target_port);
454                }
455            }
456        }
457        let retired: BTreeSet<String> = installed
458            .values()
459            .flat_map(Self::chains_of)
460            .filter(|c| !kept.contains(c))
461            .collect();
462        for chain in &retired {
463            script.chain(chain);
464        }
465        for chain in &retired {
466            script.delete_chain(chain);
467        }
468        script.commit();
469        script.to_string()
470    }
471
472    /// The chain every Service-VIP jump hangs off.
473    ///
474    /// **engenho must create this itself.** kube-proxy creates
475    /// `KUBE-SERVICES` and hooks it into nat/PREROUTING + nat/OUTPUT, and an
476    /// earlier version of this router simply appended into it — which works
477    /// only on a node where kube-proxy has run. That is exactly the node
478    /// engenho is built to replace, so the dependency was on the one thing
479    /// guaranteed absent. Measured on rio 2026-09-15: the host still carried
480    /// k3s's chains hours after k3s was stopped, so Service routing would
481    /// have appeared to work and then vanished at the next reboot, when
482    /// iptables comes up empty.
483    const ROOT_CHAIN: &'static str = "KUBE-SERVICES";
484
485    /// Comment stamped on the two hook rules so they are identifiable as
486    /// ours in `iptables -S` and matched exactly by the `-C` check.
487    const HOOK_COMMENT: &'static str = "engenho service portals";
488
489    /// The nat hooks a Service VIP must be reachable from: PREROUTING for
490    /// traffic arriving from a pod, OUTPUT for traffic originating on the
491    /// node itself. Missing OUTPUT is the classic half-fix — pods reach the
492    /// VIP and the host does not.
493    const HOOKS: [&'static str; 2] = ["PREROUTING", "OUTPUT"];
494
495    /// Run the control binary, returning (success, stderr).
496    async fn control(&self, args: &[String]) -> Result<(bool, String), RouterError> {
497        let out = tokio::process::Command::new(&self.control_binary)
498            .args(args)
499            .output()
500            .await
501            .map_err(|e| RouterError::Backend(format!("{} spawn: {e}", self.control_binary)))?;
502        Ok((
503            out.status.success(),
504            String::from_utf8_lossy(&out.stderr).to_string(),
505        ))
506    }
507
508    /// argv for creating the root chain (pure, unit-assertable).
509    #[must_use]
510    pub fn root_chain_create_argv() -> Vec<String> {
511        vec![
512            "-t".into(),
513            "nat".into(),
514            "-N".into(),
515            Self::ROOT_CHAIN.into(),
516        ]
517    }
518
519    /// argv for checking (`-C`) or inserting (`-I <hook> 1`) the hook rule.
520    /// Inserted at position 1 rather than appended: a DNAT that runs after
521    /// someone else's blanket MASQUERADE or RETURN never runs at all.
522    #[must_use]
523    pub fn hook_argv(hook: &str, verb: &str) -> Vec<String> {
524        let mut v = vec![
525            "-t".to_string(),
526            "nat".to_string(),
527            verb.to_string(),
528            hook.to_string(),
529        ];
530        if verb == "-I" {
531            v.push("1".to_string());
532        }
533        v.extend([
534            "-m".to_string(),
535            "comment".to_string(),
536            "--comment".to_string(),
537            Self::HOOK_COMMENT.to_string(),
538            "-j".to_string(),
539            Self::ROOT_CHAIN.to_string(),
540        ]);
541        v
542    }
543
544    /// Create the root chain and its two hooks if they are not already
545    /// there. Idempotent by CHECKING, never by blind append — `iptables -A`
546    /// happily installs a second identical hook rule, and nothing complains.
547    async fn ensure_root_chain(&self) -> Result<(), RouterError> {
548        let (ok, stderr) = self.control(&Self::root_chain_create_argv()).await?;
549        if !ok && !stderr.contains("already exists") {
550            return Err(RouterError::Backend(format!(
551                "create {}: {stderr}",
552                Self::ROOT_CHAIN
553            )));
554        }
555        for hook in Self::HOOKS {
556            let (present, _) = self.control(&Self::hook_argv(hook, "-C")).await?;
557            if !present {
558                let (ok, stderr) = self.control(&Self::hook_argv(hook, "-I")).await?;
559                if !ok {
560                    return Err(RouterError::Backend(format!(
561                        "hook {hook} -> {}: {stderr}",
562                        Self::ROOT_CHAIN
563                    )));
564                }
565            }
566        }
567        Ok(())
568    }
569
570    async fn run_restore(&self, script: &str) -> Result<(), RouterError> {
571        use std::process::Stdio;
572        let mut cmd = tokio::process::Command::new(&self.binary);
573        cmd.arg("--noflush")
574            .stdin(Stdio::piped())
575            .stdout(Stdio::piped())
576            .stderr(Stdio::piped());
577        let mut child = cmd
578            .spawn()
579            .map_err(|e| RouterError::Backend(format!("{} spawn: {e}", self.binary)))?;
580        use tokio::io::AsyncWriteExt;
581        if let Some(mut stdin) = child.stdin.take() {
582            stdin
583                .write_all(script.as_bytes())
584                .await
585                .map_err(|e| RouterError::Backend(format!("stdin write: {e}")))?;
586            stdin
587                .shutdown()
588                .await
589                .map_err(|e| RouterError::Backend(format!("stdin close: {e}")))?;
590        }
591        let out = child
592            .wait_with_output()
593            .await
594            .map_err(|e| RouterError::Backend(format!("wait: {e}")))?;
595        if !out.status.success() {
596            return Err(RouterError::Backend(format!(
597                "{} exit {:?}: {}",
598                self.binary,
599                out.status.code(),
600                String::from_utf8_lossy(&out.stderr)
601            )));
602        }
603        Ok(())
604    }
605}
606
607/// Hash a free-form id to a 12-char iptables-chain-safe suffix.
608fn chain_name(prefix: &str, key: &str) -> String {
609    let hash = blake3::hash(key.as_bytes());
610    let hex = hash.to_hex();
611    format!("{prefix}-{}", hex.as_str()[..12].to_uppercase())
612}
613
614/// Map a K8s protocol string to the ipvsadm transport flag.
615/// `UDP` → `-u`; everything else (TCP default) → `-t`.
616fn ipvs_proto_flag(protocol: &str) -> &'static str {
617    match protocol.to_uppercase().as_str() {
618        "UDP" => "-u",
619        _ => "-t",
620    }
621}
622
623#[async_trait]
624impl ServiceRouter for IptablesRouter {
625    fn name(&self) -> &'static str {
626        "iptables"
627    }
628
629    async fn upsert(&self, route: &ServiceRoute) -> Result<(), RouterError> {
630        if route.service_id.is_empty() {
631            return Err(RouterError::InvalidRoute("empty service_id".into()));
632        }
633        let mut desired = self.list().await?;
634        desired.insert(route.service_id.clone(), route.clone());
635        self.sync(&desired).await.map(|_| ())
636    }
637
638    async fn remove(&self, service_id: &str) -> Result<(), RouterError> {
639        let mut desired = self.list().await?;
640        desired.remove(service_id);
641        self.sync(&desired).await.map(|_| ())
642    }
643
644    async fn list(&self) -> Result<BTreeMap<String, ServiceRoute>, RouterError> {
645        Ok(self.inner.lock().await.routes.clone())
646    }
647
648    async fn sync(&self, desired: &BTreeMap<String, ServiceRoute>) -> Result<usize, RouterError> {
649        let mut state = self.inner.lock().await;
650        let changed = desired
651            .iter()
652            .filter(|(id, route)| state.routes.get(*id) != Some(*route))
653            .count()
654            + state
655                .routes
656                .keys()
657                .filter(|id| !desired.contains_key(*id))
658                .count();
659        if changed == 0 && state.synced {
660            return Ok(0);
661        }
662        self.ensure_root_chain().await?;
663        self.run_restore(&Self::render_sync_script(desired, &state.routes))
664            .await?;
665        state.routes = desired.clone();
666        state.synced = true;
667        Ok(changed)
668    }
669}
670
671// =================================================================
672// IPVSRouter — R11c — scalable backend (>1k services)
673// =================================================================
674
675/// IPVS-backed router. Production backend for large clusters
676/// where iptables rule walking becomes O(n) per packet (≥1000
677/// services). IPVS uses hash-based virtual-server lookup → O(1)
678/// regardless of cluster size.
679///
680/// Per the NO SHELL rule, this shells out to `ipvsadm` — the
681/// integration boundary. Future R11d swaps in netlink-direct
682/// IPVS control via the `ipvs` crate (no shell).
683#[derive(Clone)]
684pub struct IpvsRouter {
685    binary: String,
686    inner: Arc<Mutex<IpvsState>>,
687}
688
689#[derive(Default)]
690struct IpvsState {
691    routes: BTreeMap<String, ServiceRoute>,
692}
693
694impl Default for IpvsRouter {
695    fn default() -> Self {
696        Self::new()
697    }
698}
699
700impl IpvsRouter {
701    /// New router using `ipvsadm` from `$PATH`.
702    #[must_use]
703    pub fn new() -> Self {
704        Self::with_binary("ipvsadm")
705    }
706
707    /// New router with explicit binary path.
708    #[must_use]
709    pub fn with_binary(binary: impl Into<String>) -> Self {
710        Self {
711            binary: binary.into(),
712            inner: Arc::new(Mutex::new(IpvsState::default())),
713        }
714    }
715
716    /// Render the ipvsadm script for one route. Pure — no I/O.
717    ///
718    /// Format: sequence of `-A` (add-service) + `-a` (add-real-server)
719    /// lines that ipvsadm-restore consumes. Built as a typed
720    /// [`engenho_types::egress::IpvsScript`] + rendered through its
721    /// `Display` chokepoint (★★ TYPED EMISSION — no `format!()` of
722    /// ipvsadm syntax).
723    #[must_use]
724    pub fn render_script(route: &ServiceRoute) -> String {
725        use engenho_types::egress::{IpvsLine, IpvsScript};
726        let mut script = IpvsScript::new();
727        for port in &route.ports {
728            // -A: add virtual service. -t = TCP, -u = UDP.
729            let proto_flag = ipvs_proto_flag(&port.protocol);
730            script.push(IpvsLine::AddService {
731                proto_flag: proto_flag.to_string(),
732                vip: route.cluster_ip.clone(),
733                port: port.service_port,
734            });
735            for pod_ip in &route.endpoints {
736                // -a: add real server. -m = masquerade (NAT).
737                script.push(IpvsLine::AddRealServer {
738                    proto_flag: proto_flag.to_string(),
739                    vip: route.cluster_ip.clone(),
740                    port: port.service_port,
741                    pod_ip: pod_ip.clone(),
742                    target_port: port.target_port,
743                });
744            }
745        }
746        script.to_string()
747    }
748
749    async fn run_restore(&self, script: &str) -> Result<(), RouterError> {
750        use std::process::Stdio;
751        let mut cmd = tokio::process::Command::new(&self.binary);
752        cmd.arg("-R")
753            .stdin(Stdio::piped())
754            .stdout(Stdio::piped())
755            .stderr(Stdio::piped());
756        let mut child = cmd
757            .spawn()
758            .map_err(|e| RouterError::Backend(format!("{} spawn: {e}", self.binary)))?;
759        use tokio::io::AsyncWriteExt;
760        if let Some(mut stdin) = child.stdin.take() {
761            stdin
762                .write_all(script.as_bytes())
763                .await
764                .map_err(|e| RouterError::Backend(format!("stdin write: {e}")))?;
765            stdin
766                .shutdown()
767                .await
768                .map_err(|e| RouterError::Backend(format!("stdin close: {e}")))?;
769        }
770        let out = child
771            .wait_with_output()
772            .await
773            .map_err(|e| RouterError::Backend(format!("wait: {e}")))?;
774        if !out.status.success() {
775            return Err(RouterError::Backend(format!(
776                "{} exit {:?}: {}",
777                self.binary,
778                out.status.code(),
779                String::from_utf8_lossy(&out.stderr)
780            )));
781        }
782        Ok(())
783    }
784}
785
786#[async_trait]
787impl ServiceRouter for IpvsRouter {
788    fn name(&self) -> &'static str {
789        "ipvs"
790    }
791
792    async fn upsert(&self, route: &ServiceRoute) -> Result<(), RouterError> {
793        if route.service_id.is_empty() {
794            return Err(RouterError::InvalidRoute("empty service_id".into()));
795        }
796        let script = Self::render_script(route);
797        self.run_restore(&script).await?;
798        let mut state = self.inner.lock().await;
799        state.routes.insert(route.service_id.clone(), route.clone());
800        Ok(())
801    }
802
803    async fn remove(&self, service_id: &str) -> Result<(), RouterError> {
804        // Delete each virtual service this route owned.
805        let route = {
806            let state = self.inner.lock().await;
807            state.routes.get(service_id).cloned()
808        };
809        if let Some(route) = route {
810            use engenho_types::egress::{IpvsLine, IpvsScript};
811            let mut script = IpvsScript::new();
812            for port in &route.ports {
813                script.push(IpvsLine::DeleteService {
814                    proto_flag: ipvs_proto_flag(&port.protocol).to_string(),
815                    vip: route.cluster_ip.clone(),
816                    port: port.service_port,
817                });
818            }
819            let _ = self.run_restore(&script.to_string()).await;
820        }
821        let mut state = self.inner.lock().await;
822        state.routes.remove(service_id);
823        Ok(())
824    }
825
826    async fn list(&self) -> Result<BTreeMap<String, ServiceRoute>, RouterError> {
827        Ok(self.inner.lock().await.routes.clone())
828    }
829}
830
831// =================================================================
832// ServiceRoutingController — reads store, drives the backend
833// =================================================================
834
835/// Controller that watches Services + Endpoints in the store and
836/// drives a [`ServiceRouter`] backend to match.
837pub struct ServiceRoutingController {
838    store: Arc<StoreMesh>,
839    backend: Arc<dyn ServiceRouter>,
840    namespace: Option<String>,
841}
842
843impl ServiceRoutingController {
844    /// Construct a controller for `backend`, optionally namespace-scoped.
845    #[must_use]
846    pub fn new(
847        store: Arc<StoreMesh>,
848        backend: Arc<dyn ServiceRouter>,
849        namespace: Option<String>,
850    ) -> Self {
851        Self {
852            store,
853            backend,
854            namespace,
855        }
856    }
857
858    /// Build the canonical [`ServiceRoute`] from a Service + matching Endpoints.
859    fn build_route(
860        service: &serde_json::Value,
861        endpoints: Option<&serde_json::Value>,
862        service_id: &str,
863    ) -> Option<ServiceRoute> {
864        let spec = service.get("spec");
865        if spec.and_then(|s| s.get("type")).and_then(|t| t.as_str()) == Some("ExternalName") {
866            return None;
867        }
868        let cluster_ip = spec
869            .and_then(|s| s.get("clusterIP"))
870            .and_then(|c| c.as_str())
871            .filter(|c| c.parse::<std::net::Ipv4Addr>().is_ok())?
872            .to_string();
873        let ports = service
874            .get("spec")
875            .and_then(|s| s.get("ports"))
876            .and_then(|p| p.as_array())
877            .map(|arr| {
878                arr.iter()
879                    .filter_map(|p| {
880                        let name = p
881                            .get("name")
882                            .and_then(|n| n.as_str())
883                            .unwrap_or("default")
884                            .to_string();
885                        let service_port =
886                            p.get("port").and_then(serde_json::Value::as_u64)? as u16;
887                        let target_port = Self::target_port(p, &name, endpoints, service_port)?;
888                        let protocol = p
889                            .get("protocol")
890                            .and_then(|n| n.as_str())
891                            .unwrap_or("TCP")
892                            .to_string();
893                        Some(PortMap {
894                            name,
895                            service_port,
896                            target_port,
897                            protocol,
898                        })
899                    })
900                    .collect::<Vec<_>>()
901            })
902            .unwrap_or_default();
903        let endpoints_set: BTreeSet<String> = endpoints
904            .and_then(|e| e.get("subsets"))
905            .and_then(|s| s.as_array())
906            .map(|arr| {
907                arr.iter()
908                    .flat_map(|subset| {
909                        subset
910                            .get("addresses")
911                            .and_then(|a| a.as_array())
912                            .into_iter()
913                            .flatten()
914                    })
915                    .filter_map(|addr| addr.get("ip").and_then(|i| i.as_str()))
916                    .filter(|ip| ip.parse::<std::net::Ipv4Addr>().is_ok())
917                    .map(String::from)
918                    .collect()
919            })
920            .unwrap_or_default();
921        Some(ServiceRoute {
922            service_id: service_id.to_string(),
923            cluster_ip,
924            ports,
925            endpoints: endpoints_set,
926        })
927    }
928
929    /// The pod-side port a Service port DNATs to.
930    ///
931    /// The Endpoints controller has already resolved a NAMED `targetPort`
932    /// against the backing containers, so a port published there under the
933    /// same name is authoritative. Reading only a numeric `targetPort` here
934    /// silently treated `targetPort: "http"` as absent and `DNATed` to the
935    /// SERVICE port — measured on rio 2026-09-15, where Flux's
936    /// source-controller (`port: 80`, `targetPort: http` → 9090) refused every
937    /// `ClusterIP` connection while the Endpoints object correctly said 9090.
938    ///
939    /// A named port with no resolved Endpoints port yields `None`: no rule
940    /// beats a rule to a port nothing listens on.
941    fn target_port(
942        port: &serde_json::Value,
943        name: &str,
944        endpoints: Option<&serde_json::Value>,
945        service_port: u16,
946    ) -> Option<u16> {
947        let published = endpoints
948            .and_then(|e| e.get("subsets"))
949            .and_then(|s| s.as_array())
950            .into_iter()
951            .flatten()
952            .filter_map(|subset| subset.get("ports").and_then(|p| p.as_array()))
953            .flatten()
954            .find(|ep| ep.get("name").and_then(|n| n.as_str()).unwrap_or("default") == name)
955            .and_then(|ep| ep.get("port").and_then(serde_json::Value::as_u64))
956            .and_then(|n| u16::try_from(n).ok());
957        match port.get("targetPort") {
958            None | Some(serde_json::Value::Null) => Some(published.unwrap_or(service_port)),
959            Some(serde_json::Value::Number(n)) => n.as_u64().and_then(|n| u16::try_from(n).ok()),
960            Some(serde_json::Value::String(_)) => published,
961            Some(_) => None,
962        }
963    }
964
965    fn service_id(namespace: &str, name: &str) -> String {
966        format!("{namespace}/{name}")
967    }
968}
969
970/// The Services it routes and the Endpoints that back them. It reads no
971/// `EndpointSlice`: the hand list this replaced woke it on those too, for
972/// nothing.
973impl DeclaresReads for ServiceRoutingController {
974    fn reads(&self) -> Reads {
975        Reads::of(&[gvk("", "v1", "Service"), gvk("", "v1", "Endpoints")])
976    }
977}
978
979#[async_trait]
980impl Controller for ServiceRoutingController {
981    fn name(&self) -> &'static str {
982        "service_router"
983    }
984
985    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
986        let services = self
987            .store
988            .list("", "v1", "Service", self.namespace.as_deref())
989            .await;
990        let endpoints_list = self
991            .store
992            .list("", "v1", "Endpoints", self.namespace.as_deref())
993            .await;
994        let endpoints_by_id: BTreeMap<String, serde_json::Value> = endpoints_list
995            .into_iter()
996            .map(|(k, v)| {
997                (
998                    Self::service_id(k.namespace.as_deref().unwrap_or("default"), &k.name),
999                    v,
1000                )
1001            })
1002            .collect();
1003
1004        let mut report = ReconcileReport::default();
1005        report.objects_examined = services.len();
1006
1007        let desired: BTreeMap<String, ServiceRoute> = services
1008            .into_iter()
1009            .filter_map(|(k, svc)| {
1010                let id = Self::service_id(k.namespace.as_deref().unwrap_or("default"), &k.name);
1011                let eps = endpoints_by_id.get(&id);
1012                Self::build_route(&svc, eps, &id).map(|r| (id, r))
1013            })
1014            .collect();
1015
1016        let changed = self
1017            .backend
1018            .sync(&desired)
1019            .await
1020            .map_err(|e| ControllerError::Internal(e.to_string()))?;
1021        for _ in 0..changed {
1022            report.record(Effect::answered(true));
1023        }
1024        Ok(report.into())
1025    }
1026}
1027
1028#[cfg(test)]
1029mod tests {
1030    use super::*;
1031    use serde_json::json;
1032
1033    fn make_service(name: &str, cluster_ip: &str, port: u16) -> serde_json::Value {
1034        json!({
1035            "kind": "Service",
1036            "metadata": {"name": name, "namespace": "default"},
1037            "spec": {
1038                "clusterIP": cluster_ip,
1039                "ports": [{"name": "http", "port": port, "targetPort": port}]
1040            }
1041        })
1042    }
1043
1044    fn make_endpoints(ips: &[&str]) -> serde_json::Value {
1045        let addresses: Vec<serde_json::Value> = ips.iter().map(|ip| json!({"ip": ip})).collect();
1046        json!({"subsets": [{"addresses": addresses}]})
1047    }
1048
1049    #[test]
1050    fn build_route_extracts_cluster_ip_and_ports() {
1051        let svc = make_service("podinfo", "10.96.5.1", 80);
1052        let eps = make_endpoints(&["10.42.0.1", "10.42.0.2"]);
1053        let r = ServiceRoutingController::build_route(&svc, Some(&eps), "default/podinfo").unwrap();
1054        assert_eq!(r.cluster_ip, "10.96.5.1");
1055        assert_eq!(r.ports[0].service_port, 80);
1056        assert_eq!(r.endpoints.len(), 2);
1057        assert!(r.endpoints.contains("10.42.0.1"));
1058        assert!(r.endpoints.contains("10.42.0.2"));
1059    }
1060
1061    #[test]
1062    fn build_route_handles_missing_endpoints() {
1063        let svc = make_service("x", "10.96.0.1", 8080);
1064        let r = ServiceRoutingController::build_route(&svc, None, "default/x").unwrap();
1065        assert!(r.endpoints.is_empty());
1066    }
1067
1068    #[test]
1069    fn build_route_default_target_port_equals_service_port() {
1070        let svc = json!({
1071            "spec": {
1072                "clusterIP": "10.0.0.1",
1073                "ports": [{"name": "metrics", "port": 9090}]  // no targetPort
1074            }
1075        });
1076        let r = ServiceRoutingController::build_route(&svc, None, "x/y").unwrap();
1077        assert_eq!(r.ports[0].service_port, 9090);
1078        assert_eq!(r.ports[0].target_port, 9090);
1079    }
1080
1081    fn named_target_service() -> serde_json::Value {
1082        json!({
1083            "spec": {
1084                "clusterIP": "10.97.0.5",
1085                "ports": [{"name": "http", "port": 80, "targetPort": "http"}]
1086            }
1087        })
1088    }
1089
1090    #[test]
1091    fn build_route_named_target_port_dnats_to_the_resolved_endpoints_port() {
1092        let eps = json!({"subsets": [{
1093            "addresses": [{"ip": "10.89.0.65"}],
1094            "ports": [{"name": "http", "port": 9090, "protocol": "TCP"}]
1095        }]});
1096        let r = ServiceRoutingController::build_route(
1097            &named_target_service(),
1098            Some(&eps),
1099            "flux-system/source-controller",
1100        )
1101        .unwrap();
1102        assert_eq!(r.ports[0].service_port, 80);
1103        assert_eq!(r.ports[0].target_port, 9090);
1104    }
1105
1106    #[test]
1107    fn build_route_named_target_port_never_falls_back_to_the_service_port() {
1108        // Negative control for the test above: with nothing resolved, the old
1109        // code produced 80 — a rule to a port nothing listens on.
1110        let eps = json!({"subsets": [{"addresses": [{"ip": "10.89.0.65"}]}]});
1111        let r = ServiceRoutingController::build_route(&named_target_service(), Some(&eps), "x/y")
1112            .unwrap();
1113        assert!(
1114            r.ports.is_empty(),
1115            "unresolved named port must emit no rule, got {:?}",
1116            r.ports.first().map(|p| p.target_port)
1117        );
1118        let r =
1119            ServiceRoutingController::build_route(&named_target_service(), None, "x/y").unwrap();
1120        assert!(r.ports.is_empty());
1121    }
1122
1123    #[test]
1124    fn build_route_numeric_target_port_wins_over_endpoints() {
1125        let svc = json!({"spec": {"clusterIP": "10.0.0.1", "ports": [{"name": "http", "port": 80, "targetPort": 8080}]}});
1126        let eps = json!({"subsets": [{"addresses": [{"ip": "10.0.0.9"}], "ports": [{"name": "http", "port": 1234}]}]});
1127        let r = ServiceRoutingController::build_route(&svc, Some(&eps), "x/y").unwrap();
1128        assert_eq!(r.ports[0].target_port, 8080);
1129    }
1130
1131    #[test]
1132    fn build_route_default_protocol_is_tcp() {
1133        let svc = make_service("x", "10.0.0.1", 80);
1134        let r = ServiceRoutingController::build_route(&svc, None, "x/y").unwrap();
1135        assert_eq!(r.ports[0].protocol, "TCP");
1136    }
1137
1138    #[tokio::test]
1139    async fn fake_router_upsert_inserts_route() {
1140        let router = FakeRouter::new();
1141        let route = ServiceRoute {
1142            service_id: "default/x".into(),
1143            cluster_ip: "10.0.0.1".into(),
1144            ports: vec![],
1145            endpoints: BTreeSet::new(),
1146        };
1147        router.upsert(&route).await.unwrap();
1148        assert_eq!(router.route_count().await, 1);
1149        let evs = router.events().await;
1150        assert_eq!(evs, vec![FakeRouterEvent::Upsert("default/x".into())]);
1151    }
1152
1153    #[tokio::test]
1154    async fn fake_router_rejects_empty_service_id() {
1155        let router = FakeRouter::new();
1156        let route = ServiceRoute {
1157            service_id: String::new(),
1158            cluster_ip: "x".into(),
1159            ports: vec![],
1160            endpoints: BTreeSet::new(),
1161        };
1162        let err = router.upsert(&route).await.unwrap_err();
1163        assert_eq!(err.kind(), "invalid_route");
1164    }
1165
1166    #[tokio::test]
1167    async fn fake_router_remove_clears_route() {
1168        let router = FakeRouter::new();
1169        let route = ServiceRoute {
1170            service_id: "x".into(),
1171            cluster_ip: "10.0.0.1".into(),
1172            ports: vec![],
1173            endpoints: BTreeSet::new(),
1174        };
1175        router.upsert(&route).await.unwrap();
1176        router.remove("x").await.unwrap();
1177        assert_eq!(router.route_count().await, 0);
1178    }
1179
1180    #[tokio::test]
1181    async fn fake_router_list_returns_installed() {
1182        let router = FakeRouter::new();
1183        let route = ServiceRoute {
1184            service_id: "a".into(),
1185            cluster_ip: "10.0.0.1".into(),
1186            ports: vec![],
1187            endpoints: BTreeSet::new(),
1188        };
1189        router.upsert(&route).await.unwrap();
1190        let list = router.list().await.unwrap();
1191        assert_eq!(list.len(), 1);
1192        assert!(list.contains_key("a"));
1193    }
1194
1195    #[test]
1196    fn error_kinds_are_stable() {
1197        assert_eq!(RouterError::Backend("x".into()).kind(), "backend");
1198        assert_eq!(
1199            RouterError::InvalidRoute("x".into()).kind(),
1200            "invalid_route"
1201        );
1202    }
1203
1204    #[test]
1205    fn ipvs_router_render_script_contains_virtual_services() {
1206        let route = ServiceRoute {
1207            service_id: "default/podinfo".into(),
1208            cluster_ip: "10.96.5.1".into(),
1209            ports: vec![PortMap {
1210                name: "http".into(),
1211                service_port: 80,
1212                target_port: 9898,
1213                protocol: "TCP".into(),
1214            }],
1215            endpoints: ["10.42.0.1".to_string(), "10.42.0.2".to_string()]
1216                .into_iter()
1217                .collect(),
1218        };
1219        let script = IpvsRouter::render_script(&route);
1220        assert!(script.contains("-A -t 10.96.5.1:80 -s rr"));
1221        assert!(script.contains("-a -t 10.96.5.1:80 -r 10.42.0.1:9898 -m"));
1222        assert!(script.contains("-a -t 10.96.5.1:80 -r 10.42.0.2:9898 -m"));
1223    }
1224
1225    #[test]
1226    fn ipvs_router_renders_udp_with_u_flag() {
1227        let route = ServiceRoute {
1228            service_id: "default/dns".into(),
1229            cluster_ip: "10.96.0.10".into(),
1230            ports: vec![PortMap {
1231                name: "dns".into(),
1232                service_port: 53,
1233                target_port: 53,
1234                protocol: "UDP".into(),
1235            }],
1236            endpoints: ["10.42.0.5".to_string()].into_iter().collect(),
1237        };
1238        let script = IpvsRouter::render_script(&route);
1239        assert!(script.contains("-A -u 10.96.0.10:53"));
1240        assert!(script.contains("-a -u 10.96.0.10:53 -r 10.42.0.5:53"));
1241    }
1242
1243    #[test]
1244    fn ipvs_router_name_is_stable() {
1245        assert_eq!(IpvsRouter::new().name(), "ipvs");
1246    }
1247
1248    #[test]
1249    fn ipvs_with_binary_uses_path() {
1250        let r = IpvsRouter::with_binary("/usr/sbin/ipvsadm");
1251        assert_eq!(r.binary, "/usr/sbin/ipvsadm");
1252    }
1253
1254    #[tokio::test]
1255    async fn ipvs_rejects_empty_service_id() {
1256        let r = IpvsRouter::with_binary("/nonexistent-binary");
1257        let route = ServiceRoute {
1258            service_id: String::new(),
1259            cluster_ip: "10.0.0.1".into(),
1260            ports: vec![],
1261            endpoints: BTreeSet::new(),
1262        };
1263        let err = r.upsert(&route).await.unwrap_err();
1264        assert_eq!(err.kind(), "invalid_route");
1265    }
1266
1267    fn route(id: &str, ip: &str, ports: &[(u16, u16)], endpoints: &[&str]) -> ServiceRoute {
1268        ServiceRoute {
1269            service_id: id.into(),
1270            cluster_ip: ip.into(),
1271            ports: ports
1272                .iter()
1273                .map(|(service_port, target_port)| PortMap {
1274                    name: service_port.to_string(),
1275                    service_port: *service_port,
1276                    target_port: *target_port,
1277                    protocol: "TCP".into(),
1278                })
1279                .collect(),
1280            endpoints: endpoints.iter().map(|e| (*e).to_string()).collect(),
1281        }
1282    }
1283
1284    #[test]
1285    fn a_service_without_a_virtual_ip_has_no_route() {
1286        for spec in [
1287            json!({"clusterIP": "None", "ports": [{"port": 9093}]}),
1288            json!({"clusterIP": "", "ports": [{"port": 80}]}),
1289            json!({"type": "ExternalName", "externalName": "example.com", "ports": [{"port": 80}]}),
1290        ] {
1291            let svc = json!({"metadata": {"name": "s"}, "spec": spec});
1292            assert!(
1293                ServiceRoutingController::build_route(&svc, None, "ns/s").is_none(),
1294                "{svc}"
1295            );
1296        }
1297    }
1298
1299    #[test]
1300    fn the_sync_script_rebuilds_kube_services_so_no_stale_jump_survives() {
1301        let before = route(
1302            "monitoring/vmsingle-rio",
1303            "10.97.0.10",
1304            &[(8429, 8429)],
1305            &["10.89.0.9"],
1306        );
1307        let after = route(
1308            "monitoring/vmsingle-rio",
1309            "10.97.0.13",
1310            &[(8429, 8429)],
1311            &["10.89.0.166"],
1312        );
1313        let gone = route(
1314            "monitoring/old",
1315            "10.97.0.9",
1316            &[(8080, 8080)],
1317            &["10.89.0.5"],
1318        );
1319        let desired: BTreeMap<String, ServiceRoute> = [(after.service_id.clone(), after.clone())]
1320            .into_iter()
1321            .collect();
1322        let installed: BTreeMap<String, ServiceRoute> = [
1323            (before.service_id.clone(), before.clone()),
1324            (gone.service_id.clone(), gone.clone()),
1325        ]
1326        .into_iter()
1327        .collect();
1328        let script = IptablesRouter::render_sync_script(&desired, &installed);
1329        assert!(script.contains(":KUBE-SERVICES - [0:0]\n"), "{script}");
1330        assert!(script.contains("-A KUBE-SERVICES -d 10.97.0.13/32 -p tcp --dport 8429"));
1331        assert!(!script.contains("10.97.0.10"), "{script}");
1332        assert!(!script.contains("-d 10.97.0.9/32"), "{script}");
1333        assert!(script.contains("DNAT --to-destination 10.89.0.166:8429"));
1334        for chain in IptablesRouter::chains_of(&gone) {
1335            assert!(
1336                script.contains(&format!("-X {chain}\n")),
1337                "{chain} not deleted"
1338            );
1339        }
1340        for chain in IptablesRouter::chains_of(&after) {
1341            assert!(
1342                !script.contains(&format!("-X {chain}\n")),
1343                "{chain} deleted"
1344            );
1345        }
1346    }
1347
1348    #[test]
1349    fn each_service_port_reaches_only_its_own_target_port() {
1350        let r = route(
1351            "monitoring/operator",
1352            "10.97.0.11",
1353            &[(8080, 8080), (9443, 9443)],
1354            &["10.89.0.121"],
1355        );
1356        let one: BTreeMap<String, ServiceRoute> = [(r.service_id.clone(), r)].into_iter().collect();
1357        let script = IptablesRouter::render_sync_script(&one, &BTreeMap::new());
1358        let chain_of = |port: &str| {
1359            script
1360                .lines()
1361                .find(|l| {
1362                    l.starts_with("-A KUBE-SERVICES") && l.contains(&format!("--dport {port} "))
1363                })
1364                .and_then(|l| l.rsplit(' ').next())
1365                .unwrap()
1366                .to_string()
1367        };
1368        let (http, webhook) = (chain_of("8080"), chain_of("9443"));
1369        assert_ne!(http, webhook);
1370        let reaches = |svc_chain: &str| -> Vec<String> {
1371            let seps: Vec<String> = script
1372                .lines()
1373                .filter(|l| l.starts_with(&format!("-A {svc_chain} ")))
1374                .filter_map(|l| l.rsplit(' ').next().map(str::to_string))
1375                .collect();
1376            script
1377                .lines()
1378                .filter(|l| seps.iter().any(|s| l.starts_with(&format!("-A {s} "))))
1379                .filter_map(|l| l.rsplit(' ').next().map(str::to_string))
1380                .collect()
1381        };
1382        assert_eq!(reaches(&http), ["10.89.0.121:8080"]);
1383        assert_eq!(reaches(&webhook), ["10.89.0.121:9443"]);
1384    }
1385
1386    #[test]
1387    fn iptables_router_render_script_contains_chains() {
1388        let route = ServiceRoute {
1389            service_id: "default/podinfo".into(),
1390            cluster_ip: "10.96.5.1".into(),
1391            ports: vec![PortMap {
1392                name: "http".into(),
1393                service_port: 80,
1394                target_port: 9898,
1395                protocol: "TCP".into(),
1396            }],
1397            endpoints: ["10.42.0.1".to_string(), "10.42.0.2".to_string()]
1398                .into_iter()
1399                .collect(),
1400        };
1401        let script = IptablesRouter::render_script(&route);
1402        assert!(script.starts_with("*nat\n"));
1403        assert!(script.ends_with("COMMIT\n"));
1404        assert!(script.contains("-A KUBE-SERVICES -d 10.96.5.1/32 -p tcp --dport 80"));
1405        assert!(script.contains("DNAT --to-destination 10.42.0.1:9898"));
1406        assert!(script.contains("DNAT --to-destination 10.42.0.2:9898"));
1407        assert!(script.contains("-m statistic --mode random"));
1408    }
1409
1410    /// The root chain and its hooks are engenho's to create. A node that
1411    /// never ran kube-proxy has neither, and appending into an absent chain
1412    /// fails the whole restore.
1413    #[test]
1414    fn the_router_creates_its_own_root_chain_and_both_hooks() {
1415        assert_eq!(
1416            IptablesRouter::root_chain_create_argv(),
1417            ["-t", "nat", "-N", "KUBE-SERVICES"]
1418        );
1419        let check = IptablesRouter::hook_argv("PREROUTING", "-C");
1420        assert_eq!(check[0..4], ["-t", "nat", "-C", "PREROUTING"]);
1421        assert!(check.contains(&"KUBE-SERVICES".to_string()));
1422
1423        // Inserted at position 1, never appended: a DNAT placed after a
1424        // blanket MASQUERADE or RETURN never runs.
1425        let insert = IptablesRouter::hook_argv("OUTPUT", "-I");
1426        assert_eq!(insert[0..5], ["-t", "nat", "-I", "OUTPUT", "1"]);
1427
1428        // The check and the insert must describe the SAME rule apart from
1429        // the verb and the position, or the check never matches and a hook
1430        // is inserted on every single reconcile.
1431        let check_out = IptablesRouter::hook_argv("OUTPUT", "-C");
1432        assert_eq!(check_out[4..], insert[5..]);
1433    }
1434
1435    /// A node pinned to the legacy backend must be checked through the
1436    /// legacy binary; asking nft whether a legacy rule exists answers "no"
1437    /// forever, and the hook is re-inserted every reconcile.
1438    #[test]
1439    fn the_control_binary_keeps_the_backend_variant() {
1440        assert_eq!(
1441            IptablesRouter::control_binary_for("iptables-restore"),
1442            "iptables"
1443        );
1444        assert_eq!(
1445            IptablesRouter::control_binary_for("iptables-legacy-restore"),
1446            "iptables-legacy"
1447        );
1448        assert_eq!(
1449            IptablesRouter::control_binary_for("/usr/sbin/iptables-nft-restore"),
1450            "/usr/sbin/iptables-nft"
1451        );
1452    }
1453
1454    #[test]
1455    fn iptables_chain_name_is_deterministic_short_hex() {
1456        let n = chain_name("KUBE-SVC", "default/podinfo");
1457        assert!(n.starts_with("KUBE-SVC-"));
1458        // 12 hex chars (uppercase).
1459        let suffix = n.trim_start_matches("KUBE-SVC-");
1460        assert_eq!(suffix.len(), 12);
1461        assert!(suffix.chars().all(|c| c.is_ascii_hexdigit()));
1462        // Determinism: same input → same chain name.
1463        assert_eq!(n, chain_name("KUBE-SVC", "default/podinfo"));
1464    }
1465
1466    #[test]
1467    fn iptables_router_name_is_stable() {
1468        assert_eq!(IptablesRouter::new().name(), "iptables");
1469    }
1470
1471    #[test]
1472    fn datapath_install_maturity_is_typed_per_backend() {
1473        // FakeRouter (and the macOS-VM topology it stands in for) COMPUTES
1474        // routes but installs no kernel rule — the typed deferral.
1475        assert_eq!(FakeRouter::new().datapath(), DatapathInstall::Computed);
1476        // The kernel backends INSTALL the datapath (on a Linux node).
1477        assert_eq!(IptablesRouter::new().datapath(), DatapathInstall::Installed);
1478        assert_eq!(IpvsRouter::new().datapath(), DatapathInstall::Installed);
1479    }
1480
1481    #[test]
1482    fn iptables_with_binary_uses_path() {
1483        let r = IptablesRouter::with_binary("/sbin/iptables-restore");
1484        assert_eq!(r.binary, "/sbin/iptables-restore");
1485    }
1486
1487    #[tokio::test]
1488    async fn iptables_rejects_empty_service_id() {
1489        let r = IptablesRouter::with_binary("/nonexistent-binary");
1490        let route = ServiceRoute {
1491            service_id: String::new(),
1492            cluster_ip: "10.0.0.1".into(),
1493            ports: vec![],
1494            endpoints: BTreeSet::new(),
1495        };
1496        let err = r.upsert(&route).await.unwrap_err();
1497        assert_eq!(err.kind(), "invalid_route");
1498    }
1499
1500    #[test]
1501    fn controller_name_is_stable() {
1502        struct Fake;
1503        #[async_trait]
1504        impl Controller for Fake {
1505            fn name(&self) -> &'static str {
1506                "service_router"
1507            }
1508            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
1509                Ok(ReconcileReport::default().into())
1510            }
1511        }
1512        assert_eq!(Fake.name(), "service_router");
1513    }
1514
1515    async fn live_store() -> Arc<StoreMesh> {
1516        use engenho_store::{InProcessRouter, default_config};
1517        use std::time::Duration;
1518        let router = InProcessRouter::new();
1519        let cfg = default_config("controllers-service-router").unwrap();
1520        let store = Arc::new(
1521            StoreMesh::start(1, "in-process://1".into(), router, cfg)
1522                .await
1523                .unwrap(),
1524        );
1525        store.initialize_singleton().await.unwrap();
1526        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
1527        store
1528    }
1529
1530    /// The off-Linux dev path: a `FakeRouter` (compute-only) backend
1531    /// reconciles a Service + Endpoints into a computed route WITHOUT any
1532    /// kernel call (no iptables/ipvs binary touched), and its datapath
1533    /// maturity is the typed `DatapathInstall::Computed`. This is exactly
1534    /// the backend the runtime selects on a Darwin host (Auto → `ComputeOnly`),
1535    /// so the local daemon keeps running fine.
1536    #[tokio::test]
1537    async fn compute_only_backend_reconciles_route_without_kernel_call() {
1538        use engenho_store::{ResourceKey, command::Reason, command::ResourceCommand};
1539
1540        let store = live_store().await;
1541        store
1542            .propose(ResourceCommand::put(
1543                ResourceKey::namespaced("", "v1", "Service", "default", "podinfo"),
1544                serde_json::json!({
1545                    "kind": "Service", "apiVersion": "v1",
1546                    "metadata": {"name": "podinfo", "namespace": "default"},
1547                    "spec": {"clusterIP": "10.96.0.10",
1548                             "ports": [{"name": "http", "port": 80, "targetPort": 8080}]}
1549                }),
1550                Reason::Operator,
1551            ))
1552            .await
1553            .unwrap();
1554        store
1555            .propose(ResourceCommand::put(
1556                ResourceKey::namespaced("", "v1", "Endpoints", "default", "podinfo"),
1557                serde_json::json!({
1558                    "kind": "Endpoints", "apiVersion": "v1",
1559                    "metadata": {"name": "podinfo", "namespace": "default"},
1560                    "subsets": [{"addresses": [{"ip": "10.0.0.1"}, {"ip": "10.0.0.2"}]}]
1561                }),
1562                Reason::Operator,
1563            ))
1564            .await
1565            .unwrap();
1566
1567        // The compute-only backend = the FakeRouter. Its datapath maturity
1568        // is the typed Computed value — no kernel rule is installed.
1569        let backend = Arc::new(FakeRouter::new());
1570        assert_eq!(backend.datapath(), DatapathInstall::Computed);
1571
1572        let controller =
1573            ServiceRoutingController::new(store.clone(), backend.clone(), Some("default".into()));
1574        controller.tick().await.unwrap();
1575
1576        // The route was computed + tracked: one upsert event, one route,
1577        // the right backends — proving the controller ran end-to-end with
1578        // no real iptables shell-out.
1579        assert_eq!(backend.route_count().await, 1);
1580        let events = backend.events().await;
1581        assert_eq!(
1582            events,
1583            vec![FakeRouterEvent::Upsert("default/podinfo".into())]
1584        );
1585        let installed = backend.list().await.unwrap();
1586        let route = installed.get("default/podinfo").expect("route computed");
1587        assert_eq!(route.cluster_ip, "10.96.0.10");
1588        assert_eq!(
1589            route.endpoints,
1590            ["10.0.0.1".to_string(), "10.0.0.2".to_string()]
1591                .into_iter()
1592                .collect()
1593        );
1594    }
1595}