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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use cyfs_base::*;

use async_trait::async_trait;
use int_enum::IntEnum;
use std::convert::TryFrom;
use std::str::FromStr;

#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, IntEnum)]
pub enum TrackerDirection {
    Unknown = 0,
    From = 1,
    To = 2,
    Store = 3,
}

impl Into<u8> for TrackerDirection {
    fn into(self) -> u8 {
        unsafe { std::mem::transmute(self as u8) }
    }
}

impl From<u8> for TrackerDirection {
    fn from(code: u8) -> Self {
        match TrackerDirection::from_int(code) {
            Ok(code) => code,
            Err(e) => {
                error!("unknown TrackerDirection code: {} {}", code, e);
                TrackerDirection::Unknown
            }
        }
    }
}

// path: [range_begin, range_end)
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct PostionFileRange {
    pub path: String,
    pub range_begin: u64,
    pub range_end: u64,
}

impl PostionFileRange {
    pub fn encode(&self) -> String {
        format!("{}:{}:{}", self.range_begin, self.range_end, self.path)
    }

    pub fn decode(value: &str) -> BuckyResult<Self> {
        let parts: Vec<&str> = value.split(':').collect();
        let range_begin = u64::from_str(parts[0]).map_err(|e| {
            let msg = format!("invalid range_begin string: {}, {}", parts[0], e);
            error!("{}", msg);
            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
        })?;

        let range_end = u64::from_str(parts[1]).map_err(|e| {
            let msg = format!("invalid range_end string: {}, {}", parts[0], e);
            error!("{}", msg);
            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
        })?;

        let path = parts[2..].join(":");
        Ok(Self {
            path,
            range_begin,
            range_end,
        })
    }
}

impl ToString for PostionFileRange {
    fn to_string(&self) -> String {
        self.encode()
    }
}

impl FromStr for PostionFileRange {
    type Err = BuckyError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        PostionFileRange::decode(value)
    }
}

#[derive(Debug, Eq, PartialEq, Clone)]
pub enum TrackerPostion {
    Unknown(String),
    Device(DeviceId),
    File(String),
    FileRange(PostionFileRange),
    ChunkManager,
}

impl Into<(u8, String)> for TrackerPostion {
    fn into(self) -> (u8, String) {
        match self {
            Self::Unknown(v) => (0, v),
            Self::Device(device_id) => (1, device_id.to_string()),
            Self::File(v) => (2, v),
            Self::FileRange(v) => (3, v.to_string()),
            TrackerPostion::ChunkManager => (4, "ChunkManager".to_string())
        }
    }
}

impl TryFrom<(u8, String)> for TrackerPostion {
    type Error = BuckyError;

    fn try_from((code, value): (u8, String)) -> Result<Self, Self::Error> {
        let ret = match code {
            0 => Self::Unknown(value),
            1 => {
                let device_id = DeviceId::from_str(&value).map_err(|e| {
                    let msg = format!("invalid device_id string: {}, {}", value, e);
                    error!("{}", msg);
                    BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
                })?;

                Self::Device(device_id)
            }
            2 => Self::File(value),
            3 => {
                let file_range = PostionFileRange::from_str(&value)?;
                Self::FileRange(file_range)
            }
            4 => {
                Self::ChunkManager
            }
            _ => {
                error!("unknown TrackerPostion code: {}", code);
                Self::Unknown(value)
            }
        };

        Ok(ret)
    }
}

pub struct AddTrackerPositonRequest {
    pub id: String,
    pub direction: TrackerDirection,
    pub pos: TrackerPostion,
    pub flags: u32,
}

pub struct RemoveTrackerPositionRequest {
    pub id: String,
    pub direction: Option<TrackerDirection>,
    pub pos: Option<TrackerPostion>,
}

pub struct GetTrackerPositionRequest {
    pub id: String,
    pub direction: Option<TrackerDirection>,
}

#[derive(Debug)]
pub struct TrackerPositionCacheData {
    pub direction: TrackerDirection,
    pub pos: TrackerPostion,
    pub insert_time: u64,
    pub flags: u32,
}

#[async_trait]
pub trait TrackerCache: Sync + Send + 'static {
    fn clone(&self) -> Box<dyn TrackerCache>;

    async fn add_position(&self, req: &AddTrackerPositonRequest) -> BuckyResult<()>;
    async fn remove_position(&self, req: &RemoveTrackerPositionRequest) -> BuckyResult<usize>;

    async fn get_position(
        &self,
        req: &GetTrackerPositionRequest,
    ) -> BuckyResult<Vec<TrackerPositionCacheData>>;
}

#[cfg(test)]
mod tests {
    use crate::*;
    use std::convert::TryFrom;
    use std::str::FromStr;

    #[test]
    fn test_file_range() {
        let item = PostionFileRange {
            path: "xxxxxx:xxxx".to_owned(),
            range_begin: 1000,
            range_end: 2000,
        };

        let value = item.to_string();
        println!("{}", value);

        let r_item = PostionFileRange::from_str(&value).unwrap();
        assert!(r_item.path == item.path);
        assert!(r_item.range_begin == item.range_begin);
        assert!(r_item.range_end == item.range_end);

        let r_item2 = r_item.clone();
        let pos = TrackerPostion::FileRange(r_item);
        let value: (u8, String) = pos.into();
        let r_pos = TrackerPostion::try_from(value).unwrap();
        if let TrackerPostion::FileRange(v) = r_pos {
            assert!(v == r_item2);
        } else {
            assert!(false);
        }
    }
}