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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#![warn(missing_docs)]
//! A Framing and Message chucking implementation
//! defined in RFC4917<https://www.rfc-editor.org/rfc/rfc4975#page-9>
//! This chunking mechanism allows a sender to interrupt a chunk part of
//! the way through sending it.  The ability to interrupt messages allows
//! multiple sessions to share a TCP connection, and for large messages
//! to be sent efficiently while not blocking other messages that share
//! the same connection, or even the same MSRP session.

use bytes::Bytes;
use itertools::Itertools;
use serde::Deserialize;
use serde::Serialize;
use uuid::Uuid;

use crate::consts::DEFAULT_TTL_MS;
use crate::consts::MAX_TTL_MS;
use crate::consts::TS_OFFSET_TOLERANCE_MS;
use crate::error::Error;
use crate::error::Result;
use crate::utils::get_epoch_ms;

/// A data structure to presenting Chunks
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Chunk {
    /// chunk info, [position, total chunks]
    pub chunk: [usize; 2],
    /// bytes
    pub data: Bytes,
    /// meta data of chunk
    pub meta: ChunkMeta,
}

impl Chunk {
    /// check two chunks is belongs to same tx
    pub fn tx_eq(a: &Self, b: &Self) -> bool {
        a.meta.id == b.meta.id && a.chunk[1] == b.chunk[1]
    }

    /// serelize chunk to bytes
    pub fn to_bincode(&self) -> Result<Bytes> {
        bincode::serialize(self)
            .map(Bytes::from)
            .map_err(Error::BincodeSerialize)
    }

    /// deserialize bytes to chunk
    pub fn from_bincode(data: &[u8]) -> Result<Self> {
        bincode::deserialize(data).map_err(Error::BincodeDeserialize)
    }
}

impl PartialEq for Chunk {
    fn eq(&self, other: &Self) -> bool {
        Self::tx_eq(self, other)
    }
}

/// Meta data of a chunk
#[derive(Debug, Copy, Clone, Deserialize, Serialize)]
pub struct ChunkMeta {
    /// uuid of msg
    pub id: uuid::Uuid,
    /// Created time
    pub ts_ms: u128,
    /// Time to live
    pub ttl_ms: u64,
}

impl Default for ChunkMeta {
    fn default() -> Self {
        Self {
            id: uuid::Uuid::new_v4(),
            ts_ms: get_epoch_ms(),
            ttl_ms: DEFAULT_TTL_MS,
        }
    }
}

/// A helper for manage chunks and chunk pool
pub trait ChunkManager {
    /// list completed Chunks;
    fn list_completed(&self) -> Vec<Uuid>;
    /// list pending Chunks;
    fn list_pending(&self) -> Vec<Uuid>;
    /// get sepc msg via uuid
    /// if a msg is not completed, it will returns None
    fn get(&self, id: Uuid) -> Option<Bytes>;
    ///  remove all chunks of id
    fn remove(&mut self, id: Uuid);
    /// remove expired chunks by ttl
    fn remove_expired(&mut self);
    /// handle a chunk
    fn handle(&mut self, chunk: Chunk) -> Option<Bytes>;
}

/// List of Chunk, simply wrapped `Vec<Chunk>`
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ChunkList<const MTU: usize>(Vec<Chunk>);

impl<const MTU: usize> ChunkList<MTU> {
    /// ChunkList to Vec
    pub fn to_vec(&self) -> Vec<Chunk> {
        self.0.clone()
    }

    /// ChunkList to &Vec
    pub fn as_vec(&self) -> &Vec<Chunk> {
        &self.0
    }

    /// ChunkList to &mut Vec
    pub fn as_vec_mut(&mut self) -> &mut Vec<Chunk> {
        &mut self.0
    }

    /// dedup and sort elements in list
    pub fn formalize(&self) -> Self {
        let mut chunks = self.to_vec();
        // dedup same chunk id
        chunks.dedup_by_key(|c| c.chunk[0]);
        chunks.sort_by_key(|a| a.chunk[0]);
        Self::from(chunks)
    }

    /// search and formalize
    pub fn search(&self, id: Uuid) -> Self {
        let chunks: Vec<Chunk> = self
            .to_vec()
            .iter()
            .filter(|e| e.meta.id == id)
            .cloned()
            .collect();
        Self::from(chunks).formalize()
    }

    /// check list that is completed
    pub fn is_completed(&self) -> bool {
        let chunks = self.formalize().to_vec();
        // sample first ele, and chunk size is equal to length of grouped vec
        // we can call `unwrap` here because pre-condition is `lens() > 0 `
        !chunks.is_empty() && chunks.len() == chunks.first().unwrap().chunk[1]
    }

    /// if list is completed, withdraw data, or return None
    pub fn try_withdraw(&self) -> Option<Bytes> {
        if !self.is_completed() {
            None
        } else {
            let data = self.formalize().to_vec();
            let ret = data.into_iter().flat_map(|c| c.data).collect();
            Some(ret)
        }
    }
}

impl<const MTU: usize> Default for ChunkList<MTU> {
    fn default() -> Self {
        Self(vec![])
    }
}

impl<const MTU: usize> IntoIterator for &ChunkList<MTU> {
    type Item = Chunk;
    type IntoIter = std::vec::IntoIter<Chunk>;

    fn into_iter(self) -> Self::IntoIter {
        self.to_vec().into_iter()
    }
}

impl<const MTU: usize> IntoIterator for ChunkList<MTU> {
    type Item = Chunk;
    type IntoIter = std::vec::IntoIter<Chunk>;

    fn into_iter(self) -> Self::IntoIter {
        self.to_vec().into_iter()
    }
}

impl<const MTU: usize> From<&Bytes> for ChunkList<MTU> {
    fn from(bytes: &Bytes) -> Self {
        let chunks: Vec<Bytes> = bytes.chunks(MTU).map(|c| c.to_vec().into()).collect();
        let chunks_len: usize = chunks.len();
        let meta = ChunkMeta::default();
        Self(
            chunks
                .into_iter()
                .enumerate()
                .map(|(i, data)| Chunk {
                    meta,
                    chunk: [i, chunks_len],
                    data,
                })
                .collect::<Vec<Chunk>>(),
        )
    }
}

impl<const MTU: usize> From<ChunkList<MTU>> for Vec<Chunk> {
    fn from(l: ChunkList<MTU>) -> Self {
        l.to_vec()
    }
}

impl<const MTU: usize> From<Vec<Chunk>> for ChunkList<MTU> {
    fn from(data: Vec<Chunk>) -> Self {
        Self(data)
    }
}

impl<const MTU: usize> ChunkManager for ChunkList<MTU> {
    fn list_completed(&self) -> Vec<Uuid> {
        // group by msg uuid and chunk size
        self.into_iter()
            .group_by(|item| item.clone())
            .into_iter()
            .filter_map(|(c, g)| {
                if ChunkList::<MTU>::from(g.collect_vec()).is_completed() {
                    Some(c.meta.id)
                } else {
                    None
                }
            })
            .collect_vec()
    }

    fn list_pending(&self) -> Vec<Uuid> {
        self.into_iter()
            .group_by(|item| item.clone())
            .into_iter()
            .filter_map(|(c, g)| {
                if !ChunkList::<MTU>::from(g.collect_vec()).is_completed() {
                    Some(c.meta.id)
                } else {
                    None
                }
            })
            .collect_vec()
    }

    fn get(&self, id: Uuid) -> Option<Bytes> {
        self.search(id).try_withdraw()
    }

    fn remove(&mut self, id: Uuid) {
        self.as_vec_mut().retain(|e| e.meta.id != id)
    }

    fn remove_expired(&mut self) {
        let now = get_epoch_ms();
        self.as_vec_mut()
            .retain(|e| e.meta.ts_ms + e.meta.ttl_ms as u128 > now)
    }

    fn handle(&mut self, chunk: Chunk) -> Option<Bytes> {
        if chunk.meta.ttl_ms > MAX_TTL_MS {
            return None;
        }

        if chunk.meta.ts_ms - TS_OFFSET_TOLERANCE_MS > get_epoch_ms() {
            return None;
        }

        self.as_vec_mut().push(chunk.clone());
        self.remove_expired();

        let id = chunk.meta.id;
        let data = self.get(id)?;

        self.remove(id);
        Some(data)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_data_chunks() {
        let data = "helloworld".repeat(2).into();
        let ret: Vec<Chunk> = ChunkList::<32>::from(&data).into();
        assert_eq!(ret.len(), 1);
        assert_eq!(ret[ret.len() - 1].chunk, [0, 1]);

        let data = "helloworld".repeat(1024).into();
        let ret: Vec<Chunk> = ChunkList::<32>::from(&data).into();
        assert_eq!(ret.len(), 10 * 1024 / 32);
        assert_eq!(ret[ret.len() - 1].chunk, [319, 320]);
    }

    #[test]
    fn test_withdraw() {
        let data = "helloworld".repeat(1024).into();
        let ret: Vec<Chunk> = ChunkList::<32>::from(&data).into();
        let incomp = ret[0..30].to_vec();
        let cl = ChunkList::<32>::from(incomp);
        assert!(!cl.is_completed());
        let wd = ChunkList::<32>::from(ret).try_withdraw().unwrap();
        assert_eq!(wd, data);
    }

    #[test]
    fn test_query_complete() {
        let data1 = "hello".repeat(1024).into();
        let data2 = "world".repeat(256).into();
        let chunks1: Vec<Chunk> = ChunkList::<32>::from(&data1).into();
        let chunks2: Vec<Chunk> = ChunkList::<32>::from(&data2).into();

        let mut part = chunks1[2..5].to_vec();
        let mut fin = chunks2;
        fin.append(&mut part);

        let cl = ChunkList::<32>::from(fin);
        let comp = cl.list_completed();
        assert_eq!(comp.len(), 1);
        let id = comp[0];
        assert_eq!(cl.get(id).unwrap(), data2);
        let pend = cl.list_pending();
        assert_eq!(pend.len(), 1);
        assert_eq!(cl.get(pend[0]), None)
    }

    #[test]
    fn test_handle_chunk_save_or_withdraw() {
        let data1 = "hello".repeat(1024).into();
        let data2 = "world".repeat(256).into();
        let chunks1: Vec<Chunk> = ChunkList::<32>::from(&data1).into();
        let chunks2: Vec<Chunk> = ChunkList::<32>::from(&data2).into();

        let mut part = chunks1[2..5].to_vec();
        let mut fin = chunks2.clone();
        fin.append(&mut part);

        let mut cl = ChunkList::<32>::default();
        for c in fin {
            let ret = cl.handle(c);
            if let Some(data) = ret {
                assert_eq!(data, data2);
                assert_eq!(cl.to_vec().len(), 0);
            }
        }
        assert_eq!(cl.to_vec().len(), 3);

        let mut part = chunks1[2..5].to_vec();
        let mut fin = chunks2;
        part.append(&mut fin);

        let mut cl = ChunkList::<32>::default();
        for c in part {
            let ret = cl.handle(c);
            if let Some(data) = ret {
                assert_eq!(data, data2);
                assert_eq!(cl.to_vec().len(), 3);
            }
        }
        assert_eq!(cl.to_vec().len(), 3);
    }

    #[test]
    fn test_handle_chunk_remove_expired_chunks() {
        let mut cl = ChunkList::<32>::default();
        assert_eq!(cl.as_vec().len(), 0);

        let now = get_epoch_ms();
        let regular = Chunk {
            chunk: [0, 32],
            data: Bytes::new(),
            meta: ChunkMeta {
                id: Uuid::new_v4(),
                ts_ms: now,
                ttl_ms: DEFAULT_TTL_MS,
            },
        };
        let expired = Chunk {
            chunk: [0, 32],
            data: Bytes::new(),
            meta: ChunkMeta {
                id: Uuid::new_v4(),
                ts_ms: now - 1000,
                ttl_ms: 100,
            },
        };

        cl.handle(regular.clone());
        assert_eq!(cl.as_vec().len(), 1);

        cl.handle(regular.clone());
        assert_eq!(cl.as_vec().len(), 2);

        cl.handle(expired.clone());
        assert_eq!(cl.as_vec().len(), 2);

        cl.handle(expired.clone());
        assert_eq!(cl.as_vec().len(), 2);

        cl.handle(regular.clone());
        assert_eq!(cl.as_vec().len(), 3);

        cl.handle(regular.clone());
        assert_eq!(cl.as_vec().len(), 4);

        cl.handle(expired);
        assert_eq!(cl.as_vec().len(), 4);

        cl.handle(regular.clone());
        assert_eq!(cl.as_vec().len(), 5);

        cl.handle(regular);
        assert_eq!(cl.as_vec().len(), 6);
    }
}