Skip to main content

engenho_controllers/
hpa.rs

1//! R18 — `HorizontalPodAutoscaler` controller.
2//!
3//! Watches HPA objects + adjusts the target's `spec.replicas`
4//! based on observed metrics. Same trait shape as every other
5//! controller; metrics provider is pluggable.
6//!
7//! ## Reconcile rule
8//!
9//! For each HPA:
10//!   1. Read `spec.scaleTargetRef.{apiVersion, kind, name}` and the
11//!      target's `spec.replicas`.
12//!   2. Read `spec.minReplicas` (default 1) + `spec.maxReplicas`.
13//!   3. Read `spec.metrics`. Each `External` metric is asked of the
14//!      metrics provider by name; with no `spec.metrics`, the provider is
15//!      asked for the target's own value against `spec.targetValue`.
16//!   4. Recommend replicas per metric (`AverageValue`: ⌈value / target⌉;
17//!      `Value`: ⌈current × value / target⌉), take the largest, stabilize
18//!      it over `spec.behavior` windows, clamp to [min, max].
19//!   5. If desired ≠ current_replicas → patch the target.
20//!
21//! ## Metrics provider
22//!
23//! [`MetricsProvider`] is the seam; [`FakeMetricsProvider`] serves an
24//! explicit map for tests, and [`StatusMetricsProvider`] reads declared
25//! status fields from the store ([`PANGEA_LEAF_PENDING_WORK`]).
26
27use std::collections::{BTreeMap, VecDeque};
28use std::sync::Arc;
29use std::time::Duration;
30
31use async_trait::async_trait;
32use engenho_store::{
33    StoreMesh,
34    command::{Reason, ResourceCommand},
35    resource::ResourceKey,
36};
37use serde_json::{Value, json};
38use thiserror::Error;
39use tokio::sync::Mutex;
40use tokio::time::Instant;
41use tracing::{debug, warn};
42
43use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
44use crate::csi_provisioner::parse_quantity;
45use crate::effect::Effect;
46use crate::error::ControllerError;
47use crate::meta::{DefaultedInt, REPLICAS, warn_unreadable};
48use crate::reads::{DeclaresReads, Reads};
49
50/// `autoscaling/v2` `spec.minReplicas`, defaulted to 1.
51const MIN_REPLICAS: DefaultedInt = DefaultedInt::new(&["spec", "minReplicas"], 1);
52
53/// `spec.maxReplicas` is required upstream; an absent one reads as 1 here.
54const MAX_REPLICAS: DefaultedInt = DefaultedInt::new(&["spec", "maxReplicas"], 1);
55
56const SCALE_UP_WINDOW: DefaultedInt = DefaultedInt::new(
57    &["spec", "behavior", "scaleUp", "stabilizationWindowSeconds"],
58    0,
59);
60
61const SCALE_DOWN_WINDOW: DefaultedInt = DefaultedInt::new(
62    &[
63        "spec",
64        "behavior",
65        "scaleDown",
66        "stabilizationWindowSeconds",
67    ],
68    300,
69);
70
71const TOLERANCE: f64 = 0.1;
72
73/// Metrics-provider error.
74#[derive(Debug, Clone, Error)]
75pub enum MetricsError {
76    /// Backend (Prometheus, fake, etc.) returned an error.
77    #[error("backend: {0}")]
78    Backend(String),
79    #[error("unreadable: {0}")]
80    Unreadable(String),
81}
82
83engenho_substrate::impl_error_kind! {
84    MetricsError {
85        (Backend(_)) => "backend",
86        (Unreadable(_)) => "unreadable",
87    }
88}
89
90/// Identifies the workload an HPA is monitoring + scaling.
91#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
92pub struct ScaleTarget {
93    /// `Deployment` / `StatefulSet` / `ReplicaSet`.
94    pub kind: String,
95    /// Resource name.
96    pub name: String,
97    /// Namespace (typically same as the HPA's).
98    pub namespace: String,
99}
100
101/// Metrics-provider trait. Returns the OBSERVED current value
102/// (CPU %, memory MB, custom metric) for a workload.
103#[async_trait]
104pub trait MetricsProvider: Send + Sync {
105    /// Backend identifier for telemetry.
106    fn name(&self) -> &'static str;
107
108    /// Observed metric for `target`. None = no signal (HPA holds
109    /// current replicas + warns).
110    ///
111    /// # Errors
112    /// [`MetricsError::Backend`] on backend failure.
113    async fn observe(&self, target: &ScaleTarget) -> Result<Option<f64>, MetricsError>;
114
115    /// # Errors
116    /// [`MetricsError`] when the source cannot be read.
117    async fn external(&self, metric: &str) -> Result<Option<f64>, MetricsError>;
118}
119
120/// Explicit metric map keyed by target identity. Tests pin
121/// metrics + drive the HPA controller to see scale decisions.
122#[derive(Default, Clone)]
123pub struct FakeMetricsProvider {
124    inner: Arc<Mutex<BTreeMap<ScaleTarget, f64>>>,
125    external: Arc<Mutex<BTreeMap<String, f64>>>,
126}
127
128impl FakeMetricsProvider {
129    /// Fresh empty provider.
130    #[must_use]
131    pub fn new() -> Self {
132        Self::default()
133    }
134
135    /// Set the observed metric for a target.
136    pub async fn set(&self, target: ScaleTarget, value: f64) {
137        self.inner.lock().await.insert(target, value);
138    }
139
140    pub async fn set_external(&self, metric: &str, value: f64) {
141        self.external.lock().await.insert(metric.to_owned(), value);
142    }
143
144    /// Clear all observations.
145    pub async fn clear(&self) {
146        self.inner.lock().await.clear();
147        self.external.lock().await.clear();
148    }
149}
150
151#[async_trait]
152impl MetricsProvider for FakeMetricsProvider {
153    fn name(&self) -> &'static str {
154        "fake"
155    }
156
157    async fn observe(&self, target: &ScaleTarget) -> Result<Option<f64>, MetricsError> {
158        Ok(self.inner.lock().await.get(target).copied())
159    }
160
161    async fn external(&self, metric: &str) -> Result<Option<f64>, MetricsError> {
162        Ok(self.external.lock().await.get(metric).copied())
163    }
164}
165
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub struct StatusMetric {
168    pub name: &'static str,
169    pub group: &'static str,
170    pub version: &'static str,
171    pub kind: &'static str,
172    pub object: &'static str,
173    pub path: &'static [&'static str],
174}
175
176pub const PANGEA_LEAF_PENDING_WORK: StatusMetric = StatusMetric {
177    name: "pangea_leaf_pending_work",
178    group: "pangea.pleme.io",
179    version: "v1alpha1",
180    kind: "PangeaFleetStatus",
181    object: "default",
182    path: &["status", "leafWork", "metric"],
183};
184
185impl StatusMetric {
186    fn key(self) -> ResourceKey {
187        ResourceKey::cluster_scoped(self.group, self.version, self.kind, self.object)
188    }
189
190    fn read(self, object: &Value) -> Result<Option<f64>, MetricsError> {
191        let unreadable = |at: &Value| {
192            MetricsError::Unreadable(format!(
193                "{}/{} {}: {} is {at}, expected a non-negative number",
194                self.group,
195                self.kind,
196                self.object,
197                self.path.join(".")
198            ))
199        };
200        let mut at = object;
201        for step in self.path {
202            let Value::Object(map) = at else {
203                return Err(unreadable(at));
204            };
205            match map.get(*step) {
206                Some(Value::Null) | None => return Ok(None),
207                Some(next) => at = next,
208            }
209        }
210        match at.as_f64() {
211            Some(n) if n.is_finite() && n >= 0.0 => Ok(Some(n)),
212            _ => Err(unreadable(at)),
213        }
214    }
215}
216
217pub struct StatusMetricsProvider {
218    store: Arc<StoreMesh>,
219    metrics: Vec<StatusMetric>,
220}
221
222impl StatusMetricsProvider {
223    #[must_use]
224    pub fn new(store: Arc<StoreMesh>, metrics: Vec<StatusMetric>) -> Self {
225        Self { store, metrics }
226    }
227
228    #[must_use]
229    pub fn metrics(&self) -> &[StatusMetric] {
230        &self.metrics
231    }
232}
233
234#[async_trait]
235impl MetricsProvider for StatusMetricsProvider {
236    fn name(&self) -> &'static str {
237        "status"
238    }
239
240    async fn observe(&self, _target: &ScaleTarget) -> Result<Option<f64>, MetricsError> {
241        Ok(None)
242    }
243
244    async fn external(&self, metric: &str) -> Result<Option<f64>, MetricsError> {
245        let Some(source) = self.metrics.iter().find(|m| m.name == metric).copied() else {
246            return Ok(None);
247        };
248        match self.store.get(&source.key()).await {
249            Some(object) => source.read(&object),
250            None => Ok(None),
251        }
252    }
253}
254
255#[derive(Clone, Copy, Debug, PartialEq)]
256pub enum MetricTarget {
257    AverageValue(f64),
258    Value(f64),
259}
260
261#[derive(Clone, Debug, PartialEq)]
262pub enum MetricSpec {
263    TargetValue(f64),
264    External(Vec<(String, MetricTarget)>),
265}
266
267#[derive(Clone, Debug, PartialEq, Eq, Error)]
268pub enum MetricSpecError {
269    #[error("spec.metrics[{index}] is type {found}; only External is served")]
270    Unsupported { index: usize, found: String },
271    #[error("spec.metrics[{index}]: {reason}")]
272    Malformed { index: usize, reason: String },
273}
274
275fn quantity(value: &Value) -> Option<f64> {
276    let n = match value {
277        Value::Number(n) => n.as_f64(),
278        Value::String(s) => quantity_text(s.trim()),
279        _ => None,
280    };
281    n.filter(|n| n.is_finite() && *n > 0.0)
282}
283
284fn quantity_text(s: &str) -> Option<f64> {
285    if let Ok(n) = s.parse::<f64>() {
286        return Some(n);
287    }
288    if let Some(milli) = s.strip_suffix('m') {
289        return milli.parse::<f64>().ok().map(|n| n / 1000.0);
290    }
291    #[allow(clippy::cast_precision_loss)]
292    parse_quantity(s).map(|n| n as f64)
293}
294
295impl MetricSpec {
296    /// # Errors
297    /// [`MetricSpecError`] naming the entry that cannot be served.
298    pub fn of(hpa: &Value) -> Result<Self, MetricSpecError> {
299        let spec = hpa.get("spec");
300        let Some(metrics) = spec.and_then(|s| s.get("metrics")).filter(|m| !m.is_null()) else {
301            let target = spec
302                .and_then(|s| s.get("targetValue"))
303                .and_then(Value::as_f64)
304                .unwrap_or(50.0);
305            return Ok(Self::TargetValue(target));
306        };
307        let malformed = |index: usize, reason: &str| MetricSpecError::Malformed {
308            index,
309            reason: reason.to_owned(),
310        };
311        let Some(entries) = metrics.as_array() else {
312            return Err(malformed(0, "spec.metrics is not a list"));
313        };
314        if entries.is_empty() {
315            return Err(malformed(0, "spec.metrics is empty"));
316        }
317        let mut out = Vec::with_capacity(entries.len());
318        for (index, entry) in entries.iter().enumerate() {
319            let kind = entry.get("type").and_then(Value::as_str).unwrap_or("");
320            if kind != "External" {
321                return Err(MetricSpecError::Unsupported {
322                    index,
323                    found: kind.to_owned(),
324                });
325            }
326            let external = entry.get("external");
327            let name = external
328                .and_then(|e| e.get("metric"))
329                .and_then(|m| m.get("name"))
330                .and_then(Value::as_str)
331                .ok_or_else(|| malformed(index, "external.metric.name is missing"))?;
332            let target = external
333                .and_then(|e| e.get("target"))
334                .ok_or_else(|| malformed(index, "external.target is missing"))?;
335            let target = match target.get("type").and_then(Value::as_str) {
336                Some("AverageValue") => target
337                    .get("averageValue")
338                    .and_then(quantity)
339                    .map(MetricTarget::AverageValue)
340                    .ok_or_else(|| {
341                        malformed(index, "target.averageValue is not a positive quantity")
342                    })?,
343                Some("Value") => target
344                    .get("value")
345                    .and_then(quantity)
346                    .map(MetricTarget::Value)
347                    .ok_or_else(|| malformed(index, "target.value is not a positive quantity"))?,
348                _ => return Err(malformed(index, "target.type is not AverageValue or Value")),
349            };
350            out.push((name.to_owned(), target));
351        }
352        Ok(Self::External(out))
353    }
354}
355
356#[must_use]
357#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
358pub fn recommend(current: i64, observed: f64, target: MetricTarget) -> i64 {
359    let current_f = current as f64;
360    match target {
361        MetricTarget::AverageValue(average) => {
362            if current > 0 && (observed / (average * current_f) - 1.0).abs() <= TOLERANCE {
363                return current;
364            }
365            (observed / average).ceil() as i64
366        }
367        MetricTarget::Value(value) => {
368            let ratio = observed / value;
369            if (ratio - 1.0).abs() <= TOLERANCE {
370                return current;
371            }
372            (current_f * ratio).ceil() as i64
373        }
374    }
375}
376
377#[derive(Clone, Copy, Debug, PartialEq, Eq)]
378pub struct Windows {
379    pub up: Duration,
380    pub down: Duration,
381}
382
383impl Windows {
384    fn of(hpa: &Value) -> Result<Self, crate::meta::ShapeError> {
385        let secs = |n: i64| Duration::from_secs(u64::try_from(n.max(0)).unwrap_or(0));
386        Ok(Self {
387            up: secs(SCALE_UP_WINDOW.read(hpa)?),
388            down: secs(SCALE_DOWN_WINDOW.read(hpa)?),
389        })
390    }
391}
392
393#[derive(Clone, Debug, Default)]
394pub struct Recommendations {
395    seen: VecDeque<(Instant, i64)>,
396}
397
398impl Recommendations {
399    pub fn stabilize(&mut self, now: Instant, raw: i64, current: i64, windows: Windows) -> i64 {
400        self.seen.push_back((now, raw));
401        let keep = windows.up.max(windows.down);
402        while self
403            .seen
404            .front()
405            .is_some_and(|(at, _)| now.duration_since(*at) > keep)
406        {
407            self.seen.pop_front();
408        }
409        let within = |window: Duration| {
410            self.seen
411                .iter()
412                .filter(move |(at, _)| now.duration_since(*at) <= window)
413                .map(|(_, r)| *r)
414        };
415        let up = within(windows.up).min().unwrap_or(raw);
416        let down = within(windows.down).max().unwrap_or(raw);
417        current.max(up).min(down)
418    }
419}
420
421/// Controller — scales targets based on metric vs `target_value`.
422pub struct HorizontalPodAutoscalerController {
423    store: Arc<StoreMesh>,
424    metrics: Arc<dyn MetricsProvider>,
425    namespace: Option<String>,
426    history: Mutex<BTreeMap<String, Recommendations>>,
427}
428
429impl HorizontalPodAutoscalerController {
430    /// New controller.
431    #[must_use]
432    pub fn new(
433        store: Arc<StoreMesh>,
434        metrics: Arc<dyn MetricsProvider>,
435        namespace: Option<String>,
436    ) -> Self {
437        Self {
438            store,
439            metrics,
440            namespace,
441            history: Mutex::new(BTreeMap::new()),
442        }
443    }
444
445    fn scale_target_ref(hpa: &Value) -> Option<(String, String, String)> {
446        let r = hpa.get("spec").and_then(|s| s.get("scaleTargetRef"))?;
447        let api_version = r.get("apiVersion").and_then(|a| a.as_str())?.to_string();
448        let kind = r.get("kind").and_then(|k| k.as_str())?.to_string();
449        let name = r.get("name").and_then(|n| n.as_str())?.to_string();
450        Some((api_version, kind, name))
451    }
452
453    /// Pure: compute desired replicas from observed metric.
454    /// Exposed for tests.
455    #[must_use]
456    #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
457    pub fn compute_desired(
458        current_replicas: i64,
459        observed: f64,
460        target_value: f64,
461        min: i64,
462        max: i64,
463    ) -> i64 {
464        if target_value <= 0.0 {
465            return current_replicas.clamp(min, max);
466        }
467        let ratio = observed / target_value;
468        let desired = ((current_replicas as f64) * ratio).ceil() as i64;
469        desired.max(1).clamp(min, max)
470    }
471
472    #[must_use]
473    pub fn target_gv(api_version: &str) -> (&str, &str) {
474        match api_version.split_once('/') {
475            Some((group, version)) => (group, version),
476            None => ("", api_version),
477        }
478    }
479
480    async fn raw_recommendation(
481        &self,
482        spec: &MetricSpec,
483        target: &ScaleTarget,
484        current: i64,
485        min: i64,
486        max: i64,
487    ) -> Result<Option<i64>, MetricsError> {
488        match spec {
489            MetricSpec::TargetValue(target_value) => {
490                Ok(self.metrics.observe(target).await?.map(|observed| {
491                    Self::compute_desired(current, observed, *target_value, min, max)
492                }))
493            }
494            MetricSpec::External(metrics) => {
495                let mut best: Option<i64> = None;
496                for (name, metric_target) in metrics {
497                    let Some(observed) = self.metrics.external(name).await? else {
498                        return Ok(None);
499                    };
500                    let r = recommend(current, observed, *metric_target);
501                    best = Some(best.map_or(r, |b| b.max(r)));
502                }
503                Ok(best)
504            }
505        }
506    }
507}
508
509impl DeclaresReads for HorizontalPodAutoscalerController {
510    fn reads(&self) -> Reads {
511        Reads::every()
512    }
513}
514
515#[async_trait]
516impl Controller for HorizontalPodAutoscalerController {
517    fn name(&self) -> &'static str {
518        "hpa"
519    }
520
521    #[allow(clippy::too_many_lines)]
522    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
523        let hpas = self
524            .store
525            .list(
526                "autoscaling",
527                "v2",
528                "HorizontalPodAutoscaler",
529                self.namespace.as_deref(),
530            )
531            .await;
532        let mut report = ReconcileReport::default();
533        report.objects_examined = hpas.len();
534        let now = Instant::now();
535        let mut history = self.history.lock().await;
536        history.retain(|label, _| hpas.iter().any(|(key, _)| key.label() == *label));
537
538        for (hpa_key, hpa_value) in &hpas {
539            let Some((api_version, target_kind, target_name)) = Self::scale_target_ref(hpa_value)
540            else {
541                report.objects_skipped += 1;
542                continue;
543            };
544            let ns = hpa_key
545                .namespace
546                .as_deref()
547                .unwrap_or("default")
548                .to_string();
549            let (min, max, windows) = match (
550                MIN_REPLICAS.read(hpa_value),
551                MAX_REPLICAS.read(hpa_value),
552                Windows::of(hpa_value),
553            ) {
554                (Ok(min), Ok(max), Ok(windows)) => (min, max, windows),
555                (Err(e), _, _) | (_, Err(e), _) | (_, _, Err(e)) => {
556                    warn_unreadable("hpa", &hpa_key.label(), &e);
557                    report.objects_skipped += 1;
558                    continue;
559                }
560            };
561            let spec = match MetricSpec::of(hpa_value) {
562                Ok(spec) => spec,
563                Err(e) => {
564                    warn!(hpa = %hpa_key.label(), error = %e, "metric spec refused; target left alone");
565                    report.objects_skipped += 1;
566                    continue;
567                }
568            };
569
570            let (g, v) = Self::target_gv(&api_version);
571            let target_key = ResourceKey::namespaced(g, v, &target_kind, &ns, &target_name);
572            let Some(target) = self.store.get(&target_key).await else {
573                report.objects_skipped += 1;
574                continue;
575            };
576            let current = match REPLICAS.read(&target) {
577                Ok(current) => current,
578                Err(e) => {
579                    warn_unreadable("hpa", &target_key.label(), &e);
580                    report.objects_skipped += 1;
581                    continue;
582                }
583            };
584
585            let scale_target = ScaleTarget {
586                kind: target_kind.clone(),
587                name: target_name.clone(),
588                namespace: ns.clone(),
589            };
590            let raw = match self
591                .raw_recommendation(&spec, &scale_target, current, min, max)
592                .await
593            {
594                Ok(Some(raw)) => raw,
595                Ok(None) => {
596                    debug!(
597                        target = %format!("{ns}/{target_kind}/{target_name}"),
598                        "no metric signal; holding current replicas"
599                    );
600                    continue;
601                }
602                Err(e) => {
603                    warn!(hpa = %hpa_key.label(), error = %e, "metric unreadable; holding current replicas");
604                    report.objects_skipped += 1;
605                    continue;
606                }
607            };
608
609            let desired = history
610                .entry(hpa_key.label())
611                .or_default()
612                .stabilize(now, raw, current, windows)
613                .clamp(min, max);
614            if desired == current {
615                continue;
616            }
617            debug!(
618                target = %format!("{ns}/{target_kind}/{target_name}"),
619                current,
620                desired,
621                raw,
622                "HPA scaling"
623            );
624            let applied = self
625                .store
626                .propose(ResourceCommand::patch(
627                    target_key,
628                    json!({"spec": {"replicas": desired}}),
629                    Reason::Controller,
630                ))
631                .await?;
632            report.record(Effect::of(applied.op));
633        }
634        Ok(report.into())
635    }
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641
642    #[test]
643    fn min_replicas_defaults_to_1() {
644        assert_eq!(MIN_REPLICAS.read(&json!({})), Ok(1));
645    }
646
647    #[test]
648    fn max_replicas_defaults_to_1() {
649        assert_eq!(MAX_REPLICAS.read(&json!({})), Ok(1));
650    }
651
652    #[test]
653    fn a_malformed_bound_is_an_error_not_the_default() {
654        assert!(
655            MIN_REPLICAS
656                .read(&json!({"spec": {"minReplicas": "2"}}))
657                .is_err()
658        );
659        assert!(
660            MAX_REPLICAS
661                .read(&json!({"spec": {"maxReplicas": 9.5}}))
662                .is_err()
663        );
664    }
665
666    #[test]
667    fn target_value_defaults_to_50() {
668        assert_eq!(
669            MetricSpec::of(&json!({})),
670            Ok(MetricSpec::TargetValue(50.0))
671        );
672    }
673
674    #[test]
675    fn scale_target_ref_reads_spec_field() {
676        let hpa = json!({"spec": {"scaleTargetRef": {"apiVersion": "apps/v1", "kind": "Deployment", "name": "podinfo"}}});
677        let (a, k, n) = HorizontalPodAutoscalerController::scale_target_ref(&hpa).unwrap();
678        assert_eq!(a, "apps/v1");
679        assert_eq!(k, "Deployment");
680        assert_eq!(n, "podinfo");
681        let no_api_version =
682            json!({"spec": {"scaleTargetRef": {"kind": "Deployment", "name": "podinfo"}}});
683        assert!(HorizontalPodAutoscalerController::scale_target_ref(&no_api_version).is_none());
684    }
685
686    #[test]
687    fn target_gv_reads_the_targets_own_api_version() {
688        let gv = HorizontalPodAutoscalerController::target_gv;
689        assert_eq!(gv("apps/v1"), ("apps", "v1"));
690        assert_eq!(gv("v1"), ("", "v1"));
691        assert_eq!(gv("argoproj.io/v1alpha1"), ("argoproj.io", "v1alpha1"));
692        assert_eq!(
693            gv("pangea.pleme.io/v1alpha1"),
694            ("pangea.pleme.io", "v1alpha1")
695        );
696    }
697
698    #[test]
699    fn compute_desired_scales_up_on_high_metric() {
700        // 80% observed vs 50% target → 2× replicas
701        let d = HorizontalPodAutoscalerController::compute_desired(2, 80.0, 50.0, 1, 10);
702        assert_eq!(d, 4);
703    }
704
705    #[test]
706    fn compute_desired_scales_down_on_low_metric() {
707        // 25% observed vs 50% target → ½× replicas
708        let d = HorizontalPodAutoscalerController::compute_desired(4, 25.0, 50.0, 1, 10);
709        assert_eq!(d, 2);
710    }
711
712    #[test]
713    fn compute_desired_clamps_to_min() {
714        let d = HorizontalPodAutoscalerController::compute_desired(2, 1.0, 50.0, 3, 10);
715        assert_eq!(d, 3);
716    }
717
718    #[test]
719    fn compute_desired_clamps_to_max() {
720        let d = HorizontalPodAutoscalerController::compute_desired(5, 1000.0, 50.0, 1, 10);
721        assert_eq!(d, 10);
722    }
723
724    #[test]
725    fn compute_desired_never_below_1() {
726        let d = HorizontalPodAutoscalerController::compute_desired(1, 0.0, 50.0, 1, 10);
727        assert_eq!(d, 1);
728    }
729
730    fn leaf_work_hpa(min: i64, max: i64, average: &Value) -> Value {
731        json!({"spec": {
732            "scaleTargetRef": {"apiVersion": "apps/v1", "kind": "Deployment", "name": "workers"},
733            "minReplicas": min, "maxReplicas": max,
734            "metrics": [{"type": "External", "external": {
735                "metric": {"name": "pangea_leaf_pending_work"},
736                "target": {"type": "AverageValue", "averageValue": average}
737            }}]
738        }})
739    }
740
741    #[test]
742    fn metric_spec_reads_an_external_average_value() {
743        assert_eq!(
744            MetricSpec::of(&leaf_work_hpa(0, 4, &json!("600"))),
745            Ok(MetricSpec::External(vec![(
746                "pangea_leaf_pending_work".into(),
747                MetricTarget::AverageValue(600.0)
748            )]))
749        );
750        assert_eq!(
751            MetricSpec::of(&leaf_work_hpa(0, 4, &json!(600))),
752            MetricSpec::of(&leaf_work_hpa(0, 4, &json!("600")))
753        );
754        assert_eq!(
755            MetricSpec::of(&leaf_work_hpa(0, 4, &json!("1500m"))),
756            Ok(MetricSpec::External(vec![(
757                "pangea_leaf_pending_work".into(),
758                MetricTarget::AverageValue(1.5)
759            )]))
760        );
761        assert_eq!(
762            MetricSpec::of(&leaf_work_hpa(0, 4, &json!("1k"))),
763            Ok(MetricSpec::External(vec![(
764                "pangea_leaf_pending_work".into(),
765                MetricTarget::AverageValue(1000.0)
766            )]))
767        );
768    }
769
770    #[test]
771    fn metric_spec_refuses_what_it_cannot_serve() {
772        let resource = json!({"spec": {"metrics": [{"type": "Resource", "resource": {}}]}});
773        assert_eq!(
774            MetricSpec::of(&resource),
775            Err(MetricSpecError::Unsupported {
776                index: 0,
777                found: "Resource".into()
778            })
779        );
780        assert!(matches!(
781            MetricSpec::of(&leaf_work_hpa(0, 4, &json!("0"))),
782            Err(MetricSpecError::Malformed { index: 0, .. })
783        ));
784        assert!(matches!(
785            MetricSpec::of(&leaf_work_hpa(0, 4, &json!("lots"))),
786            Err(MetricSpecError::Malformed { index: 0, .. })
787        ));
788        assert!(matches!(
789            MetricSpec::of(&json!({"spec": {"metrics": []}})),
790            Err(MetricSpecError::Malformed { .. })
791        ));
792    }
793
794    #[test]
795    fn average_value_is_work_per_replica() {
796        let t = MetricTarget::AverageValue(600.0);
797        assert_eq!(recommend(0, 0.0, t), 0);
798        assert_eq!(recommend(0, 1.0, t), 1);
799        assert_eq!(recommend(0, 1800.0, t), 3);
800        assert_eq!(recommend(1, 1801.0, t), 4);
801        assert_eq!(recommend(4, 600.0, t), 1);
802    }
803
804    #[test]
805    fn average_value_holds_inside_the_tolerance() {
806        let t = MetricTarget::AverageValue(600.0);
807        assert_eq!(recommend(2, 1250.0, t), 2);
808        assert_eq!(recommend(2, 1100.0, t), 2);
809        assert_eq!(recommend(2, 1400.0, t), 3);
810    }
811
812    #[test]
813    fn value_scales_by_ratio() {
814        let t = MetricTarget::Value(100.0);
815        assert_eq!(recommend(2, 200.0, t), 4);
816        assert_eq!(recommend(4, 50.0, t), 2);
817        assert_eq!(recommend(3, 105.0, t), 3);
818    }
819
820    fn windows(up: u64, down: u64) -> Windows {
821        Windows {
822            up: Duration::from_secs(up),
823            down: Duration::from_secs(down),
824        }
825    }
826
827    #[test]
828    fn scale_up_is_immediate_by_default() {
829        let t0 = Instant::now();
830        let mut r = Recommendations::default();
831        assert_eq!(r.stabilize(t0, 4, 1, windows(0, 300)), 4);
832    }
833
834    #[test]
835    fn scale_down_holds_the_highest_recommendation_in_the_window() {
836        let t0 = Instant::now();
837        let w = windows(0, 300);
838        let mut r = Recommendations::default();
839        assert_eq!(r.stabilize(t0, 4, 1, w), 4);
840        assert_eq!(r.stabilize(t0 + Duration::from_secs(60), 1, 4, w), 4);
841        assert_eq!(r.stabilize(t0 + Duration::from_secs(299), 2, 4, w), 4);
842        assert_eq!(r.stabilize(t0 + Duration::from_secs(301), 0, 4, w), 2);
843        assert_eq!(r.stabilize(t0 + Duration::from_secs(700), 0, 2, w), 0);
844    }
845
846    #[test]
847    fn scale_up_window_holds_the_lowest_recommendation() {
848        let t0 = Instant::now();
849        let w = windows(120, 0);
850        let mut r = Recommendations::default();
851        assert_eq!(r.stabilize(t0, 1, 1, w), 1);
852        assert_eq!(r.stabilize(t0 + Duration::from_secs(30), 5, 1, w), 1);
853        assert_eq!(r.stabilize(t0 + Duration::from_secs(121), 5, 1, w), 5);
854    }
855
856    #[test]
857    fn windows_read_behavior_with_upstream_defaults() {
858        assert_eq!(Windows::of(&json!({})), Ok(windows(0, 300)));
859        let hpa = json!({"spec": {"behavior": {
860            "scaleUp": {"stabilizationWindowSeconds": 30},
861            "scaleDown": {"stabilizationWindowSeconds": 0}
862        }}});
863        assert_eq!(Windows::of(&hpa), Ok(windows(30, 0)));
864    }
865
866    #[test]
867    fn leaf_work_reads_the_operators_metric_as_a_non_negative_number() {
868        let m = PANGEA_LEAF_PENDING_WORK;
869        assert_eq!(
870            m.read(&json!({"status": {"leafWork": {
871                "metric": 1800, "desired": 3, "unpaced": 0,
872                "credentials": [{"credential": "c", "pending": 5000, "cap": 937, "counted": 937}]
873            }}}))
874            .unwrap(),
875            Some(1800.0)
876        );
877        assert_eq!(m.read(&json!({"status": {}})).unwrap(), None);
878        assert_eq!(
879            m.read(&json!({"status": {"leafWork": null}})).unwrap(),
880            None
881        );
882        assert!(
883            m.read(&json!({"status": {"leafWork": {"metric": -1}}}))
884                .is_err()
885        );
886        assert!(
887            m.read(&json!({"status": {"leafWork": {"metric": "9"}}}))
888                .is_err()
889        );
890        assert!(m.read(&json!({"status": {"leafWork": 9}})).is_err());
891    }
892
893    #[tokio::test]
894    async fn fake_metrics_provider_round_trip() {
895        let p = FakeMetricsProvider::new();
896        let target = ScaleTarget {
897            kind: "Deployment".into(),
898            name: "x".into(),
899            namespace: "default".into(),
900        };
901        assert_eq!(p.observe(&target).await.unwrap(), None);
902        p.set(target.clone(), 75.0).await;
903        assert_eq!(p.observe(&target).await.unwrap(), Some(75.0));
904        p.clear().await;
905        assert_eq!(p.observe(&target).await.unwrap(), None);
906    }
907
908    #[test]
909    fn provider_name_is_stable() {
910        assert_eq!(FakeMetricsProvider::new().name(), "fake");
911    }
912
913    #[test]
914    fn metrics_error_kind_is_stable() {
915        assert_eq!(MetricsError::Backend("x".into()).kind(), "backend");
916        assert_eq!(MetricsError::Unreadable("x".into()).kind(), "unreadable");
917    }
918
919    #[test]
920    fn controller_name_is_stable() {
921        struct F;
922        #[async_trait]
923        impl Controller for F {
924            fn name(&self) -> &'static str {
925                "hpa"
926            }
927            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
928                Ok(ReconcileReport::default().into())
929            }
930        }
931        assert_eq!(F.name(), "hpa");
932    }
933}