1use std::collections::HashMap;
68
69use edgestore::error::EdgestoreError;
70use edgestore::types::encode_key;
71use edgestore::{Engine, ImmutableEngine, ImportResult, RemoteStore};
72use lru::LruCache;
73use std::num::NonZeroUsize;
74
75type KvPairs = Vec<(Vec<u8>, Vec<u8>)>;
76
77#[derive(Debug, Clone)]
79pub struct ArchivedSegment {
80 pub hash: [u8; 32],
82 pub min_key: Vec<u8>,
84 pub max_key: Vec<u8>,
86}
87
88const DEFAULT_SEGMENT_CACHE_MAX_BYTES: usize = 32 * 1024 * 1024;
90
91const SEGMENT_CACHE_MAX_ENTRIES: NonZeroUsize =
94 unsafe { NonZeroUsize::new_unchecked(65536) };
96
97const MAX_RETRIES: u32 = 3;
99
100const BASE_DELAY_MS: u64 = 10;
102
103pub struct TieredEngine {
108 pub(crate) local: Engine,
109 pub(crate) remote: Box<dyn RemoteStore>,
110 archived: Vec<ArchivedSegment>,
112 fetched: HashMap<[u8; 32], ()>,
114 upload_sidecars: bool,
116 strip_text_after_archive: bool,
118 strip_vector_after_archive: bool,
120 segment_cache: LruCache<[u8; 32], Vec<u8>>,
122 pub(crate) segment_cache_bytes: usize,
124 segment_cache_max_bytes: usize,
126}
127
128impl TieredEngine {
129 pub fn new(local: Engine, remote: Box<dyn RemoteStore>) -> Self {
131 Self {
132 local,
133 remote,
134 archived: Vec::new(),
135 fetched: HashMap::new(),
136 upload_sidecars: false,
137 strip_text_after_archive: false,
138 strip_vector_after_archive: false,
139 segment_cache: LruCache::new(SEGMENT_CACHE_MAX_ENTRIES),
142 segment_cache_bytes: 0,
143 segment_cache_max_bytes: DEFAULT_SEGMENT_CACHE_MAX_BYTES,
144 }
145 }
146
147 pub fn with_segment_cache_bytes(mut self, max_bytes: usize) -> Self {
150 self.segment_cache_max_bytes = max_bytes;
151 self
152 }
153
154 pub fn with_sidecars(mut self, enabled: bool) -> Self {
156 self.upload_sidecars = enabled;
157 self
158 }
159
160 pub fn with_text_stripping(mut self, enabled: bool) -> Self {
162 self.strip_text_after_archive = enabled;
163 self
164 }
165
166 pub fn with_vector_stripping(mut self, enabled: bool) -> Self {
168 self.strip_vector_after_archive = enabled;
169 self
170 }
171
172 pub fn local(&self) -> &Engine {
174 &self.local
175 }
176
177 pub fn local_mut(&mut self) -> &mut Engine {
179 &mut self.local
180 }
181
182 pub fn archived_segments(&self) -> Vec<ArchivedSegment> {
184 self.archived.clone()
185 }
186
187 pub fn register_archived(&mut self, segments: Vec<ArchivedSegment>) {
192 for seg in segments {
193 if !self.archived.iter().any(|s| s.hash == seg.hash) {
194 self.archived.push(seg);
195 }
196 }
197 }
198
199 pub fn put(&mut self, ns: &[u8], key: &[u8], val: &[u8]) -> Result<u64, EdgestoreError> {
203 self.local.put(ns, key, val)
204 }
205
206 pub fn put_with_ttl(
208 &mut self,
209 ns: &[u8],
210 key: &[u8],
211 val: &[u8],
212 ttl_secs: u32,
213 ) -> Result<u64, EdgestoreError> {
214 self.local.put_with_ttl(ns, key, val, ttl_secs)
215 }
216
217 pub fn delete(&mut self, ns: &[u8], key: &[u8]) -> Result<u64, EdgestoreError> {
219 self.local.delete(ns, key)
220 }
221
222 pub fn get(&mut self, ns: &[u8], key: &[u8]) -> Result<Option<Vec<u8>>, EdgestoreError> {
226 if let Some(val) = self.local.get(ns, key)? {
227 return Ok(Some(val));
228 }
229
230 let encoded_key = edgestore::types::encode_key(ns, key);
231 let to_fetch: Vec<[u8; 32]> = self
232 .archived
233 .iter()
234 .filter(|seg| encoded_key >= seg.min_key && encoded_key <= seg.max_key)
235 .filter(|seg| !self.fetched.contains_key(&seg.hash))
236 .map(|seg| seg.hash)
237 .collect();
238
239 for hash in to_fetch {
240 if let Err(e) = self.fetch_and_import(&hash) {
241 eprintln!(
242 "[edgestore-tier] failed to fetch segment {}: {}",
243 hex_hash(&hash),
244 e
245 );
246 }
247 }
248
249 self.local.get(ns, key)
250 }
251
252 #[allow(clippy::type_complexity)]
255 pub fn range(
256 &mut self,
257 ns: &[u8],
258 start: &[u8],
259 end: &[u8],
260 ) -> Result<KvPairs, EdgestoreError> {
261 let local = self.local.range(ns, start, end)?;
262 let archived = self.range_archived(ns, start, end)?;
263 Ok(merge_local_wins(local, archived))
264 }
265
266 #[allow(clippy::type_complexity)]
269 pub fn prefix(&mut self, ns: &[u8], prefix: &[u8]) -> Result<KvPairs, EdgestoreError> {
270 let local = self.local.prefix(ns, prefix)?;
271 let archived = self.prefix_archived(ns, prefix)?;
272 Ok(merge_local_wins(local, archived))
273 }
274
275 pub fn archive_segments(
282 &mut self,
283 metas: &[edgestore::types::SegmentMeta],
284 ) -> Result<(), EdgestoreError> {
285 assert!(!metas.is_empty() || true, "metas slice accepted (may be empty)");
286 let base = self.local.db_path().to_path_buf();
287
288 for meta in metas {
289 let hash: [u8; 32] = meta.segment_hash.as_slice().try_into().map_err(|_| {
290 EdgestoreError::ReplicationError(format!(
291 "segment {} hash is not 32 bytes",
292 meta.segment_id
293 ))
294 })?;
295
296 let dat_path = base.join(format!("segment-{:08}.dat", meta.segment_id));
297 if !dat_path.exists() {
298 continue; }
300
301 let data = std::fs::read(&dat_path).map_err(EdgestoreError::Io)?;
302 assert!(!data.is_empty(), "segment .dat file must not be empty");
303 self.upload_with_retry(&hash, &data)?;
304
305 if self.upload_sidecars {
306 for ext in &["idx", "xf", "meta"] {
307 let sidecar_path =
308 base.join(format!("segment-{:08}.{}", meta.segment_id, ext));
309 if let Ok(bytes) = std::fs::read(&sidecar_path) {
310 if let Err(e) = self.remote.upload_aux(&hash, ext, &bytes) {
311 eprintln!(
312 "[edgestore-tier] sidecar upload skipped for {}.{}: {}",
313 hex_hash(&hash),
314 ext,
315 e
316 );
317 }
318 }
319 }
320 }
321
322 self.archived.push(ArchivedSegment {
323 hash,
324 min_key: meta.min_key.clone(),
325 max_key: meta.max_key.clone(),
326 });
327
328 if self.strip_text_after_archive {
329 if let Err(e) = self.local.strip_text_index(meta.segment_id) {
330 eprintln!(
331 "[edgestore-tier] strip_text_index skipped for segment {}: {}",
332 meta.segment_id, e
333 );
334 }
335 }
336
337 if self.strip_vector_after_archive {
338 if let Err(e) = self.local.strip_vector_index(meta.segment_id) {
339 eprintln!(
340 "[edgestore-tier] strip_vector_index skipped for segment {}: {}",
341 meta.segment_id, e
342 );
343 }
344 }
345 }
346
347 Ok(())
348 }
349
350 pub fn fetch_segment(&mut self, hash: &[u8; 32]) -> Result<(), EdgestoreError> {
352 self.fetch_and_import(hash)
353 }
354
355 pub fn download_segment(&self, hash: &[u8; 32]) -> Result<Vec<u8>, EdgestoreError> {
360 assert!(hash.len() == 32, "hash must be 32 bytes");
361 self.remote.download(hash).map_err(|e| {
362 EdgestoreError::ReplicationError(format!("download segment {}: {}", hex_hash(hash), e))
363 })
364 }
365
366 pub fn fetch_archived_overlapping(
369 &mut self,
370 ns: &[u8],
371 start: &[u8],
372 end: &[u8],
373 ) -> Result<(), EdgestoreError> {
374 let start = edgestore::types::encode_key(ns, start);
375 let end = edgestore::types::encode_key(ns, end);
376
377 let overlapping: Vec<[u8; 32]> = self
378 .archived
379 .iter()
380 .filter(|seg| seg.max_key >= start && seg.min_key < end)
381 .map(|seg| seg.hash)
382 .collect();
383
384 for hash in overlapping {
385 self.fetch_and_import(&hash)?;
386 }
387 Ok(())
388 }
389
390 pub fn fetch_all_archived(&mut self) -> Result<(), EdgestoreError> {
392 let archived = self.archived.clone();
393 for seg in &archived {
394 if !self.fetched.contains_key(&seg.hash) {
395 self.fetch_and_import(&seg.hash)?;
396 }
397 }
398 Ok(())
399 }
400
401 pub fn local_only_get(&self, ns: &[u8], key: &[u8]) -> Result<Option<Vec<u8>>, EdgestoreError> {
410 self.local.get(ns, key)
411 }
412
413 fn has_unfetched_archived_overlap(&self, enc_start: &[u8], enc_end: &[u8]) -> bool {
414 self.archived.iter().any(|seg| {
415 seg.max_key.as_slice() >= enc_start
416 && seg.min_key.as_slice() < enc_end
417 && !self.fetched.contains_key(&seg.hash)
418 })
419 }
420
421 fn has_unfetched_archived_point(&self, enc_key: &[u8]) -> bool {
422 self.archived.iter().any(|seg| {
423 seg.min_key.as_slice() <= enc_key
424 && seg.max_key.as_slice() >= enc_key
425 && !self.fetched.contains_key(&seg.hash)
426 })
427 }
428
429 pub fn get_needs_archived_fetch(&self, ns: &[u8], key: &[u8]) -> bool {
431 let enc_key = encode_key(ns, key);
432 self.has_unfetched_archived_point(&enc_key)
433 }
434
435 pub fn range_needs_archived_fetch(&self, ns: &[u8], start: &[u8], end: &[u8]) -> bool {
437 let enc_start = encode_key(ns, start);
438 let enc_end = encode_key(ns, end);
439 self.has_unfetched_archived_overlap(&enc_start, &enc_end)
440 }
441
442 pub fn local_only_range(
444 &self,
445 ns: &[u8],
446 start: &[u8],
447 end: &[u8],
448 ) -> Result<KvPairs, EdgestoreError> {
449 self.local.range(ns, start, end)
450 }
451
452 pub fn prefix_needs_archived_fetch(&self, ns: &[u8], prefix: &[u8]) -> bool {
454 let enc_prefix = encode_key(ns, prefix);
455 let enc_end = edgestore::types::prefix_upper_bound(&enc_prefix)
456 .unwrap_or_else(|| vec![0xFF; enc_prefix.len() + 1]);
457 self.has_unfetched_archived_overlap(&enc_prefix, &enc_end)
458 }
459
460 pub fn local_only_prefix(&self, ns: &[u8], prefix: &[u8]) -> Result<KvPairs, EdgestoreError> {
462 self.local.prefix(ns, prefix)
463 }
464
465 fn ephemeral_engine_for_range(
470 &mut self,
471 enc_start: &[u8],
472 enc_end: &[u8],
473 ) -> Result<Option<ImmutableEngine>, EdgestoreError> {
474 let to_load: Vec<[u8; 32]> = self
475 .archived
476 .iter()
477 .filter(|seg| seg.max_key.as_slice() >= enc_start && seg.min_key.as_slice() < enc_end)
478 .filter(|seg| !self.fetched.contains_key(&seg.hash))
479 .map(|seg| seg.hash)
480 .collect();
481
482 if to_load.is_empty() {
483 return Ok(None);
484 }
485
486 let mut pairs: Vec<(edgestore::types::SegmentMeta, Vec<u8>)> =
487 Vec::with_capacity(to_load.len());
488
489 for hash in to_load {
490 let data = if let Some(cached) = self.segment_cache.get(&hash) {
491 cached.clone()
492 } else {
493 match self.remote.download(&hash) {
494 Ok(data) => {
495 self.cache_segment(hash, data.clone());
496 data
497 }
498 Err(e) => {
499 eprintln!(
500 "[edgestore-tier] ephemeral download skipped for {}: {}",
501 hex_hash(&hash),
502 e
503 );
504 continue;
505 }
506 }
507 };
508 pairs.push((synthetic_meta(&hash), data));
509 }
510
511 if pairs.is_empty() {
512 return Ok(None);
513 }
514
515 Ok(Some(ImmutableEngine::from_segment_bytes(pairs)?))
516 }
517
518 fn range_archived(
519 &mut self,
520 ns: &[u8],
521 start: &[u8],
522 end: &[u8],
523 ) -> Result<KvPairs, EdgestoreError> {
524 let enc_start = encode_key(ns, start);
525 let enc_end = encode_key(ns, end);
526 match self.ephemeral_engine_for_range(&enc_start, &enc_end)? {
527 Some(engine) => engine.range(ns, start, end),
528 None => Ok(Vec::new()),
529 }
530 }
531
532 fn prefix_archived(&mut self, ns: &[u8], prefix: &[u8]) -> Result<KvPairs, EdgestoreError> {
533 let enc_prefix = encode_key(ns, prefix);
534 let enc_end = edgestore::types::prefix_upper_bound(&enc_prefix)
535 .unwrap_or_else(|| vec![0xFF; enc_prefix.len() + 1]);
536 match self.ephemeral_engine_for_range(&enc_prefix, &enc_end)? {
537 Some(engine) => engine.prefix(ns, prefix),
538 None => Ok(Vec::new()),
539 }
540 }
541
542 fn upload_with_retry(&self, hash: &[u8; 32], data: &[u8]) -> Result<(), EdgestoreError> {
544 assert!(!data.is_empty(), "upload data must not be empty");
545 let label = format!("upload segment {}", hex_hash(hash));
546 retry_transient(&label, || {
547 self.remote.upload_if_absent(hash, data).map(|_| ())
548 })
549 }
550
551 fn fetch_and_import(&mut self, hash: &[u8; 32]) -> Result<(), EdgestoreError> {
553 assert!(hash.len() == 32, "hash must be 32 bytes");
554 let label = format!("download segment {}", hex_hash(hash));
555 let data = retry_transient(&label, || self.remote.download(hash))?;
556
557 assert!(!data.is_empty(), "downloaded segment must not be empty");
558
559 match self.local.import_segment(&data, hash)? {
560 ImportResult::Applied {
561 keys_written,
562 keys_skipped,
563 } => {
564 eprintln!(
565 "[edgestore-tier] imported {} ({} written, {} skipped)",
566 hex_hash(hash),
567 keys_written,
568 keys_skipped
569 );
570 }
571 ImportResult::Skipped => {
572 eprintln!("[edgestore-tier] segment {} already local", hex_hash(hash));
573 }
574 ImportResult::HashMismatch => {
575 return Err(EdgestoreError::ReplicationError(format!(
576 "hash mismatch for segment {}",
577 hex_hash(hash)
578 )));
579 }
580 ImportResult::Rejected { reason } => {
581 return Err(EdgestoreError::ReplicationError(format!(
582 "segment {} permanently rejected: {}",
583 hex_hash(hash),
584 reason
585 )));
586 }
587 }
588 self.fetched.insert(*hash, ());
589 Ok(())
590 }
591
592 fn cache_segment(&mut self, hash: [u8; 32], data: Vec<u8>) {
595 if self.segment_cache_max_bytes == 0 {
596 return;
597 }
598 let incoming = data.len();
599 while self.segment_cache_bytes + incoming > self.segment_cache_max_bytes {
600 match self.segment_cache.pop_lru() {
601 Some((_, evicted)) => {
602 self.segment_cache_bytes =
603 self.segment_cache_bytes.saturating_sub(evicted.len())
604 }
605 None => break,
606 }
607 }
608 self.segment_cache_bytes += incoming;
609 self.segment_cache.put(hash, data);
610 }
611
612 pub fn flush(&mut self) -> Result<(), EdgestoreError> {
614 self.local.flush()
615 }
616
617 pub fn compact_once(&mut self) -> Result<edgestore::CompactionStats, EdgestoreError> {
619 self.local.compact_once()
620 }
621
622 pub fn prune_local_segment(
627 &mut self,
628 segment_id: edgestore::types::SegmentId,
629 ) -> Result<(), EdgestoreError> {
630 self.local.prune_local_segment(segment_id)
631 }
632}
633
634fn hex_hash(hash: &[u8; 32]) -> String {
637 assert!(hash.len() == 32, "hash must be 32 bytes");
638 let mut s = String::with_capacity(64);
639 for b in hash {
640 s.push_str(&format!("{b:02x}"));
641 }
642 assert!(s.len() == 64, "hex_hash must produce 64 chars");
643 s
644}
645
646fn synthetic_meta(hash: &[u8; 32]) -> edgestore::types::SegmentMeta {
650 assert!(hash.len() == 32, "hash must be 32 bytes");
651 edgestore::types::SegmentMeta {
652 segment_id: 0,
653 segment_hash: hash.to_vec(),
654 min_key: vec![],
655 max_key: vec![0xFF; 2],
656 min_lsn: 0,
657 max_lsn: u64::MAX,
658 record_count: 0,
659 compressed_bytes: 0,
660 uncompressed_bytes: 0,
661 compression: "zstd:1".to_string(),
662 cohort_bucket: 0,
663 death_time: i64::MAX,
664 merkle_root: vec![0u8; 32],
665 created_at: 0,
666 text_index_stripped: false,
667 vector_index_stripped: false,
668 }
669}
670
671fn merge_local_wins(local: KvPairs, archived: KvPairs) -> KvPairs {
674 if archived.is_empty() {
675 return local;
676 }
677 let local_keys: std::collections::HashSet<Vec<u8>> =
678 local.iter().map(|(k, _)| k.clone()).collect();
679 let mut result = local;
680 for (k, v) in archived {
681 if !local_keys.contains(&k) {
682 result.push((k, v));
683 }
684 }
685 result.sort_by(|(a, _), (b, _)| a.cmp(b));
686 result
687}
688
689fn retry_transient<T, F>(label: &str, mut f: F) -> Result<T, EdgestoreError>
692where
693 F: FnMut() -> Result<T, EdgestoreError>,
694{
695 assert!(!label.is_empty(), "retry label must not be empty");
696 let mut last_err = None;
697
698 for attempt in 0..=MAX_RETRIES {
699 match f() {
700 Ok(v) => return Ok(v),
701 Err(e) => {
702 let msg = e.to_string();
703 last_err = Some(e);
704 let is_transient = msg.contains("throttled")
705 || msg.contains("timeout")
706 || msg.contains("503");
707 if is_transient && attempt < MAX_RETRIES {
708 let delay_ms = BASE_DELAY_MS * (1u64 << attempt);
709 eprintln!(
710 "[edgestore-tier] retry {} for {} after {} ms",
711 attempt + 1,
712 label,
713 delay_ms
714 );
715 std::thread::sleep(std::time::Duration::from_millis(delay_ms));
716 } else if !is_transient {
717 break;
718 }
719 }
720 }
721 }
722
723 assert!(last_err.is_some(), "last_err must be set after all retries");
724 Err(EdgestoreError::ReplicationError(format!(
725 "{label} failed after {MAX_RETRIES} retries: {}",
726 last_err.map(|e| e.to_string()).unwrap_or_default()
727 )))
728}
729
730#[cfg(test)]
731mod tests;