tsfile 0.0.2

Apache IoTDB TsFile written in Rust
Documentation
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use std::borrow::BorrowMut;
use std::convert::TryFrom;
use std::io::{Cursor, Read};
use std::sync::Arc;

use bit_set::BitSet;
use byteorder::{BigEndian, ReadBytesExt};
use snafu::ResultExt;
use varint::VarintRead;

use crate::file::metadata::MetadataIndexNodeType::{
    InternalDevice, InternalMeasurement, LeafDevice, LeafMeasurement,
};
use crate::file::metadata::TSDataType::Boolean;
use crate::file::metadata::TimeseriesMetadataType::{MoreChunks, OneChunk};
use crate::file::statistics;
use crate::file::statistics::*;
use crate::utils::cursor;
use crate::utils::cursor::VarIntReader;
use snafu::Snafu;

#[derive(Debug, Snafu)]
pub enum Error {
    #[snafu(display("Unable to read VarInt or string: {}", source))]
    ReadVarInt { source: cursor::Error },
    #[snafu(display("Unable to read cursor data: {}", source))]
    ReadCursorData { source: std::io::Error },
    #[snafu(display("Unable to parser {} type statistics: {}", s_type, source))]
    ParserStatistics {
        s_type: String,
        source: statistics::Error,
    },
}

type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Debug)]
pub struct TsFileMetadata {
    size: u64,
    file_meta: FileMeta,
}

impl TsFileMetadata {
    pub fn file_meta(&self) -> &FileMeta {
        &self.file_meta
    }
}

#[derive(Debug)]
pub struct FileMeta {
    metadata_index: Arc<MetadataIndexNodeType>,
    meta_offset: i64,
    bloom_filter: Option<BloomFilter>,
}

impl FileMeta {
    pub fn new(index: MetadataIndexNodeType, offset: i64, filter: Option<BloomFilter>) -> Self {
        FileMeta {
            metadata_index: Arc::new(index),
            meta_offset: offset,
            bloom_filter: filter,
        }
    }

    pub fn bloom_filter(&self) -> &Option<BloomFilter> {
        &self.bloom_filter
    }

    pub fn metadata_index(&self) -> &MetadataIndexNodeType {
        &self.metadata_index
    }
}

#[derive(Debug)]
pub struct BloomFilter {
    minimal_size: i32,
    maximal_hash_function_size: i32,
    seeds: Vec<u32>,
    size: u32,
    hash_function_size: u32,
    bits: BitSet,
    func: Vec<HashFunction>,
}

impl BloomFilter {
    pub fn contains(&self, path: &str) -> bool {
        if path.is_empty() {
            return false;
        }
        let mut ret = true;
        let mut index: usize = 0;
        while ret && index < self.hash_function_size as usize {
            ret = self.bits.contains(self.func[index].hash(path) as usize);
            index += 1;
        }
        ret
    }
}

#[derive(Debug)]
pub struct HashFunction {
    cap: u32,
    seed: u32,
}

impl HashFunction {
    pub fn hash(&self, path: &str) -> i32 {
        let hash_data = murmurhash3::murmurhash3_x64_128(path.as_bytes(), self.seed as u64);
        let data = hash_data.0 as i32 + hash_data.1 as i32;
        data % self.cap as i32
    }
}

#[derive(Debug)]
pub enum MetadataIndexNodeType {
    InternalDevice(MetaDataIndexNode),
    LeafDevice(MetaDataIndexNode),
    InternalMeasurement(MetaDataIndexNode),
    LeafMeasurement(MetaDataIndexNode),
}

impl Clone for MetadataIndexNodeType {
    fn clone(&self) -> Self {
        match self {
            InternalDevice(m) => InternalDevice(m.clone()),
            LeafDevice(m) => LeafDevice(m.clone()),
            InternalMeasurement(m) => InternalMeasurement(m.clone()),
            LeafMeasurement(m) => LeafMeasurement(m.clone()),
        }
    }
}

#[derive(Debug)]
pub struct MetaDataIndexNode {
    children: Vec<MetadataIndexEntry>,
    end_offset: i64,
}

impl MetaDataIndexNode {
    pub fn children(&self) -> &Vec<MetadataIndexEntry> {
        &self.children
    }

    pub fn end_offset(&self) -> i64 {
        self.end_offset
    }
}

impl Clone for MetaDataIndexNode {
    fn clone(&self) -> Self {
        let mut vec: Vec<MetadataIndexEntry> = Vec::with_capacity(self.children.len());
        Vec::clone_from(&mut vec, self.children());
        MetaDataIndexNode {
            children: vec,
            end_offset: self.end_offset,
        }
    }

    fn clone_from(&mut self, _source: &Self) {
        todo!()
    }
}

#[derive(Debug)]
pub struct MetadataIndexEntry {
    name: String,
    offset: i64,
}

impl MetadataIndexEntry {
    pub fn offset(&self) -> i64 {
        self.offset
    }
    pub fn name(&self) -> &str {
        self.name.as_str()
    }
}

impl Clone for MetadataIndexEntry {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            offset: self.offset,
        }
    }
}

#[derive(Debug)]
pub enum TimeseriesMetadataType {
    OneChunk,
    MoreChunks,
}

#[derive(Debug)]
pub struct TimeseriesMetadata {
    chunk_metadata_list: Vec<ChunkMetadata>,
    chunk_metadata_list_size: u32,
    measurement_id: String,
    data_type: TSDataType,
    metadata_type: TimeseriesMetadataType,
}

impl TimeseriesMetadata {
    pub fn chunk_metadata_list(self) -> Vec<ChunkMetadata> {
        self.chunk_metadata_list
    }
    pub fn measurement_id(&self) -> &str {
        self.measurement_id.as_str()
    }
}

impl TimeseriesMetadata {
    pub fn new(cursor: &mut Cursor<Vec<u8>>) -> Result<TimeseriesMetadata> {
        let meta_type = match cursor.read_u8().context(ReadCursorData)? {
            0 => TimeseriesMetadataType::OneChunk,
            _ => TimeseriesMetadataType::MoreChunks,
        };
        let measurement_id = cursor.read_varint_string().context(ReadVarInt)?;
        let data_type = TSDataType::new(cursor.read_u8().context(ReadCursorData)?);
        let chunk_metadata_list_size = cursor.read_unsigned_varint_32().context(ReadCursorData)?;

        let statistics = Arc::new(match data_type {
            Boolean => Statistic::Boolean(
                BooleanStatistics::try_from(cursor.borrow_mut()).context(ParserStatistics {
                    s_type: "Boolean".to_string(),
                })?,
            ),
            TSDataType::Int32 => Statistic::Int32(
                IntegerStatistics::try_from(cursor.borrow_mut()).context(ParserStatistics {
                    s_type: "Int32".to_string(),
                })?,
            ),
            TSDataType::Int64 => Statistic::Int64(
                LongStatistics::try_from(cursor.borrow_mut()).context(ParserStatistics {
                    s_type: "Int64".to_string(),
                })?,
            ),
            TSDataType::FLOAT => Statistic::FLOAT(
                FloatStatistics::try_from(cursor.borrow_mut()).context(ParserStatistics {
                    s_type: "FLOAT".to_string(),
                })?,
            ),
            TSDataType::DOUBLE => Statistic::DOUBLE(
                DoubleStatistics::try_from(cursor.borrow_mut()).context(ParserStatistics {
                    s_type: "DOUBLE".to_string(),
                })?,
            ),
            TSDataType::TEXT => Statistic::TEXT(
                BinaryStatistics::try_from(cursor.borrow_mut()).context(ParserStatistics {
                    s_type: "TEXT".to_string(),
                })?,
            ),
        });
        let end_pos = cursor.position() + chunk_metadata_list_size as u64;
        let mut chunk_metadata_list = Vec::new();
        while cursor.position() < end_pos {
            let offset_chunk_header = cursor.read_i64::<BigEndian>().context(ReadCursorData)?;

            let statistic = match meta_type {
                OneChunk => statistics.clone(),
                MoreChunks => Arc::new(match data_type {
                    Boolean => Statistic::Boolean(
                        BooleanStatistics::try_from(cursor.borrow_mut()).context(
                            ParserStatistics {
                                s_type: "Boolean".to_string(),
                            },
                        )?,
                    ),
                    TSDataType::Int32 => {
                        Statistic::Int32(IntegerStatistics::try_from(cursor.borrow_mut()).context(
                            ParserStatistics {
                                s_type: "Int32".to_string(),
                            },
                        )?)
                    }
                    TSDataType::Int64 => {
                        Statistic::Int64(LongStatistics::try_from(cursor.borrow_mut()).context(
                            ParserStatistics {
                                s_type: "Int64".to_string(),
                            },
                        )?)
                    }
                    TSDataType::FLOAT => {
                        Statistic::FLOAT(FloatStatistics::try_from(cursor.borrow_mut()).context(
                            ParserStatistics {
                                s_type: "FLOAT".to_string(),
                            },
                        )?)
                    }
                    TSDataType::DOUBLE => {
                        Statistic::DOUBLE(DoubleStatistics::try_from(cursor.borrow_mut()).context(
                            ParserStatistics {
                                s_type: "DOUBLE".to_string(),
                            },
                        )?)
                    }
                    TSDataType::TEXT => {
                        Statistic::TEXT(BinaryStatistics::try_from(cursor.borrow_mut()).context(
                            ParserStatistics {
                                s_type: "TEXT".to_string(),
                            },
                        )?)
                    }
                }),
            };
            chunk_metadata_list.push(ChunkMetadata::new(
                measurement_id.clone(),
                offset_chunk_header,
                data_type.clone(),
                statistic,
            ));
        }
        Ok(TimeseriesMetadata {
            measurement_id,
            data_type,
            metadata_type: meta_type,
            chunk_metadata_list_size,
            chunk_metadata_list,
        })
    }
}

#[derive(Debug)]
pub enum TSDataType {
    Boolean,
    Int32,
    Int64,
    FLOAT,
    DOUBLE,
    TEXT,
}

impl Clone for TSDataType {
    fn clone(&self) -> Self {
        match self {
            Boolean => Self::Boolean,
            TSDataType::Int32 => Self::Int32,
            TSDataType::Int64 => Self::Int64,
            TSDataType::FLOAT => Self::FLOAT,
            TSDataType::DOUBLE => Self::DOUBLE,
            TSDataType::TEXT => Self::TEXT,
        }
    }
}

impl TSDataType {
    pub fn new(id: u8) -> Self {
        match id {
            0 => Self::Boolean,
            1 => Self::Int32,
            2 => Self::Int64,
            3 => Self::FLOAT,
            4 => Self::DOUBLE,
            _ => Self::TEXT,
        }
    }
    // fn new(flag: u8, cursor: &mut Cursor<Vec<u8>>) -> Result<TSDataType> {
    //     match flag {
    //         0 => Ok(Self::Boolean(BooleanStatistics::try_from(cursor).unwrap())),
    //         1 => Ok(Self::Int32(IntegerStatistics::try_from(cursor).unwrap())),
    //         2 => Ok(Self::Int64(LongStatistics::try_from(cursor).unwrap())),
    //         3 => Ok(Self::FLOAT(FloatStatistics::try_from(cursor).unwrap())),
    //         4 => Ok(Self::DOUBLE(DoubleStatistics::try_from(cursor).unwrap())),
    //         5 => Ok(Self::TEXT(BinaryStatistics::try_from(cursor).unwrap())),
    //         _ => Err(TsFileError::General("123".to_string())),
    //     }
    // }

    fn int_id(&self) -> u8 {
        match self {
            Boolean => 0,
            TSDataType::Int32 => 1,
            TSDataType::Int64 => 2,
            TSDataType::FLOAT => 3,
            TSDataType::DOUBLE => 4,
            TSDataType::TEXT => 5,
        }
    }
}

#[derive(Debug)]
pub struct ChunkMetadata {
    measurement_uid: String,
    ts_data_type: TSDataType,
    offset_chunk_header: i64,
    statistic: Arc<Statistic>,
}

impl ChunkMetadata {
    fn new(
        measurement_uid: String,
        offset_chunk_header: i64,
        ts_data_type: TSDataType,
        statistic: Arc<Statistic>,
    ) -> Self {
        Self {
            measurement_uid,
            ts_data_type,
            offset_chunk_header,
            statistic,
        }
    }

    pub fn ts_data_type(&self) -> &TSDataType {
        &self.ts_data_type
    }

    pub fn offset_chunk_header(&self) -> i64 {
        self.offset_chunk_header
    }

    pub fn statistic(&self) -> Arc<Statistic> {
        self.statistic.clone()
    }
}

impl TsFileMetadata {
    pub fn parser(mut data: Cursor<Vec<u8>>) -> Result<Self> {
        // metadataIndex
        let metadata_index = MetadataIndexNodeType::new(&mut data).unwrap();
        // metaOffset
        let meta_offset = data.read_i64::<BigEndian>().context(ReadCursorData)?;

        // read bloom filter
        let mut bloom_filter = None;
        let length = data.get_ref().capacity();
        if data.position() < length as u64 {
            let bloom_filter_size = data.read_unsigned_varint_32().context(ReadCursorData)?;
            let mut bytes = vec![0; bloom_filter_size as usize];
            data.read_exact(&mut bytes).context(ReadCursorData)?;

            let filter_size = data.read_unsigned_varint_32().context(ReadCursorData)?;
            let hash_function_size = data.read_unsigned_varint_32().context(ReadCursorData)?;
            bloom_filter = Some(BloomFilter::new(bytes, filter_size, hash_function_size));
        }
        Ok(Self {
            size: 0,
            file_meta: FileMeta::new(metadata_index, meta_offset, bloom_filter),
        })
    }
}

impl BloomFilter {
    pub fn new(data: Vec<u8>, filter_size: u32, hash_function_size: u32) -> Self {
        let seeds = vec![5, 7, 11, 19, 31, 37, 43, 59];
        let hash_function_size = std::cmp::min(8, hash_function_size);

        let mut func: Vec<HashFunction> = Vec::with_capacity(hash_function_size as usize);
        for i in 0..hash_function_size {
            func.push(HashFunction::new(filter_size, seeds[i as usize]));
        }

        Self {
            size: filter_size,
            minimal_size: 256,
            maximal_hash_function_size: 8,
            seeds,
            hash_function_size,
            func,
            bits: BitSet::from_bytes(&data[8..]),
        }
    }
}

impl HashFunction {
    pub fn new(filter_size: u32, seed: u32) -> Self {
        Self {
            cap: filter_size,
            seed,
        }
    }
}

impl MetadataIndexNodeType {
    pub fn new(data: &mut Cursor<Vec<u8>>) -> Result<Self> {
        let len = data.read_unsigned_varint_32().context(ReadCursorData)?;
        let mut children: Vec<MetadataIndexEntry> = Vec::with_capacity(len as usize);
        for _i in 0..len {
            children.push(MetadataIndexEntry::new(data.borrow_mut()).unwrap());
        }

        let end_offset = data.read_i64::<BigEndian>().context(ReadCursorData)?;

        let mut vec = vec![255; 1];
        data.read_exact(&mut vec);

        let node = MetaDataIndexNode {
            children,
            end_offset,
        };
        match vec[0] {
            0 => Ok(InternalDevice(node)),
            1 => Ok(LeafDevice(node)),
            2 => Ok(InternalMeasurement(node)),
            _ => Ok(LeafMeasurement(node)),
        }
    }
}

impl MetadataIndexEntry {
    fn new(data: &mut Cursor<Vec<u8>>) -> Result<Self> {
        let name = data.read_varint_string().context(ReadVarInt)?;
        let offset = data.read_i64::<BigEndian>().context(ReadCursorData)?;
        Ok(Self { name, offset })
    }
}