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]
303 pub fn total_memory(&self) -> usize {
304 self.shards
305 .read()
306 .values()
307 .map(|e| e.controller.total_memory())
308 .sum()
309 }
310
311 #[must_use]
317 pub fn total_interner_memory(&self) -> usize {
318 self.shards
319 .read()
320 .values()
321 .map(|e| e.controller.total_interner_memory())
322 .sum()
323 }
324
325 #[must_use]
329 pub fn min_unflushed_wal_seq(&self) -> Option<u64> {
330 self.shards
331 .read()
332 .values()
333 .filter_map(|e| e.controller.min_unflushed_wal_seq())
334 .min()
335 }
336
337 #[must_use]
339 pub fn scan(
340 &self,
341 series_key: &chronix_core::SeriesKey,
342 min_ts: Timestamp,
343 max_ts: Timestamp,
344 ) -> Vec<Point> {
345 let controllers: Vec<Arc<FlushController>> = self
347 .shards
348 .read()
349 .values()
350 .map(|e| Arc::clone(&e.controller))
351 .collect();
352
353 let mut all_points = Vec::new();
354 for ctrl in &controllers {
355 all_points.extend(ctrl.scan(series_key, min_ts, max_ts));
356 }
357
358 all_points.sort_by_key(Point::timestamp);
360 all_points
361 }
362
363 #[must_use]
368 pub fn scan_measurement(
369 &self,
370 measurement: &str,
371 min_ts: Timestamp,
372 max_ts: Timestamp,
373 ) -> Vec<Point> {
374 let controllers: Vec<Arc<FlushController>> = self
376 .shards
377 .read()
378 .values()
379 .map(|e| Arc::clone(&e.controller))
380 .collect();
381
382 let mut all_points = Vec::new();
383 for ctrl in &controllers {
384 all_points.extend(ctrl.scan_measurement(measurement, min_ts, max_ts));
385 }
386
387 all_points.sort_by_key(Point::timestamp);
389 all_points
390 }
391
392 #[must_use]
394 pub fn shard_for_timestamp(&self, timestamp: Timestamp) -> ShardId {
395 ShardId::from_timestamp(timestamp, self.config.shard_duration)
396 }
397
398 fn ensure_shard_allowed(&self, shard_id: ShardId, timestamp: Timestamp) -> Result<()> {
403 let mut active_guard = self.active_shard.write();
404
405 let active = if let Some(active) = *active_guard {
406 if shard_id.0 > active.0 {
408 *active_guard = Some(shard_id);
409 shard_id
410 } else {
411 active
412 }
413 } else {
414 *active_guard = Some(shard_id);
415 shard_id
416 };
417
418 let min_allowed = active.0.saturating_sub(self.config.ooo_shard_tolerance);
419 let max_allowed = active.0.saturating_add(self.config.ooo_shard_tolerance);
420
421 if shard_id.0 < min_allowed || shard_id.0 > max_allowed {
422 return Err(MemtableError::ShardOutOfRange {
423 timestamp,
424 earliest: ShardId(min_allowed).start_timestamp(self.config.shard_duration),
425 latest: ShardId(max_allowed).end_timestamp(self.config.shard_duration),
426 tolerance: self.config.ooo_shard_tolerance,
427 shard_secs: self.config.shard_duration.as_secs(),
428 });
429 }
430
431 Ok(())
432 }
433
434 fn with_shard<F, R>(&self, shard_id: ShardId, f: F) -> Result<R>
437 where
438 F: FnOnce(&FlushController) -> Result<R>,
439 {
440 {
442 let shards = self.shards.read();
443 if let Some(entry) = shards.get(&shard_id) {
444 return f(&entry.controller);
445 }
446 }
447
448 let mut shards = self.shards.write();
450 let entry = shards.entry(shard_id).or_insert_with(|| {
451 let mut config = self.config.flush_config.clone();
452 config.segment_dir = config.segment_dir.join(format!("shard_{}", shard_id.0));
453 ShardEntry {
454 controller: Arc::new(FlushController::new(config)),
455 }
456 });
457 f(&entry.controller)
458 }
459
460 fn insert_into_shard(&self, shard_id: ShardId, point: &Point) -> Result<()> {
462 self.with_shard(shard_id, |ctrl| ctrl.insert(point))
463 }
464
465 fn insert_into_shard_with_wal_seq(
467 &self,
468 shard_id: ShardId,
469 point: &Point,
470 wal_seq: u64,
471 ) -> Result<()> {
472 self.with_shard(shard_id, |ctrl| ctrl.insert_with_wal_seq(point, wal_seq))
473 }
474}
475#[cfg(test)]
476mod tests {
477 use super::*;
478 use std::collections::BTreeMap as StdBTreeMap;
479
480 use crate::segment::writer::SegmentWriterConfig;
481 use chronix_core::types::{FieldValue, SeriesKey};
482
483 fn make_point(ts: Timestamp, value: f64) -> Point {
484 make_point_with_measurement("cpu", ts, value)
485 }
486
487 fn make_point_with_measurement(measurement: &str, ts: Timestamp, value: f64) -> Point {
488 let tags: StdBTreeMap<String, String> = [("host".to_string(), "a".to_string())]
489 .into_iter()
490 .collect();
491 let series_key = SeriesKey::new(measurement.to_string(), tags).unwrap();
492 let fields: StdBTreeMap<String, FieldValue> =
493 [("value".to_string(), FieldValue::F64(value))]
494 .into_iter()
495 .collect();
496 Point::new(series_key, fields, ts).unwrap()
497 }
498
499 fn test_router_config(dir: &std::path::Path) -> ShardRouterConfig {
500 ShardRouterConfig {
501 shard_duration: Duration::from_secs(3600),
502 ooo_shard_tolerance: 1,
503 flush_config: FlushConfig {
504 flush_threshold: 64 * 1024 * 1024,
505 max_memory: 256 * 1024 * 1024,
506 segment_dir: dir.to_path_buf(),
507 segment_writer_config: SegmentWriterConfig {
508 compress: false,
509 ..Default::default()
510 },
511 ..Default::default()
512 },
513 }
514 }
515
516 const NS_PER_HOUR: i64 = 3_600_000_000_000;
518
519 #[test]
520 fn routes_to_correct_shard() {
521 let dir = tempfile::tempdir().unwrap();
522 let router = ShardRouter::new(test_router_config(dir.path()));
523
524 let p1 = make_point(100, 1.0);
526 router.insert(&p1).unwrap();
527
528 assert_eq!(router.shard_ids().len(), 1);
529 assert_eq!(router.shard_ids()[0], ShardId(0));
530 }
531
532 #[test]
533 fn routes_to_multiple_shards() {
534 let dir = tempfile::tempdir().unwrap();
535 let router = ShardRouter::new(test_router_config(dir.path()));
536
537 router.insert(&make_point(100, 1.0)).unwrap();
539 router.insert(&make_point(NS_PER_HOUR + 100, 2.0)).unwrap();
541
542 let shard_ids = router.shard_ids();
543 assert_eq!(shard_ids.len(), 2);
544 }
545
546 #[test]
547 fn ooo_within_tolerance_accepted() {
548 let dir = tempfile::tempdir().unwrap();
549 let router = ShardRouter::new(test_router_config(dir.path()));
550
551 router.insert(&make_point(NS_PER_HOUR + 100, 1.0)).unwrap();
553
554 router.insert(&make_point(100, 2.0)).unwrap();
556
557 assert_eq!(router.shard_ids().len(), 2);
558 }
559
560 #[test]
561 fn ooo_beyond_tolerance_rejected() {
562 let dir = tempfile::tempdir().unwrap();
563 let mut config = test_router_config(dir.path());
564 config.ooo_shard_tolerance = 0; let router = ShardRouter::new(config);
566
567 router.insert(&make_point(NS_PER_HOUR + 100, 1.0)).unwrap();
569
570 let result = router.insert(&make_point(100, 2.0));
572 assert!(result.is_err());
573 }
574
575 #[test]
576 fn flush_shard() {
577 let dir = tempfile::tempdir().unwrap();
578 let router = ShardRouter::new(test_router_config(dir.path()));
579
580 for i in 0..10 {
581 router.insert(&make_point(i * 100, i as f64)).unwrap();
582 }
583
584 let shard_id = ShardId(0);
585 let results = router.flush_shard(shard_id).unwrap();
586 assert_eq!(results.len(), 1);
587 assert_eq!(results[0].measurement, "cpu");
588 assert_eq!(results[0].points_flushed, 10);
589 }
590
591 #[test]
592 fn scan_across_shards() {
593 let dir = tempfile::tempdir().unwrap();
594 let router = ShardRouter::new(test_router_config(dir.path()));
595
596 router.insert(&make_point(100, 1.0)).unwrap();
598 router.insert(&make_point(NS_PER_HOUR + 100, 2.0)).unwrap();
600
601 let key = SeriesKey::new(
602 "cpu".to_string(),
603 [("host".to_string(), "a".to_string())]
604 .into_iter()
605 .collect(),
606 )
607 .unwrap();
608
609 let points = router.scan(&key, 0, NS_PER_HOUR * 2);
610 assert_eq!(points.len(), 2);
611 assert!(points[0].timestamp() < points[1].timestamp());
612 }
613
614 #[test]
615 fn total_memory_across_shards() {
616 let dir = tempfile::tempdir().unwrap();
617 let router = ShardRouter::new(test_router_config(dir.path()));
618
619 router.insert(&make_point(100, 1.0)).unwrap();
620 router.insert(&make_point(NS_PER_HOUR + 100, 2.0)).unwrap();
621
622 assert!(router.total_memory() > 0);
623 }
624
625 #[test]
626 fn shard_for_timestamp_computation() {
627 let dir = tempfile::tempdir().unwrap();
628 let router = ShardRouter::new(test_router_config(dir.path()));
629
630 assert_eq!(router.shard_for_timestamp(0), ShardId(0));
631 assert_eq!(router.shard_for_timestamp(NS_PER_HOUR), ShardId(1));
632 assert_eq!(router.shard_for_timestamp(NS_PER_HOUR - 1), ShardId(0));
633 }
634
635 #[test]
636 fn scan_measurement_across_shards() {
637 let dir = tempfile::tempdir().unwrap();
638 let router = ShardRouter::new(test_router_config(dir.path()));
639
640 router
642 .insert(&make_point_with_measurement("cpu", 100, 1.0))
643 .unwrap();
644 router
645 .insert(&make_point_with_measurement("mem", 200, 2.0))
646 .unwrap();
647 router
649 .insert(&make_point_with_measurement("cpu", NS_PER_HOUR + 100, 3.0))
650 .unwrap();
651
652 let cpu = router.scan_measurement("cpu", 0, i64::MAX);
654 assert_eq!(cpu.len(), 2);
655 assert!(cpu.iter().all(|p| p.series_key().measurement() == "cpu"));
656 assert!(cpu[0].timestamp() < cpu[1].timestamp()); let mem = router.scan_measurement("mem", 0, i64::MAX);
660 assert_eq!(mem.len(), 1);
661
662 let none = router.scan_measurement("disk", 0, i64::MAX);
664 assert!(none.is_empty());
665 }
666
667 #[test]
668 fn scan_measurement_respects_time_range() {
669 let dir = tempfile::tempdir().unwrap();
670 let router = ShardRouter::new(test_router_config(dir.path()));
671
672 router
673 .insert(&make_point_with_measurement("cpu", 100, 1.0))
674 .unwrap();
675 router
676 .insert(&make_point_with_measurement("cpu", 200, 2.0))
677 .unwrap();
678 router
679 .insert(&make_point_with_measurement("cpu", 300, 3.0))
680 .unwrap();
681
682 let result = router.scan_measurement("cpu", 150, 250);
683 assert_eq!(result.len(), 1);
684 assert_eq!(result[0].timestamp(), 200);
685 }
686}