syncable-cli 0.37.1

A Rust-based CLI that analyzes code repositories and generates Infrastructure as Code configurations
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
//! Resource specification parsing utilities.
//!
//! Parses Kubernetes resource values (CPU and memory) from their string
//! representations to numeric values for comparison and calculation.

use crate::analyzer::k8s_optimize::types::{ResourceSpec, WorkloadType};
use regex::Regex;
use std::sync::LazyLock;

// ============================================================================
// CPU Parsing
// ============================================================================

/// Regex for parsing CPU values (e.g., "100m", "1", "1.5", "0.1")
static CPU_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\d+(?:\.\d+)?)(m)?$").unwrap());

/// Parse a CPU value string to millicores.
///
/// # Examples
/// - "100m" -> 100
/// - "1" -> 1000
/// - "1.5" -> 1500
/// - "0.1" -> 100
pub fn parse_cpu_to_millicores(cpu: &str) -> Option<u64> {
    let cpu = cpu.trim();
    if cpu.is_empty() {
        return None;
    }

    if let Some(caps) = CPU_REGEX.captures(cpu) {
        let value: f64 = caps.get(1)?.as_str().parse().ok()?;
        let is_millicores = caps.get(2).is_some();

        if is_millicores {
            Some(value as u64)
        } else {
            Some((value * 1000.0) as u64)
        }
    } else {
        None
    }
}

/// Convert millicores to a human-readable CPU string.
///
/// # Examples
/// - 100 -> "100m"
/// - 1000 -> "1"
/// - 1500 -> "1500m"
pub fn millicores_to_cpu_string(millicores: u64) -> String {
    if millicores >= 1000 && millicores.is_multiple_of(1000) {
        format!("{}", millicores / 1000)
    } else {
        format!("{}m", millicores)
    }
}

// ============================================================================
// Memory Parsing
// ============================================================================

/// Regex for parsing memory values (e.g., "128Mi", "1Gi", "1024Ki", "1000000000")
static MEMORY_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(\d+(?:\.\d+)?)(Ki|Mi|Gi|Ti|Pi|Ei|K|M|G|T|P|E)?$").unwrap());

/// Parse a memory value string to bytes.
///
/// # Examples
/// - "128Mi" -> 134217728
/// - "1Gi" -> 1073741824
/// - "1024Ki" -> 1048576
/// - "1000000000" -> 1000000000
pub fn parse_memory_to_bytes(memory: &str) -> Option<u64> {
    let memory = memory.trim();
    if memory.is_empty() {
        return None;
    }

    if let Some(caps) = MEMORY_REGEX.captures(memory) {
        let value: f64 = caps.get(1)?.as_str().parse().ok()?;
        let unit = caps.get(2).map(|m| m.as_str()).unwrap_or("");

        let multiplier: f64 = match unit {
            "" => 1.0,
            "Ki" => 1024.0,
            "Mi" => 1024.0 * 1024.0,
            "Gi" => 1024.0 * 1024.0 * 1024.0,
            "Ti" => 1024.0 * 1024.0 * 1024.0 * 1024.0,
            "Pi" => 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0,
            "Ei" => 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0,
            // Decimal units
            "K" => 1000.0,
            "M" => 1000.0 * 1000.0,
            "G" => 1000.0 * 1000.0 * 1000.0,
            "T" => 1000.0 * 1000.0 * 1000.0 * 1000.0,
            "P" => 1000.0 * 1000.0 * 1000.0 * 1000.0 * 1000.0,
            "E" => 1000.0 * 1000.0 * 1000.0 * 1000.0 * 1000.0 * 1000.0,
            _ => return None,
        };

        Some((value * multiplier) as u64)
    } else {
        None
    }
}

/// Convert bytes to a human-readable memory string (using binary units).
///
/// # Examples
/// - 134217728 -> "128Mi"
/// - 1073741824 -> "1Gi"
pub fn bytes_to_memory_string(bytes: u64) -> String {
    const KI: u64 = 1024;
    const MI: u64 = KI * 1024;
    const GI: u64 = MI * 1024;
    const TI: u64 = GI * 1024;

    if bytes >= TI && bytes.is_multiple_of(TI) {
        format!("{}Ti", bytes / TI)
    } else if bytes >= GI && bytes.is_multiple_of(GI) {
        format!("{}Gi", bytes / GI)
    } else if bytes >= MI && bytes.is_multiple_of(MI) {
        format!("{}Mi", bytes / MI)
    } else if bytes >= KI && bytes.is_multiple_of(KI) {
        format!("{}Ki", bytes / KI)
    } else if bytes >= MI {
        // Round to Mi for readability
        format!("{}Mi", bytes / MI)
    } else {
        format!("{}", bytes)
    }
}

// ============================================================================
// Resource Spec Parsing from YAML
// ============================================================================

/// Extract resources from a container YAML value.
pub fn extract_resources(container: &serde_yaml::Value) -> ResourceSpec {
    let mut spec = ResourceSpec::new();

    if let Some(resources) = container.get("resources") {
        if let Some(requests) = resources.get("requests") {
            if let Some(cpu) = requests.get("cpu") {
                spec.cpu_request = cpu.as_str().map(String::from);
            }
            if let Some(memory) = requests.get("memory") {
                spec.memory_request = memory.as_str().map(String::from);
            }
        }
        if let Some(limits) = resources.get("limits") {
            if let Some(cpu) = limits.get("cpu") {
                spec.cpu_limit = cpu.as_str().map(String::from);
            }
            if let Some(memory) = limits.get("memory") {
                spec.memory_limit = memory.as_str().map(String::from);
            }
        }
    }

    spec
}

/// Extract container name from a container YAML value.
pub fn extract_container_name(container: &serde_yaml::Value) -> Option<String> {
    container.get("name")?.as_str().map(String::from)
}

/// Extract image from a container YAML value.
pub fn extract_container_image(container: &serde_yaml::Value) -> Option<String> {
    container.get("image")?.as_str().map(String::from)
}

// ============================================================================
// Workload Type Detection
// ============================================================================

/// Detect workload type from container image and name.
pub fn detect_workload_type(
    image: Option<&str>,
    container_name: Option<&str>,
    kind: &str,
) -> WorkloadType {
    let image = image.unwrap_or("").to_lowercase();
    let name = container_name.unwrap_or("").to_lowercase();

    // Database indicators
    const DB_IMAGES: &[&str] = &[
        "postgres",
        "mysql",
        "mariadb",
        "mongodb",
        "mongo",
        "redis",
        "memcached",
        "elasticsearch",
        "cassandra",
        "couchdb",
        "cockroach",
        "timescale",
        "influx",
    ];
    for db in DB_IMAGES {
        if image.contains(db) || name.contains(db) {
            // Redis and Memcached are caches
            if *db == "redis" || *db == "memcached" {
                return WorkloadType::Cache;
            }
            return WorkloadType::Database;
        }
    }

    // Message broker indicators
    const BROKER_IMAGES: &[&str] = &["kafka", "rabbitmq", "nats", "pulsar", "activemq", "zeromq"];
    for broker in BROKER_IMAGES {
        if image.contains(broker) || name.contains(broker) {
            return WorkloadType::MessageBroker;
        }
    }

    // ML/AI indicators
    const ML_IMAGES: &[&str] = &[
        "tensorflow",
        "pytorch",
        "nvidia",
        "cuda",
        "gpu",
        "ml",
        "ai",
        "jupyter",
        "notebook",
        "training",
    ];
    for ml in ML_IMAGES {
        if image.contains(ml) || name.contains(ml) {
            return WorkloadType::MachineLearning;
        }
    }

    // Worker indicators
    const WORKER_PATTERNS: &[&str] = &[
        "worker",
        "consumer",
        "processor",
        "handler",
        "queue",
        "celery",
        "sidekiq",
        "resque",
        "bull",
        "bee",
    ];
    for pattern in WORKER_PATTERNS {
        if name.contains(pattern) {
            return WorkloadType::Worker;
        }
    }

    // Job/CronJob kinds are batch
    if kind == "Job" || kind == "CronJob" {
        return WorkloadType::Batch;
    }

    // Web indicators
    const WEB_IMAGES: &[&str] = &[
        "nginx", "apache", "httpd", "caddy", "traefik", "envoy", "api", "web", "frontend",
        "backend", "gateway",
    ];
    for web in WEB_IMAGES {
        if image.contains(web) || name.contains(web) {
            return WorkloadType::Web;
        }
    }

    // Default to general
    WorkloadType::General
}

// ============================================================================
// Ratio Calculations
// ============================================================================

/// Calculate the limit to request ratio for CPU.
pub fn cpu_limit_to_request_ratio(spec: &ResourceSpec) -> Option<f64> {
    let request = parse_cpu_to_millicores(spec.cpu_request.as_deref()?)?;
    let limit = parse_cpu_to_millicores(spec.cpu_limit.as_deref()?)?;

    if request == 0 {
        return None;
    }

    Some(limit as f64 / request as f64)
}

/// Calculate the limit to request ratio for memory.
pub fn memory_limit_to_request_ratio(spec: &ResourceSpec) -> Option<f64> {
    let request = parse_memory_to_bytes(spec.memory_request.as_deref()?)?;
    let limit = parse_memory_to_bytes(spec.memory_limit.as_deref()?)?;

    if request == 0 {
        return None;
    }

    Some(limit as f64 / request as f64)
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_parse_cpu_millicores() {
        assert_eq!(parse_cpu_to_millicores("100m"), Some(100));
        assert_eq!(parse_cpu_to_millicores("1"), Some(1000));
        assert_eq!(parse_cpu_to_millicores("1.5"), Some(1500));
        assert_eq!(parse_cpu_to_millicores("0.1"), Some(100));
        assert_eq!(parse_cpu_to_millicores("500m"), Some(500));
        assert_eq!(parse_cpu_to_millicores("2000m"), Some(2000));
    }

    #[test]
    fn test_millicores_to_string() {
        assert_eq!(millicores_to_cpu_string(100), "100m");
        assert_eq!(millicores_to_cpu_string(1000), "1");
        assert_eq!(millicores_to_cpu_string(2000), "2");
        assert_eq!(millicores_to_cpu_string(1500), "1500m");
    }

    #[test]
    fn test_parse_memory_bytes() {
        assert_eq!(parse_memory_to_bytes("128Mi"), Some(128 * 1024 * 1024));
        assert_eq!(parse_memory_to_bytes("1Gi"), Some(1024 * 1024 * 1024));
        assert_eq!(parse_memory_to_bytes("1024Ki"), Some(1024 * 1024));
        assert_eq!(parse_memory_to_bytes("1000000000"), Some(1000000000));
    }

    #[test]
    fn test_bytes_to_memory_string() {
        assert_eq!(bytes_to_memory_string(128 * 1024 * 1024), "128Mi");
        assert_eq!(bytes_to_memory_string(1024 * 1024 * 1024), "1Gi");
        assert_eq!(bytes_to_memory_string(1024 * 1024), "1Mi");
    }

    #[test]
    fn test_detect_workload_type() {
        assert_eq!(
            detect_workload_type(Some("postgres:14"), None, "Deployment"),
            WorkloadType::Database
        );
        assert_eq!(
            detect_workload_type(Some("redis:7"), None, "Deployment"),
            WorkloadType::Cache
        );
        assert_eq!(
            detect_workload_type(Some("nginx:latest"), None, "Deployment"),
            WorkloadType::Web
        );
        assert_eq!(
            detect_workload_type(Some("myapp:v1"), Some("worker"), "Deployment"),
            WorkloadType::Worker
        );
        assert_eq!(
            detect_workload_type(Some("myapp:v1"), None, "Job"),
            WorkloadType::Batch
        );
        assert_eq!(
            detect_workload_type(Some("myapp:v1"), None, "Deployment"),
            WorkloadType::General
        );
    }

    #[test]
    fn test_cpu_ratio() {
        let spec = ResourceSpec {
            cpu_request: Some("100m".to_string()),
            cpu_limit: Some("500m".to_string()),
            memory_request: None,
            memory_limit: None,
        };
        let ratio = cpu_limit_to_request_ratio(&spec).unwrap();
        assert!((ratio - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_memory_ratio() {
        let spec = ResourceSpec {
            cpu_request: None,
            cpu_limit: None,
            memory_request: Some("256Mi".to_string()),
            memory_limit: Some("1Gi".to_string()),
        };
        let ratio = memory_limit_to_request_ratio(&spec).unwrap();
        assert!((ratio - 4.0).abs() < 0.01);
    }

    #[test]
    fn test_extract_resources() {
        let yaml = serde_yaml::from_str::<serde_yaml::Value>(
            r#"
            name: nginx
            image: nginx:1.21
            resources:
              requests:
                cpu: 100m
                memory: 128Mi
              limits:
                cpu: 500m
                memory: 512Mi
            "#,
        )
        .unwrap();

        let spec = extract_resources(&yaml);
        assert_eq!(spec.cpu_request, Some("100m".to_string()));
        assert_eq!(spec.memory_request, Some("128Mi".to_string()));
        assert_eq!(spec.cpu_limit, Some("500m".to_string()));
        assert_eq!(spec.memory_limit, Some("512Mi".to_string()));
    }
}