a3s-box-core 2.4.0

Core types, config, and error handling for A3S Box MicroVM runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Kubernetes BoxAutoscaler CRD types.
//!
//! Defines the Custom Resource Definition for autoscaling Box instances
//! in a Kubernetes cluster. The controller watches these resources and
//! adjusts replica counts based on metrics.
//!
//! ## CRD Schema
//!
//! ```yaml
//! apiVersion: box.a3s.dev/v1alpha1
//! kind: BoxAutoscaler
//! metadata:
//!   name: my-service-autoscaler
//! spec:
//!   targetRef:
//!     kind: BoxService
//!     name: my-service
//!   minReplicas: 1
//!   maxReplicas: 10
//!   metrics:
//!     - type: cpu
//!       target: 70
//!     - type: inflight
//!       target: 50
//!   behavior:
//!     scaleUp:
//!       stabilizationWindowSeconds: 60
//!       maxScalePerMinute: 3
//!     scaleDown:
//!       stabilizationWindowSeconds: 300
//!       maxScalePerMinute: 1
//! ```

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// API group for Box CRDs.
pub const API_GROUP: &str = "box.a3s.dev";
/// API version for BoxAutoscaler.
pub const API_VERSION: &str = "v1alpha1";
/// CRD kind.
pub const KIND: &str = "BoxAutoscaler";

/// BoxAutoscaler CRD spec — desired autoscaling behavior.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoxAutoscalerSpec {
    /// Reference to the target resource to scale.
    pub target_ref: TargetRef,
    /// Minimum number of replicas (default: 1).
    #[serde(default = "default_min_replicas")]
    pub min_replicas: u32,
    /// Maximum number of replicas.
    pub max_replicas: u32,
    /// Metrics to evaluate for scaling decisions.
    #[serde(default)]
    pub metrics: Vec<MetricSpec>,
    /// Scaling behavior configuration.
    #[serde(default)]
    pub behavior: ScalingBehavior,
    /// Cooldown period in seconds after a scale event (default: 60).
    #[serde(default = "default_cooldown")]
    pub cooldown_secs: u64,
}

fn default_min_replicas() -> u32 {
    1
}

fn default_cooldown() -> u64 {
    60
}

/// Reference to the target resource being scaled.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TargetRef {
    /// Resource kind (e.g., "BoxService", "Deployment").
    pub kind: String,
    /// Resource name.
    pub name: String,
    /// Namespace (optional, defaults to "default").
    #[serde(default = "default_namespace")]
    pub namespace: String,
}

fn default_namespace() -> String {
    "default".to_string()
}

/// A metric used for autoscaling decisions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricSpec {
    /// Metric type.
    #[serde(rename = "type")]
    pub metric_type: MetricType,
    /// Target value (interpretation depends on metric type).
    pub target: u32,
    /// Tolerance percentage before triggering scale (default: 10%).
    #[serde(default = "default_tolerance")]
    pub tolerance_percent: u32,
}

fn default_tolerance() -> u32 {
    10
}

/// Supported metric types for autoscaling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MetricType {
    /// Average CPU utilization percentage across instances.
    Cpu,
    /// Average memory utilization percentage across instances.
    Memory,
    /// Total in-flight requests across instances.
    Inflight,
    /// Requests per second across all instances.
    Rps,
    /// Custom metric (from Prometheus or external source).
    Custom,
}

impl std::fmt::Display for MetricType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cpu => write!(f, "cpu"),
            Self::Memory => write!(f, "memory"),
            Self::Inflight => write!(f, "inflight"),
            Self::Rps => write!(f, "rps"),
            Self::Custom => write!(f, "custom"),
        }
    }
}

/// Scaling behavior configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingBehavior {
    /// Scale-up behavior.
    #[serde(default)]
    pub scale_up: ScalingRules,
    /// Scale-down behavior.
    #[serde(default)]
    pub scale_down: ScalingRules,
}

impl Default for ScalingBehavior {
    fn default() -> Self {
        Self {
            scale_up: ScalingRules {
                stabilization_window_secs: 60,
                max_scale_per_minute: 3,
            },
            scale_down: ScalingRules {
                stabilization_window_secs: 300,
                max_scale_per_minute: 1,
            },
        }
    }
}

/// Rules for a scaling direction (up or down).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingRules {
    /// Seconds to wait after a metric change before acting.
    #[serde(default = "default_stabilization")]
    pub stabilization_window_secs: u64,
    /// Maximum replica changes per minute.
    #[serde(default = "default_max_scale")]
    pub max_scale_per_minute: u32,
}

fn default_stabilization() -> u64 {
    60
}

fn default_max_scale() -> u32 {
    2
}

impl Default for ScalingRules {
    fn default() -> Self {
        Self {
            stabilization_window_secs: 60,
            max_scale_per_minute: 2,
        }
    }
}

/// BoxAutoscaler CRD status — observed state.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BoxAutoscalerStatus {
    /// Current number of replicas.
    pub current_replicas: u32,
    /// Desired number of replicas (as computed by the controller).
    pub desired_replicas: u32,
    /// Last time the autoscaler scaled.
    #[serde(default)]
    pub last_scale_time: Option<DateTime<Utc>>,
    /// Current metric values.
    #[serde(default)]
    pub current_metrics: Vec<MetricValue>,
    /// Conditions describing the autoscaler state.
    #[serde(default)]
    pub conditions: Vec<AutoscalerCondition>,
}

/// An observed metric value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricValue {
    /// Metric type.
    #[serde(rename = "type")]
    pub metric_type: MetricType,
    /// Current observed value.
    pub current: u32,
    /// Target value from spec.
    pub target: u32,
}

/// A condition on the autoscaler.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoscalerCondition {
    /// Condition type (e.g., "Ready", "ScalingActive", "ScalingLimited").
    #[serde(rename = "type")]
    pub condition_type: String,
    /// Status: "True", "False", or "Unknown".
    pub status: String,
    /// Last time the condition transitioned.
    #[serde(default)]
    pub last_transition_time: Option<DateTime<Utc>>,
    /// Human-readable reason.
    #[serde(default)]
    pub reason: String,
    /// Human-readable message.
    #[serde(default)]
    pub message: String,
}

/// Full BoxAutoscaler resource (spec + status + metadata).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BoxAutoscaler {
    /// API version.
    pub api_version: String,
    /// Resource kind.
    pub kind: String,
    /// Resource name.
    pub name: String,
    /// Namespace.
    #[serde(default = "default_namespace")]
    pub namespace: String,
    /// Labels.
    #[serde(default)]
    pub labels: HashMap<String, String>,
    /// Spec.
    pub spec: BoxAutoscalerSpec,
    /// Status.
    #[serde(default)]
    pub status: BoxAutoscalerStatus,
}

impl BoxAutoscaler {
    /// Create a new BoxAutoscaler resource.
    pub fn new(name: &str, spec: BoxAutoscalerSpec) -> Self {
        Self {
            api_version: format!("{}/{}", API_GROUP, API_VERSION),
            kind: KIND.to_string(),
            name: name.to_string(),
            namespace: "default".to_string(),
            labels: HashMap::new(),
            spec,
            status: BoxAutoscalerStatus::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_spec() -> BoxAutoscalerSpec {
        BoxAutoscalerSpec {
            target_ref: TargetRef {
                kind: "BoxService".to_string(),
                name: "my-service".to_string(),
                namespace: "default".to_string(),
            },
            min_replicas: 1,
            max_replicas: 10,
            metrics: vec![MetricSpec {
                metric_type: MetricType::Cpu,
                target: 70,
                tolerance_percent: 10,
            }],
            behavior: ScalingBehavior::default(),
            cooldown_secs: 60,
        }
    }

    #[test]
    fn test_box_autoscaler_new() {
        let ba = BoxAutoscaler::new("test-scaler", sample_spec());
        assert_eq!(ba.name, "test-scaler");
        assert_eq!(ba.api_version, "box.a3s.dev/v1alpha1");
        assert_eq!(ba.kind, "BoxAutoscaler");
        assert_eq!(ba.namespace, "default");
        assert_eq!(ba.spec.min_replicas, 1);
        assert_eq!(ba.spec.max_replicas, 10);
    }

    #[test]
    fn test_spec_serde_roundtrip() {
        let spec = sample_spec();
        let json = serde_json::to_string(&spec).unwrap();
        let parsed: BoxAutoscalerSpec = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.min_replicas, 1);
        assert_eq!(parsed.max_replicas, 10);
        assert_eq!(parsed.metrics.len(), 1);
        assert_eq!(parsed.metrics[0].metric_type, MetricType::Cpu);
        assert_eq!(parsed.metrics[0].target, 70);
    }

    #[test]
    fn test_spec_deserialize_minimal() {
        let json = r#"{
            "target_ref": {"kind": "BoxService", "name": "svc"},
            "max_replicas": 5
        }"#;
        let spec: BoxAutoscalerSpec = serde_json::from_str(json).unwrap();
        assert_eq!(spec.min_replicas, 1); // default
        assert_eq!(spec.max_replicas, 5);
        assert_eq!(spec.cooldown_secs, 60); // default
        assert!(spec.metrics.is_empty());
        assert_eq!(spec.target_ref.namespace, "default"); // default
    }

    #[test]
    fn test_metric_type_display() {
        assert_eq!(MetricType::Cpu.to_string(), "cpu");
        assert_eq!(MetricType::Memory.to_string(), "memory");
        assert_eq!(MetricType::Inflight.to_string(), "inflight");
        assert_eq!(MetricType::Rps.to_string(), "rps");
        assert_eq!(MetricType::Custom.to_string(), "custom");
    }

    #[test]
    fn test_metric_type_serde() {
        let json = r#""cpu""#;
        let mt: MetricType = serde_json::from_str(json).unwrap();
        assert_eq!(mt, MetricType::Cpu);

        let json = serde_json::to_string(&MetricType::Inflight).unwrap();
        assert_eq!(json, r#""inflight""#);
    }

    #[test]
    fn test_scaling_behavior_default() {
        let behavior = ScalingBehavior::default();
        assert_eq!(behavior.scale_up.stabilization_window_secs, 60);
        assert_eq!(behavior.scale_up.max_scale_per_minute, 3);
        assert_eq!(behavior.scale_down.stabilization_window_secs, 300);
        assert_eq!(behavior.scale_down.max_scale_per_minute, 1);
    }

    #[test]
    fn test_status_default() {
        let status = BoxAutoscalerStatus::default();
        assert_eq!(status.current_replicas, 0);
        assert_eq!(status.desired_replicas, 0);
        assert!(status.last_scale_time.is_none());
        assert!(status.current_metrics.is_empty());
        assert!(status.conditions.is_empty());
    }

    #[test]
    fn test_status_serde_roundtrip() {
        let status = BoxAutoscalerStatus {
            current_replicas: 3,
            desired_replicas: 5,
            last_scale_time: Some(Utc::now()),
            current_metrics: vec![MetricValue {
                metric_type: MetricType::Cpu,
                current: 85,
                target: 70,
            }],
            conditions: vec![AutoscalerCondition {
                condition_type: "ScalingActive".to_string(),
                status: "True".to_string(),
                last_transition_time: Some(Utc::now()),
                reason: "HighCPU".to_string(),
                message: "CPU above target".to_string(),
            }],
        };
        let json = serde_json::to_string(&status).unwrap();
        let parsed: BoxAutoscalerStatus = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.current_replicas, 3);
        assert_eq!(parsed.desired_replicas, 5);
        assert_eq!(parsed.current_metrics.len(), 1);
        assert_eq!(parsed.conditions.len(), 1);
        assert_eq!(parsed.conditions[0].reason, "HighCPU");
    }

    #[test]
    fn test_full_resource_serde() {
        let ba = BoxAutoscaler::new("my-scaler", sample_spec());
        let json = serde_json::to_string_pretty(&ba).unwrap();
        let parsed: BoxAutoscaler = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, "my-scaler");
        assert_eq!(parsed.spec.max_replicas, 10);
        assert_eq!(parsed.status.current_replicas, 0);
    }

    #[test]
    fn test_target_ref_serde() {
        let tr = TargetRef {
            kind: "BoxService".to_string(),
            name: "web".to_string(),
            namespace: "production".to_string(),
        };
        let json = serde_json::to_string(&tr).unwrap();
        let parsed: TargetRef = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.kind, "BoxService");
        assert_eq!(parsed.name, "web");
        assert_eq!(parsed.namespace, "production");
    }

    #[test]
    fn test_metric_spec_with_tolerance() {
        let ms = MetricSpec {
            metric_type: MetricType::Rps,
            target: 1000,
            tolerance_percent: 15,
        };
        let json = serde_json::to_string(&ms).unwrap();
        let parsed: MetricSpec = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.metric_type, MetricType::Rps);
        assert_eq!(parsed.target, 1000);
        assert_eq!(parsed.tolerance_percent, 15);
    }

    #[test]
    fn test_metric_spec_default_tolerance() {
        let json = r#"{"type": "cpu", "target": 80}"#;
        let ms: MetricSpec = serde_json::from_str(json).unwrap();
        assert_eq!(ms.tolerance_percent, 10); // default
    }

    #[test]
    fn test_constants() {
        assert_eq!(API_GROUP, "box.a3s.dev");
        assert_eq!(API_VERSION, "v1alpha1");
        assert_eq!(KIND, "BoxAutoscaler");
    }
}