1#![allow(unsafe_code)]
4
5use std::ffi::{CStr, c_char, c_void};
6use std::ptr;
7use std::sync::{Arc, Mutex};
8
9use waratah_rocksdb_sys::*;
10use waratah_storage::{IndexPermutation, decode_storage_value, decode_versioned_key};
11
12use crate::LiveQuadsProfile;
13use crate::StatsProfile;
14use crate::observe::{observe_catalog_sst_key, observe_quad};
15use crate::serde_bin::to_bytes;
16use crate::shard::{STATS_USER_PROPERTY_KEY, ShardStats, SstInvalidationFlags};
17
18const TEMPORAL_COLLECTOR_NAME: &CStr = c"WaratahTemporalStatsCollector";
19const TEMPORAL_FACTORY_NAME: &CStr = c"WaratahTemporalStatsCollectorFactory";
20const GEO_COLLECTOR_NAME: &CStr = c"WaratahGeoStatsCollector";
21const GEO_FACTORY_NAME: &CStr = c"WaratahGeoStatsCollectorFactory";
22const COLLECTOR_NAME: &CStr = c"WaratahStatsCollector";
23const FACTORY_NAME: &CStr = c"WaratahStatsCollectorFactory";
24const CATALOG_COLLECTOR_NAME: &CStr = c"WaratahCatalogStatsCollector";
25const CATALOG_FACTORY_NAME: &CStr = c"WaratahCatalogStatsCollectorFactory";
26
27struct FactoryState {
28 permutation: IndexPermutation,
29}
30
31struct CollectorState {
32 permutation: IndexPermutation,
33 profile: LiveQuadsProfile,
37}
38
39unsafe extern "C" fn collector_name(_state: *mut c_void) -> *const c_char {
40 COLLECTOR_NAME.as_ptr()
41}
42
43unsafe extern "C" fn collector_destruct(state: *mut c_void) {
44 if !state.is_null() {
45 drop(unsafe { Box::from_raw(state.cast::<CollectorState>()) });
47 }
48}
49
50unsafe extern "C" fn collector_add(
51 state: *mut c_void,
52 key: *const c_char,
53 key_len: usize,
54 value: *const c_char,
55 value_len: usize,
56 _entry_type: u32,
57 _seq: u64,
58 _file_size: u64,
59) {
60 if state.is_null() || key.is_null() || value.is_null() {
61 return;
62 }
63 let state = unsafe { &mut *state.cast::<CollectorState>() };
65 let key = unsafe { std::slice::from_raw_parts(key.cast::<u8>(), key_len) };
67 let value = unsafe { std::slice::from_raw_parts(value.cast::<u8>(), value_len) };
68 let Ok((quad, _)) = decode_versioned_key(state.permutation, key) else {
69 return;
70 };
71 let Ok((op, _)) = decode_storage_value(value) else {
72 return;
73 };
74 observe_quad(&mut state.profile, &quad, op);
75}
76
77unsafe extern "C" fn collector_finish(
78 state: *mut c_void,
79 props: *mut oxrocksdb_user_collected_properties_t,
80) {
81 if state.is_null() || props.is_null() {
82 return;
83 }
84 let state = unsafe { &*state.cast::<CollectorState>() };
86 let blob = to_bytes(&StatsProfile::from(&state.profile));
87 unsafe {
88 oxrocksdb_user_collected_properties_add(
89 props,
90 STATS_USER_PROPERTY_KEY.as_ptr().cast(),
91 STATS_USER_PROPERTY_KEY.len(),
92 blob.as_ptr().cast(),
93 blob.len(),
94 );
95 }
96}
97
98unsafe extern "C" fn factory_name(_state: *mut c_void) -> *const c_char {
99 FACTORY_NAME.as_ptr()
100}
101
102unsafe extern "C" fn factory_destruct(state: *mut c_void) {
103 if !state.is_null() {
104 drop(unsafe { Box::from_raw(state.cast::<FactoryState>()) });
106 }
107}
108
109unsafe extern "C" fn create_collector(
110 state: *mut c_void,
111 _cf: u32,
112) -> *mut oxrocksdb_table_properties_collector_t {
113 if state.is_null() {
114 return ptr::null_mut();
115 }
116 let factory = unsafe { &*state.cast::<FactoryState>() };
118 let collector_state = Box::into_raw(Box::new(CollectorState {
119 permutation: factory.permutation,
120 profile: LiveQuadsProfile::default(),
121 }));
122 unsafe {
124 oxrocksdb_table_properties_collector_create(
125 collector_state.cast(),
126 Some(collector_name),
127 Some(collector_destruct),
128 Some(collector_add),
129 Some(collector_finish),
130 )
131 }
132}
133
134pub fn attach_stats_collector(perm: IndexPermutation, options: *mut c_void) {
139 if options.is_null() || !perm.is_stats_canonical() {
140 return;
141 }
142 let factory_state = Box::into_raw(Box::new(FactoryState { permutation: perm }));
143 unsafe {
144 let factory = oxrocksdb_table_properties_collector_factory_create(
145 factory_state.cast(),
146 Some(factory_name),
147 Some(factory_destruct),
148 Some(create_collector),
149 );
150 if factory.is_null() {
151 drop(Box::from_raw(factory_state));
152 return;
153 }
154 oxrocksdb_options_add_table_properties_collector_factory(options.cast(), factory);
155 oxrocksdb_table_properties_collector_factory_destroy(factory);
156 }
157}
158
159struct CatalogCollectorState {
160 profile: StatsProfile,
161 last_prefix: Option<Vec<u8>>,
162}
163
164unsafe extern "C" fn catalog_collector_name(_state: *mut c_void) -> *const c_char {
165 CATALOG_COLLECTOR_NAME.as_ptr()
166}
167
168unsafe extern "C" fn catalog_collector_destruct(state: *mut c_void) {
169 if !state.is_null() {
170 drop(unsafe { Box::from_raw(state.cast::<CatalogCollectorState>()) });
172 }
173}
174
175unsafe extern "C" fn catalog_collector_add(
176 state: *mut c_void,
177 key: *const c_char,
178 key_len: usize,
179 value: *const c_char,
180 value_len: usize,
181 _entry_type: u32,
182 _seq: u64,
183 _file_size: u64,
184) {
185 if state.is_null() || key.is_null() || value.is_null() {
186 return;
187 }
188 let state = unsafe { &mut *state.cast::<CatalogCollectorState>() };
190 let key = unsafe { std::slice::from_raw_parts(key.cast::<u8>(), key_len) };
192 let value = unsafe { std::slice::from_raw_parts(value.cast::<u8>(), value_len) };
193 observe_catalog_sst_key(&mut state.profile, &mut state.last_prefix, key, value);
194}
195
196unsafe extern "C" fn catalog_collector_finish(
197 state: *mut c_void,
198 props: *mut oxrocksdb_user_collected_properties_t,
199) {
200 if state.is_null() || props.is_null() {
201 return;
202 }
203 let state = unsafe { &*state.cast::<CatalogCollectorState>() };
205 let blob = to_bytes(&state.profile);
206 unsafe {
207 oxrocksdb_user_collected_properties_add(
208 props,
209 STATS_USER_PROPERTY_KEY.as_ptr().cast(),
210 STATS_USER_PROPERTY_KEY.len(),
211 blob.as_ptr().cast(),
212 blob.len(),
213 );
214 }
215}
216
217unsafe extern "C" fn catalog_factory_name(_state: *mut c_void) -> *const c_char {
218 CATALOG_FACTORY_NAME.as_ptr()
219}
220
221unsafe extern "C" fn catalog_factory_destruct(_state: *mut c_void) {
222 }
224
225unsafe extern "C" fn create_catalog_collector(
226 _state: *mut c_void,
227 _cf: u32,
228) -> *mut oxrocksdb_table_properties_collector_t {
229 let collector_state = Box::into_raw(Box::new(CatalogCollectorState {
230 profile: StatsProfile::default(),
231 last_prefix: None,
232 }));
233 unsafe {
235 oxrocksdb_table_properties_collector_create(
236 collector_state.cast(),
237 Some(catalog_collector_name),
238 Some(catalog_collector_destruct),
239 Some(catalog_collector_add),
240 Some(catalog_collector_finish),
241 )
242 }
243}
244
245struct TemporalCollectorState {
246 histogram: crate::tick_histogram::TickHistogram,
247}
248
249unsafe extern "C" fn temporal_collector_name(_state: *mut c_void) -> *const c_char {
250 TEMPORAL_COLLECTOR_NAME.as_ptr()
251}
252
253unsafe extern "C" fn temporal_collector_destruct(state: *mut c_void) {
254 if !state.is_null() {
255 drop(unsafe { Box::from_raw(state.cast::<TemporalCollectorState>()) });
257 }
258}
259
260unsafe extern "C" fn temporal_collector_add(
261 state: *mut c_void,
262 key: *const c_char,
263 key_len: usize,
264 value: *const c_char,
265 value_len: usize,
266 _entry_type: u32,
267 _seq: u64,
268 _file_size: u64,
269) {
270 if state.is_null() || key.is_null() || value.is_null() {
271 return;
272 }
273 let state = unsafe { &mut *state.cast::<TemporalCollectorState>() };
276 let key = unsafe { std::slice::from_raw_parts(key.cast::<u8>(), key_len) };
278 let value = unsafe { std::slice::from_raw_parts(value.cast::<u8>(), value_len) };
279 if key.len() < 16 || value.len() < 5 {
280 return;
281 }
282 let (op, _) = match decode_storage_value(&value[..5]) {
285 Ok(decoded) => decoded,
286 Err(_) => return,
287 };
288 if op != waratah_storage::StorageOp::Put {
289 return;
290 }
291 let node_key = u128::from_be_bytes(key[..16].try_into().expect("16-byte slice"));
292 state.histogram.observe(node_key);
293}
294
295unsafe extern "C" fn temporal_collector_finish(
296 state: *mut c_void,
297 props: *mut oxrocksdb_user_collected_properties_t,
298) {
299 if state.is_null() || props.is_null() {
300 return;
301 }
302 let state = unsafe { &*state.cast::<TemporalCollectorState>() };
304 let profile = StatsProfile {
308 temporal_histogram: state.histogram.clone(),
309 ..StatsProfile::default()
310 };
311 let blob = to_bytes(&profile);
312 unsafe {
313 oxrocksdb_user_collected_properties_add(
314 props,
315 STATS_USER_PROPERTY_KEY.as_ptr().cast(),
316 STATS_USER_PROPERTY_KEY.len(),
317 blob.as_ptr().cast(),
318 blob.len(),
319 );
320 }
321}
322
323unsafe extern "C" fn temporal_factory_name(_state: *mut c_void) -> *const c_char {
324 TEMPORAL_FACTORY_NAME.as_ptr()
325}
326
327unsafe extern "C" fn temporal_factory_destruct(_state: *mut c_void) {
328 }
330
331unsafe extern "C" fn create_temporal_collector(
332 _state: *mut c_void,
333 _cf: u32,
334) -> *mut oxrocksdb_table_properties_collector_t {
335 let collector_state = Box::into_raw(Box::new(TemporalCollectorState {
336 histogram: crate::tick_histogram::TickHistogram::default(),
337 }));
338 unsafe {
340 oxrocksdb_table_properties_collector_create(
341 collector_state.cast(),
342 Some(temporal_collector_name),
343 Some(temporal_collector_destruct),
344 Some(temporal_collector_add),
345 Some(temporal_collector_finish),
346 )
347 }
348}
349
350pub fn attach_temporal_stats_collector(options: *mut c_void) {
357 if options.is_null() {
358 return;
359 }
360 unsafe {
361 let factory = oxrocksdb_table_properties_collector_factory_create(
362 ptr::null_mut(),
363 Some(temporal_factory_name),
364 Some(temporal_factory_destruct),
365 Some(create_temporal_collector),
366 );
367 if factory.is_null() {
368 return;
369 }
370 oxrocksdb_options_add_table_properties_collector_factory(options.cast(), factory);
371 oxrocksdb_table_properties_collector_factory_destroy(factory);
372 }
373}
374
375struct GeoCollectorState {
376 histogram: crate::geo_cell_histogram::GeoCellHistogram,
377}
378
379unsafe extern "C" fn geo_collector_name(_state: *mut c_void) -> *const c_char {
380 GEO_COLLECTOR_NAME.as_ptr()
381}
382
383unsafe extern "C" fn geo_collector_destruct(state: *mut c_void) {
384 if !state.is_null() {
385 drop(unsafe { Box::from_raw(state.cast::<GeoCollectorState>()) });
387 }
388}
389
390unsafe extern "C" fn geo_collector_add(
391 state: *mut c_void,
392 key: *const c_char,
393 key_len: usize,
394 value: *const c_char,
395 value_len: usize,
396 _entry_type: u32,
397 _seq: u64,
398 _file_size: u64,
399) {
400 if state.is_null() || key.is_null() || value.is_null() {
401 return;
402 }
403 let state = unsafe { &mut *state.cast::<GeoCollectorState>() };
406 let key = unsafe { std::slice::from_raw_parts(key.cast::<u8>(), key_len) };
408 let value = unsafe { std::slice::from_raw_parts(value.cast::<u8>(), value_len) };
409 if key.len() < waratah_storage::GEO_CELL_ID_LEN || value.len() < 5 {
413 return;
414 }
415 let (op, _) = match decode_storage_value(&value[..5]) {
416 Ok(decoded) => decoded,
417 Err(_) => return,
418 };
419 if op != waratah_storage::StorageOp::Put {
420 return;
421 }
422 let cell_id = u64::from_be_bytes(
423 key[..waratah_storage::GEO_CELL_ID_LEN]
424 .try_into()
425 .expect("8-byte slice"),
426 );
427 state.histogram.observe_posting(cell_id);
428}
429
430unsafe extern "C" fn geo_collector_finish(
431 state: *mut c_void,
432 props: *mut oxrocksdb_user_collected_properties_t,
433) {
434 if state.is_null() || props.is_null() {
435 return;
436 }
437 let state = unsafe { &*state.cast::<GeoCollectorState>() };
439 let profile = StatsProfile {
443 geo_cell_histogram: state.histogram.clone(),
444 ..StatsProfile::default()
445 };
446 let blob = to_bytes(&profile);
447 unsafe {
448 oxrocksdb_user_collected_properties_add(
449 props,
450 STATS_USER_PROPERTY_KEY.as_ptr().cast(),
451 STATS_USER_PROPERTY_KEY.len(),
452 blob.as_ptr().cast(),
453 blob.len(),
454 );
455 }
456}
457
458unsafe extern "C" fn geo_factory_name(_state: *mut c_void) -> *const c_char {
459 GEO_FACTORY_NAME.as_ptr()
460}
461
462unsafe extern "C" fn geo_factory_destruct(_state: *mut c_void) {
463 }
465
466unsafe extern "C" fn create_geo_collector(
467 _state: *mut c_void,
468 _cf: u32,
469) -> *mut oxrocksdb_table_properties_collector_t {
470 let collector_state = Box::into_raw(Box::new(GeoCollectorState {
471 histogram: crate::geo_cell_histogram::GeoCellHistogram::default(),
472 }));
473 unsafe {
475 oxrocksdb_table_properties_collector_create(
476 collector_state.cast(),
477 Some(geo_collector_name),
478 Some(geo_collector_destruct),
479 Some(geo_collector_add),
480 Some(geo_collector_finish),
481 )
482 }
483}
484
485pub fn attach_geo_stats_collector(options: *mut c_void) {
494 if options.is_null() {
495 return;
496 }
497 unsafe {
498 let factory = oxrocksdb_table_properties_collector_factory_create(
499 ptr::null_mut(),
500 Some(geo_factory_name),
501 Some(geo_factory_destruct),
502 Some(create_geo_collector),
503 );
504 if factory.is_null() {
505 return;
506 }
507 oxrocksdb_options_add_table_properties_collector_factory(options.cast(), factory);
508 oxrocksdb_table_properties_collector_factory_destroy(factory);
509 }
510}
511
512pub fn attach_catalog_stats_collector(options: *mut c_void) {
517 if options.is_null() {
518 return;
519 }
520 unsafe {
521 let factory = oxrocksdb_table_properties_collector_factory_create(
522 ptr::null_mut(),
523 Some(catalog_factory_name),
524 Some(catalog_factory_destruct),
525 Some(create_catalog_collector),
526 );
527 if factory.is_null() {
528 return;
529 }
530 oxrocksdb_options_add_table_properties_collector_factory(options.cast(), factory);
531 oxrocksdb_table_properties_collector_factory_destroy(factory);
532 }
533}
534
535struct ListenerState {
536 flags: Arc<SstInvalidationFlags>,
537 stats: Arc<Mutex<ShardStats>>,
538 canonical_cf: &'static str,
539 catalog_cf: Option<&'static str>,
540 temporal_cf: Option<&'static str>,
541 geo_cf: Option<&'static str>,
542}
543
544fn cf_name_matches(ptr: *const c_char, len: usize, canonical: &str) -> bool {
545 if ptr.is_null() {
546 return false;
547 }
548 let name = unsafe { std::slice::from_raw_parts(ptr.cast::<u8>(), len) };
550 name == canonical.as_bytes()
551}
552
553fn flush_is_canonical(info: *const rocksdb_flushjobinfo_t, canonical: &str) -> bool {
554 if info.is_null() {
555 return false;
556 }
557 let mut len = 0usize;
558 let ptr = unsafe { rocksdb_flushjobinfo_cf_name(info, &raw mut len) };
560 cf_name_matches(ptr, len, canonical)
561}
562
563fn compaction_is_canonical(info: *const rocksdb_compactionjobinfo_t, canonical: &str) -> bool {
564 if info.is_null() {
565 return false;
566 }
567 let mut len = 0usize;
568 let ptr = unsafe { rocksdb_compactionjobinfo_cf_name(info, &raw mut len) };
570 cf_name_matches(ptr, len, canonical)
571}
572
573unsafe extern "C" fn listener_destruct(state: *mut c_void) {
574 if !state.is_null() {
575 drop(unsafe { Arc::from_raw(state.cast::<ListenerState>()) });
577 }
578}
579
580unsafe extern "C" fn on_flush_begin(
581 state: *mut c_void,
582 _db: *mut rocksdb_t,
583 info: *const rocksdb_flushjobinfo_t,
584) {
585 if state.is_null() {
586 return;
587 }
588 let listener = unsafe { &*state.cast::<ListenerState>() };
590 if flush_is_canonical(info, listener.canonical_cf) {
593 if let Ok(mut stats) = listener.stats.lock() {
594 stats.rotate_on_flush_begin();
595 }
596 return;
597 }
598 if listener
599 .catalog_cf
600 .is_some_and(|name| flush_is_canonical(info, name))
601 && let Ok(mut stats) = listener.stats.lock()
602 {
603 stats.rotate_catalog_on_flush_begin();
604 return;
605 }
606 if listener
607 .temporal_cf
608 .is_some_and(|name| flush_is_canonical(info, name))
609 && let Ok(mut stats) = listener.stats.lock()
610 {
611 stats.rotate_temporal_on_flush_begin();
612 return;
613 }
614 if listener
615 .geo_cf
616 .is_some_and(|name| flush_is_canonical(info, name))
617 && let Ok(mut stats) = listener.stats.lock()
618 {
619 stats.rotate_geo_on_flush_begin();
620 }
621}
622
623unsafe extern "C" fn on_flush_completed(
624 state: *mut c_void,
625 _db: *mut rocksdb_t,
626 info: *const rocksdb_flushjobinfo_t,
627) {
628 if state.is_null() {
629 return;
630 }
631 let listener = unsafe { &*state.cast::<ListenerState>() };
633 if flush_is_canonical(info, listener.canonical_cf) {
634 listener.flags.mark_flush();
635 return;
636 }
637 if listener
638 .catalog_cf
639 .is_some_and(|name| flush_is_canonical(info, name))
640 {
641 listener.flags.mark_catalog_flush();
642 return;
643 }
644 if listener
645 .temporal_cf
646 .is_some_and(|name| flush_is_canonical(info, name))
647 {
648 listener.flags.mark_temporal_flush();
649 return;
650 }
651 if listener
652 .geo_cf
653 .is_some_and(|name| flush_is_canonical(info, name))
654 {
655 listener.flags.mark_geo_flush();
656 }
657}
658
659unsafe extern "C" fn on_compaction_completed(
660 state: *mut c_void,
661 _db: *mut rocksdb_t,
662 info: *const rocksdb_compactionjobinfo_t,
663) {
664 if state.is_null() {
665 return;
666 }
667 let listener = unsafe { &*state.cast::<ListenerState>() };
668 if compaction_is_canonical(info, listener.canonical_cf)
669 || listener
670 .catalog_cf
671 .is_some_and(|name| compaction_is_canonical(info, name))
672 || listener
673 .temporal_cf
674 .is_some_and(|name| compaction_is_canonical(info, name))
675 || listener
676 .geo_cf
677 .is_some_and(|name| compaction_is_canonical(info, name))
678 {
679 listener.flags.mark_compaction();
680 }
681}
682
683pub fn attach_stats_event_listener(
693 options: *mut c_void,
694 flags: Arc<SstInvalidationFlags>,
695 stats: Arc<Mutex<ShardStats>>,
696 canonical: IndexPermutation,
697 catalog_cf: Option<&'static str>,
698 temporal_cf: Option<&'static str>,
699 geo_cf: Option<&'static str>,
700) {
701 if options.is_null() || !canonical.is_stats_canonical() {
702 return;
703 }
704 let listener_ptr = Arc::into_raw(Arc::new(ListenerState {
705 flags,
706 stats,
707 canonical_cf: canonical.cf_name(),
708 catalog_cf,
709 temporal_cf,
710 geo_cf,
711 }));
712 unsafe {
713 let listener = oxrocksdb_eventlistener_create(
714 listener_ptr.cast::<c_void>().cast_mut(),
715 Some(listener_destruct),
716 Some(on_flush_begin),
717 Some(on_flush_completed),
718 None,
719 Some(on_compaction_completed),
720 );
721 if listener.is_null() {
722 drop(Arc::from_raw(listener_ptr));
723 return;
724 }
725 oxrocksdb_options_add_eventlistener(options.cast(), listener);
726 oxrocksdb_eventlistener_destroy(listener);
727 }
728}