1use std::collections::BTreeMap;
17use std::sync::Arc;
18use std::time::Duration;
19
20use parking_lot::RwLock;
21
22use chronix_core::types::{Point, ShardId, Timestamp};
23
24use crate::memtable::error::{MemtableError, Result};
25use crate::memtable::flush::{FlushConfig, FlushController, FlushResult};
26
27#[derive(Debug, Clone)]
29pub struct ShardRouterConfig {
30 pub shard_duration: Duration,
32 pub ooo_shard_tolerance: i64,
35 pub flush_config: FlushConfig,
37}
38
39impl Default for ShardRouterConfig {
40 fn default() -> Self {
41 Self {
42 shard_duration: Duration::from_secs(3600), ooo_shard_tolerance: 1,
44 flush_config: FlushConfig::default(),
45 }
46 }
47}
48
49struct ShardEntry {
51 controller: Arc<FlushController>,
53}
54
55pub struct ShardRouter {
61 shards: Arc<RwLock<BTreeMap<ShardId, ShardEntry>>>,
63 config: ShardRouterConfig,
65 active_shard: Arc<RwLock<Option<ShardId>>>,
67}
68
69impl std::fmt::Debug for ShardRouter {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 f.debug_struct("ShardRouter")
72 .field("config", &self.config)
73 .field("active_shard", &*self.active_shard.read())
74 .field("shard_count", &self.shards.read().len())
75 .finish()
76 }
77}
78
79impl ShardRouter {
80 #[must_use]
82 pub fn new(config: ShardRouterConfig) -> Self {
83 Self {
84 shards: Arc::new(RwLock::new(BTreeMap::new())),
85 config,
86 active_shard: Arc::new(RwLock::new(None)),
87 }
88 }
89
90 pub fn insert(&self, point: &Point) -> Result<()> {
97 let shard_id = ShardId::from_timestamp(point.timestamp(), self.config.shard_duration);
98
99 self.ensure_shard_allowed(shard_id, point.timestamp())?;
100 self.insert_into_shard(shard_id, point)
101 }
102
103 pub fn insert_with_wal_seq(&self, point: &Point, wal_seq: u64) -> Result<()> {
110 let shard_id = ShardId::from_timestamp(point.timestamp(), self.config.shard_duration);
111
112 self.ensure_shard_allowed(shard_id, point.timestamp())?;
113 self.insert_into_shard_with_wal_seq(shard_id, point, wal_seq)
114 }
115
116 pub fn admit(&self, timestamp: Timestamp) -> Result<ShardId> {
131 let shard_id = ShardId::from_timestamp(timestamp, self.config.shard_duration);
132 self.ensure_shard_allowed(shard_id, timestamp)?;
133 Ok(shard_id)
134 }
135
136 pub fn insert_admitted(&self, point: &Point, wal_seq: u64) -> Result<()> {
149 let shard_id = ShardId::from_timestamp(point.timestamp(), self.config.shard_duration);
150 self.insert_into_shard_with_wal_seq(shard_id, point, wal_seq)
151 }
152
153 pub fn insert_replay(&self, point: &Point, wal_seq: u64) -> Result<()> {
167 let shard_id = ShardId::from_timestamp(point.timestamp(), self.config.shard_duration);
168
169 {
171 let mut active_guard = self.active_shard.write();
172 match *active_guard {
173 Some(active) if shard_id.0 > active.0 => {
174 *active_guard = Some(shard_id);
175 }
176 None => {
177 *active_guard = Some(shard_id);
178 }
179 _ => {}
180 }
181 }
182
183 self.insert_into_shard_with_wal_seq(shard_id, point, wal_seq)
184 }
185
186 pub fn flush_shard(&self, shard_id: ShardId) -> Result<Vec<FlushResult>> {
195 self.flush_shard_with(shard_id, |_| Ok(()))
196 }
197
198 pub fn flush_shard_with<F>(
212 &self,
213 shard_id: ShardId,
214 mut register: F,
215 ) -> Result<Vec<FlushResult>>
216 where
217 F: FnMut(&[FlushResult]) -> Result<()>,
218 {
219 let controller = {
220 let shards = self.shards.read();
221 let entry = shards
222 .get(&shard_id)
223 .ok_or(MemtableError::NoSuchShard(shard_id.0))?;
224 Arc::clone(&entry.controller)
225 };
226
227 match controller.freeze_and_swap() {
230 Ok(()) | Err(MemtableError::CapacityExceeded { .. }) => {}
231 Err(e) => return Err(e),
232 }
233 let mut all = Vec::new();
235 while controller.frozen_count() > 0 {
236 match controller.flush_frozen_with(&mut register) {
237 Ok(results) => all.extend(results),
238 Err(MemtableError::NoFrozenMemtable) => continue,
239 Err(e) => {
240 if all.is_empty() {
241 return Err(e);
242 }
243 tracing::warn!(shard = %shard_id, error = %e, "flush stopped early");
246 return Ok(all);
247 }
248 }
249 }
250 if all.is_empty() {
251 return Err(MemtableError::NoFrozenMemtable);
252 }
253 Ok(all)
254 }
255
256 #[must_use]
262 pub fn active_shard(&self) -> Option<ShardId> {
263 *self.active_shard.read()
264 }
265
266 pub fn seed_active_shard(&self, shard: ShardId) {
274 let mut active = self.active_shard.write();
275 if active.is_none_or(|a| shard.0 > a.0) {
276 *active = Some(shard);
277 }
278 }
279
280 pub fn retire_idle_shards(&self) {
287 let Some(active) = self.active_shard() else {
288 return;
289 };
290 let oldest_live = active.0.saturating_sub(self.config.ooo_shard_tolerance);
291 let mut shards = self.shards.write();
292 shards.retain(|id, entry| id.0 >= oldest_live || !entry.controller.is_idle());
293 }
294
295 #[must_use]
297 pub fn shard_ids(&self) -> Vec<ShardId> {
298 self.shards.read().keys().copied().collect()
299 }
300
301 #[must_use]
309 pub fn live_series(&self) -> std::collections::HashSet<String> {
310 let mut out = std::collections::HashSet::new();
311 for entry in self.shards.read().values() {
312 for key in entry.controller.all_series_canonical_forms() {
313 out.insert(key.to_string());
314 }
315 }
316 out
317 }
318
319 #[must_use]
321 pub fn total_memory(&self) -> usize {
322 self.shards
323 .read()
324 .values()
325 .map(|e| e.controller.total_memory())
326 .sum()
327 }
328
329 #[must_use]
335 pub fn total_interner_memory(&self) -> usize {
336 self.shards
337 .read()
338 .values()
339 .map(|e| e.controller.total_interner_memory())
340 .sum()
341 }
342
343 #[must_use]
347 pub fn min_unflushed_wal_seq(&self) -> Option<u64> {
348 self.shards
349 .read()
350 .values()
351 .filter_map(|e| e.controller.min_unflushed_wal_seq())
352 .min()
353 }
354
355 #[must_use]
357 pub fn scan(
358 &self,
359 series_key: &chronix_core::SeriesKey,
360 min_ts: Timestamp,
361 max_ts: Timestamp,
362 ) -> Vec<Point> {
363 let controllers: Vec<Arc<FlushController>> = self
365 .shards
366 .read()
367 .values()
368 .map(|e| Arc::clone(&e.controller))
369 .collect();
370
371 let mut all_points = Vec::new();
372 for ctrl in &controllers {
373 all_points.extend(ctrl.scan(series_key, min_ts, max_ts));
374 }
375
376 all_points.sort_by_key(Point::timestamp);
378 all_points
379 }
380
381 #[must_use]
386 pub fn scan_measurement(
387 &self,
388 measurement: &str,
389 min_ts: Timestamp,
390 max_ts: Timestamp,
391 ) -> Vec<Point> {
392 let controllers: Vec<Arc<FlushController>> = self
394 .shards
395 .read()
396 .values()
397 .map(|e| Arc::clone(&e.controller))
398 .collect();
399
400 let mut all_points = Vec::new();
401 for ctrl in &controllers {
402 all_points.extend(ctrl.scan_measurement(measurement, min_ts, max_ts));
403 }
404
405 all_points.sort_by_key(Point::timestamp);
407 all_points
408 }
409
410 #[must_use]
412 pub fn shard_for_timestamp(&self, timestamp: Timestamp) -> ShardId {
413 ShardId::from_timestamp(timestamp, self.config.shard_duration)
414 }
415
416 fn ensure_shard_allowed(&self, shard_id: ShardId, timestamp: Timestamp) -> Result<()> {
421 let mut active_guard = self.active_shard.write();
422
423 let active = if let Some(active) = *active_guard {
424 if shard_id.0 > active.0 {
426 *active_guard = Some(shard_id);
427 shard_id
428 } else {
429 active
430 }
431 } else {
432 *active_guard = Some(shard_id);
433 shard_id
434 };
435
436 let min_allowed = active.0.saturating_sub(self.config.ooo_shard_tolerance);
437 let max_allowed = active.0.saturating_add(self.config.ooo_shard_tolerance);
438
439 if shard_id.0 < min_allowed || shard_id.0 > max_allowed {
440 return Err(MemtableError::ShardOutOfRange {
441 timestamp,
442 earliest: ShardId(min_allowed).start_timestamp(self.config.shard_duration),
443 latest: ShardId(max_allowed).end_timestamp(self.config.shard_duration),
444 tolerance: self.config.ooo_shard_tolerance,
445 shard_secs: self.config.shard_duration.as_secs(),
446 });
447 }
448
449 Ok(())
450 }
451
452 fn with_shard<F, R>(&self, shard_id: ShardId, f: F) -> Result<R>
455 where
456 F: FnOnce(&FlushController) -> Result<R>,
457 {
458 {
460 let shards = self.shards.read();
461 if let Some(entry) = shards.get(&shard_id) {
462 return f(&entry.controller);
463 }
464 }
465
466 let mut shards = self.shards.write();
468 let entry = shards.entry(shard_id).or_insert_with(|| {
469 let mut config = self.config.flush_config.clone();
470 config.segment_dir = config.segment_dir.join(format!("shard_{}", shard_id.0));
471 ShardEntry {
472 controller: Arc::new(FlushController::new(config)),
473 }
474 });
475 f(&entry.controller)
476 }
477
478 fn insert_into_shard(&self, shard_id: ShardId, point: &Point) -> Result<()> {
480 self.with_shard(shard_id, |ctrl| ctrl.insert(point))
481 }
482
483 fn insert_into_shard_with_wal_seq(
485 &self,
486 shard_id: ShardId,
487 point: &Point,
488 wal_seq: u64,
489 ) -> Result<()> {
490 self.with_shard(shard_id, |ctrl| ctrl.insert_with_wal_seq(point, wal_seq))
491 }
492}
493#[cfg(test)]
494mod tests {
495 use super::*;
496 use std::collections::BTreeMap as StdBTreeMap;
497
498 use crate::segment::writer::SegmentWriterConfig;
499 use chronix_core::types::{FieldValue, SeriesKey};
500
501 fn make_point(ts: Timestamp, value: f64) -> Point {
502 make_point_with_measurement("cpu", ts, value)
503 }
504
505 fn make_point_with_measurement(measurement: &str, ts: Timestamp, value: f64) -> Point {
506 let tags: StdBTreeMap<String, String> = [("host".to_string(), "a".to_string())]
507 .into_iter()
508 .collect();
509 let series_key = SeriesKey::new(measurement.to_string(), tags).unwrap();
510 let fields: StdBTreeMap<String, FieldValue> =
511 [("value".to_string(), FieldValue::F64(value))]
512 .into_iter()
513 .collect();
514 Point::new(series_key, fields, ts).unwrap()
515 }
516
517 fn test_router_config(dir: &std::path::Path) -> ShardRouterConfig {
518 ShardRouterConfig {
519 shard_duration: Duration::from_secs(3600),
520 ooo_shard_tolerance: 1,
521 flush_config: FlushConfig {
522 flush_threshold: 64 * 1024 * 1024,
523 max_memory: 256 * 1024 * 1024,
524 segment_dir: dir.to_path_buf(),
525 segment_writer_config: SegmentWriterConfig {
526 compress: false,
527 ..Default::default()
528 },
529 ..Default::default()
530 },
531 }
532 }
533
534 const NS_PER_HOUR: i64 = 3_600_000_000_000;
536
537 #[test]
538 fn routes_to_correct_shard() {
539 let dir = tempfile::tempdir().unwrap();
540 let router = ShardRouter::new(test_router_config(dir.path()));
541
542 let p1 = make_point(100, 1.0);
544 router.insert(&p1).unwrap();
545
546 assert_eq!(router.shard_ids().len(), 1);
547 assert_eq!(router.shard_ids()[0], ShardId(0));
548 }
549
550 #[test]
551 fn routes_to_multiple_shards() {
552 let dir = tempfile::tempdir().unwrap();
553 let router = ShardRouter::new(test_router_config(dir.path()));
554
555 router.insert(&make_point(100, 1.0)).unwrap();
557 router.insert(&make_point(NS_PER_HOUR + 100, 2.0)).unwrap();
559
560 let shard_ids = router.shard_ids();
561 assert_eq!(shard_ids.len(), 2);
562 }
563
564 #[test]
565 fn ooo_within_tolerance_accepted() {
566 let dir = tempfile::tempdir().unwrap();
567 let router = ShardRouter::new(test_router_config(dir.path()));
568
569 router.insert(&make_point(NS_PER_HOUR + 100, 1.0)).unwrap();
571
572 router.insert(&make_point(100, 2.0)).unwrap();
574
575 assert_eq!(router.shard_ids().len(), 2);
576 }
577
578 #[test]
579 fn ooo_beyond_tolerance_rejected() {
580 let dir = tempfile::tempdir().unwrap();
581 let mut config = test_router_config(dir.path());
582 config.ooo_shard_tolerance = 0; let router = ShardRouter::new(config);
584
585 router.insert(&make_point(NS_PER_HOUR + 100, 1.0)).unwrap();
587
588 let result = router.insert(&make_point(100, 2.0));
590 assert!(result.is_err());
591 }
592
593 #[test]
594 fn flush_shard() {
595 let dir = tempfile::tempdir().unwrap();
596 let router = ShardRouter::new(test_router_config(dir.path()));
597
598 for i in 0..10 {
599 router.insert(&make_point(i * 100, i as f64)).unwrap();
600 }
601
602 let shard_id = ShardId(0);
603 let results = router.flush_shard(shard_id).unwrap();
604 assert_eq!(results.len(), 1);
605 assert_eq!(results[0].measurement, "cpu");
606 assert_eq!(results[0].points_flushed, 10);
607 }
608
609 #[test]
610 fn scan_across_shards() {
611 let dir = tempfile::tempdir().unwrap();
612 let router = ShardRouter::new(test_router_config(dir.path()));
613
614 router.insert(&make_point(100, 1.0)).unwrap();
616 router.insert(&make_point(NS_PER_HOUR + 100, 2.0)).unwrap();
618
619 let key = SeriesKey::new(
620 "cpu".to_string(),
621 [("host".to_string(), "a".to_string())]
622 .into_iter()
623 .collect(),
624 )
625 .unwrap();
626
627 let points = router.scan(&key, 0, NS_PER_HOUR * 2);
628 assert_eq!(points.len(), 2);
629 assert!(points[0].timestamp() < points[1].timestamp());
630 }
631
632 #[test]
633 fn total_memory_across_shards() {
634 let dir = tempfile::tempdir().unwrap();
635 let router = ShardRouter::new(test_router_config(dir.path()));
636
637 router.insert(&make_point(100, 1.0)).unwrap();
638 router.insert(&make_point(NS_PER_HOUR + 100, 2.0)).unwrap();
639
640 assert!(router.total_memory() > 0);
641 }
642
643 #[test]
644 fn shard_for_timestamp_computation() {
645 let dir = tempfile::tempdir().unwrap();
646 let router = ShardRouter::new(test_router_config(dir.path()));
647
648 assert_eq!(router.shard_for_timestamp(0), ShardId(0));
649 assert_eq!(router.shard_for_timestamp(NS_PER_HOUR), ShardId(1));
650 assert_eq!(router.shard_for_timestamp(NS_PER_HOUR - 1), ShardId(0));
651 }
652
653 #[test]
654 fn scan_measurement_across_shards() {
655 let dir = tempfile::tempdir().unwrap();
656 let router = ShardRouter::new(test_router_config(dir.path()));
657
658 router
660 .insert(&make_point_with_measurement("cpu", 100, 1.0))
661 .unwrap();
662 router
663 .insert(&make_point_with_measurement("mem", 200, 2.0))
664 .unwrap();
665 router
667 .insert(&make_point_with_measurement("cpu", NS_PER_HOUR + 100, 3.0))
668 .unwrap();
669
670 let cpu = router.scan_measurement("cpu", 0, i64::MAX);
672 assert_eq!(cpu.len(), 2);
673 assert!(cpu.iter().all(|p| p.series_key().measurement() == "cpu"));
674 assert!(cpu[0].timestamp() < cpu[1].timestamp()); let mem = router.scan_measurement("mem", 0, i64::MAX);
678 assert_eq!(mem.len(), 1);
679
680 let none = router.scan_measurement("disk", 0, i64::MAX);
682 assert!(none.is_empty());
683 }
684
685 #[test]
686 fn scan_measurement_respects_time_range() {
687 let dir = tempfile::tempdir().unwrap();
688 let router = ShardRouter::new(test_router_config(dir.path()));
689
690 router
691 .insert(&make_point_with_measurement("cpu", 100, 1.0))
692 .unwrap();
693 router
694 .insert(&make_point_with_measurement("cpu", 200, 2.0))
695 .unwrap();
696 router
697 .insert(&make_point_with_measurement("cpu", 300, 3.0))
698 .unwrap();
699
700 let result = router.scan_measurement("cpu", 150, 250);
701 assert_eq!(result.len(), 1);
702 assert_eq!(result[0].timestamp(), 200);
703 }
704}