litvc 1.2.1

Lit - The agentic-first distributed version control system. A complete Git replacement designed for AI agents first and humans second.
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
//! Datacenter deployment optimizations — cluster node management, object store
//! sharding, replication factor control, health monitoring, Prometheus-style
//! metrics, and connection pooling configuration.
//!
//! These features enable Lit to operate in distributed datacenter environments
//! with high availability, fault tolerance, and observability requirements.

use crate::core::find_repo_root;
use crate::errors::LitError;
use crate::response::DatacenterResponse;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;

// ── Data types ──────────────────────────────────────────────────────────────

/// Role a node plays in the cluster
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum NodeRole {
    /// Full read-write primary
    Primary,
    /// Read replica
    Replica,
    /// Relay / edge cache only
    Relay,
    /// Metrics & monitoring observer
    Observer,
}

impl std::fmt::Display for NodeRole {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NodeRole::Primary => write!(f, "primary"),
            NodeRole::Replica => write!(f, "replica"),
            NodeRole::Relay => write!(f, "relay"),
            NodeRole::Observer => write!(f, "observer"),
        }
    }
}

/// Health status of a node
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum HealthStatus {
    Healthy,
    Degraded,
    Unreachable,
    Draining,
    Bootstrapping,
}

impl std::fmt::Display for HealthStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HealthStatus::Healthy => write!(f, "healthy"),
            HealthStatus::Degraded => write!(f, "degraded"),
            HealthStatus::Unreachable => write!(f, "unreachable"),
            HealthStatus::Draining => write!(f, "draining"),
            HealthStatus::Bootstrapping => write!(f, "bootstrapping"),
        }
    }
}

/// Sharding strategy for distributing objects across nodes
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ShardStrategy {
    /// Consistent hash ring (default)
    ConsistentHash,
    /// Range-based on object hash prefix
    RangePrefix,
    /// Round-robin object distribution
    RoundRobin,
    /// Domain-aware — keep a content domain's objects co-located
    DomainAffinity,
}

/// Replication mode
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ReplicationMode {
    /// Synchronous — wait for all replicas to confirm
    Synchronous,
    /// Async — primary confirms immediately, replicas catch up
    Asynchronous,
    /// Semi-sync — wait for at least quorum to confirm
    SemiSync,
}

/// A registered datacenter cluster node
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterNode {
    /// Unique node identifier
    pub node_id: String,
    /// Display name
    pub name: String,
    /// Network endpoint (host:port or URL)
    pub endpoint: String,
    /// Region / availability zone
    pub region: String,
    /// Node role
    pub role: NodeRole,
    /// Current health
    pub health: HealthStatus,
    /// Shard assignments (hex prefixes this node owns)
    pub shard_ranges: Vec<String>,
    /// Last heartbeat timestamp
    pub last_heartbeat: String,
    /// Node capacity metrics
    pub capacity: NodeCapacity,
    /// ISO 8601 date the node was registered
    pub registered_at: String,
}

/// Capacity and utilization metrics for a node
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeCapacity {
    /// Total storage in bytes
    pub storage_total: u64,
    /// Used storage in bytes
    pub storage_used: u64,
    /// Object count on this node
    pub object_count: u64,
    /// Maximum concurrent connections
    pub max_connections: u32,
    /// Current active connections
    pub active_connections: u32,
    /// CPU utilization (0.0 – 1.0)
    pub cpu_utilization: f64,
    /// Memory utilization (0.0 – 1.0)
    pub memory_utilization: f64,
}

/// Cluster-level configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClusterConfig {
    /// Replication factor (how many copies per object)
    pub replication_factor: u32,
    /// Replication mode
    pub replication_mode: ReplicationMode,
    /// Sharding strategy
    pub shard_strategy: ShardStrategy,
    /// Number of virtual shards (powers of 16, e.g. 256 = 2 hex chars)
    pub shard_count: u32,
    /// Connection pool size per node
    pub connection_pool_size: u32,
    /// Heartbeat interval in seconds
    pub heartbeat_interval_secs: u32,
    /// Node timeout before marking unreachable
    pub node_timeout_secs: u32,
    /// Whether to enable Prometheus-style metrics endpoint
    pub metrics_enabled: bool,
    /// Metrics endpoint port (default: 9090)
    pub metrics_port: u16,
    /// Maximum object size before chunked transfer (bytes)
    pub chunk_threshold: u64,
    /// Chunk size for large object transfer (bytes)
    pub chunk_size: u64,
    /// Compression for inter-node transfer
    pub transfer_compression: bool,
    /// Enable read replicas for load balancing reads
    pub read_load_balance: bool,
    /// Write concern — how many nodes must confirm a write
    pub write_concern: u32,
}

impl Default for ClusterConfig {
    fn default() -> Self {
        Self {
            replication_factor: 3,
            replication_mode: ReplicationMode::SemiSync,
            shard_strategy: ShardStrategy::ConsistentHash,
            shard_count: 256,
            connection_pool_size: 32,
            heartbeat_interval_secs: 10,
            node_timeout_secs: 30,
            metrics_enabled: true,
            metrics_port: 9090,
            chunk_threshold: 64 * 1024 * 1024,
            chunk_size: 4 * 1024 * 1024,
            transfer_compression: true,
            read_load_balance: true,
            write_concern: 2,
        }
    }
}

/// Prometheus-style metric representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metric {
    pub name: String,
    pub help: String,
    pub metric_type: String,
    pub value: f64,
    pub labels: HashMap<String, String>,
}

// ── Helpers ─────────────────────────────────────────────────────────────────

fn datacenter_dir(repo_root: &Path) -> std::path::PathBuf {
    repo_root.join(".lit").join("datacenter")
}

fn nodes_dir(repo_root: &Path) -> std::path::PathBuf {
    datacenter_dir(repo_root).join("nodes")
}

fn load_cluster_config(repo_root: &Path) -> Result<ClusterConfig, LitError> {
    let path = datacenter_dir(repo_root).join("cluster.json");
    if path.exists() {
        let json = fs::read_to_string(&path).map_err(|e| LitError::io(e.to_string()))?;
        serde_json::from_str(&json)
            .map_err(|e| LitError::general(format!("Parse cluster config: {}", e)))
    } else {
        Ok(ClusterConfig::default())
    }
}

fn save_cluster_config(repo_root: &Path, config: &ClusterConfig) -> Result<(), LitError> {
    let dir = datacenter_dir(repo_root);
    fs::create_dir_all(&dir).map_err(|e| LitError::io(e.to_string()))?;
    let json = serde_json::to_string_pretty(config)
        .map_err(|e| LitError::general(format!("Serialize cluster config: {}", e)))?;
    fs::write(dir.join("cluster.json"), json).map_err(|e| LitError::io(e.to_string()))?;
    Ok(())
}

fn save_node(repo_root: &Path, node: &ClusterNode) -> Result<(), LitError> {
    let dir = nodes_dir(repo_root);
    fs::create_dir_all(&dir).map_err(|e| LitError::io(e.to_string()))?;
    let json = serde_json::to_string_pretty(node)
        .map_err(|e| LitError::general(format!("Serialize node: {}", e)))?;
    fs::write(dir.join(format!("{}.json", node.node_id)), json)
        .map_err(|e| LitError::io(e.to_string()))?;
    Ok(())
}

fn load_all_nodes(repo_root: &Path) -> Result<Vec<ClusterNode>, LitError> {
    let dir = nodes_dir(repo_root);
    let mut nodes = Vec::new();
    if dir.exists() {
        for entry in fs::read_dir(&dir).map_err(|e| LitError::io(e.to_string()))? {
            let entry = entry.map_err(|e| LitError::io(e.to_string()))?;
            if entry
                .path()
                .extension()
                .map(|e| e == "json")
                .unwrap_or(false)
            {
                let json =
                    fs::read_to_string(entry.path()).map_err(|e| LitError::io(e.to_string()))?;
                if let Ok(node) = serde_json::from_str::<ClusterNode>(&json) {
                    nodes.push(node);
                }
            }
        }
    }
    Ok(nodes)
}

/// Assign shard ranges to a node based on current cluster state
fn compute_shard_ranges(node_id: &str, all_nodes: &[ClusterNode], shard_count: u32) -> Vec<String> {
    let active_nodes: Vec<&ClusterNode> = all_nodes
        .iter()
        .filter(|n| n.health != HealthStatus::Unreachable && n.health != HealthStatus::Draining)
        .collect();

    if active_nodes.is_empty() {
        return (0..shard_count).map(|i| format!("{:02x}", i)).collect();
    }

    let pos = active_nodes
        .iter()
        .position(|n| n.node_id == node_id)
        .unwrap_or(active_nodes.len());

    let total = active_nodes.len() as u32;
    let shards_per_node = shard_count / total.max(1);
    let start = pos as u32 * shards_per_node;
    let end = if pos as u32 == total - 1 {
        shard_count
    } else {
        start + shards_per_node
    };

    (start..end).map(|i| format!("{:02x}", i % 256)).collect()
}

/// Collect Prometheus-style metrics for the local node
fn collect_metrics(repo_root: &Path) -> Vec<Metric> {
    let objects_dir = repo_root.join(".lit").join("objects");
    let mut object_count: u64 = 0;
    let mut total_size: u64 = 0;

    if let Ok(entries) = fs::read_dir(&objects_dir) {
        for shard in entries.flatten() {
            if shard.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                if let Ok(files) = fs::read_dir(shard.path()) {
                    for file in files.flatten() {
                        object_count += 1;
                        total_size += file.metadata().map(|m| m.len()).unwrap_or(0);
                    }
                }
            }
        }
    }

    let refs_count = repo_root
        .join(".lit")
        .join("refs")
        .read_dir()
        .map(|e| e.count() as u64)
        .unwrap_or(0);

    vec![
        Metric {
            name: "lit_objects_total".into(),
            help: "Total number of objects in the local store".into(),
            metric_type: "gauge".into(),
            value: object_count as f64,
            labels: HashMap::new(),
        },
        Metric {
            name: "lit_objects_size_bytes".into(),
            help: "Total size of all objects in bytes".into(),
            metric_type: "gauge".into(),
            value: total_size as f64,
            labels: HashMap::new(),
        },
        Metric {
            name: "lit_refs_total".into(),
            help: "Total number of refs".into(),
            metric_type: "gauge".into(),
            value: refs_count as f64,
            labels: HashMap::new(),
        },
    ]
}

// ── Public API ──────────────────────────────────────────────────────────────

/// Show cluster status — nodes, shard distribution, config
pub fn execute_status() -> Result<DatacenterResponse, LitError> {
    let repo_root = find_repo_root()?;
    let config = load_cluster_config(&repo_root)?;
    let nodes = load_all_nodes(&repo_root)?;

    let healthy = nodes
        .iter()
        .filter(|n| n.health == HealthStatus::Healthy)
        .count();
    let total = nodes.len();

    Ok(DatacenterResponse {
        action: "status".into(),
        message: format!(
            "Cluster: {} node(s) ({} healthy), replication_factor={}, shards={}, strategy={}",
            total,
            healthy,
            config.replication_factor,
            config.shard_count,
            match config.shard_strategy {
                ShardStrategy::ConsistentHash => "consistent-hash",
                ShardStrategy::RangePrefix => "range-prefix",
                ShardStrategy::RoundRobin => "round-robin",
                ShardStrategy::DomainAffinity => "domain-affinity",
            }
        ),
        details: Some(serde_json::json!({
            "config": config,
            "nodes": nodes,
            "summary": {
                "total_nodes": total,
                "healthy_nodes": healthy,
                "total_storage": nodes.iter().map(|n| n.capacity.storage_total).sum::<u64>(),
                "used_storage": nodes.iter().map(|n| n.capacity.storage_used).sum::<u64>(),
                "total_objects": nodes.iter().map(|n| n.capacity.object_count).sum::<u64>(),
            }
        })),
    })
}

/// Register a new cluster node
pub fn execute_register_node(
    node_id: String,
    name: String,
    endpoint: String,
    region: String,
    role: Option<String>,
) -> Result<DatacenterResponse, LitError> {
    let repo_root = find_repo_root()?;
    let config = load_cluster_config(&repo_root)?;
    let existing = load_all_nodes(&repo_root)?;

    let role_enum = match role.as_deref() {
        Some("primary") => NodeRole::Primary,
        Some("replica") => NodeRole::Replica,
        Some("relay") => NodeRole::Relay,
        Some("observer") => NodeRole::Observer,
        _ => NodeRole::Replica,
    };

    let node = ClusterNode {
        node_id: node_id.clone(),
        name: name.clone(),
        endpoint,
        region: region.clone(),
        role: role_enum,
        health: HealthStatus::Bootstrapping,
        shard_ranges: compute_shard_ranges(&node_id, &existing, config.shard_count),
        last_heartbeat: Utc::now().to_rfc3339(),
        capacity: NodeCapacity {
            storage_total: 0,
            storage_used: 0,
            object_count: 0,
            max_connections: config.connection_pool_size,
            active_connections: 0,
            cpu_utilization: 0.0,
            memory_utilization: 0.0,
        },
        registered_at: Utc::now().to_rfc3339(),
    };

    save_node(&repo_root, &node)?;

    Ok(DatacenterResponse {
        action: "register-node".into(),
        message: format!(
            "Node '{}' ({}) registered in region '{}' with {} shard(s)",
            name,
            node_id,
            region,
            node.shard_ranges.len()
        ),
        details: Some(serde_json::to_value(&node).unwrap_or_default()),
    })
}

/// Configure cluster-level settings
#[allow(clippy::too_many_arguments)]
pub fn execute_configure(
    replication_factor: Option<u32>,
    shard_count: Option<u32>,
    shard_strategy: Option<String>,
    replication_mode: Option<String>,
    connection_pool_size: Option<u32>,
    metrics_enabled: Option<bool>,
    metrics_port: Option<u16>,
    write_concern: Option<u32>,
) -> Result<DatacenterResponse, LitError> {
    let repo_root = find_repo_root()?;
    let mut config = load_cluster_config(&repo_root)?;

    if let Some(rf) = replication_factor {
        config.replication_factor = rf;
    }
    if let Some(sc) = shard_count {
        config.shard_count = sc;
    }
    if let Some(ss) = shard_strategy {
        config.shard_strategy = match ss.as_str() {
            "consistent-hash" => ShardStrategy::ConsistentHash,
            "range-prefix" => ShardStrategy::RangePrefix,
            "round-robin" => ShardStrategy::RoundRobin,
            "domain-affinity" => ShardStrategy::DomainAffinity,
            _ => ShardStrategy::ConsistentHash,
        };
    }
    if let Some(rm) = replication_mode {
        config.replication_mode = match rm.as_str() {
            "sync" | "synchronous" => ReplicationMode::Synchronous,
            "async" | "asynchronous" => ReplicationMode::Asynchronous,
            _ => ReplicationMode::SemiSync,
        };
    }
    if let Some(cps) = connection_pool_size {
        config.connection_pool_size = cps;
    }
    if let Some(me) = metrics_enabled {
        config.metrics_enabled = me;
    }
    if let Some(mp) = metrics_port {
        config.metrics_port = mp;
    }
    if let Some(wc) = write_concern {
        config.write_concern = wc;
    }

    save_cluster_config(&repo_root, &config)?;

    Ok(DatacenterResponse {
        action: "configure".into(),
        message: "Cluster configuration updated".into(),
        details: Some(serde_json::to_value(&config).unwrap_or_default()),
    })
}

/// Run health checks on all registered nodes
pub fn execute_health() -> Result<DatacenterResponse, LitError> {
    let repo_root = find_repo_root()?;
    let config = load_cluster_config(&repo_root)?;
    let nodes = load_all_nodes(&repo_root)?;

    let mut health_report: Vec<serde_json::Value> = Vec::new();
    let timeout_cutoff = Utc::now() - chrono::Duration::seconds(config.node_timeout_secs as i64);

    for node in &nodes {
        let last_hb = chrono::DateTime::parse_from_rfc3339(&node.last_heartbeat)
            .map(|dt| dt.with_timezone(&Utc))
            .unwrap_or_else(|_| Utc::now());

        let effective_health = if last_hb < timeout_cutoff && node.health == HealthStatus::Healthy {
            HealthStatus::Unreachable
        } else {
            node.health.clone()
        };

        let storage_pct = if node.capacity.storage_total > 0 {
            (node.capacity.storage_used as f64 / node.capacity.storage_total as f64) * 100.0
        } else {
            0.0
        };

        health_report.push(serde_json::json!({
            "node_id": node.node_id,
            "name": node.name,
            "role": node.role.to_string(),
            "health": effective_health.to_string(),
            "region": node.region,
            "storage_pct": format!("{:.1}%", storage_pct),
            "cpu": format!("{:.1}%", node.capacity.cpu_utilization * 100.0),
            "memory": format!("{:.1}%", node.capacity.memory_utilization * 100.0),
            "connections": format!("{}/{}", node.capacity.active_connections, node.capacity.max_connections),
            "last_heartbeat": node.last_heartbeat,
        }));
    }

    Ok(DatacenterResponse {
        action: "health".into(),
        message: format!("Health check for {} node(s)", nodes.len()),
        details: Some(serde_json::to_value(&health_report).unwrap_or_default()),
    })
}

/// Collect and return Prometheus-style metrics
pub fn execute_metrics() -> Result<DatacenterResponse, LitError> {
    let repo_root = find_repo_root()?;
    let metrics = collect_metrics(&repo_root);

    // Also include per-node metrics if cluster is configured
    let nodes = load_all_nodes(&repo_root)?;
    let mut all_metrics = metrics;

    all_metrics.push(Metric {
        name: "lit_cluster_nodes_total".into(),
        help: "Total nodes in cluster".into(),
        metric_type: "gauge".into(),
        value: nodes.len() as f64,
        labels: HashMap::new(),
    });

    let healthy = nodes
        .iter()
        .filter(|n| n.health == HealthStatus::Healthy)
        .count();
    all_metrics.push(Metric {
        name: "lit_cluster_nodes_healthy".into(),
        help: "Healthy nodes in cluster".into(),
        metric_type: "gauge".into(),
        value: healthy as f64,
        labels: HashMap::new(),
    });

    // Render as Prometheus exposition format
    let exposition: String = all_metrics
        .iter()
        .map(|m| {
            let labels_str = if m.labels.is_empty() {
                String::new()
            } else {
                let pairs: Vec<String> = m
                    .labels
                    .iter()
                    .map(|(k, v)| format!("{}=\"{}\"", k, v))
                    .collect();
                format!("{{{}}}", pairs.join(","))
            };
            format!(
                "# HELP {} {}\n# TYPE {} {}\n{}{} {}",
                m.name, m.help, m.name, m.metric_type, m.name, labels_str, m.value
            )
        })
        .collect::<Vec<_>>()
        .join("\n\n");

    Ok(DatacenterResponse {
        action: "metrics".into(),
        message: format!("{} metric(s) collected", all_metrics.len()),
        details: Some(serde_json::json!({
            "metrics": all_metrics,
            "exposition": exposition,
        })),
    })
}

/// Remove a node from the cluster (drain first recommended)
pub fn execute_remove_node(node_id: String) -> Result<DatacenterResponse, LitError> {
    let repo_root = find_repo_root()?;
    let dir = nodes_dir(&repo_root);
    let path = dir.join(format!("{}.json", node_id));

    if !path.exists() {
        return Err(LitError::general(format!("Node not found: {}", node_id)));
    }

    fs::remove_file(&path).map_err(|e| LitError::io(e.to_string()))?;

    Ok(DatacenterResponse {
        action: "remove-node".into(),
        message: format!("Node '{}' removed from cluster", node_id),
        details: None,
    })
}