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
#![warn(missing_docs)]
use std::str::FromStr;

use async_trait::async_trait;
use serde::Deserialize;
use serde::Serialize;

use super::chord::PeerRing;
use super::chord::PeerRingAction;
use super::chord::RemoteAction;
use super::types::Chord;
use super::types::SubRingManager;
use super::vnode::VNodeType;
use super::vnode::VirtualNode;
use super::FingerTable;
use crate::dht::Did;
use crate::ecc::HashStr;
use crate::err::Error;
use crate::err::Result;
use crate::storage::PersistenceStorageReadAndWrite;
// use crate::storage::PersistenceStorageOperation;

/// A SubRing is a full functional Ring.
/// But with a name and it's finger table can be
/// stored on Main Rings DHT, For a SubRing, it's virtual address is `sha1(name)`
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubRing {
    /// name of subring
    pub name: String,
    /// did of subring, generate with hash(name)
    pub did: Did,
    /// finger table
    pub finger: FingerTable,
    /// admin of ring, for verify that a message is come from ring
    pub admin: Option<Did>,
    /// creator
    pub creator: Did,
}

#[cfg_attr(feature = "wasm", async_trait(?Send))]
#[cfg_attr(not(feature = "wasm"), async_trait)]
impl SubRingManager<PeerRingAction> for PeerRing {
    async fn join_subring(&self, did: Did, rid: Did) -> Result<PeerRingAction> {
        match self.find_successor(rid) {
            Ok(PeerRingAction::Some(_)) => {
                if let Ok(subring) = self.get_subring(rid).await {
                    let mut sr = subring;
                    sr.finger.join(did);
                    self.store_subring(&sr).await?;
                }
                Ok(PeerRingAction::None)
            }
            Ok(PeerRingAction::RemoteAction(n, RemoteAction::FindSuccessor(_))) => Ok(
                PeerRingAction::RemoteAction(n, RemoteAction::FindAndJoinSubRing(rid)),
            ),
            Ok(a) => Err(Error::PeerRingUnexpectedAction(a)),
            Err(e) => Err(e),
        }
    }

    async fn get_subring(&self, rid: Did) -> Result<SubRing> {
        let vnode: VirtualNode = self.storage.get(&rid).await?;
        Ok(vnode.try_into()?)
    }

    async fn store_subring(&self, subring: &SubRing) -> Result<()> {
        let id = subring.did;
        let vn: VirtualNode = subring.clone().try_into()?;
        self.storage.put(&id, &vn).await?;
        Ok(())
    }

    async fn get_subring_by_name(&self, name: &str) -> Result<SubRing> {
        let address: HashStr = name.to_owned().into();
        // trans Result to Option here
        let did = Did::from_str(&address.inner())?;
        self.get_subring(did).await
    }
    // get subring, update and putback
    // async fn get_subring_for_update(
    //     &self,
    //     id: Did,
    //     callback: Arc<dyn FnOnce(SubRing) -> SubRing>,
    // ) -> Result<bool> {
    //     if let Ok(subring) = self.get_subring(id).await {
    //         let sr = callback(subring);
    //         self.store_subring(&sr).await?;
    //         Ok(true)
    //     } else {
    //         Ok(false)
    //     }
    // }

    // /// get subring, update and putback
    // async fn get_subring_for_update_by_name(
    //     &self,
    //     name: &str,
    //     callback: Box<dyn FnOnce(SubRing) -> SubRing>,
    // ) -> Result<bool> {
    //     let address: HashStr = name.to_owned().into();
    //     let did = Did::from_str(&address.inner())?;
    //     self.get_subring_for_update(&did, callback)
    // }
}

impl SubRing {
    /// Create a new SubRing
    pub fn new(name: &str, creator: Did) -> Result<Self> {
        let address: HashStr = name.to_owned().into();
        let did = Did::from_str(&address.inner())?;
        Ok(Self {
            name: name.to_owned(),
            did,
            finger: FingerTable::new(did, 1),
            admin: None,
            creator,
        })
    }

    /// Create a SubRing from Ring
    pub fn from_ring(name: &str, ring: &PeerRing) -> Result<Self> {
        let address: HashStr = name.to_owned().into();
        let did = Did::from_str(&address.inner())?;
        let finger = ring.lock_finger()?;
        Ok(Self {
            name: name.to_owned(),
            did,
            finger: (*finger).clone(),
            admin: None,
            creator: ring.did,
        })
    }
}

impl TryFrom<SubRing> for VirtualNode {
    type Error = Error;
    fn try_from(ring: SubRing) -> Result<Self> {
        let data = serde_json::to_string(&ring).map_err(|_| Error::SerializeToString)?;
        Ok(Self {
            did: ring.did,
            data: vec![data.into()],
            kind: VNodeType::SubRing,
        })
    }
}

impl TryFrom<VirtualNode> for SubRing {
    type Error = Error;
    fn try_from(vnode: VirtualNode) -> Result<Self> {
        match &vnode.kind {
            VNodeType::SubRing => {
                let decoded: String = vnode.data[0].decode()?;
                let subring: SubRing =
                    serde_json::from_str(&decoded).map_err(Error::Deserialize)?;
                Ok(subring)
            }
            _ => Err(Error::InvalidVNodeType),
        }
    }
}