Skip to main content

engenho_controllers/
endpoints.rs

1//! `EndpointsController` — materializes Endpoints **and** `EndpointSlice`
2//! objects from Service selectors + matching Pod IPs.
3//!
4//! K8s rule: for each Service, find Pods in the same namespace
5//! whose labels satisfy `service.spec.selector` AND are ready
6//! AND have a `status.podIP`. Materialize one Endpoints object
7//! (same name + namespace as the Service) with the Pod IPs in
8//! `subsets[].addresses`.
9//!
10//! ## `EndpointSlice` (discovery.k8s.io/v1)
11//!
12//! In addition to the legacy Endpoints object, the controller emits ONE
13//! `discovery.k8s.io/v1` `EndpointSlice` per Service — the modern endpoint-
14//! publishing kind kube-proxy + many controllers consume. Both objects
15//! are derived from the SAME selector→pod resolution (no fork): the slice
16//! is a parallel projection of the identical `(ip, pod_name)` set. The
17//! slice carries the upstream-required `kubernetes.io/service-name` label
18//! + an owner reference back to the Service, and is named `<service>`
19//! (engenho emits exactly one slice per Service; upstream shards into
20//! `<service>-<hash>` only above 1000 endpoints — a typed follow-up).
21//!
22//! This is the FIRST selector-based controller in engenho-controllers
23//! (vs the owner-ref-based ReplicaSet/Deployment/GC). It validates
24//! that the Controller trait is general — the trait knows nothing
25//! about ownership; selector matching is just a different
26//! reconciliation predicate.
27
28use std::sync::Arc;
29
30use async_trait::async_trait;
31use engenho_store::{
32    StoreMesh,
33    command::{Reason, ResourceCommand},
34    resource::ResourceKey,
35};
36use serde_json::{Value, json};
37use tracing::debug;
38
39use crate::controller::{Controller, ReconcileOutcome};
40use crate::create_stamp::{CreateClock, stamp_create_timestamp, wall_clock};
41use crate::effect::Effect;
42use crate::error::ControllerError;
43use crate::event_recorder::Reason as EventReason;
44use crate::meta::ObjectMeta;
45use crate::owner::{owner_ref_for, set_owner_reference};
46use crate::reads::{DeclaresReads, Reads, gvk};
47use crate::selector::{matches_labels, service_selector};
48use crate::status::pod_is_ready;
49use crate::sweep::{ObjectOutcome, Sweep, impl_sweep_event_sink};
50
51pub struct EndpointsController {
52    store: Arc<StoreMesh>,
53    namespace: Option<String>,
54    /// Boundary clock read ONCE per created Endpoints object to freeze
55    /// `metadata.creationTimestamp` into the replicated `Put` (see
56    /// [`crate::create_stamp`]). Production = [`wall_clock`]; unit tests
57    /// pin a fixed instant via [`Self::with_clock`].
58    create_clock: CreateClock,
59    /// Per-Service isolation (`FailedToUpdateEndpoint` on an Item failure).
60    sweep: Sweep,
61}
62
63impl_sweep_event_sink!(EndpointsController);
64
65impl EndpointsController {
66    #[must_use]
67    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
68        Self::with_clock(store, namespace, wall_clock)
69    }
70
71    /// Construct with a pinned [`CreateClock`] — the unit-test determinism seam
72    /// for the `creationTimestamp` boundary stamp.
73    #[must_use]
74    pub fn with_clock(
75        store: Arc<StoreMesh>,
76        namespace: Option<String>,
77        clock: CreateClock,
78    ) -> Self {
79        Self {
80            store,
81            namespace,
82            create_clock: clock,
83            sweep: Sweep::new("endpoint-controller", EventReason::FailedToUpdateEndpoint),
84        }
85    }
86
87    /// Pod's IP from `status.podIP`. Returns None for unbound
88    /// pods (no status yet) or for pods missing the field.
89    fn pod_ip(pod: &Value) -> Option<&str> {
90        pod.get("status")
91            .and_then(|s| s.get("podIP"))
92            .and_then(|i| i.as_str())
93    }
94
95    /// Resolve a Service's ports to the POD-SIDE ports an Endpoints object
96    /// must publish.
97    ///
98    /// **`subsets[].ports[].port` is the TARGET port, not the service port.**
99    /// Getting this wrong does not produce an error anywhere: the Endpoints
100    /// object is well-formed, the Service looks healthy, and the datapath
101    /// faithfully DNATs to a port nothing listens on. Measured on rio
102    /// 2026-09-15 — Flux's source-controller Service is
103    /// `port: 80, targetPort: "http"` and the container serves 9090.
104    /// engenho published `port: 80`, so every connection to the `ClusterIP`
105    /// was refused while the pod answered 200 on its real port, and
106    /// kustomize-controller could never fetch an artifact.
107    ///
108    /// Three cases, and the middle one is the one that bites:
109    ///   * `targetPort` absent      -> the service port (upstream's default)
110    ///   * `targetPort` a STRING    -> the containerPort with that NAME
111    ///   * `targetPort` an integer  -> itself
112    ///
113    /// A named port is resolved against the pods actually backing the
114    /// Service. If no backing container declares the name, the port is
115    /// dropped rather than guessed: publishing a wrong number produces a
116    /// silent blackhole, publishing nothing produces a Service with no port,
117    /// which is at least visible.
118    fn resolve_service_ports(svc: &Value, pods: &[&Value]) -> Vec<Value> {
119        svc.get("spec")
120            .and_then(|s| s.get("ports"))
121            .and_then(|p| p.as_array())
122            .map(|arr| {
123                arr.iter()
124                    .filter_map(|p| {
125                        let protocol = p.get("protocol").cloned().unwrap_or_else(|| json!("TCP"));
126                        let name = p.get("name").cloned().unwrap_or(Value::Null);
127                        let resolved = match p.get("targetPort") {
128                            None | Some(Value::Null) => p.get("port").and_then(Value::as_i64),
129                            Some(Value::Number(n)) => n.as_i64(),
130                            Some(Value::String(named)) => Self::container_port_named(pods, named),
131                            Some(_) => None,
132                        }?;
133                        Some(json!({ "name": name, "port": resolved, "protocol": protocol }))
134                    })
135                    .collect()
136            })
137            .unwrap_or_default()
138    }
139
140    /// The `containerPort` declared under `name` by any container of any
141    /// backing pod. Upstream resolves per-pod; engenho publishes one subset,
142    /// so the first match wins — which is correct whenever the backing pods
143    /// share a template, and every Service selecting a single workload does.
144    fn container_port_named(pods: &[&Value], name: &str) -> Option<i64> {
145        pods.iter()
146            .filter_map(|pod| pod.get("spec")?.get("containers")?.as_array())
147            .flatten()
148            .filter_map(|c| c.get("ports")?.as_array())
149            .flatten()
150            .find(|port| port.get("name").and_then(Value::as_str) == Some(name))
151            .and_then(|port| port.get("containerPort").and_then(Value::as_i64))
152    }
153
154    /// Build the Endpoints object body. `addresses` is a typed
155    /// list of (ip, `target_pod_name`) pairs.
156    fn build_endpoints(svc: &Value, addresses: Vec<(String, String)>, pods: &[&Value]) -> Value {
157        let name = svc.name().unwrap_or("");
158        // The pod-side ports, NOT the Service's spec.ports verbatim.
159        let ports = Value::Array(Self::resolve_service_ports(svc, pods));
160
161        let subset_addresses: Vec<Value> = addresses
162            .into_iter()
163            .map(|(ip, pod_name)| {
164                json!({
165                    "ip": ip,
166                    "targetRef": {
167                        "kind": "Pod",
168                        "name": pod_name
169                    }
170                })
171            })
172            .collect();
173
174        json!({
175            "kind": "Endpoints",
176            "apiVersion": "v1",
177            "metadata": { "name": name },
178            "subsets": [
179                {
180                    "addresses": subset_addresses,
181                    "ports": ports
182                }
183            ]
184        })
185    }
186
187    /// Build the `discovery.k8s.io/v1` `EndpointSlice` body from the SAME
188    /// `(ip, pod_name)` set the Endpoints object uses. Parallel projection,
189    /// not a fork: the caller resolves the selector once and feeds both.
190    ///
191    /// The slice carries the required `kubernetes.io/service-name` label so
192    /// consumers (kube-proxy, the routing controller) can locate every
193    /// slice for a Service. `addressType: IPv4` (engenho's pods are IPv4
194    /// today; dual-stack is a typed follow-up). Each endpoint is marked
195    /// `conditions.ready = true` (the caller already filtered to ready,
196    /// ip-bearing pods).
197    fn build_endpoint_slice(svc: &Value, addresses: &[(String, String)], pods: &[&Value]) -> Value {
198        let name = svc.name().unwrap_or("");
199        // EndpointSlice ports use the same `(name, port, protocol)` shape as
200        // the Service ports — projected verbatim (the Service's targetPort is
201        // the pod-side port the slice publishes; engenho's Endpoints carries
202        // the Service ports today, mirrored here for one source of truth).
203        // The SAME resolution the Endpoints object uses — one source of truth,
204        // as the doc comment above promises. Projecting `targetPort` verbatim
205        // here would republish a NAMED port as the literal string "http".
206        let ports = Self::resolve_service_ports(svc, pods);
207
208        let endpoints: Vec<Value> = addresses
209            .iter()
210            .map(|(ip, pod_name)| {
211                json!({
212                    "addresses": [ip],
213                    "conditions": { "ready": true },
214                    "targetRef": { "kind": "Pod", "name": pod_name }
215                })
216            })
217            .collect();
218
219        json!({
220            "kind": "EndpointSlice",
221            "apiVersion": "discovery.k8s.io/v1",
222            "metadata": {
223                "name": name,
224                "labels": { "kubernetes.io/service-name": name }
225            },
226            "addressType": "IPv4",
227            "endpoints": endpoints,
228            "ports": ports
229        })
230    }
231
232    /// Reconcile the `EndpointSlice` for a Service: owner-ref it, stamp the
233    /// creationTimestamp on create, and write it only when the slice body
234    /// changed (idempotent). Mirrors the Endpoints reconcile shape so both
235    /// projections share one convergence discipline. Returns what the
236    /// write did (`Unchanged` when none was needed).
237    async fn reconcile_endpoint_slice(
238        &self,
239        namespace: &str,
240        svc_name: &str,
241        mut slice: Value,
242        owner_ref: crate::owner::OwnerReference,
243    ) -> Result<Effect, ControllerError> {
244        let slice_key = ResourceKey::namespaced(
245            "discovery.k8s.io",
246            "v1",
247            "EndpointSlice",
248            namespace,
249            svc_name,
250        );
251        set_owner_reference(&mut slice, owner_ref)?;
252
253        let existing = self.store.get(&slice_key).await;
254        if let Some(ref current) = existing {
255            if slice_bodies_equivalent(current, &slice) {
256                return Ok(Effect::Unchanged);
257            }
258        } else {
259            // First materialization: freeze the creationTimestamp from one
260            // boundary clock read (same discipline as Endpoints).
261            stamp_create_timestamp(&mut slice, self.create_clock);
262        }
263
264        let applied = self
265            .store
266            .propose(ResourceCommand::Put {
267                key: slice_key,
268                value: slice,
269                expected: None,
270                reason: Reason::Controller,
271            })
272            .await?;
273        Ok(Effect::of(applied.op))
274    }
275}
276
277/// The Services it projects, the Pods their selectors match, and the
278/// Endpoints and `EndpointSlice` it compares against before writing.
279impl DeclaresReads for EndpointsController {
280    fn reads(&self) -> Reads {
281        Reads::of(&[
282            gvk("", "v1", "Service"),
283            gvk("", "v1", "Pod"),
284            gvk("", "v1", "Endpoints"),
285            gvk("discovery.k8s.io", "v1", "EndpointSlice"),
286        ])
287    }
288}
289
290#[async_trait]
291impl Controller for EndpointsController {
292    fn name(&self) -> &'static str {
293        "endpoints"
294    }
295
296    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
297        let services = self
298            .store
299            .list("", "v1", "Service", self.namespace.as_deref())
300            .await;
301        // Each Service isolated: an Item failure is announced on that
302        // Service and the rest still converge; a store failure ends the
303        // tick, as before.
304        let report = self
305            .sweep
306            .run(&services, |svc_key, svc_value| async move {
307                ObjectOutcome::settle(self.reconcile_service(svc_key, svc_value).await)
308            })
309            .await?;
310        Ok(ReconcileOutcome::from(report))
311    }
312}
313
314impl EndpointsController {
315    /// One Service's `Endpoints` + `EndpointSlice`.
316    async fn reconcile_service(
317        &self,
318        svc_key: &ResourceKey,
319        svc_value: &Value,
320    ) -> Result<ObjectOutcome, ControllerError> {
321        let Some(selector) = service_selector(svc_value) else {
322            return Ok(ObjectOutcome::SKIPPED);
323        };
324        let Some(owner_ref) = owner_ref_for(svc_value, "v1", "Service") else {
325            return Ok(ObjectOutcome::SKIPPED);
326        };
327        let ns = svc_key.namespace.as_deref();
328        let all_pods = self.store.list("", "v1", "Pod", ns).await;
329
330        // The pods backing this Service, kept so a NAMED targetPort can be
331        // resolved against the containerPort that actually declares it.
332        let matched_pods: Vec<&Value> = all_pods
333            .iter()
334            .filter(|(_, pod)| matches_labels(pod, selector))
335            .filter(|(_, pod)| pod_is_ready(pod))
336            .map(|(_, pod)| pod)
337            .collect();
338
339        // Filter to ready, ip-bearing pods matching the selector.
340        let mut addresses: Vec<(String, String)> = all_pods
341            .iter()
342            .filter(|(_, pod)| matches_labels(pod, selector))
343            .filter(|(_, pod)| pod_is_ready(pod))
344            .filter_map(|(_, pod)| {
345                let ip = Self::pod_ip(pod)?.to_string();
346                let name = pod
347                    .get("metadata")
348                    .and_then(|m| m.get("name"))
349                    .and_then(|n| n.as_str())?
350                    .to_string();
351                Some((ip, name))
352            })
353            .collect();
354        // Deterministic order for tests + diffing.
355        addresses.sort();
356
357        let endpoints_ns = ns.unwrap_or("default");
358        let svc_name = svc_value.name().unwrap_or("");
359        let endpoints_key = ResourceKey::namespaced("", "v1", "Endpoints", endpoints_ns, svc_name);
360
361        // Build the EndpointSlice from the SAME resolved address set
362        // (borrowed before `addresses` is moved into build_endpoints).
363        let slice_body = Self::build_endpoint_slice(svc_value, &addresses, &matched_pods);
364
365        // Check if existing Endpoints already matches what we'd write.
366        let existing = self.store.get(&endpoints_key).await;
367        let mut new_endpoints = Self::build_endpoints(svc_value, addresses, &matched_pods);
368        set_owner_reference(&mut new_endpoints, owner_ref.clone())?;
369
370        // Emit the EndpointSlice (parallel projection). Done before the
371        // Endpoints early-return so the slice converges even when the
372        // Endpoints subsets are unchanged (e.g. first slice on an
373        // already-materialized Endpoints).
374        let slice = self
375            .reconcile_endpoint_slice(endpoints_ns, svc_name, slice_body, owner_ref.clone())
376            .await?;
377
378        if let Some(ref current) = existing {
379            if subsets_equivalent(current, &new_endpoints) {
380                return Ok(ObjectOutcome::from(slice));
381            }
382        } else {
383            // CREATE (no existing Endpoints): freeze creationTimestamp
384            // from ONE boundary clock read so kubectl AGE renders. An
385            // UPDATE (existing) is left untouched — never bumped.
386            stamp_create_timestamp(&mut new_endpoints, self.create_clock);
387        }
388
389        debug!(
390            svc = %svc_key.label(),
391            endpoint_count = new_endpoints
392                .get("subsets")
393                .and_then(|s| s.get(0))
394                .and_then(|s| s.get("addresses"))
395                .and_then(|a| a.as_array())
396                .map_or(0, Vec::len),
397            "writing endpoints"
398        );
399
400        let applied = self
401            .store
402            .propose(ResourceCommand::Put {
403                key: endpoints_key,
404                value: new_endpoints,
405                expected: None,
406                reason: Reason::Controller,
407            })
408            .await?;
409        Ok(ObjectOutcome::from(slice.and(Effect::of(applied.op))))
410    }
411}
412
413/// Compare two Endpoints values for subset equivalence (ignores
414/// metadata.resourceVersion, uid, etc. which the store auto-fills).
415fn subsets_equivalent(a: &Value, b: &Value) -> bool {
416    a.get("subsets") == b.get("subsets")
417}
418
419/// Compare two `EndpointSlice` values for body equivalence — the
420/// `endpoints` + `ports` + `addressType` carry the load-bearing state;
421/// metadata.resourceVersion/uid (store-filled) is ignored so a re-tick
422/// with the same pods is a no-op.
423fn slice_bodies_equivalent(a: &Value, b: &Value) -> bool {
424    a.get("endpoints") == b.get("endpoints")
425        && a.get("ports") == b.get("ports")
426        && a.get("addressType") == b.get("addressType")
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432
433    #[test]
434    fn pod_ip_reads_status_podip() {
435        let p = json!({"status": {"podIP": "10.0.0.1"}});
436        assert_eq!(EndpointsController::pod_ip(&p), Some("10.0.0.1"));
437    }
438
439    #[test]
440    fn pod_ip_none_when_missing() {
441        assert!(EndpointsController::pod_ip(&json!({})).is_none());
442        assert!(EndpointsController::pod_ip(&json!({"status": {}})).is_none());
443    }
444
445    #[test]
446    fn pod_is_ready_true_when_condition_true() {
447        let p = json!({
448            "status": {
449                "conditions": [{"type": "Ready", "status": "True"}]
450            }
451        });
452        assert!(crate::status::pod_is_ready(&p));
453    }
454
455    #[test]
456    fn pod_is_ready_false_when_condition_false() {
457        let p = json!({
458            "status": {
459                "conditions": [{"type": "Ready", "status": "False"}]
460            }
461        });
462        assert!(!crate::status::pod_is_ready(&p));
463    }
464
465    #[test]
466    fn pod_is_ready_false_when_no_status() {
467        let p = json!({"metadata": {"name": "p"}});
468        assert!(!crate::status::pod_is_ready(&p));
469    }
470
471    #[test]
472    fn build_endpoints_carries_selector_addresses() {
473        let svc = json!({
474            "metadata": {"name": "podinfo"},
475            "spec": {"selector": {"app": "podinfo"}, "ports": [{"port": 80}]}
476        });
477        let addrs = vec![
478            ("10.0.0.1".into(), "p1".into()),
479            ("10.0.0.2".into(), "p2".into()),
480        ];
481        let ep = EndpointsController::build_endpoints(&svc, addrs, &[]);
482        assert_eq!(ep.get("kind").unwrap(), "Endpoints");
483        let subsets = ep.get("subsets").unwrap().as_array().unwrap();
484        assert_eq!(subsets.len(), 1);
485        let addresses = subsets[0].get("addresses").unwrap().as_array().unwrap();
486        assert_eq!(addresses.len(), 2);
487        assert_eq!(addresses[0].get("ip").unwrap(), "10.0.0.1");
488        assert_eq!(
489            addresses[0].get("targetRef").unwrap().get("kind").unwrap(),
490            "Pod"
491        );
492        // Ports carried through from service.
493        let ports = subsets[0].get("ports").unwrap().as_array().unwrap();
494        assert_eq!(ports.len(), 1);
495        assert_eq!(ports[0].get("port").unwrap(), 80);
496    }
497
498    #[test]
499    fn build_endpoints_two_addresses_in_sorted_order() {
500        // M0.3 podIP→Endpoints math: two ready pods on the same selector
501        // produce a 2-address subset. The controller sorts addresses
502        // (endpoints.rs:170) before building, so the IP+name pairs land in
503        // deterministic order regardless of pod-listing order — proven
504        // here by feeding them pre-sorted (as the controller does) and
505        // asserting both IPs + their targetRefs survive intact. This pins
506        // the Endpoints-from-pods computation with NO container runtime.
507        let svc = json!({
508            "metadata": {"name": "podinfo"},
509            "spec": {"selector": {"app": "podinfo"}, "ports": [{"port": 80, "targetPort": 80}]}
510        });
511        let mut addrs = vec![
512            ("10.89.0.7".to_string(), "pod-b".to_string()),
513            ("10.89.0.4".to_string(), "pod-a".to_string()),
514        ];
515        // Mirror the controller's `addresses.sort()` before build.
516        addrs.sort();
517        let ep = EndpointsController::build_endpoints(&svc, addrs, &[]);
518        let subsets = ep.get("subsets").unwrap().as_array().unwrap();
519        assert_eq!(subsets.len(), 1);
520        let addresses = subsets[0].get("addresses").unwrap().as_array().unwrap();
521        assert_eq!(addresses.len(), 2);
522        // Sorted: 10.89.0.4 (pod-a) before 10.89.0.7 (pod-b).
523        assert_eq!(addresses[0].get("ip").unwrap(), "10.89.0.4");
524        assert_eq!(
525            addresses[0].get("targetRef").unwrap().get("name").unwrap(),
526            "pod-a"
527        );
528        assert_eq!(addresses[1].get("ip").unwrap(), "10.89.0.7");
529        assert_eq!(
530            addresses[1].get("targetRef").unwrap().get("name").unwrap(),
531            "pod-b"
532        );
533        // targetPort 80 == the service port here, so the published port is 80.
534        let ports = subsets[0].get("ports").unwrap().as_array().unwrap();
535        assert_eq!(ports[0].get("port").unwrap(), 80);
536    }
537
538    /// The exact Service that broke rio: `port: 80, targetPort: "http"`, a
539    /// container serving 9090. Publishing 80 gives a well-formed Endpoints,
540    /// a healthy-looking Service, and a datapath that DNATs to a port
541    /// nothing listens on.
542    #[test]
543    fn a_named_target_port_resolves_to_the_container_port() {
544        let svc = json!({
545            "metadata": {"name": "source-controller"},
546            "spec": {
547                "selector": {"app": "source-controller"},
548                "ports": [{"name": "http", "port": 80, "targetPort": "http", "protocol": "TCP"}]
549            }
550        });
551        let pod = json!({
552            "metadata": {"name": "source-controller-0"},
553            "spec": {"containers": [{"name": "manager", "ports": [{"name": "http", "containerPort": 9090}]}]}
554        });
555        let ports = EndpointsController::resolve_service_ports(&svc, &[&pod]);
556        assert_eq!(ports.len(), 1);
557        assert_eq!(
558            ports[0].get("port").unwrap(),
559            9090,
560            "the pod-side port, not the service port: {ports:?}"
561        );
562        assert_eq!(ports[0].get("name").unwrap(), "http");
563        assert_eq!(ports[0].get("protocol").unwrap(), "TCP");
564    }
565
566    /// Negative control: with NO pod declaring the name there is nothing to
567    /// resolve to, and the port is DROPPED rather than guessed. A wrong
568    /// number is a silent blackhole; an absent port is at least visible.
569    #[test]
570    fn an_unresolvable_named_port_is_dropped_not_guessed() {
571        let svc = json!({
572            "metadata": {"name": "svc"},
573            "spec": {"ports": [{"name": "http", "port": 80, "targetPort": "grpc"}]}
574        });
575        let pod = json!({
576            "metadata": {"name": "p"},
577            "spec": {"containers": [{"name": "c", "ports": [{"name": "http", "containerPort": 9090}]}]}
578        });
579        assert!(
580            EndpointsController::resolve_service_ports(&svc, &[&pod]).is_empty(),
581            "an unresolvable name must not fall back to the service port"
582        );
583    }
584
585    /// A numeric targetPort is itself, and an ABSENT one is the service port
586    /// — upstream's default. Without this the common case would regress
587    /// while the named case was being fixed.
588    #[test]
589    fn numeric_and_absent_target_ports_keep_their_upstream_meaning() {
590        let numeric = json!({"spec": {"ports": [{"port": 80, "targetPort": 9898}]}});
591        assert_eq!(
592            EndpointsController::resolve_service_ports(&numeric, &[])[0]
593                .get("port")
594                .unwrap(),
595            9898
596        );
597        let absent = json!({"spec": {"ports": [{"port": 5432}]}});
598        assert_eq!(
599            EndpointsController::resolve_service_ports(&absent, &[])[0]
600                .get("port")
601                .unwrap(),
602            5432
603        );
604    }
605
606    /// Both projections must agree. They are separate objects consumed by
607    /// different clients, and a datapath built from one while a consumer
608    /// reads the other is the drift this shares a resolver to prevent.
609    #[test]
610    fn the_endpoints_and_the_slice_publish_the_same_port() {
611        let svc = json!({
612            "metadata": {"name": "source-controller"},
613            "spec": {"selector": {"app": "x"},
614                     "ports": [{"name": "http", "port": 80, "targetPort": "http"}]}
615        });
616        let pod = json!({
617            "metadata": {"name": "p"},
618            "spec": {"containers": [{"name": "c", "ports": [{"name": "http", "containerPort": 9090}]}]}
619        });
620        let addrs = vec![("10.89.0.104".to_string(), "p".to_string())];
621        let ep = EndpointsController::build_endpoints(&svc, addrs.clone(), &[&pod]);
622        let slice = EndpointsController::build_endpoint_slice(&svc, &addrs, &[&pod]);
623        let ep_port = ep["subsets"][0]["ports"][0]["port"].clone();
624        let slice_port = slice["ports"][0]["port"].clone();
625        assert_eq!(ep_port, json!(9090));
626        assert_eq!(ep_port, slice_port, "Endpoints and EndpointSlice disagree");
627    }
628
629    #[test]
630    fn build_endpoint_slice_projects_addresses_and_label() {
631        let svc = json!({
632            "metadata": {"name": "podinfo"},
633            "spec": {"selector": {"app": "podinfo"},
634                     "ports": [{"name": "http", "port": 80, "targetPort": 9898}]}
635        });
636        let addrs = vec![
637            ("10.0.0.1".to_string(), "p1".to_string()),
638            ("10.0.0.2".to_string(), "p2".to_string()),
639        ];
640        let slice = EndpointsController::build_endpoint_slice(&svc, &addrs, &[]);
641        assert_eq!(slice["kind"], "EndpointSlice");
642        assert_eq!(slice["apiVersion"], "discovery.k8s.io/v1");
643        assert_eq!(slice["addressType"], "IPv4");
644        // Required service-name label so consumers can find the slice.
645        assert_eq!(
646            slice["metadata"]["labels"]["kubernetes.io/service-name"],
647            "podinfo"
648        );
649        // One endpoint per address, each ready, with its pod targetRef.
650        let eps = slice["endpoints"].as_array().unwrap();
651        assert_eq!(eps.len(), 2);
652        assert_eq!(eps[0]["addresses"][0], "10.0.0.1");
653        assert_eq!(eps[0]["conditions"]["ready"], true);
654        assert_eq!(eps[0]["targetRef"]["name"], "p1");
655        // Port published is the pod-side targetPort (9898), not service 80.
656        let ports = slice["ports"].as_array().unwrap();
657        assert_eq!(ports[0]["name"], "http");
658        assert_eq!(ports[0]["port"], 9898);
659        assert_eq!(ports[0]["protocol"], "TCP");
660    }
661
662    #[test]
663    fn build_endpoint_slice_empty_when_no_addresses() {
664        let svc = json!({"metadata": {"name": "x"}, "spec": {"ports": [{"port": 80}]}});
665        let slice = EndpointsController::build_endpoint_slice(&svc, &[], &[]);
666        assert!(slice["endpoints"].as_array().unwrap().is_empty());
667    }
668
669    #[test]
670    fn slice_bodies_equivalent_ignores_metadata() {
671        let a = json!({"metadata": {"resourceVersion": "5"},
672                       "addressType": "IPv4", "endpoints": [{"addresses": ["10.0.0.1"]}],
673                       "ports": [{"port": 80}]});
674        let b = json!({"metadata": {"resourceVersion": "99"},
675                       "addressType": "IPv4", "endpoints": [{"addresses": ["10.0.0.1"]}],
676                       "ports": [{"port": 80}]});
677        assert!(slice_bodies_equivalent(&a, &b));
678        let c = json!({"addressType": "IPv4",
679                       "endpoints": [{"addresses": ["10.0.0.2"]}], "ports": [{"port": 80}]});
680        assert!(!slice_bodies_equivalent(&a, &c));
681    }
682
683    #[test]
684    fn subsets_equivalent_compares_only_subsets() {
685        let a = json!({"metadata": {"resourceVersion": "5"}, "subsets": [{"x": 1}]});
686        let b = json!({"metadata": {"resourceVersion": "99"}, "subsets": [{"x": 1}]});
687        assert!(subsets_equivalent(&a, &b));
688        let c = json!({"subsets": [{"x": 2}]});
689        assert!(!subsets_equivalent(&a, &c));
690    }
691
692    #[test]
693    fn controller_name_is_stable() {
694        struct Fake;
695        #[async_trait]
696        impl Controller for Fake {
697            fn name(&self) -> &'static str {
698                "endpoints"
699            }
700            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
701                Ok(crate::controller::ReconcileReport::default().into())
702            }
703        }
704        assert_eq!(Fake.name(), "endpoints");
705    }
706
707    // ── creationTimestamp on controller-created Endpoints (Part B) ────────
708
709    const FIXED_TS: &str = "2026-06-14T09:00:00Z";
710    fn fixed_clock() -> String {
711        FIXED_TS.to_string()
712    }
713
714    async fn live_store() -> Arc<StoreMesh> {
715        use engenho_store::{InProcessRouter, default_config};
716        use std::time::Duration;
717        let router = InProcessRouter::new();
718        let cfg = default_config("controllers-endpoints").unwrap();
719        let store = Arc::new(
720            StoreMesh::start(1, "in-process://1".into(), router, cfg)
721                .await
722                .unwrap(),
723        );
724        store.initialize_singleton().await.unwrap();
725        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
726        store
727    }
728
729    #[tokio::test]
730    async fn created_endpoints_carries_frozen_creation_timestamp() {
731        let store = live_store().await;
732        // A Service with a selector + a ready, ip-bearing Pod matching it.
733        store
734            .propose(ResourceCommand::put(
735                ResourceKey::namespaced("", "v1", "Service", "ns1", "svc"),
736                json!({"kind": "Service", "apiVersion": "v1",
737                       "metadata": {"name": "svc", "namespace": "ns1"},
738                       "spec": {"selector": {"app": "x"},
739                                "ports": [{"port": 80, "targetPort": 80}]}}),
740                Reason::Operator,
741            ))
742            .await
743            .unwrap();
744        store
745            .propose(ResourceCommand::put(
746                ResourceKey::namespaced("", "v1", "Pod", "ns1", "p"),
747                json!({"kind": "Pod", "apiVersion": "v1",
748                       "metadata": {"name": "p", "namespace": "ns1", "labels": {"app": "x"}},
749                       "status": {"podIP": "10.0.0.1",
750                                  "conditions": [{"type": "Ready", "status": "True"}]}}),
751                Reason::Operator,
752            ))
753            .await
754            .unwrap();
755
756        let c = EndpointsController::with_clock(store.clone(), None, fixed_clock);
757        c.tick().await.unwrap();
758
759        let ep = store
760            .get(&ResourceKey::namespaced(
761                "",
762                "v1",
763                "Endpoints",
764                "ns1",
765                "svc",
766            ))
767            .await
768            .expect("Endpoints created");
769        assert_eq!(
770            ep.get("metadata")
771                .unwrap()
772                .get("creationTimestamp")
773                .unwrap(),
774            FIXED_TS,
775            "controller-created Endpoints must carry the frozen creationTimestamp"
776        );
777
778        // A subsequent tick that re-writes the subsets (e.g. a new pod) must
779        // NOT bump creationTimestamp — it is preserved from the prior object.
780        store
781            .propose(ResourceCommand::put(
782                ResourceKey::namespaced("", "v1", "Pod", "ns1", "p2"),
783                json!({"kind": "Pod", "apiVersion": "v1",
784                       "metadata": {"name": "p2", "namespace": "ns1", "labels": {"app": "x"}},
785                       "status": {"podIP": "10.0.0.2",
786                                  "conditions": [{"type": "Ready", "status": "True"}]}}),
787                Reason::Operator,
788            ))
789            .await
790            .unwrap();
791        // Use a DIFFERENT clock to prove the update path never stamps.
792        let c2 = EndpointsController::with_clock(store.clone(), None, || {
793            "2099-01-01T00:00:00Z".to_string()
794        });
795        c2.tick().await.unwrap();
796        let ep2 = store
797            .get(&ResourceKey::namespaced(
798                "",
799                "v1",
800                "Endpoints",
801                "ns1",
802                "svc",
803            ))
804            .await
805            .unwrap();
806        // The Endpoints was updated (now 2 addresses) but the timestamp held.
807        // NOTE: the store preserves metadata.creationTimestamp across an
808        // update Put (it carries the prior object's value); the controller's
809        // create-only stamp simply never fires on the update path.
810        assert_eq!(
811            ep2.get("metadata")
812                .unwrap()
813                .get("creationTimestamp")
814                .unwrap(),
815            FIXED_TS,
816            "creationTimestamp must be stable across the update (never bumped)"
817        );
818    }
819
820    #[tokio::test]
821    async fn controller_emits_endpoint_slice_alongside_endpoints() {
822        let store = live_store().await;
823        // A Service with a selector + a ready, ip-bearing Pod matching it.
824        store
825            .propose(ResourceCommand::put(
826                ResourceKey::namespaced("", "v1", "Service", "ns1", "svc"),
827                json!({"kind": "Service", "apiVersion": "v1",
828                       "metadata": {"name": "svc", "namespace": "ns1",
829                                    "uid": "svc-uid"},
830                       "spec": {"selector": {"app": "x"},
831                                "ports": [{"name": "http", "port": 80, "targetPort": 9898}]}}),
832                Reason::Operator,
833            ))
834            .await
835            .unwrap();
836        store
837            .propose(ResourceCommand::put(
838                ResourceKey::namespaced("", "v1", "Pod", "ns1", "p"),
839                json!({"kind": "Pod", "apiVersion": "v1",
840                       "metadata": {"name": "p", "namespace": "ns1", "labels": {"app": "x"}},
841                       "status": {"podIP": "10.0.0.1",
842                                  "conditions": [{"type": "Ready", "status": "True"}]}}),
843                Reason::Operator,
844            ))
845            .await
846            .unwrap();
847
848        let c = EndpointsController::with_clock(store.clone(), None, fixed_clock);
849        c.tick().await.unwrap();
850
851        // The legacy Endpoints object exists.
852        let ep = store
853            .get(&ResourceKey::namespaced(
854                "",
855                "v1",
856                "Endpoints",
857                "ns1",
858                "svc",
859            ))
860            .await
861            .expect("Endpoints created");
862        assert_eq!(ep["subsets"][0]["addresses"][0]["ip"], "10.0.0.1");
863
864        // The EndpointSlice exists in parallel, derived from the SAME pod.
865        let slice = store
866            .get(&ResourceKey::namespaced(
867                "discovery.k8s.io",
868                "v1",
869                "EndpointSlice",
870                "ns1",
871                "svc",
872            ))
873            .await
874            .expect("EndpointSlice created");
875        assert_eq!(slice["kind"], "EndpointSlice");
876        assert_eq!(
877            slice["metadata"]["labels"]["kubernetes.io/service-name"],
878            "svc"
879        );
880        assert_eq!(slice["endpoints"][0]["addresses"][0], "10.0.0.1");
881        assert_eq!(slice["endpoints"][0]["conditions"]["ready"], true);
882        // The slice carries the frozen creationTimestamp + an owner ref.
883        assert_eq!(slice["metadata"]["creationTimestamp"], FIXED_TS);
884        assert_eq!(slice["metadata"]["ownerReferences"][0]["kind"], "Service");
885
886        // Idempotent: a re-tick with no pod change writes nothing new.
887        c.tick().await.unwrap();
888        let slice2 = store
889            .get(&ResourceKey::namespaced(
890                "discovery.k8s.io",
891                "v1",
892                "EndpointSlice",
893                "ns1",
894                "svc",
895            ))
896            .await
897            .unwrap();
898        assert_eq!(
899            slice2["endpoints"], slice["endpoints"],
900            "stable across re-tick"
901        );
902    }
903}