Skip to main content

carbonfr_sdk/
enums.rs

1//! Petits enums de domaine **dupliqués** depuis le contrat HTTP `/v1`, comme
2//! [`crate::Region`] (ADR-0031 décision 5) — pas de dépendance à
3//! `carbonfr-core`. Valeurs sérialisées identiques aux slugs HTTP (query
4//! string et JSON), sans renommage : `#[serde(rename_all = "kebab-case")]`
5//! transforme un nom de variante `PascalCase` en son slug (`RteDirect` →
6//! `rte-direct`), vérifié par les tests `serde_matches_http_slug` en bas de
7//! fichier plutôt que supposé.
8//!
9//! **Exhaustifs** (ADR-0030 §3 : catalogue **fini par construction du
10//! domaine** — l'étendre serait un changement de méthodologie/modèle
11//! nécessitant un nouvel ADR, rien à protéger côté SemVer) : [`Methodology`],
12//! [`Estimator`], [`EligibilityFramework`], [`Interval`], [`FlowDirection`],
13//! [`ThresholdDirection`], [`WebhookStatus`], [`EligibilitySignalVerdict`].
14//!
15//! **Ouverts** : [`EligibilitySignalProvenance`] (`sdk-spec.json`
16//! `enums_to_duplicate.EligibilitySignalProvenance.open = true`) et
17//! [`IntensityIndex`] (index qualitatif, ADR-0033) — même doctrine que
18//! [`crate::Region`] : `#[non_exhaustive]` + variante `Other`
19//! ([`EligibilitySignalProvenance::Other`], [`IntensityIndex::Other`]), pour
20//! ne jamais faire échouer la désérialisation d'une réponse si le serveur
21//! ajoute une provenance ou une bande avant la prochaine version du SDK.
22
23use std::fmt;
24
25use serde::de::Error as _;
26use serde::{Deserialize, Deserializer, Serialize, Serializer};
27
28/// Méthodologie de calcul de l'intensité carbone (ADR-0005) : `rte-direct`
29/// (national, taux CO₂ publié directement) ou `acv-ademe` (cycle de vie,
30/// national + 12 régions). Catalogue **fini** : une nouvelle méthodologie est
31/// un changement de méthodologie, donc un nouvel ADR (`CONTRIBUTING.md`) —
32/// exhaustif, pas `#[non_exhaustive]` (ADR-0030 §3).
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "kebab-case")]
35pub enum Methodology {
36    RteDirect,
37    AcvAdeme,
38}
39
40impl Methodology {
41    pub fn as_str(&self) -> &'static str {
42        match self {
43            Methodology::RteDirect => "rte-direct",
44            Methodology::AcvAdeme => "acv-ademe",
45        }
46    }
47}
48
49impl fmt::Display for Methodology {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.write_str(self.as_str())
52    }
53}
54
55/// Estimateur d'intensité prévue (ADR-0009/0011) : `central` (estimation) ou
56/// `prudent` (borne haute de l'intervalle de confiance).
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
58#[serde(rename_all = "kebab-case")]
59pub enum Estimator {
60    Central,
61    Prudent,
62}
63
64impl Estimator {
65    pub fn as_str(&self) -> &'static str {
66        match self {
67            Estimator::Central => "central",
68            Estimator::Prudent => "prudent",
69        }
70    }
71}
72
73impl fmt::Display for Estimator {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.write_str(self.as_str())
76    }
77}
78
79/// Cadre d'éligibilité électrolyseur (ADR-0025/0026) : `rfnbo` (Règl. délégués
80/// UE 2023/1184-1185) ou `low-carbon` (Acte délégué UE 2025/2359). Deux
81/// piliers du droit européen tel qu'adopté ; une révision réglementaire
82/// (`rfnbo:2026-revision`, `planned`) reste une **version** du même cadre
83/// (`RulesetInfo::version`), pas un 3ᵉ cadre.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
85#[serde(rename_all = "kebab-case")]
86pub enum EligibilityFramework {
87    Rfnbo,
88    LowCarbon,
89}
90
91impl EligibilityFramework {
92    pub fn as_str(&self) -> &'static str {
93        match self {
94            EligibilityFramework::Rfnbo => "rfnbo",
95            EligibilityFramework::LowCarbon => "low-carbon",
96        }
97    }
98}
99
100impl fmt::Display for EligibilityFramework {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        f.write_str(self.as_str())
103    }
104}
105
106/// Pas d'agrégation d'une série (`GET /v1/intensity/stats?interval=`) :
107/// `hour` ou `day`.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
109#[serde(rename_all = "kebab-case")]
110pub enum Interval {
111    Hour,
112    Day,
113}
114
115impl Interval {
116    pub fn as_str(&self) -> &'static str {
117        match self {
118            Interval::Hour => "hour",
119            Interval::Day => "day",
120        }
121    }
122}
123
124impl fmt::Display for Interval {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        f.write_str(self.as_str())
127    }
128}
129
130/// Sens d'un flux transfrontalier (`ExchangeEntry`/`ExchangesResponse`,
131/// ADR-0017) — **champ de réponse uniquement**, jamais un paramètre de
132/// requête : `import` (`> 0`), `export` (`< 0`) ou `balanced`.
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
134#[serde(rename_all = "kebab-case")]
135pub enum FlowDirection {
136    Import,
137    Export,
138    Balanced,
139}
140
141impl FlowDirection {
142    pub fn as_str(&self) -> &'static str {
143        match self {
144            FlowDirection::Import => "import",
145            FlowDirection::Export => "export",
146            FlowDirection::Balanced => "balanced",
147        }
148    }
149}
150
151impl fmt::Display for FlowDirection {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.write_str(self.as_str())
154    }
155}
156
157/// Sens de franchissement d'un seuil (webhooks, ADR-0016) — paramètre de
158/// requête **et** champ de réponse (`CreateWebhookRequest`/`WebhookSummary`) :
159/// `below` ou `above`.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
161#[serde(rename_all = "kebab-case")]
162pub enum ThresholdDirection {
163    Below,
164    Above,
165}
166
167impl ThresholdDirection {
168    pub fn as_str(&self) -> &'static str {
169        match self {
170            ThresholdDirection::Below => "below",
171            ThresholdDirection::Above => "above",
172        }
173    }
174}
175
176impl fmt::Display for ThresholdDirection {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        f.write_str(self.as_str())
179    }
180}
181
182/// État d'un abonnement webhook (`WebhookSummary::status`, ADR-0016) :
183/// `active`, ou `disabled` (désactivé automatiquement après une série de
184/// livraisons échouées — le réactiver suppose de le supprimer puis le
185/// recréer, nouveau secret).
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
187#[serde(rename_all = "kebab-case")]
188pub enum WebhookStatus {
189    Active,
190    Disabled,
191}
192
193impl WebhookStatus {
194    pub fn as_str(&self) -> &'static str {
195        match self {
196            WebhookStatus::Active => "active",
197            WebhookStatus::Disabled => "disabled",
198        }
199    }
200}
201
202impl fmt::Display for WebhookStatus {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        f.write_str(self.as_str())
205    }
206}
207
208/// Verdict d'un signal d'éligibilité (`EligibilitySignalBody::verdict`,
209/// ADR-0025/0026) : `pass`, `fail` ou `indeterminate` (donnée manquante,
210/// jamais extrapolée).
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
212#[serde(rename_all = "kebab-case")]
213pub enum EligibilitySignalVerdict {
214    Pass,
215    Fail,
216    Indeterminate,
217}
218
219impl EligibilitySignalVerdict {
220    pub fn as_str(&self) -> &'static str {
221        match self {
222            EligibilitySignalVerdict::Pass => "pass",
223            EligibilitySignalVerdict::Fail => "fail",
224            EligibilitySignalVerdict::Indeterminate => "indeterminate",
225        }
226    }
227}
228
229impl fmt::Display for EligibilitySignalVerdict {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        f.write_str(self.as_str())
232    }
233}
234
235/// Provenance de la valeur d'un signal d'éligibilité
236/// (`EligibilitySignalBody::provenance`, absente sur un signal
237/// `indeterminate`) : `observed` (donnée mesurée/publiée) ou `forecast`
238/// (prévision, `share-clim@1`). **Ouverte** (`#[non_exhaustive]` +
239/// [`EligibilitySignalProvenance::Other`], comme [`crate::Region`]) :
240/// `sdk-spec.json` la marque `open: true`, contrairement aux autres enums de
241/// ce fichier.
242#[derive(Debug, Clone, PartialEq, Eq, Hash)]
243#[non_exhaustive]
244pub enum EligibilitySignalProvenance {
245    Observed,
246    Forecast,
247    /// Valeur non reconnue par cette version du SDK — transmise telle quelle.
248    Other(String),
249}
250
251impl EligibilitySignalProvenance {
252    pub fn as_str(&self) -> &str {
253        match self {
254            EligibilitySignalProvenance::Observed => "observed",
255            EligibilitySignalProvenance::Forecast => "forecast",
256            EligibilitySignalProvenance::Other(s) => s.as_str(),
257        }
258    }
259}
260
261impl fmt::Display for EligibilitySignalProvenance {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.write_str(self.as_str())
264    }
265}
266
267impl From<&str> for EligibilitySignalProvenance {
268    fn from(value: &str) -> Self {
269        match value {
270            "observed" => EligibilitySignalProvenance::Observed,
271            "forecast" => EligibilitySignalProvenance::Forecast,
272            other => EligibilitySignalProvenance::Other(other.to_string()),
273        }
274    }
275}
276
277impl Serialize for EligibilitySignalProvenance {
278    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
279        serializer.serialize_str(self.as_str())
280    }
281}
282
283impl<'de> Deserialize<'de> for EligibilitySignalProvenance {
284    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
285        let value = String::deserialize(deserializer).map_err(D::Error::custom)?;
286        Ok(EligibilitySignalProvenance::from(value.as_str()))
287    }
288}
289
290/// Index qualitatif d'une intensité carbone (ADR-0033, barème `index@1`) :
291/// cinq bandes **absolues** en gCO₂eq/kWh, séparées par les bornes
292/// 20 · 64,8 · 100 · 200 — **basses incluses, hautes exclues** (`[a, b[` :
293/// 20 g est `low`, 19,9 g est `very-low`). Un seul barème pour toutes les
294/// méthodologies et toutes les régions ; le catalogue des bornes et de leurs
295/// sources est servi par `GET /v1/intensity/index`
296/// ([`CarbonFr::intensity_index`](crate::CarbonFr::intensity_index)).
297///
298/// Porté par le champ `index` de [`IntensityResponse`](crate::IntensityResponse),
299/// de [`HistoryPoint`](crate::HistoryPoint), de
300/// [`ForecastPointBody`](crate::ForecastPointBody) (calculé sur `expected`) et
301/// de chaque événement du flux SSE (`IntensityEvent`, feature `stream`) :
302/// `Some` face à un serveur ≥ 0.11, `None` face à un serveur plus ancien.
303///
304/// **Ouvert** : `#[non_exhaustive]` **et** variante [`IntensityIndex::Other`],
305/// comme [`crate::Region`] — une bande ajoutée un jour par le serveur
306/// (nouveau barème `index@2`, donc nouvel ADR) arrive en `Other(libellé)` au
307/// lieu de faire échouer la désérialisation de la réponse entière (doctrine
308/// d'ADR-0031 décision 5). Pas d'`Ord` : la variante `Other` n'a pas de rang
309/// connu ; pour ordonner des bandes, lire `min`/`max` du catalogue
310/// ([`IndexBand`](crate::IndexBand)).
311#[derive(Debug, Clone, PartialEq, Eq, Hash)]
312#[non_exhaustive]
313pub enum IntensityIndex {
314    /// `< 20` gCO₂eq/kWh.
315    VeryLow,
316    /// `20 ≤ x < 64,8` gCO₂eq/kWh — sous le seuil RFNBO de 18 gCO₂eq/MJ.
317    Low,
318    /// `64,8 ≤ x < 100` gCO₂eq/kWh — sous le seuil de la taxonomie européenne.
319    Moderate,
320    /// `100 ≤ x < 200` gCO₂eq/kWh.
321    High,
322    /// `≥ 200` gCO₂eq/kWh.
323    VeryHigh,
324    /// Libellé de bande non reconnu par cette version du SDK — transmis tel
325    /// quel.
326    Other(String),
327}
328
329impl IntensityIndex {
330    /// Libellé HTTP, identique à la valeur servie dans le champ `index` :
331    /// `very-low`, `low`, `moderate`, `high` ou `very-high` ; pour
332    /// [`IntensityIndex::Other`], le libellé tel que reçu.
333    pub fn as_str(&self) -> &str {
334        match self {
335            IntensityIndex::VeryLow => "very-low",
336            IntensityIndex::Low => "low",
337            IntensityIndex::Moderate => "moderate",
338            IntensityIndex::High => "high",
339            IntensityIndex::VeryHigh => "very-high",
340            IntensityIndex::Other(label) => label.as_str(),
341        }
342    }
343}
344
345impl fmt::Display for IntensityIndex {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        f.write_str(self.as_str())
348    }
349}
350
351impl From<&str> for IntensityIndex {
352    fn from(label: &str) -> Self {
353        match label {
354            "very-low" => IntensityIndex::VeryLow,
355            "low" => IntensityIndex::Low,
356            "moderate" => IntensityIndex::Moderate,
357            "high" => IntensityIndex::High,
358            "very-high" => IntensityIndex::VeryHigh,
359            other => IntensityIndex::Other(other.to_string()),
360        }
361    }
362}
363
364impl From<String> for IntensityIndex {
365    fn from(label: String) -> Self {
366        IntensityIndex::from(label.as_str())
367    }
368}
369
370/// Sérialisé comme le libellé HTTP (`as_str`), comme [`crate::Region`].
371impl Serialize for IntensityIndex {
372    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
373        serializer.serialize_str(self.as_str())
374    }
375}
376
377/// Désérialisé depuis n'importe quel libellé (`From<String>` : un libellé
378/// inconnu devient [`IntensityIndex::Other`], jamais une erreur — cf. la doc
379/// du type), comme [`crate::Region`].
380impl<'de> Deserialize<'de> for IntensityIndex {
381    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
382        let label = String::deserialize(deserializer).map_err(D::Error::custom)?;
383        Ok(IntensityIndex::from(label))
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    /// Garde-fou : la conversion `#[serde(rename_all = "kebab-case")]`
392    /// produit bien le même slug que `as_str()` (et donc que la query string
393    /// HTTP construite avec `as_str()`, cf. `crate::methods`) — les deux
394    /// chemins ne doivent jamais diverger.
395    macro_rules! assert_serde_matches_as_str {
396        ($($value:expr),+ $(,)?) => {
397            $(
398                let value = $value;
399                let json = serde_json::to_string(&value).expect("sérialisation");
400                assert_eq!(json, format!("\"{}\"", value.as_str()));
401                let back = serde_json::from_str(&json).expect("désérialisation");
402                assert_eq!(value, back);
403            )+
404        };
405    }
406
407    #[test]
408    fn serde_matches_http_slug() {
409        assert_serde_matches_as_str!(Methodology::RteDirect, Methodology::AcvAdeme);
410        assert_serde_matches_as_str!(Estimator::Central, Estimator::Prudent);
411        assert_serde_matches_as_str!(EligibilityFramework::Rfnbo, EligibilityFramework::LowCarbon);
412        assert_serde_matches_as_str!(Interval::Hour, Interval::Day);
413        assert_serde_matches_as_str!(
414            FlowDirection::Import,
415            FlowDirection::Export,
416            FlowDirection::Balanced
417        );
418        assert_serde_matches_as_str!(ThresholdDirection::Below, ThresholdDirection::Above);
419        assert_serde_matches_as_str!(WebhookStatus::Active, WebhookStatus::Disabled);
420        assert_serde_matches_as_str!(
421            EligibilitySignalVerdict::Pass,
422            EligibilitySignalVerdict::Fail,
423            EligibilitySignalVerdict::Indeterminate
424        );
425    }
426
427    #[test]
428    fn eligibility_signal_provenance_round_trips_known_and_unknown() {
429        for slug in ["observed", "forecast", "measured-2027"] {
430            let value = EligibilitySignalProvenance::from(slug);
431            let json = serde_json::to_string(&value).expect("sérialisation");
432            assert_eq!(json, format!("\"{slug}\""));
433            let back: EligibilitySignalProvenance =
434                serde_json::from_str(&json).expect("désérialisation");
435            assert_eq!(back, value);
436        }
437        assert!(matches!(
438            EligibilitySignalProvenance::from("measured-2027"),
439            EligibilitySignalProvenance::Other(_)
440        ));
441    }
442
443    #[test]
444    fn intensity_index_round_trips_known_slugs() {
445        for (slug, expected) in [
446            ("very-low", IntensityIndex::VeryLow),
447            ("low", IntensityIndex::Low),
448            ("moderate", IntensityIndex::Moderate),
449            ("high", IntensityIndex::High),
450            ("very-high", IntensityIndex::VeryHigh),
451        ] {
452            let index = IntensityIndex::from(slug);
453            assert_eq!(index, expected);
454            assert_eq!(index.as_str(), slug);
455            assert_eq!(index.to_string(), slug);
456            assert_eq!(IntensityIndex::from(slug.to_string()), expected);
457        }
458    }
459
460    #[test]
461    fn intensity_index_unknown_slug_stays_open() {
462        let index = IntensityIndex::from("nouvelle-bande");
463        assert_eq!(index.as_str(), "nouvelle-bande");
464        assert_eq!(index.to_string(), "nouvelle-bande");
465        assert!(matches!(index, IntensityIndex::Other(_)));
466        assert!(matches!(
467            IntensityIndex::from("nouvelle-bande".to_string()),
468            IntensityIndex::Other(_)
469        ));
470    }
471
472    #[test]
473    fn intensity_index_serde_round_trips_known_and_unknown_slugs() {
474        for slug in ["very-low", "low", "moderate", "high", "very-high"] {
475            let index = IntensityIndex::from(slug);
476            assert!(!matches!(index, IntensityIndex::Other(_)), "{slug}");
477            let json = serde_json::to_string(&index).expect("sérialisation");
478            assert_eq!(json, format!("\"{slug}\""));
479            let back: IntensityIndex = serde_json::from_str(&json).expect("désérialisation");
480            assert_eq!(back, index);
481        }
482
483        // Un libellé inconnu se désérialise en `Other` (jamais d'erreur) et
484        // se réserialise à l'identique.
485        let unknown: IntensityIndex =
486            serde_json::from_str("\"nouvelle-bande\"").expect("libellé inconnu toléré");
487        assert_eq!(unknown, IntensityIndex::Other("nouvelle-bande".to_string()));
488        let json = serde_json::to_string(&unknown).expect("sérialisation");
489        assert_eq!(json, "\"nouvelle-bande\"");
490        let back: IntensityIndex = serde_json::from_str(&json).expect("désérialisation");
491        assert_eq!(back, unknown);
492    }
493}