Skip to main content

rc_core/admin/
cluster.rs

1//! Cluster management type definitions
2//!
3//! This module contains data structures for cluster management operations
4//! including server information, disk status, and heal operations.
5
6use serde::{Deserialize, Serialize};
7use std::collections::{BTreeMap, HashMap};
8
9/// Server information representing a RustFS node
10#[derive(Debug, Clone, Serialize, Deserialize, Default)]
11#[serde(rename_all = "camelCase")]
12pub struct ServerInfo {
13    /// Server state (online, offline, initializing)
14    #[serde(default)]
15    pub state: String,
16
17    /// Server endpoint URL
18    #[serde(default)]
19    pub endpoint: String,
20
21    /// Connection scheme (http/https)
22    #[serde(default)]
23    pub scheme: String,
24
25    /// Uptime in seconds
26    #[serde(default)]
27    pub uptime: u64,
28
29    /// Server version
30    #[serde(default)]
31    pub version: String,
32
33    /// Git commit ID
34    #[serde(default, rename = "commitID")]
35    pub commit_id: String,
36
37    /// Network interfaces
38    #[serde(default)]
39    pub network: HashMap<String, String>,
40
41    /// Attached drives
42    #[serde(default, rename = "drives")]
43    pub disks: Vec<DiskInfo>,
44
45    /// Pool number
46    #[serde(default, rename = "poolNumber")]
47    pub pool_number: i32,
48
49    /// Memory statistics
50    #[serde(default, rename = "mem_stats")]
51    pub mem_stats: MemStats,
52}
53
54/// Disk information
55#[derive(Debug, Clone, Serialize, Deserialize, Default)]
56#[serde(rename_all = "camelCase")]
57pub struct DiskInfo {
58    /// Disk endpoint
59    #[serde(default)]
60    pub endpoint: String,
61
62    /// Whether this is a root disk
63    #[serde(default, rename = "rootDisk")]
64    pub root_disk: bool,
65
66    /// Drive path
67    #[serde(default, rename = "path")]
68    pub drive_path: String,
69
70    /// Whether healing is in progress
71    #[serde(default)]
72    pub healing: bool,
73
74    /// Whether scanning is in progress
75    #[serde(default)]
76    pub scanning: bool,
77
78    /// Disk state (online, offline)
79    #[serde(default)]
80    pub state: String,
81
82    /// Disk UUID
83    #[serde(default)]
84    pub uuid: String,
85
86    /// Total space in bytes
87    #[serde(default, rename = "totalspace")]
88    pub total_space: u64,
89
90    /// Used space in bytes
91    #[serde(default, rename = "usedspace")]
92    pub used_space: u64,
93
94    /// Available space in bytes
95    #[serde(default, rename = "availspace")]
96    pub available_space: u64,
97
98    /// Pool index
99    #[serde(default, alias = "pool_index")]
100    pub pool_index: i32,
101
102    /// Set index
103    #[serde(default, alias = "set_index")]
104    pub set_index: i32,
105
106    /// Disk index within set
107    #[serde(default, alias = "disk_index")]
108    pub disk_index: i32,
109
110    /// Healing info if disk is being healed
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub heal_info: Option<HealingDiskInfo>,
113}
114
115/// Healing disk information
116#[derive(Debug, Clone, Serialize, Deserialize, Default)]
117#[serde(rename_all = "camelCase")]
118pub struct HealingDiskInfo {
119    /// Heal ID
120    #[serde(default)]
121    pub id: String,
122
123    /// Heal session ID
124    #[serde(default)]
125    pub heal_id: String,
126
127    /// Pool index
128    #[serde(default)]
129    pub pool_index: Option<usize>,
130
131    /// Set index
132    #[serde(default)]
133    pub set_index: Option<usize>,
134
135    /// Disk index
136    #[serde(default)]
137    pub disk_index: Option<usize>,
138
139    /// Endpoint being healed
140    #[serde(default)]
141    pub endpoint: String,
142
143    /// Path being healed
144    #[serde(default)]
145    pub path: String,
146
147    /// Objects total count
148    #[serde(default)]
149    pub objects_total_count: u64,
150
151    /// Objects total size
152    #[serde(default)]
153    pub objects_total_size: u64,
154
155    /// Items healed count
156    #[serde(default)]
157    pub items_healed: u64,
158
159    /// Items failed count
160    #[serde(default)]
161    pub items_failed: u64,
162
163    /// Bytes done
164    #[serde(default)]
165    pub bytes_done: u64,
166
167    /// Whether healing is finished
168    #[serde(default)]
169    pub finished: bool,
170
171    /// Current bucket being healed
172    #[serde(default)]
173    pub bucket: String,
174
175    /// Current object being healed
176    #[serde(default)]
177    pub object: String,
178}
179
180/// Memory statistics
181#[derive(Debug, Clone, Serialize, Deserialize, Default)]
182pub struct MemStats {
183    /// Current allocated memory
184    #[serde(default)]
185    pub alloc: u64,
186
187    /// Total allocated memory over lifetime
188    #[serde(default)]
189    pub total_alloc: u64,
190
191    /// Heap allocated memory
192    #[serde(default)]
193    pub heap_alloc: u64,
194}
195
196/// Storage backend type
197#[derive(Debug, Clone, Serialize, Deserialize, Default)]
198#[serde(rename_all = "lowercase")]
199pub enum BackendType {
200    /// Filesystem backend (single drive)
201    #[default]
202    #[serde(rename = "FS")]
203    Fs,
204    /// Erasure coding backend (distributed)
205    #[serde(rename = "Erasure")]
206    Erasure,
207}
208
209impl std::fmt::Display for BackendType {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        match self {
212            BackendType::Fs => write!(f, "FS"),
213            BackendType::Erasure => write!(f, "Erasure"),
214        }
215    }
216}
217
218/// Backend information
219#[derive(Debug, Clone, Serialize, Deserialize, Default)]
220#[serde(rename_all = "camelCase")]
221pub struct BackendInfo {
222    /// Backend type
223    #[serde(default, rename = "backendType")]
224    pub backend_type: BackendType,
225
226    /// Number of online disks
227    #[serde(default, rename = "onlineDisks")]
228    pub online_disks: usize,
229
230    /// Number of offline disks
231    #[serde(default, rename = "offlineDisks")]
232    pub offline_disks: usize,
233
234    /// Standard storage class parity
235    #[serde(default, rename = "standardSCParity")]
236    pub standard_sc_parity: Option<usize>,
237
238    /// Reduced redundancy storage class parity
239    #[serde(default, rename = "rrSCParity")]
240    pub rr_sc_parity: Option<usize>,
241
242    /// Total erasure sets
243    #[serde(default, rename = "totalSets")]
244    pub total_sets: Vec<usize>,
245
246    /// Drives per erasure set
247    #[serde(default, rename = "totalDrivesPerSet")]
248    pub drives_per_set: Vec<usize>,
249}
250
251/// Cluster usage statistics
252#[derive(Debug, Clone, Serialize, Deserialize, Default)]
253pub struct UsageInfo {
254    /// Total storage size in bytes
255    #[serde(default)]
256    pub size: u64,
257
258    /// Error message if any
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub error: Option<String>,
261}
262
263/// Bucket count information
264#[derive(Debug, Clone, Serialize, Deserialize, Default)]
265pub struct BucketsInfo {
266    /// Number of buckets
267    #[serde(default)]
268    pub count: u64,
269
270    /// Error message if any
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub error: Option<String>,
273}
274
275/// Object count information
276#[derive(Debug, Clone, Serialize, Deserialize, Default)]
277pub struct ObjectsInfo {
278    /// Number of objects
279    #[serde(default)]
280    pub count: u64,
281
282    /// Error message if any
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub error: Option<String>,
285}
286
287/// Pool erasure set metrics returned by cluster information.
288#[derive(Debug, Clone, Serialize, Deserialize, Default)]
289#[serde(rename_all = "camelCase")]
290pub struct PoolErasureSetInfo {
291    /// Erasure set ID within the pool.
292    #[serde(default)]
293    pub id: i32,
294
295    /// Raw used capacity in bytes.
296    #[serde(default, rename = "rawUsage")]
297    pub raw_usage: u64,
298
299    /// Raw total capacity in bytes.
300    #[serde(default, rename = "rawCapacity")]
301    pub raw_capacity: u64,
302
303    /// Object data usage in bytes.
304    #[serde(default)]
305    pub usage: u64,
306
307    /// Number of objects in the set.
308    #[serde(default, rename = "objectsCount")]
309    pub objects_count: u64,
310
311    /// Number of versions in the set.
312    #[serde(default, rename = "versionsCount")]
313    pub versions_count: u64,
314
315    /// Number of delete markers in the set.
316    #[serde(default, rename = "deleteMarkersCount")]
317    pub delete_markers_count: u64,
318
319    /// Number of healing disks in the set.
320    #[serde(default, rename = "healDisks")]
321    pub heal_disks: i32,
322}
323
324/// Complete cluster information response
325#[derive(Debug, Clone, Serialize, Deserialize, Default)]
326#[serde(rename_all = "camelCase")]
327pub struct ClusterInfo {
328    /// Deployment mode (distributed, standalone)
329    #[serde(default)]
330    pub mode: Option<String>,
331
332    /// Domain names
333    #[serde(default)]
334    pub domain: Option<Vec<String>>,
335
336    /// Region
337    #[serde(default)]
338    pub region: Option<String>,
339
340    /// Deployment ID
341    #[serde(default, rename = "deploymentID")]
342    pub deployment_id: Option<String>,
343
344    /// Bucket information
345    #[serde(default)]
346    pub buckets: Option<BucketsInfo>,
347
348    /// Object information
349    #[serde(default)]
350    pub objects: Option<ObjectsInfo>,
351
352    /// Storage usage
353    #[serde(default)]
354    pub usage: Option<UsageInfo>,
355
356    /// Backend information
357    #[serde(default)]
358    pub backend: Option<BackendInfo>,
359
360    /// Server information
361    #[serde(default)]
362    pub servers: Option<Vec<ServerInfo>>,
363
364    /// Pool metrics keyed by pool and erasure set index.
365    #[serde(default)]
366    pub pools: Option<BTreeMap<i32, BTreeMap<i32, PoolErasureSetInfo>>>,
367}
368
369impl ClusterInfo {
370    /// Get the total number of online disks across all servers
371    pub fn online_disks(&self) -> usize {
372        self.servers
373            .as_ref()
374            .map(|servers| {
375                servers
376                    .iter()
377                    .flat_map(|s| &s.disks)
378                    .filter(|d| d.state == "online" || d.state == "ok")
379                    .count()
380            })
381            .unwrap_or(0)
382    }
383
384    /// Get the total number of offline disks across all servers
385    pub fn offline_disks(&self) -> usize {
386        self.servers
387            .as_ref()
388            .map(|servers| {
389                servers
390                    .iter()
391                    .flat_map(|s| &s.disks)
392                    .filter(|d| d.state == "offline")
393                    .count()
394            })
395            .unwrap_or(0)
396    }
397
398    /// Get total storage capacity in bytes
399    pub fn total_capacity(&self) -> u64 {
400        self.servers
401            .as_ref()
402            .map(|servers| {
403                servers
404                    .iter()
405                    .flat_map(|s| &s.disks)
406                    .map(|d| d.total_space)
407                    .sum()
408            })
409            .unwrap_or(0)
410    }
411
412    /// Get used storage in bytes
413    pub fn used_capacity(&self) -> u64 {
414        self.servers
415            .as_ref()
416            .map(|servers| {
417                servers
418                    .iter()
419                    .flat_map(|s| &s.disks)
420                    .map(|d| d.used_space)
421                    .sum()
422            })
423            .unwrap_or(0)
424    }
425}
426
427/// Heal operation mode
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
429#[serde(rename_all = "lowercase")]
430pub enum HealScanMode {
431    /// Normal scan (default)
432    #[default]
433    Normal,
434    /// Deep scan (slower but more thorough)
435    Deep,
436}
437
438impl std::fmt::Display for HealScanMode {
439    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440        match self {
441            HealScanMode::Normal => write!(f, "normal"),
442            HealScanMode::Deep => write!(f, "deep"),
443        }
444    }
445}
446
447impl std::str::FromStr for HealScanMode {
448    type Err = String;
449
450    fn from_str(s: &str) -> Result<Self, Self::Err> {
451        match s.to_lowercase().as_str() {
452            "normal" => Ok(HealScanMode::Normal),
453            "deep" => Ok(HealScanMode::Deep),
454            _ => Err(format!("Invalid heal scan mode: {s}")),
455        }
456    }
457}
458
459#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
460#[serde(rename_all = "lowercase")]
461pub enum HealRuntimeState {
462    Disabled,
463    Uninitialized,
464    Idle,
465    Active,
466    #[serde(other)]
467    Unknown,
468}
469
470/// Request to start a heal operation
471#[derive(Debug, Clone, Serialize, Deserialize, Default)]
472#[serde(rename_all = "camelCase")]
473pub struct HealStartRequest {
474    /// Bucket to heal (empty for all buckets)
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub bucket: Option<String>,
477
478    /// Object prefix to heal
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub prefix: Option<String>,
481
482    /// Scan mode
483    #[serde(default)]
484    pub scan_mode: HealScanMode,
485
486    /// Whether to remove dangling objects
487    #[serde(default)]
488    pub remove: bool,
489
490    /// Whether to recreate missing data
491    #[serde(default)]
492    pub recreate: bool,
493
494    /// Dry run mode (don't actually heal)
495    #[serde(default)]
496    pub dry_run: bool,
497}
498
499/// Request to inspect or stop a token-scoped heal task
500#[derive(Debug, Clone, Serialize, Deserialize)]
501#[serde(rename_all = "camelCase")]
502pub struct HealTaskRequest {
503    /// Bucket being healed
504    pub bucket: String,
505
506    /// Object prefix being healed
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub prefix: Option<String>,
509
510    /// Client token returned by the heal start request
511    pub client_token: String,
512}
513
514/// Information about a single heal drive
515#[derive(Debug, Clone, Serialize, Deserialize, Default)]
516pub struct HealDriveInfo {
517    /// Drive UUID
518    #[serde(default)]
519    pub uuid: String,
520
521    /// Drive endpoint
522    #[serde(default)]
523    pub endpoint: String,
524
525    /// Drive state
526    #[serde(default)]
527    pub state: String,
528}
529
530/// Result of a heal operation on a single item
531#[derive(Debug, Clone, Serialize, Deserialize, Default)]
532#[serde(rename_all = "camelCase")]
533pub struct HealResultItem {
534    /// Result index
535    #[serde(default, rename = "resultId")]
536    pub result_index: usize,
537
538    /// Type of item healed (bucket, object, metadata)
539    #[serde(default, rename = "type")]
540    pub item_type: String,
541
542    /// Bucket name
543    #[serde(default)]
544    pub bucket: String,
545
546    /// Object key
547    #[serde(default)]
548    pub object: String,
549
550    /// Version ID
551    #[serde(default, rename = "versionId")]
552    pub version_id: String,
553
554    /// Detail message
555    #[serde(default)]
556    pub detail: String,
557
558    /// Number of parity blocks
559    #[serde(default, rename = "parityBlocks")]
560    pub parity_blocks: usize,
561
562    /// Number of data blocks
563    #[serde(default, rename = "dataBlocks")]
564    pub data_blocks: usize,
565
566    /// Object size
567    #[serde(default, rename = "objectSize")]
568    pub object_size: u64,
569
570    /// Drive info before healing
571    #[serde(default)]
572    pub before: HealDriveInfos,
573
574    /// Drive info after healing
575    #[serde(default)]
576    pub after: HealDriveInfos,
577}
578
579/// Collection of heal drive infos
580#[derive(Debug, Clone, Serialize, Deserialize, Default)]
581pub struct HealDriveInfos {
582    /// Drive information
583    #[serde(default)]
584    pub drives: Vec<HealDriveInfo>,
585}
586
587/// Status of a heal operation
588#[derive(Debug, Clone, Serialize, Deserialize, Default)]
589#[serde(rename_all = "camelCase")]
590pub struct HealStatus {
591    /// Heal ID
592    #[serde(default)]
593    pub heal_id: String,
594
595    /// Whether healing is in progress
596    #[serde(default)]
597    pub healing: bool,
598
599    #[serde(default, skip_serializing_if = "Option::is_none")]
600    pub state: Option<HealRuntimeState>,
601
602    /// Task summary for token-scoped manual heal status
603    #[serde(default, skip_serializing_if = "Option::is_none")]
604    pub summary: Option<String>,
605
606    /// Task detail for token-scoped manual heal status
607    #[serde(default, skip_serializing_if = "Option::is_none")]
608    pub detail: Option<String>,
609
610    /// Current bucket being healed
611    #[serde(default)]
612    pub bucket: String,
613
614    /// Current object being healed
615    #[serde(default)]
616    pub object: String,
617
618    /// Current scan mode reported by background healing
619    #[serde(default, skip_serializing_if = "Option::is_none")]
620    pub scan_mode: Option<HealScanMode>,
621
622    /// Background heal scan cycle
623    #[serde(default)]
624    pub scan_cycle: u64,
625
626    /// Number of queued heal tasks
627    #[serde(default)]
628    pub heal_queue_length: u64,
629
630    /// Number of active heal tasks
631    #[serde(default)]
632    pub heal_active_tasks: u64,
633
634    /// Number of items scanned
635    #[serde(default)]
636    pub items_scanned: u64,
637
638    /// Number of items healed
639    #[serde(default)]
640    pub items_healed: u64,
641
642    /// Number of items failed
643    #[serde(default)]
644    pub items_failed: u64,
645
646    /// Bytes scanned
647    #[serde(default)]
648    pub bytes_scanned: u64,
649
650    /// Bytes healed
651    #[serde(default)]
652    pub bytes_healed: u64,
653
654    /// Start time
655    #[serde(default)]
656    pub started: Option<String>,
657
658    /// Last update time
659    #[serde(default)]
660    pub last_update: Option<String>,
661}
662
663/// Request targeting a storage pool by command line or numeric ID.
664#[derive(Debug, Clone, Serialize, Deserialize, Default)]
665#[serde(rename_all = "camelCase")]
666pub struct PoolTarget {
667    /// Pool command line, or zero-based pool ID when `by_id` is true.
668    pub pool: String,
669
670    /// Interpret `pool` as a zero-based pool ID.
671    #[serde(default)]
672    pub by_id: bool,
673}
674
675/// Status of a server pool.
676#[derive(Debug, Clone, Serialize, Deserialize, Default)]
677pub struct PoolStatus {
678    /// Zero-based pool ID.
679    #[serde(default)]
680    pub id: usize,
681
682    /// Pool command line used by the server process.
683    #[serde(default, rename = "cmdline")]
684    pub cmd_line: String,
685
686    /// Last pool metadata update timestamp.
687    #[serde(default, rename = "lastUpdate")]
688    pub last_update: String,
689
690    /// Pool lifecycle status.
691    #[serde(default)]
692    pub status: String,
693
694    /// Decommission operation status for this pool.
695    #[serde(default, rename = "decommissionStatus")]
696    pub decommission_status: String,
697
698    /// Rebalance operation status for this pool.
699    #[serde(default, rename = "rebalanceStatus")]
700    pub rebalance_status: String,
701
702    /// Total pool size in bytes.
703    #[serde(default, rename = "totalSize")]
704    pub total_size: u64,
705
706    /// Current free size in bytes.
707    #[serde(default, rename = "currentSize")]
708    pub current_size: u64,
709
710    /// Used pool size in bytes.
711    #[serde(default, rename = "usedSize")]
712    pub used_size: u64,
713
714    /// Used capacity ratio in the range 0.0..=1.0.
715    #[serde(default)]
716    pub used: f64,
717
718    /// Decommission status and progress for this pool.
719    #[serde(default, rename = "decommissionInfo")]
720    pub decommission: Option<PoolDecommissionInfo>,
721}
722
723/// Decommission status response.
724#[derive(Debug, Clone, Serialize, Deserialize, Default)]
725pub struct DecommissionStatus {
726    /// Per-pool decommission status.
727    #[serde(default)]
728    pub pools: Vec<DecommissionPoolStatus>,
729}
730
731/// Decommission operation status for a single pool.
732#[derive(Debug, Clone, Serialize, Deserialize, Default)]
733pub struct DecommissionPoolStatus {
734    /// Zero-based pool ID.
735    #[serde(default)]
736    pub id: usize,
737
738    /// Pool command line used by the server process.
739    #[serde(default, rename = "cmdline")]
740    pub cmd_line: String,
741
742    /// Decommission operation status for this pool.
743    #[serde(default)]
744    pub status: String,
745
746    /// Pool lifecycle status.
747    #[serde(default, rename = "poolStatus")]
748    pub pool_status: String,
749
750    /// Decommission state and progress for this pool.
751    #[serde(default, rename = "decommissionInfo")]
752    pub decommission: Option<PoolDecommissionInfo>,
753}
754
755/// Decommission state and progress for a server pool.
756#[derive(Debug, Clone, Serialize, Deserialize, Default)]
757pub struct PoolDecommissionInfo {
758    /// Decommission start timestamp.
759    #[serde(default, rename = "startTime")]
760    pub start_time: Option<String>,
761
762    /// Free bytes when decommission started.
763    #[serde(default, rename = "startSize")]
764    pub start_size: u64,
765
766    /// Total pool size in bytes.
767    #[serde(default, rename = "totalSize")]
768    pub total_size: u64,
769
770    /// Current free size in bytes.
771    #[serde(default, rename = "currentSize")]
772    pub current_size: u64,
773
774    /// Whether decommission completed.
775    #[serde(default)]
776    pub complete: bool,
777
778    /// Whether decommission failed.
779    #[serde(default)]
780    pub failed: bool,
781
782    /// Whether decommission was canceled.
783    #[serde(default)]
784    pub canceled: bool,
785
786    /// Whether decommission is queued.
787    #[serde(default)]
788    pub queued: bool,
789
790    /// Buckets waiting to be decommissioned.
791    #[serde(default, rename = "queuedBuckets")]
792    pub queued_buckets: Vec<String>,
793
794    /// Buckets already decommissioned.
795    #[serde(default, rename = "decommissionedBuckets")]
796    pub decommissioned_buckets: Vec<String>,
797
798    /// Current bucket.
799    #[serde(default)]
800    pub bucket: String,
801
802    /// Current prefix.
803    #[serde(default)]
804    pub prefix: String,
805
806    /// Current object.
807    #[serde(default)]
808    pub object: String,
809
810    /// Current decommission stage.
811    #[serde(default)]
812    pub stage: String,
813
814    /// Number of successfully decommissioned objects.
815    #[serde(default, rename = "objectsDecommissioned")]
816    pub objects_decommissioned: u64,
817
818    /// Number of objects that failed to decommission.
819    #[serde(default, rename = "objectsDecommissionedFailed")]
820    pub objects_decommissioned_failed: u64,
821
822    /// Bytes successfully moved off the pool.
823    #[serde(default, rename = "bytesDecommissioned")]
824    pub bytes_decommissioned: u64,
825
826    /// Bytes that failed to move off the pool.
827    #[serde(default, rename = "bytesDecommissionedFailed")]
828    pub bytes_decommissioned_failed: u64,
829
830    /// Reason why decommission is waiting.
831    #[serde(default, rename = "waitingReason")]
832    pub waiting_reason: Option<String>,
833}
834
835/// Response from starting a rebalance operation.
836#[derive(Debug, Clone, Serialize, Deserialize, Default)]
837pub struct RebalanceStartResult {
838    /// Rebalance operation ID.
839    #[serde(default)]
840    pub id: String,
841}
842
843/// Cluster-wide rebalance status.
844#[derive(Debug, Clone, Serialize, Deserialize, Default)]
845pub struct RebalanceStatus {
846    /// Rebalance operation ID.
847    #[serde(default)]
848    pub id: String,
849
850    /// Per-pool rebalance status.
851    #[serde(default)]
852    pub pools: Vec<RebalancePoolStatus>,
853
854    /// Timestamp when rebalance was stopped.
855    #[serde(default, rename = "stoppedAt")]
856    pub stopped_at: Option<String>,
857}
858
859/// Rebalance status for a single pool.
860#[derive(Debug, Clone, Serialize, Deserialize, Default)]
861pub struct RebalancePoolStatus {
862    /// Zero-based pool ID.
863    #[serde(default)]
864    pub id: usize,
865
866    /// Rebalance status for this pool.
867    #[serde(default)]
868    pub status: String,
869
870    /// Used capacity ratio in the range 0.0..=1.0.
871    #[serde(default)]
872    pub used: f64,
873
874    /// Last rebalance error, if any.
875    #[serde(default, rename = "lastError")]
876    pub last_error: Option<String>,
877
878    /// Cleanup warnings observed after this pool finishes rebalance.
879    #[serde(default, rename = "cleanupWarnings")]
880    pub cleanup_warnings: RebalanceCleanupWarnings,
881
882    /// Rebalance progress, if this pool is active.
883    #[serde(default)]
884    pub progress: Option<RebalancePoolProgress>,
885}
886
887/// Cleanup warnings recorded for a rebalanced pool.
888#[derive(Debug, Clone, Serialize, Deserialize, Default)]
889pub struct RebalanceCleanupWarnings {
890    /// Number of cleanup warnings observed.
891    #[serde(default)]
892    pub count: u64,
893
894    /// Last cleanup warning message.
895    #[serde(default, rename = "lastMsg")]
896    pub last_message: Option<String>,
897
898    /// Bucket associated with the last cleanup warning.
899    #[serde(default, rename = "lastBucket")]
900    pub last_bucket: Option<String>,
901
902    /// Object associated with the last cleanup warning.
903    #[serde(default, rename = "lastObject")]
904    pub last_object: Option<String>,
905
906    /// Timestamp of the last cleanup warning.
907    #[serde(default, rename = "lastAt")]
908    pub last_at: Option<String>,
909}
910
911/// Rebalance progress for a single pool.
912#[derive(Debug, Clone, Serialize, Deserialize, Default)]
913pub struct RebalancePoolProgress {
914    /// Number of objects moved.
915    #[serde(default, rename = "objects")]
916    pub num_objects: u64,
917
918    /// Number of object versions moved.
919    #[serde(default, rename = "versions")]
920    pub num_versions: u64,
921
922    /// Number of bytes moved.
923    #[serde(default)]
924    pub bytes: u64,
925
926    /// Number of buckets remaining.
927    #[serde(default, rename = "remainingBuckets")]
928    pub remaining_buckets: usize,
929
930    /// Current bucket.
931    #[serde(default)]
932    pub bucket: String,
933
934    /// Current object.
935    #[serde(default)]
936    pub object: String,
937
938    /// Elapsed seconds.
939    #[serde(default)]
940    pub elapsed: u64,
941
942    /// Estimated seconds remaining.
943    #[serde(default)]
944    pub eta: u64,
945}
946
947#[cfg(test)]
948mod tests {
949    use super::*;
950
951    #[test]
952    fn test_backend_type_display() {
953        assert_eq!(BackendType::Fs.to_string(), "FS");
954        assert_eq!(BackendType::Erasure.to_string(), "Erasure");
955    }
956
957    #[test]
958    fn test_heal_scan_mode_display() {
959        assert_eq!(HealScanMode::Normal.to_string(), "normal");
960        assert_eq!(HealScanMode::Deep.to_string(), "deep");
961    }
962
963    #[test]
964    fn test_heal_scan_mode_from_str() {
965        assert_eq!(
966            "normal".parse::<HealScanMode>().unwrap(),
967            HealScanMode::Normal
968        );
969        assert_eq!("deep".parse::<HealScanMode>().unwrap(), HealScanMode::Deep);
970        assert!("invalid".parse::<HealScanMode>().is_err());
971    }
972
973    #[test]
974    fn test_cluster_info_default() {
975        let info = ClusterInfo::default();
976        assert!(info.mode.is_none());
977        assert!(info.servers.is_none());
978        assert_eq!(info.online_disks(), 0);
979        assert_eq!(info.offline_disks(), 0);
980    }
981
982    #[test]
983    fn test_cluster_info_disk_counts() {
984        let info = ClusterInfo {
985            servers: Some(vec![ServerInfo {
986                disks: vec![
987                    DiskInfo {
988                        state: "online".to_string(),
989                        ..Default::default()
990                    },
991                    DiskInfo {
992                        state: "online".to_string(),
993                        ..Default::default()
994                    },
995                    DiskInfo {
996                        state: "offline".to_string(),
997                        ..Default::default()
998                    },
999                ],
1000                ..Default::default()
1001            }]),
1002            ..Default::default()
1003        };
1004
1005        assert_eq!(info.online_disks(), 2);
1006        assert_eq!(info.offline_disks(), 1);
1007    }
1008
1009    #[test]
1010    fn test_cluster_info_capacity() {
1011        let info = ClusterInfo {
1012            servers: Some(vec![ServerInfo {
1013                disks: vec![
1014                    DiskInfo {
1015                        total_space: 1000,
1016                        used_space: 300,
1017                        ..Default::default()
1018                    },
1019                    DiskInfo {
1020                        total_space: 2000,
1021                        used_space: 500,
1022                        ..Default::default()
1023                    },
1024                ],
1025                ..Default::default()
1026            }]),
1027            ..Default::default()
1028        };
1029
1030        assert_eq!(info.total_capacity(), 3000);
1031        assert_eq!(info.used_capacity(), 800);
1032    }
1033
1034    #[test]
1035    fn test_disk_info_default() {
1036        let disk = DiskInfo::default();
1037        assert!(disk.endpoint.is_empty());
1038        assert!(!disk.healing);
1039        assert!(!disk.scanning);
1040        assert_eq!(disk.total_space, 0);
1041    }
1042
1043    #[test]
1044    fn test_disk_info_deserializes_snake_case_location_indexes() {
1045        let json = r#"{"pool_index":1,"set_index":2,"disk_index":3}"#;
1046
1047        let disk: DiskInfo = serde_json::from_str(json).unwrap();
1048
1049        assert_eq!(disk.pool_index, 1);
1050        assert_eq!(disk.set_index, 2);
1051        assert_eq!(disk.disk_index, 3);
1052    }
1053
1054    #[test]
1055    fn test_server_info_default() {
1056        let server = ServerInfo::default();
1057        assert!(server.state.is_empty());
1058        assert!(server.endpoint.is_empty());
1059        assert_eq!(server.uptime, 0);
1060    }
1061
1062    #[test]
1063    fn test_heal_start_request_default() {
1064        let req = HealStartRequest::default();
1065        assert!(req.bucket.is_none());
1066        assert!(req.prefix.is_none());
1067        assert_eq!(req.scan_mode, HealScanMode::Normal);
1068        assert!(!req.remove);
1069        assert!(!req.dry_run);
1070    }
1071
1072    #[test]
1073    fn test_heal_status_default() {
1074        let status = HealStatus::default();
1075        assert!(status.heal_id.is_empty());
1076        assert!(!status.healing);
1077        assert!(status.state.is_none());
1078        assert!(status.scan_mode.is_none());
1079        assert_eq!(status.scan_cycle, 0);
1080        assert_eq!(status.heal_queue_length, 0);
1081        assert_eq!(status.heal_active_tasks, 0);
1082        assert_eq!(status.items_scanned, 0);
1083    }
1084
1085    #[test]
1086    fn test_heal_runtime_state_unknown_value_is_preserved() {
1087        let state: HealRuntimeState = serde_json::from_str(r#""future""#).unwrap();
1088
1089        assert_eq!(state, HealRuntimeState::Unknown);
1090    }
1091
1092    #[test]
1093    fn test_pool_status_deserialization() {
1094        let json = r#"{"id":1,"cmdline":"/data/pool1/disk{1...4}","lastUpdate":"2026-05-06T00:00:00Z","status":"decommissioning","decommissionStatus":"running","rebalanceStatus":"none","totalSize":1000,"currentSize":600,"usedSize":400,"used":0.4,"decommissionInfo":{"startTime":"2026-05-06T00:00:01Z","startSize":100,"totalSize":1000,"currentSize":600,"complete":false,"failed":false,"canceled":false,"queued":true,"queuedBuckets":["bucket-a"],"decommissionedBuckets":["bucket-b"],"bucket":"bucket-a","prefix":"","object":"object.txt","stage":"migrate_object","objectsDecommissioned":2,"objectsDecommissionedFailed":1,"bytesDecommissioned":128,"bytesDecommissionedFailed":64,"waitingReason":"queued"}}"#;
1095
1096        let status: PoolStatus = serde_json::from_str(json).unwrap();
1097
1098        assert_eq!(status.id, 1);
1099        assert_eq!(status.cmd_line, "/data/pool1/disk{1...4}");
1100        assert_eq!(status.status, "decommissioning");
1101        assert_eq!(status.decommission_status, "running");
1102        assert_eq!(status.rebalance_status, "none");
1103        assert_eq!(status.used_size, 400);
1104        let info = status.decommission.expect("decommission info exists");
1105        assert!(info.queued);
1106        assert_eq!(info.queued_buckets, vec!["bucket-a"]);
1107        assert_eq!(info.bucket, "bucket-a");
1108        assert_eq!(info.object, "object.txt");
1109        assert_eq!(info.waiting_reason.as_deref(), Some("queued"));
1110        assert_eq!(info.objects_decommissioned, 2);
1111        assert_eq!(info.bytes_decommissioned_failed, 64);
1112    }
1113
1114    #[test]
1115    fn test_decommission_status_deserialization() {
1116        let json = r#"{"pools":[{"id":2,"cmdline":"/data/pool2/disk{1...4}","status":"failed","poolStatus":"blocked","decommissionInfo":{"failed":true,"totalSize":1000,"currentSize":900}}]}"#;
1117
1118        let status: DecommissionStatus = serde_json::from_str(json).unwrap();
1119
1120        assert_eq!(status.pools.len(), 1);
1121        assert_eq!(status.pools[0].id, 2);
1122        assert_eq!(status.pools[0].status, "failed");
1123        assert_eq!(status.pools[0].pool_status, "blocked");
1124        assert!(
1125            status.pools[0]
1126                .decommission
1127                .as_ref()
1128                .is_some_and(|info| info.failed)
1129        );
1130    }
1131
1132    #[test]
1133    fn test_rebalance_status_deserialization() {
1134        let json = r#"{"id":"rebalance-1","pools":[{"id":0,"status":"Started","used":0.5,"lastError":null,"cleanupWarnings":{"count":1,"lastMsg":"cleanup warning","lastBucket":"bucket","lastObject":"object","lastAt":"2026-06-12T00:00:00Z"},"progress":{"objects":3,"versions":4,"bytes":1024,"remainingBuckets":2,"bucket":"bucket","object":"object","elapsed":10,"eta":20}}],"stoppedAt":null}"#;
1135
1136        let status: RebalanceStatus = serde_json::from_str(json).unwrap();
1137
1138        assert_eq!(status.id, "rebalance-1");
1139        assert_eq!(status.pools.len(), 1);
1140        assert_eq!(status.pools[0].used, 0.5);
1141        assert_eq!(status.pools[0].cleanup_warnings.count, 1);
1142        assert_eq!(
1143            status.pools[0].cleanup_warnings.last_message.as_deref(),
1144            Some("cleanup warning")
1145        );
1146        let progress = status.pools[0]
1147            .progress
1148            .as_ref()
1149            .expect("progress should exist");
1150        assert_eq!(progress.num_objects, 3);
1151        assert_eq!(progress.remaining_buckets, 2);
1152    }
1153
1154    #[test]
1155    fn test_rebalance_status_defaults_cleanup_warnings() {
1156        let json = r#"{"id":"rebalance-1","pools":[{"id":0,"status":"Completed","used":0.5,"lastError":null,"progress":null}],"stoppedAt":null}"#;
1157
1158        let status: RebalanceStatus = serde_json::from_str(json).unwrap();
1159
1160        assert_eq!(status.pools[0].cleanup_warnings.count, 0);
1161        assert_eq!(status.pools[0].cleanup_warnings.last_message, None);
1162    }
1163
1164    #[test]
1165    fn test_serialization() {
1166        let info = ClusterInfo {
1167            mode: Some("distributed".to_string()),
1168            deployment_id: Some("test-123".to_string()),
1169            ..Default::default()
1170        };
1171
1172        let json = serde_json::to_string(&info).unwrap();
1173        assert!(json.contains("distributed"));
1174        assert!(json.contains("test-123"));
1175
1176        let deserialized: ClusterInfo = serde_json::from_str(&json).unwrap();
1177        assert_eq!(deserialized.mode, Some("distributed".to_string()));
1178    }
1179}