wedb_embed 0.1.5

Embedded database engine providing Redis-like APIs, built on fjall / 嵌入式数据库引擎,提供类似 Redis 的接口,底层基于 fjall 开发
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use std::ptr::read_unaligned;

use super::{
  gorilla::{TSSample, compress_timestamps, decompress_last_timestamp, decompress_timestamps_into},
  meta::{ChunkType, DuplicatePolicy},
};
use crate::error::{Error, Result};

/// TSChunk header metadata (8 bytes: 4-byte flag + 4-byte count).
/// TSChunk 头部元数据(8 字节:4 字节 is_compressed + 4 字节 count)
#[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> {
    let chunk = bytes.first_chunk::<8>()?;
    let flag = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
    let count = u32::from_be_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]);
    Some(Self {
      is_compressed: flag != 0,
      count,
    })
  }
}

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

/// Operation definition.
/// TSChunk 操作封装(支持 Uncompressed 原始块与 FastALP 列式压缩块)
pub struct TSChunk;

impl TSChunk {
  /// Encodes data into binary format.
  /// 编码为未压缩块(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
  }

  /// Encodes data into binary format.
  /// 编码为 FastALP 列式压缩块(Header + [ts_len: u32] + [compressed_ts] + [compressed_values_fastalp])
  #[inline]
  pub fn encode_compressed(samples: &[TSSample]) -> Vec<u8> {
    if samples.is_empty() {
      return Self::encode_uncompressed(samples);
    }
    let count = samples.len() as u32;
    let mut timestamps = Vec::with_capacity(samples.len());
    let mut values = Vec::with_capacity(samples.len());
    for s in samples {
      timestamps.push(s.ts);
      values.push(s.v);
    }

    let ts_payload = compress_timestamps(&timestamps);
    let header = ChunkHeader {
      is_compressed: true,
      count,
    };
    let mut buf =
      Vec::with_capacity(ChunkHeader::ENCODED_SIZE + 4 + ts_payload.len() + values.len() * 2 + 16);
    buf.extend_from_slice(&header.encode());
    buf.extend_from_slice(&(ts_payload.len() as u32).to_be_bytes());
    buf.extend_from_slice(&ts_payload);
    fastalp::compress_into(&values, &mut buf);
    buf
  }

  /// Encodes data into binary format.
  /// 根据 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),
    }
  }

  /// Decodes data from binary format.
  /// 解码 Chunk 字节流并写入指定样本点向量(复用堆分配)
  pub fn decode_samples_into(chunk_data: &[u8], samples: &mut Vec<TSSample>) -> Result<()> {
    if chunk_data.is_empty() {
      return Ok(());
    }
    if chunk_data.len() < ChunkHeader::ENCODED_SIZE {
      if chunk_data.len() == 8 {
        let mut b = [0u8; 8];
        b.copy_from_slice(chunk_data);
        samples.push(TSSample::new(0, f64::from_be_bytes(b)));
        return Ok(());
      }
      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(());
    }

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

    if header.is_compressed {
      if payload.len() < 4 {
        return Err(Error::invalid_data(
          "ERR TSDB: corrupted compressed chunk payload",
        ));
      }
      let ts_len = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) as usize;
      if payload.len() < 4 + ts_len {
        return Err(Error::invalid_data(
          "ERR TSDB: corrupted compressed chunk ts stream",
        ));
      }
      let ts_payload = &payload[4..4 + ts_len];
      let val_payload = &payload[4 + ts_len..];

      let count = header.count as usize;
      let mut timestamps = Vec::with_capacity(count);
      decompress_timestamps_into(ts_payload, count, &mut timestamps)?;

      let mut values = Vec::with_capacity(count);
      fastalp::decompress_into(val_payload, &mut values)
        .map_err(|e| Error::invalid_data(format!("ERR TSDB: ALP decode error: {e}")))?;

      if timestamps.len() != count || values.len() != count {
        return Err(Error::invalid_data(
          "ERR TSDB: compressed chunk length mismatch",
        ));
      }

      samples.reserve(count);
      for (&ts, &v) in timestamps.iter().zip(values.iter()) {
        samples.push(TSSample::new(ts, v));
      }
      Ok(())
    } else {
      let count = header.count as usize;
      let needed = count * 16;
      if payload.len() < needed {
        return Err(Error::invalid_data(
          "ERR TSDB: uncompressed TSChunk payload too short",
        ));
      }
      samples.reserve(count);
      for chunk in payload[..needed].as_chunks::<16>().0 {
        let ts = u64::from_be_bytes([
          chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
        ]);
        let v = f64::from_be_bytes([
          chunk[8], chunk[9], chunk[10], chunk[11], chunk[12], chunk[13], chunk[14], chunk[15],
        ]);
        samples.push(TSSample::new(ts, v));
      }
      Ok(())
    }
  }

  /// Decodes data from binary format.
  /// 解码 Chunk 字节流为采样点向量
  pub fn decode_samples(chunk_data: &[u8]) -> Result<Vec<TSSample>> {
    let mut samples = Vec::new();
    Self::decode_samples_into(chunk_data, &mut samples)?;
    Ok(samples)
  }

  /// Domain operation (aligned with Kvrocks GetFirstTimestamp).
  /// 提取 Chunk 首个时间戳(零全量解压轻量级提取,对标 Kvrocks GetFirstTimestamp)
  #[inline]
  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 header.is_compressed {
      if payload.len() < 4 + 8 {
        return None;
      }
      let b8: [u8; 8] = payload[4..12].try_into().ok()?;
      Some(u64::from_be_bytes(b8))
    } else {
      if payload.len() < 8 {
        return None;
      }
      let b8: [u8; 8] = payload[..8].try_into().ok()?;
      Some(u64::from_be_bytes(b8))
    }
  }

  /// Domain operation (aligned with Kvrocks GetLastTimestamp).
  /// 提取 Chunk 末尾时间戳(未压缩与压缩均实现 O(1) 空间零堆分配提取,对标 Kvrocks GetLastTimestamp)
  #[inline]
  pub fn get_last_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 header.is_compressed {
      if payload.len() < 4 {
        return None;
      }
      let ts_len = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) as usize;
      if payload.len() < 4 + ts_len {
        return None;
      }
      let ts_payload = &payload[4..4 + ts_len];
      decompress_last_timestamp(ts_payload, header.count as usize)
    } else {
      let offset = (header.count as usize - 1) * 16;
      if payload.len() >= offset + 8 {
        let b8: [u8; 8] = payload[offset..offset + 8].try_into().ok()?;
        return Some(u64::from_be_bytes(b8));
      }
      None
    }
  }

  /// Domain operation (aligned with Kvrocks GetLatestSample).
  /// 提取末尾采样点 (ts, val)(未压缩模式零拷贝/零堆分配 O(1) 提取,对标 Kvrocks GetLatestSample)
  #[inline]
  pub fn get_latest_sample(chunk_data: &[u8]) -> Result<Option<(u64, f64)>> {
    if chunk_data.len() < ChunkHeader::ENCODED_SIZE {
      return Ok(None);
    }
    let header = match ChunkHeader::decode(chunk_data) {
      Some(h) => h,
      None => return Ok(None),
    };
    if header.count == 0 {
      return Ok(None);
    }
    let payload = &chunk_data[ChunkHeader::ENCODED_SIZE..];
    if !header.is_compressed {
      let offset = (header.count as usize - 1) * 16;
      if let Some(chunk) = payload.get(offset..offset + 16) {
        // SAFETY: payload.get(offset..offset + 16) 保证 chunk 具有 16 字节有效可读内存,read_unaligned 避免对齐与越界开销。
        let (ts, v) = unsafe {
          let ts_bytes = read_unaligned(chunk.as_ptr().cast::<[u8; 8]>());
          let v_bytes = read_unaligned(chunk.as_ptr().add(8).cast::<[u8; 8]>());
          (u64::from_be_bytes(ts_bytes), f64::from_be_bytes(v_bytes))
        };
        return Ok(Some((ts, v)));
      }
      Ok(None)
    } else {
      let samples = Self::decode_samples(chunk_data)?;
      Ok(samples.last().map(|s| (s.ts, s.v)))
    }
  }

  /// Operation definition.
  /// 提取 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)
  }

  /// Operation definition.
  /// 合并新样本点并应用 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 deduped_new: Vec<TSSample> = Vec::with_capacity(sorted_new.len());
    for s in sorted_new {
      if let Some(last) = deduped_new.last_mut()
        && last.ts == s.ts
      {
        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 (last.v - s.v).abs() < f64::EPSILON {
              stats.skipped += 1;
            } else {
              last.v = s.v;
              stats.updated += 1;
            }
          }
          DuplicatePolicy::Min => {
            if s.v < last.v {
              last.v = s.v;
              stats.updated += 1;
            } else {
              stats.skipped += 1;
            }
          }
          DuplicatePolicy::Max => {
            if s.v > last.v {
              last.v = s.v;
              stats.updated += 1;
            } else {
              stats.skipped += 1;
            }
          }
          DuplicatePolicy::Sum => {
            if s.v == 0.0 {
              stats.skipped += 1;
            } else {
              last.v += s.v;
              stats.updated += 1;
            }
          }
        }
      } else {
        deduped_new.push(s);
      }
    }

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

    while i < existing.len() && j < deduped_new.len() {
      let e = existing[i];
      let n = deduped_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 < deduped_new.len() {
      merged.push(deduped_new[j]);
      stats.inserted += 1;
      j += 1;
    }

    *existing = merged;
    Ok(stats)
  }

  /// Domain operation (aligned with Apache Kvrocks UpsertSampleAndSplit).
  /// 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)
  }

  /// Operation definition.
  /// 删除指定时间范围内的样本点 [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 mut samples = Self::decode_samples(chunk_data)?;
    let orig_len = samples.len();
    samples.retain(|s| s.ts < from_ts || s.ts > to_ts);
    let deleted = orig_len - samples.len();
    if deleted == 0 {
      return Ok((chunk_data.to_vec(), 0));
    }
    let encoded = Self::encode_with_type(&samples, chunk_type);
    Ok((encoded, deleted))
  }

  /// Operation definition.
  /// 更新指定时间戳的样本点数值
  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)
    }
  }
}