wedb_embed 0.1.0

Embedded Kvrocks-compatible storage engine for WeDb
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
use super::gorilla::{TSSample, gorilla_compress_samples, gorilla_decompress_samples};
use super::meta::{ChunkType, DuplicatePolicy};
use crate::error::{Error, Result};

/// TSChunk 头部元数据(8 字节:4 字节 Flag + 4 字节 Count,对标 Apache Kvrocks TSChunk::MetaData)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ChunkHeader {
    pub is_compressed: bool,
    pub count: u32,
}

impl ChunkHeader {
    pub const ENCODED_SIZE: usize = 8;

    #[inline]
    pub fn encode(&self) -> [u8; Self::ENCODED_SIZE] {
        let mut buf = [0u8; Self::ENCODED_SIZE];
        let flag = if self.is_compressed { 1u32 } else { 0u32 };
        buf[0..4].copy_from_slice(&flag.to_be_bytes());
        buf[4..8].copy_from_slice(&self.count.to_be_bytes());
        buf
    }

    #[inline]
    pub fn decode(bytes: &[u8]) -> Option<Self> {
        if bytes.len() < Self::ENCODED_SIZE {
            return None;
        }
        let mut b4 = [0u8; 4];
        b4.copy_from_slice(&bytes[0..4]);
        let flag = u32::from_be_bytes(b4);
        b4.copy_from_slice(&bytes[4..8]);
        let count = u32::from_be_bytes(b4);
        Some(Self {
            is_compressed: (flag & 1) != 0,
            count,
        })
    }
}

/// 样本合并统计结果
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MergeStats {
    pub inserted: usize,
    pub updated: usize,
    pub skipped: usize,
}

/// TSChunk 操作封装(支持 Uncompressed 及 Gorilla Compressed 切片与合并)
pub struct TSChunk;

impl TSChunk {
    /// 编码为未压缩块(Header + [TSSample (16B)] * count)
    #[inline]
    pub fn encode_uncompressed(samples: &[TSSample]) -> Vec<u8> {
        let header = ChunkHeader {
            is_compressed: false,
            count: samples.len() as u32,
        };
        let mut buf = Vec::with_capacity(ChunkHeader::ENCODED_SIZE + samples.len() * 16);
        buf.extend_from_slice(&header.encode());
        for s in samples {
            buf.extend_from_slice(&s.ts.to_be_bytes());
            buf.extend_from_slice(&s.v.to_be_bytes());
        }
        buf
    }

    /// 编码为 Gorilla 压缩块(Header + Gorilla Bitstream)
    #[inline]
    pub fn encode_compressed(samples: &[TSSample]) -> Vec<u8> {
        let compressed_payload = gorilla_compress_samples(samples);
        let header = ChunkHeader {
            is_compressed: true,
            count: samples.len() as u32,
        };
        let mut buf = Vec::with_capacity(ChunkHeader::ENCODED_SIZE + compressed_payload.len());
        buf.extend_from_slice(&header.encode());
        buf.extend_from_slice(&compressed_payload);
        buf
    }

    /// 根据 ChunkType 自动编码
    #[inline]
    pub fn encode_with_type(samples: &[TSSample], chunk_type: ChunkType) -> Vec<u8> {
        match chunk_type {
            ChunkType::Compressed => Self::encode_compressed(samples),
            ChunkType::Uncompressed => Self::encode_uncompressed(samples),
        }
    }

    /// 解码 Chunk 字节流为采样点向量
    pub fn decode_samples(chunk_data: &[u8]) -> Result<Vec<TSSample>> {
        if chunk_data.is_empty() {
            return Ok(Vec::new());
        }
        if chunk_data.len() < ChunkHeader::ENCODED_SIZE {
            if chunk_data.len() == 8 {
                let mut b = [0u8; 8];
                b.copy_from_slice(chunk_data);
                return Ok(vec![TSSample::new(0, f64::from_be_bytes(b))]);
            }
            return Err(Error::invalid_data(
                "ERR TSDB: TSChunk payload data too short",
            ));
        }

        let header = ChunkHeader::decode(chunk_data)
            .ok_or_else(|| Error::invalid_data("ERR TSDB: invalid TSChunk header"))?;

        if header.count == 0 {
            return Ok(Vec::new());
        }

        let payload = &chunk_data[ChunkHeader::ENCODED_SIZE..];

        if header.is_compressed {
            gorilla_decompress_samples(payload, header.count as usize)
        } else {
            let count = header.count as usize;
            if payload.len() < count * 16 {
                return Err(Error::invalid_data(
                    "ERR TSDB: uncompressed TSChunk payload too short",
                ));
            }
            let mut samples = Vec::with_capacity(count);
            for i in 0..count {
                let offset = i * 16;
                let mut b8 = [0u8; 8];
                b8.copy_from_slice(&payload[offset..offset + 8]);
                let ts = u64::from_be_bytes(b8);
                b8.copy_from_slice(&payload[offset + 8..offset + 16]);
                let v = f64::from_be_bytes(b8);
                samples.push(TSSample::new(ts, v));
            }
            Ok(samples)
        }
    }

    /// 提取 Chunk 首个时间戳(零全量解压轻量级提取)
    pub fn get_first_timestamp(chunk_data: &[u8]) -> Option<u64> {
        if chunk_data.len() < ChunkHeader::ENCODED_SIZE {
            return None;
        }
        let header = ChunkHeader::decode(chunk_data)?;
        if header.count == 0 {
            return None;
        }
        let payload = &chunk_data[ChunkHeader::ENCODED_SIZE..];
        if payload.len() >= 8 {
            let mut b8 = [0u8; 8];
            b8.copy_from_slice(&payload[0..8]);
            Some(u64::from_be_bytes(b8))
        } else {
            None
        }
    }

    /// 提取 Chunk 末尾时间戳
    pub fn get_last_timestamp(chunk_data: &[u8]) -> Option<u64> {
        let samples = Self::decode_samples(chunk_data).ok()?;
        samples.last().map(|s| s.ts)
    }

    /// 提取 Chunk 采样点总数
    #[inline]
    pub fn get_count(chunk_data: &[u8]) -> u32 {
        if chunk_data.len() < ChunkHeader::ENCODED_SIZE {
            return 0;
        }
        ChunkHeader::decode(chunk_data)
            .map(|h| h.count)
            .unwrap_or(0)
    }

    /// 合并新样本点并应用 DuplicatePolicy(若 Block 策略冲突则返回错误)
    pub fn merge_samples(
        existing: &mut Vec<TSSample>,
        new_samples: &[TSSample],
        policy: DuplicatePolicy,
    ) -> Result<MergeStats> {
        let mut stats = MergeStats::default();
        if new_samples.is_empty() {
            return Ok(stats);
        }

        // 单样本优化快路径
        if new_samples.len() == 1 {
            let new_s = new_samples[0];
            match existing.binary_search_by_key(&new_s.ts, |s| s.ts) {
                Ok(idx) => {
                    let old_v = existing[idx].v;
                    match policy {
                        DuplicatePolicy::Block => {
                            return Err(Error::invalid_data(
                                "ERR TSDB: Error at upsert, update is not supported when DUPLICATE_POLICY is set to BLOCK mode",
                            ));
                        }
                        DuplicatePolicy::First => {
                            stats.skipped += 1;
                        }
                        DuplicatePolicy::Last => {
                            if (existing[idx].v - new_s.v).abs() < f64::EPSILON {
                                stats.skipped += 1;
                            } else {
                                existing[idx].v = new_s.v;
                                stats.updated += 1;
                            }
                        }
                        DuplicatePolicy::Min => {
                            if new_s.v < old_v {
                                existing[idx].v = new_s.v;
                                stats.updated += 1;
                            } else {
                                stats.skipped += 1;
                            }
                        }
                        DuplicatePolicy::Max => {
                            if new_s.v > old_v {
                                existing[idx].v = new_s.v;
                                stats.updated += 1;
                            } else {
                                stats.skipped += 1;
                            }
                        }
                        DuplicatePolicy::Sum => {
                            if new_s.v == 0.0 {
                                stats.skipped += 1;
                            } else {
                                existing[idx].v = old_v + new_s.v;
                                stats.updated += 1;
                            }
                        }
                    }
                }
                Err(idx) => {
                    existing.insert(idx, new_s);
                    stats.inserted += 1;
                }
            }
            return Ok(stats);
        }

        // 多样本双指针归并
        let mut sorted_new = new_samples.to_vec();
        sorted_new.sort_by_key(|s| s.ts);

        let mut merged = Vec::with_capacity(existing.len() + sorted_new.len());
        let mut i = 0;
        let mut j = 0;

        while i < existing.len() && j < sorted_new.len() {
            let e = existing[i];
            let n = sorted_new[j];
            if e.ts < n.ts {
                merged.push(e);
                i += 1;
            } else if e.ts > n.ts {
                merged.push(n);
                stats.inserted += 1;
                j += 1;
            } else {
                let old_v = e.v;
                let final_v = match policy {
                    DuplicatePolicy::Block => {
                        return Err(Error::invalid_data(
                            "ERR TSDB: Error at upsert, update is not supported when DUPLICATE_POLICY is set to BLOCK mode",
                        ));
                    }
                    DuplicatePolicy::First => {
                        stats.skipped += 1;
                        old_v
                    }
                    DuplicatePolicy::Last => {
                        if (old_v - n.v).abs() < f64::EPSILON {
                            stats.skipped += 1;
                        } else {
                            stats.updated += 1;
                        }
                        n.v
                    }
                    DuplicatePolicy::Min => {
                        if n.v < old_v {
                            stats.updated += 1;
                            n.v
                        } else {
                            stats.skipped += 1;
                            old_v
                        }
                    }
                    DuplicatePolicy::Max => {
                        if n.v > old_v {
                            stats.updated += 1;
                            n.v
                        } else {
                            stats.skipped += 1;
                            old_v
                        }
                    }
                    DuplicatePolicy::Sum => {
                        if n.v == 0.0 {
                            stats.skipped += 1;
                        } else {
                            stats.updated += 1;
                        }
                        old_v + n.v
                    }
                };
                merged.push(TSSample::new(e.ts, final_v));
                i += 1;
                j += 1;
            }
        }

        while i < existing.len() {
            merged.push(existing[i]);
            i += 1;
        }

        while j < sorted_new.len() {
            merged.push(sorted_new[j]);
            stats.inserted += 1;
            j += 1;
        }

        *existing = merged;
        Ok(stats)
    }

    /// Upsert 并按 chunk_size 拆分(对标 Apache Kvrocks UpsertSampleAndSplit)
    pub fn upsert_and_split(
        existing_data: &[u8],
        new_samples: &[TSSample],
        policy: DuplicatePolicy,
        preferred_chunk_size: usize,
        chunk_type: ChunkType,
    ) -> Result<Vec<Vec<u8>>> {
        let mut samples = if existing_data.is_empty() {
            Vec::new()
        } else {
            Self::decode_samples(existing_data)?
        };

        Self::merge_samples(&mut samples, new_samples, policy)?;

        if samples.is_empty() {
            return Ok(Vec::new());
        }

        let chunk_size = preferred_chunk_size.max(1);
        let mut chunks = Vec::new();

        for chunk_slice in samples.chunks(chunk_size) {
            chunks.push(Self::encode_with_type(chunk_slice, chunk_type));
        }

        Ok(chunks)
    }

    /// 删除指定时间范围内的样本点 [from_ts, to_ts]
    pub fn remove_samples_between(
        chunk_data: &[u8],
        from_ts: u64,
        to_ts: u64,
        chunk_type: ChunkType,
    ) -> Result<(Vec<u8>, usize)> {
        if from_ts > to_ts || chunk_data.is_empty() {
            return Ok((chunk_data.to_vec(), 0));
        }
        let samples = Self::decode_samples(chunk_data)?;
        let orig_len = samples.len();
        let filtered: Vec<TSSample> = samples
            .into_iter()
            .filter(|s| s.ts < from_ts || s.ts > to_ts)
            .collect();
        let deleted = orig_len - filtered.len();
        if deleted == 0 {
            return Ok((chunk_data.to_vec(), 0));
        }
        let encoded = Self::encode_with_type(&filtered, chunk_type);
        Ok((encoded, deleted))
    }

    /// 更新指定时间戳的样本点数值
    pub fn update_sample_value(
        chunk_data: &[u8],
        ts: u64,
        value: f64,
        is_add_on: bool,
        chunk_type: ChunkType,
    ) -> Result<Option<Vec<u8>>> {
        let mut samples = Self::decode_samples(chunk_data)?;
        if let Ok(idx) = samples.binary_search_by_key(&ts, |s| s.ts) {
            if is_add_on {
                samples[idx].v += value;
            } else {
                samples[idx].v = value;
            }
            Ok(Some(Self::encode_with_type(&samples, chunk_type)))
        } else {
            Ok(None)
        }
    }
}