Skip to main content

rustfs_storage_api/
capability.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16
17use serde::{Deserialize, Serialize};
18
19#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum CapabilityState {
22    Supported,
23    Unsupported,
24    Disabled,
25    #[serde(other)]
26    #[default]
27    Unknown,
28}
29
30impl CapabilityState {
31    pub const fn is_supported(self) -> bool {
32        matches!(self, Self::Supported)
33    }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct CapabilityStatus {
39    pub state: CapabilityState,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub reason: Option<String>,
42}
43
44impl CapabilityStatus {
45    pub const fn new(state: CapabilityState) -> Self {
46        Self { state, reason: None }
47    }
48
49    pub const fn supported() -> Self {
50        Self::new(CapabilityState::Supported)
51    }
52
53    pub const fn unsupported() -> Self {
54        Self::new(CapabilityState::Unsupported)
55    }
56
57    pub const fn disabled() -> Self {
58        Self::new(CapabilityState::Disabled)
59    }
60
61    pub const fn unknown() -> Self {
62        Self::new(CapabilityState::Unknown)
63    }
64
65    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
66        self.reason = Some(reason.into());
67        self
68    }
69}
70
71impl Default for CapabilityStatus {
72    fn default() -> Self {
73        Self::unknown()
74    }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum CapabilitySnapshotError {
79    Unavailable,
80    Unsupported,
81    InvalidSnapshot(String),
82}
83
84impl fmt::Display for CapabilitySnapshotError {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::Unavailable => f.write_str("capability snapshot unavailable"),
88            Self::Unsupported => f.write_str("capability snapshot unsupported"),
89            Self::InvalidSnapshot(reason) => write!(f, "invalid capability snapshot: {reason}"),
90        }
91    }
92}
93
94impl std::error::Error for CapabilitySnapshotError {}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use serde_json::Value;
100
101    fn sorted_json_value(value: Value) -> Value {
102        match value {
103            Value::Array(values) => Value::Array(values.into_iter().map(sorted_json_value).collect()),
104            Value::Object(object) => {
105                let mut entries: Vec<_> = object.into_iter().collect();
106                entries.sort_by(|(left, _), (right, _)| left.cmp(right));
107
108                Value::Object(
109                    entries
110                        .into_iter()
111                        .map(|(key, value)| (key, sorted_json_value(value)))
112                        .collect(),
113                )
114            }
115            value => value,
116        }
117    }
118
119    #[test]
120    fn capability_status_serializes_unknown_and_unsupported_states() {
121        let unknown = CapabilityStatus::unknown();
122        let unsupported = CapabilityStatus::unsupported().with_reason("target does not expose profiler");
123
124        let encoded = serde_json::to_string(&(&unknown, &unsupported)).expect("serialize capability statuses");
125        insta::assert_json_snapshot!(
126            "capability_status_contract",
127            sorted_json_value(serde_json::to_value((&unknown, &unsupported)).expect("capability statuses should serialize"))
128        );
129        let decoded: (CapabilityStatus, CapabilityStatus) =
130            serde_json::from_str(&encoded).expect("deserialize capability statuses");
131
132        assert_eq!(decoded.0.state, CapabilityState::Unknown);
133        assert_eq!(decoded.1.state, CapabilityState::Unsupported);
134        assert_eq!(decoded.1.reason.as_deref(), Some("target does not expose profiler"));
135        assert!(!decoded.1.state.is_supported());
136    }
137
138    #[test]
139    fn future_capability_state_deserializes_as_unknown() {
140        let status: CapabilityStatus = serde_json::from_str(r#"{"state":"future_state"}"#)
141            .expect("future capability states should preserve conservative compatibility");
142
143        assert_eq!(status.state, CapabilityState::Unknown);
144    }
145}