snap_dataplane/
state.rs

1// Copyright 2025 Anapaya Systems
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//! SNAP data plane state.
15
16use std::{collections::BTreeMap, fmt};
17
18use anyhow::Context as _;
19use scion_proto::address::IsdAsn;
20use scion_sdk_address_manager::manager::AddressManager;
21use serde::{Deserialize, Serialize};
22use utoipa::ToSchema;
23
24use crate::dto::DataPlaneStateDto;
25
26/// The SNAP data plane state.
27#[derive(Debug, Default, PartialEq, Clone)]
28pub struct DataPlaneState {
29    /// The address registries (per ISD AS).
30    pub address_registries: BTreeMap<IsdAsn, AddressManager>,
31}
32
33impl From<&DataPlaneState> for DataPlaneStateDto {
34    fn from(value: &DataPlaneState) -> Self {
35        DataPlaneStateDto {
36            address_registries: value
37                .address_registries
38                .values()
39                .map(|registry| registry.into())
40                .collect(),
41        }
42    }
43}
44
45impl TryFrom<DataPlaneStateDto> for DataPlaneState {
46    type Error = anyhow::Error;
47
48    fn try_from(state: DataPlaneStateDto) -> Result<Self, Self::Error> {
49        let registries = state
50            .address_registries
51            .into_iter()
52            .map(|mngr| {
53                let addr_mngr: AddressManager = mngr
54                    .try_into()
55                    .context("Failed to convert manager to AddressManager")?;
56                Ok((addr_mngr.isd_asn(), addr_mngr))
57            })
58            .collect::<Result<BTreeMap<_, _>, Self::Error>>()?;
59
60        Ok(Self {
61            address_registries: registries,
62        })
63    }
64}
65
66/// Generic identifier trait.
67pub trait Id {
68    /// Creates an identifier from a `usize`.
69    fn from_usize(val: usize) -> Self;
70    /// Returns the identifier as a `usize`.
71    fn as_usize(&self) -> usize;
72}
73
74/// Data plane identifier.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ToSchema, Serialize, Deserialize)]
76#[serde(transparent)]
77pub struct DataPlaneId(usize);
78
79impl Id for DataPlaneId {
80    fn as_usize(&self) -> usize {
81        self.0
82    }
83
84    fn from_usize(val: usize) -> Self {
85        Self(val)
86    }
87}
88
89impl fmt::Display for DataPlaneId {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        write!(f, "{}", self.0)
92    }
93}