1#![warn(missing_docs)]
18
19use std::convert::AsRef;
20use std::ops::Deref;
21use std::path::{Path, PathBuf};
22use std::time::Instant;
23
24use itertools::Itertools;
25use mz_ore::cast::CastFrom;
26use mz_ore::error::ErrorExt;
27use mz_ore::metrics::{DeleteOnDropCounter, DeleteOnDropHistogram};
28use mz_ore::retry::{Retry, RetryResult};
29use prometheus::core::AtomicU64;
30use rocksdb::merge_operator::MergeOperandsIter;
31use rocksdb::{DB, Env, Error as RocksDBError, ErrorKind, Options as RocksDBOptions, WriteOptions};
32use serde::Serialize;
33use serde::de::DeserializeOwned;
34use tokio::sync::{mpsc, oneshot};
35
36pub mod config;
37pub use config::{RocksDBConfig, RocksDBTuningParameters, defaults};
38
39use crate::config::WriteBufferManagerHandle;
40
41type Diff = mz_ore::Overflowing<i64>;
42
43#[derive(Debug, thiserror::Error)]
45pub enum Error {
46 #[error(transparent)]
48 RocksDB(#[from] RocksDBError),
49
50 #[error("RocksDB thread has been shut down or errored")]
53 RocksDBThreadGoneAway,
54
55 #[error("failed to decode value")]
57 DecodeError(#[from] bincode::Error),
58
59 #[error("tokio thread panicked")]
61 TokioPanic(#[from] tokio::task::JoinError),
62
63 #[error("failed to cleanup in time")]
65 CleanupTimeout(#[from] tokio::time::error::Elapsed),
66
67 #[error("error with value: {0}")]
69 ValueError(String),
70}
71
72pub struct ValueIterator<'a, O, V>
76where
77 O: bincode::Options + Copy + Send + Sync + 'static,
78 V: DeserializeOwned + Serialize + Send + Sync + 'static,
79{
80 iter: std::iter::Chain<std::option::IntoIter<&'a [u8]>, MergeOperandsIter<'a>>,
81 bincode: &'a O,
82 v: std::marker::PhantomData<V>,
83}
84
85impl<O, V> Iterator for ValueIterator<'_, O, V>
86where
87 O: bincode::Options + Copy + Send + Sync + 'static,
88 V: DeserializeOwned + Serialize + Send + Sync + 'static,
89{
90 type Item = V;
91
92 fn next(&mut self) -> Option<Self::Item> {
93 self.iter
94 .next()
95 .map(|v| self.bincode.deserialize(v).unwrap())
96 }
97}
98
99pub type StubMergeOperator<V> =
102 fn(key: &[u8], operands: ValueIterator<bincode::DefaultOptions, V>) -> V;
103
104pub struct InstanceOptions<O, V, F> {
107 pub cleanup_on_new: bool,
110
111 pub cleanup_tries: usize,
113
114 pub use_wal: bool,
118
119 pub env: Env,
121
122 pub bincode: O,
124
125 pub merge_operator: Option<(String, F)>,
129
130 v: std::marker::PhantomData<V>,
131}
132
133impl<O, V, F> InstanceOptions<O, V, F>
134where
135 O: bincode::Options + Copy + Send + Sync + 'static,
136 V: DeserializeOwned + Serialize + Send + Sync + 'static,
137 F: for<'a> Fn(&'a [u8], ValueIterator<'a, O, V>) -> V + Copy + Send + Sync + 'static,
138{
139 pub fn new(
141 env: rocksdb::Env,
142 cleanup_tries: usize,
143 merge_operator: Option<(String, F)>,
144 bincode: O,
145 ) -> Self {
146 InstanceOptions {
147 cleanup_on_new: true,
148 cleanup_tries,
149 use_wal: false,
150 env,
151 merge_operator,
152 bincode,
153 v: std::marker::PhantomData,
154 }
155 }
156
157 fn as_rocksdb_options(
158 &self,
159 tuning_config: &RocksDBConfig,
160 ) -> (RocksDBOptions, Option<WriteBufferManagerHandle>) {
161 let mut options = rocksdb::Options::default();
163 options.create_if_missing(true);
164
165 options.set_env(&self.env);
167
168 if let Some((fn_name, merge_fn)) = &self.merge_operator {
169 let bincode = self.bincode.clone();
170 let merge_fn = merge_fn.clone();
171 options.set_merge_operator_associative(fn_name, move |key, existing, operands| {
176 let operands = ValueIterator {
177 iter: existing.into_iter().chain(operands.iter()),
178 bincode: &bincode,
179 v: std::marker::PhantomData::<V>,
180 };
181 let result = merge_fn(key, operands);
182 Some(bincode.serialize(&result).unwrap())
185 });
186 }
187
188 let write_buffer_handle = config::apply_to_options(tuning_config, &mut options);
189 (options, write_buffer_handle)
192 }
193
194 fn as_rocksdb_write_options(&self) -> WriteOptions {
195 let mut wo = rocksdb::WriteOptions::new();
196 wo.disable_wal(!self.use_wal);
197 wo
198 }
199}
200
201pub struct RocksDBSharedMetrics {
204 pub multi_get_latency: DeleteOnDropHistogram<Vec<String>>,
206 pub multi_put_latency: DeleteOnDropHistogram<Vec<String>>,
208}
209
210pub struct RocksDBInstanceMetrics {
213 pub multi_get_size: DeleteOnDropCounter<AtomicU64, Vec<String>>,
215 pub multi_get_result_count: DeleteOnDropCounter<AtomicU64, Vec<String>>,
217 pub multi_get_result_bytes: DeleteOnDropCounter<AtomicU64, Vec<String>>,
219 pub multi_get_count: DeleteOnDropCounter<AtomicU64, Vec<String>>,
221 pub multi_put_count: DeleteOnDropCounter<AtomicU64, Vec<String>>,
223 pub multi_put_size: DeleteOnDropCounter<AtomicU64, Vec<String>>,
225}
226
227#[derive(Default, Debug)]
229pub struct MultiGetResult {
230 pub processed_gets: u64,
232 pub processed_gets_size: u64,
234 pub returned_gets: u64,
236}
237
238#[derive(Debug, Default, Clone)]
240pub struct GetResult<V> {
241 pub value: V,
243 pub size: u64,
246}
247
248#[derive(Default, Debug)]
250pub struct MultiUpdateResult {
251 pub processed_updates: u64,
253 pub size_written: u64,
256 pub size_diff: Option<Diff>,
260}
261
262#[derive(Debug)]
264pub enum KeyUpdate<V> {
265 Put(V),
267 Merge(V),
270 Delete,
272}
273
274#[derive(Debug)]
275enum Command<K, V> {
276 MultiGet {
277 batch: Vec<K>,
278 results_scratch: Vec<Option<GetResult<V>>>,
280 response_sender: oneshot::Sender<
281 Result<
282 (
283 MultiGetResult,
284 Vec<K>,
286 Vec<Option<GetResult<V>>>,
287 ),
288 Error,
289 >,
290 >,
291 },
292 MultiUpdate {
293 batch: Vec<(K, KeyUpdate<V>, Option<Diff>)>,
297 response_sender: oneshot::Sender<
299 Result<(MultiUpdateResult, Vec<(K, KeyUpdate<V>, Option<Diff>)>), Error>,
300 >,
301 },
302 Shutdown {
303 done_sender: oneshot::Sender<()>,
304 },
305 ManualCompaction {
306 done_sender: oneshot::Sender<()>,
307 },
308}
309
310pub struct RocksDBInstance<K, V> {
312 tx: mpsc::Sender<Command<K, V>>,
313
314 multi_get_scratch: Vec<K>,
317
318 multi_get_results_scratch: Vec<Option<GetResult<V>>>,
321
322 multi_update_scratch: Vec<(K, KeyUpdate<V>, Option<Diff>)>,
325
326 dynamic_config: config::RocksDBDynamicConfig,
328
329 pub supports_merges: bool,
332}
333
334impl<K, V> RocksDBInstance<K, V>
335where
336 K: AsRef<[u8]> + Send + Sync + 'static,
337 V: Serialize + DeserializeOwned + Send + Sync + 'static,
338{
339 pub fn new<M, O, IM, F>(
347 instance_path: &Path,
348 options: InstanceOptions<O, V, F>,
349 tuning_config: RocksDBConfig,
350 shared_metrics: M,
351 instance_metrics: IM,
352 ) -> Result<Self, Error>
353 where
354 O: bincode::Options + Copy + Send + Sync + 'static,
355 M: Deref<Target = RocksDBSharedMetrics> + Send + 'static,
356 IM: Deref<Target = RocksDBInstanceMetrics> + Send + 'static,
357 F: for<'a> Fn(&'a [u8], ValueIterator<'a, O, V>) -> V + Copy + Send + Sync + 'static,
358 {
359 let dynamic_config = tuning_config.dynamic.clone();
360 let supports_merges = options.merge_operator.is_some();
361
362 let (tx, rx): (mpsc::Sender<Command<K, V>>, _) = mpsc::channel(10);
364
365 let instance_path = instance_path.to_owned();
366 std::thread::spawn(move || {
372 rocksdb_core_loop(
373 options,
374 tuning_config,
375 instance_path,
376 rx,
377 shared_metrics,
378 instance_metrics,
379 )
380 });
381
382 Ok(Self {
383 tx,
384 multi_get_scratch: Vec::new(),
385 multi_get_results_scratch: Vec::new(),
386 multi_update_scratch: Vec::new(),
387 dynamic_config,
388 supports_merges,
389 })
390 }
391
392 pub async fn multi_get<'r, G, R, Ret, Placement>(
396 &mut self,
397 gets: G,
398 results_out: R,
399 placement: Placement,
400 ) -> Result<MultiGetResult, Error>
401 where
402 G: IntoIterator<Item = K>,
403 R: IntoIterator<Item = &'r mut Ret>,
404 Ret: 'r,
405 Placement: Fn(Option<GetResult<V>>) -> Ret,
406 {
407 let batch_size = self.dynamic_config.batch_size();
408 let mut stats = MultiGetResult::default();
409
410 let mut gets = gets.into_iter().peekable();
411 if gets.peek().is_some() {
412 let gets = gets.chunks(batch_size);
413 let results_out = results_out.into_iter().chunks(batch_size);
414
415 for (gets, results_out) in gets.into_iter().zip_eq(results_out.into_iter()) {
416 let ret = self.multi_get_inner(gets, results_out, &placement).await?;
417 stats.processed_gets += ret.processed_gets;
418 }
419 }
420
421 Ok(stats)
422 }
423
424 async fn multi_get_inner<'r, G, R, Ret, Placement>(
425 &mut self,
426 gets: G,
427 results_out: R,
428 placement: &Placement,
429 ) -> Result<MultiGetResult, Error>
430 where
431 G: IntoIterator<Item = K>,
432 R: IntoIterator<Item = &'r mut Ret>,
433 Ret: 'r,
434 Placement: Fn(Option<GetResult<V>>) -> Ret,
435 {
436 let mut multi_get_vec = std::mem::take(&mut self.multi_get_scratch);
437 let mut results_vec = std::mem::take(&mut self.multi_get_results_scratch);
438 multi_get_vec.clear();
439 results_vec.clear();
440
441 multi_get_vec.extend(gets);
442 if multi_get_vec.is_empty() {
443 self.multi_get_scratch = multi_get_vec;
444 self.multi_get_results_scratch = results_vec;
445 return Ok(MultiGetResult {
446 processed_gets: 0,
447 processed_gets_size: 0,
448 returned_gets: 0,
449 });
450 }
451
452 let (tx, rx) = oneshot::channel();
453 self.tx
454 .send(Command::MultiGet {
455 batch: multi_get_vec,
456 results_scratch: results_vec,
457 response_sender: tx,
458 })
459 .await
460 .map_err(|_| Error::RocksDBThreadGoneAway)?;
461
462 match rx.await.map_err(|_| Error::RocksDBThreadGoneAway)? {
464 Ok((ret, get_scratch, mut results_scratch)) => {
465 for (place, get) in results_out.into_iter().zip_eq(results_scratch.drain(..)) {
466 *place = placement(get);
467 }
468 self.multi_get_scratch = get_scratch;
469 self.multi_get_results_scratch = results_scratch;
470 Ok(ret)
471 }
472 Err(e) => {
473 Err(e)
475 }
476 }
477 }
478
479 pub async fn multi_update<P>(&mut self, puts: P) -> Result<MultiUpdateResult, Error>
486 where
487 P: IntoIterator<Item = (K, KeyUpdate<V>, Option<Diff>)>,
488 {
489 let batch_size = self.dynamic_config.batch_size();
490 let mut stats = MultiUpdateResult::default();
491
492 let mut puts = puts.into_iter().peekable();
493 if puts.peek().is_some() {
494 let puts = puts.chunks(batch_size);
495
496 for puts in puts.into_iter() {
497 let ret = self.multi_update_inner(puts).await?;
498 stats.processed_updates += ret.processed_updates;
499 stats.size_written += ret.size_written;
500 if let Some(diff) = ret.size_diff {
501 stats.size_diff = Some(stats.size_diff.unwrap_or(Diff::ZERO) + diff);
502 }
503 }
504 }
505
506 Ok(stats)
507 }
508
509 async fn multi_update_inner<P>(&mut self, updates: P) -> Result<MultiUpdateResult, Error>
510 where
511 P: IntoIterator<Item = (K, KeyUpdate<V>, Option<Diff>)>,
512 {
513 let mut multi_put_vec = std::mem::take(&mut self.multi_update_scratch);
514 multi_put_vec.clear();
515
516 multi_put_vec.extend(updates);
517 if multi_put_vec.is_empty() {
518 self.multi_update_scratch = multi_put_vec;
519 return Ok(MultiUpdateResult {
520 processed_updates: 0,
521 size_written: 0,
522 size_diff: None,
523 });
524 }
525
526 let (tx, rx) = oneshot::channel();
527 self.tx
528 .send(Command::MultiUpdate {
529 batch: multi_put_vec,
530 response_sender: tx,
531 })
532 .await
533 .map_err(|_| Error::RocksDBThreadGoneAway)?;
534
535 match rx.await.map_err(|_| Error::RocksDBThreadGoneAway)? {
537 Ok((ret, scratch)) => {
538 self.multi_update_scratch = scratch;
539 Ok(ret)
540 }
541 Err(e) => {
542 Err(e)
544 }
545 }
546 }
547
548 pub async fn manual_compaction(&self) -> Result<(), Error> {
550 let (tx, rx) = oneshot::channel();
551 self.tx
552 .send(Command::ManualCompaction { done_sender: tx })
553 .await
554 .map_err(|_| Error::RocksDBThreadGoneAway)?;
555
556 rx.await.map_err(|_| Error::RocksDBThreadGoneAway)
557 }
558
559 pub async fn close(self) -> Result<(), Error> {
562 let (tx, rx) = oneshot::channel();
563 self.tx
564 .send(Command::Shutdown { done_sender: tx })
565 .await
566 .map_err(|_| Error::RocksDBThreadGoneAway)?;
567
568 let _ = rx.await;
569
570 Ok(())
571 }
572}
573
574fn rocksdb_core_loop<K, V, M, O, IM, F>(
575 options: InstanceOptions<O, V, F>,
576 tuning_config: RocksDBConfig,
577 instance_path: PathBuf,
578 mut cmd_rx: mpsc::Receiver<Command<K, V>>,
579 shared_metrics: M,
580 instance_metrics: IM,
581) where
582 K: AsRef<[u8]> + Send + Sync + 'static,
583 V: Serialize + DeserializeOwned + Send + Sync + 'static,
584 M: Deref<Target = RocksDBSharedMetrics> + Send + 'static,
585 O: bincode::Options + Copy + Send + Sync + 'static,
586 F: for<'a> Fn(&'a [u8], ValueIterator<'a, O, V>) -> V + Send + Sync + Copy + 'static,
587 IM: Deref<Target = RocksDBInstanceMetrics> + Send + 'static,
588{
589 if options.cleanup_on_new && instance_path.exists() {
590 let retry = mz_ore::retry::Retry::default()
594 .max_tries(options.cleanup_tries)
595 .initial_backoff(std::time::Duration::from_secs(1));
597
598 let destroy_result = retry.retry(|_rs| {
599 if let Err(e) = DB::destroy(&RocksDBOptions::default(), &*instance_path) {
600 tracing::warn!(
601 "failed to cleanup rocksdb dir on creation {}: {}",
602 instance_path.display(),
603 e.display_with_causes(),
604 );
605 RetryResult::RetryableErr(Error::from(e))
606 } else {
607 RetryResult::Ok(())
608 }
609 });
610 if let Err(e) = destroy_result {
611 tracing::error!(
612 "retries exhausted trying to cleanup rocksdb dir on creation {}: {}",
613 instance_path.display(),
614 e.display_with_causes(),
615 );
616 return;
617 }
618 }
619
620 let retry_max_duration = tuning_config.retry_max_duration;
621
622 let (rocksdb_options, write_buffer_handle) = options.as_rocksdb_options(&tuning_config);
627 tracing::info!(
628 "Starting rocksdb at {:?} with write_buffer_manager: {:?}",
629 instance_path,
630 write_buffer_handle
631 );
632
633 let retry_result = Retry::default()
634 .max_duration(retry_max_duration)
635 .retry(|_| match DB::open(&rocksdb_options, &instance_path) {
636 Ok(db) => RetryResult::Ok(db),
637 Err(e) => match e.kind() {
638 ErrorKind::TryAgain => RetryResult::RetryableErr(Error::RocksDB(e)),
639 _ => RetryResult::FatalErr(Error::RocksDB(e)),
640 },
641 });
642
643 let db: DB = match retry_result {
644 Ok(db) => db,
645 Err(e) => {
646 tracing::error!(
647 "failed to create rocksdb at {}: {}",
648 instance_path.display(),
649 e.display_with_causes(),
650 );
651 return;
652 }
653 };
654
655 let mut encoded_batch_buffers: Vec<Option<Vec<u8>>> = Vec::new();
656 let mut encoded_batch: Vec<(K, KeyUpdate<Vec<u8>>)> = Vec::new();
657
658 let wo = options.as_rocksdb_write_options();
659 while let Some(cmd) = cmd_rx.blocking_recv() {
660 match cmd {
661 Command::Shutdown { done_sender } => {
662 shutdown_and_cleanup(db, &instance_path);
663 drop(write_buffer_handle);
664 let _ = done_sender.send(());
665 return;
666 }
667 Command::ManualCompaction { done_sender } => {
668 db.compact_range::<&[u8], &[u8]>(None, None);
670 let _ = done_sender.send(());
671 }
672 Command::MultiGet {
673 mut batch,
674 mut results_scratch,
675 response_sender,
676 } => {
677 let batch_size = batch.len();
678
679 let now = Instant::now();
681 let retry_result = Retry::default()
682 .max_duration(retry_max_duration)
683 .retry(|_| {
684 let gets = db.multi_get(batch.iter());
685 let latency = now.elapsed();
686
687 let gets: Result<Vec<_>, _> = gets.into_iter().collect();
688 match gets {
689 Ok(gets) => {
690 shared_metrics
691 .multi_get_latency
692 .observe(latency.as_secs_f64());
693 instance_metrics
694 .multi_get_size
695 .inc_by(batch_size.try_into().unwrap());
696 instance_metrics.multi_get_count.inc();
697
698 RetryResult::Ok(gets)
699 }
700 Err(e) => match e.kind() {
701 ErrorKind::TryAgain => RetryResult::RetryableErr(Error::RocksDB(e)),
702 _ => RetryResult::FatalErr(Error::RocksDB(e)),
703 },
704 }
705 });
706
707 let _ = match retry_result {
708 Ok(gets) => {
709 let processed_gets: u64 = gets.len().try_into().unwrap();
710 let mut processed_gets_size = 0;
711 let mut returned_gets: u64 = 0;
712 for previous_value in gets {
713 let get_result = match previous_value {
714 Some(previous_value) => {
715 match options.bincode.deserialize(&previous_value) {
716 Ok(value) => {
717 let size = u64::cast_from(previous_value.len());
718 processed_gets_size += size;
719 returned_gets += 1;
720 Some(GetResult { value, size })
721 }
722 Err(e) => {
723 let _ =
724 response_sender.send(Err(Error::DecodeError(e)));
725 return;
726 }
727 }
728 }
729 None => None,
730 };
731 results_scratch.push(get_result);
732 }
733
734 instance_metrics
735 .multi_get_result_count
736 .inc_by(returned_gets);
737 instance_metrics
738 .multi_get_result_bytes
739 .inc_by(processed_gets_size);
740 batch.clear();
741 response_sender.send(Ok((
742 MultiGetResult {
743 processed_gets,
744 processed_gets_size,
745 returned_gets,
746 },
747 batch,
748 results_scratch,
749 )))
750 }
751 Err(e) => response_sender.send(Err(e)),
752 };
753 }
754 Command::MultiUpdate {
755 mut batch,
756 response_sender,
757 } => {
758 let batch_size = batch.len();
759
760 let mut ret = MultiUpdateResult {
761 processed_updates: 0,
762 size_written: 0,
763 size_diff: None,
764 };
765
766 let buf_size = encoded_batch_buffers.len();
768 for _ in buf_size..batch_size {
769 encoded_batch_buffers.push(Some(Vec::new()));
770 }
771 if tuning_config.shrink_buffers_by_ratio > 0 {
774 let reduced_capacity =
775 encoded_batch_buffers.capacity() / tuning_config.shrink_buffers_by_ratio;
776 if reduced_capacity > batch_size {
777 encoded_batch_buffers.truncate(reduced_capacity);
778 encoded_batch_buffers.shrink_to(reduced_capacity);
779
780 encoded_batch.truncate(reduced_capacity);
781 encoded_batch.shrink_to(reduced_capacity);
782 }
783 }
784 assert!(encoded_batch_buffers.len() >= batch_size);
785
786 for ((key, value, diff), encode_buf) in
788 batch.drain(..).zip(encoded_batch_buffers.iter_mut())
789 {
790 ret.processed_updates += 1;
791
792 match &value {
793 update_type @ (KeyUpdate::Put(update) | KeyUpdate::Merge(update)) => {
794 let mut encode_buf =
795 encode_buf.take().expect("encode_buf should not be empty");
796 encode_buf.clear();
797 match options
798 .bincode
799 .serialize_into::<&mut Vec<u8>, _>(&mut encode_buf, update)
800 {
801 Ok(()) => {
802 ret.size_written += u64::cast_from(encode_buf.len());
803 if let Some(diff) = diff {
805 let encoded_len = Diff::try_from(encode_buf.len())
806 .expect("less than i64 size");
807 ret.size_diff = Some(
808 ret.size_diff.unwrap_or(Diff::ZERO)
809 + (diff * encoded_len),
810 );
811 }
812 }
813 Err(e) => {
814 let _ = response_sender.send(Err(Error::DecodeError(e)));
815 return;
816 }
817 };
818 if matches!(update_type, KeyUpdate::Put(_)) {
819 encoded_batch.push((key, KeyUpdate::Put(encode_buf)));
820 } else {
821 encoded_batch.push((key, KeyUpdate::Merge(encode_buf)));
822 }
823 }
824 KeyUpdate::Delete => encoded_batch.push((key, KeyUpdate::Delete)),
825 }
826 }
827 let now = Instant::now();
829 let retry_result = Retry::default()
830 .max_duration(retry_max_duration)
831 .retry(|_| {
832 let mut writes = rocksdb::WriteBatch::default();
833
834 for (key, value) in encoded_batch.iter() {
835 match value {
836 KeyUpdate::Put(update) => writes.put(key, update),
837 KeyUpdate::Merge(update) => writes.merge(key, update),
838 KeyUpdate::Delete => writes.delete(key),
839 }
840 }
841
842 match db.write_opt(writes, &wo) {
843 Ok(()) => {
844 let latency = now.elapsed();
845 shared_metrics
846 .multi_put_latency
847 .observe(latency.as_secs_f64());
848 instance_metrics
849 .multi_put_size
850 .inc_by(batch_size.try_into().unwrap());
851 instance_metrics.multi_put_count.inc();
852 RetryResult::Ok(())
853 }
854 Err(e) => match e.kind() {
855 ErrorKind::TryAgain => RetryResult::RetryableErr(Error::RocksDB(e)),
856 _ => RetryResult::FatalErr(Error::RocksDB(e)),
857 },
858 }
859 });
860
861 for (i, (_, encoded_buffer)) in encoded_batch.drain(..).enumerate() {
863 if let KeyUpdate::Put(encoded_buffer) | KeyUpdate::Merge(encoded_buffer) =
864 encoded_buffer
865 {
866 encoded_batch_buffers[i] = Some(encoded_buffer);
867 }
868 }
869
870 match retry_result {
871 Ok(()) => {
872 batch.clear();
873 let _ = response_sender.send(Ok((ret, batch)));
874 }
875 Err(e) => {
876 let db_err = match e {
877 Error::RocksDB(ref inner) => Some(inner.clone()),
878 _ => None,
879 };
880 let _ = response_sender.send(Err(e));
881 if let Some(db_err) = db_err {
882 if !matches!(db_err.kind(), ErrorKind::TryAgain) {
883 tracing::warn!(
884 "exiting on fatal rocksdb error at {}: {}",
885 instance_path.display(),
886 db_err.display_with_causes(),
887 );
888 break;
889 }
890 }
891 }
892 };
893 }
894 }
895 }
896 shutdown_and_cleanup(db, &instance_path);
897}
898
899fn shutdown_and_cleanup(db: DB, instance_path: &PathBuf) {
900 db.cancel_all_background_work(true);
902 drop(db);
903 tracing::info!("dropped rocksdb at {}", instance_path.display());
904
905 if let Err(e) = DB::destroy(&RocksDBOptions::default(), &*instance_path) {
907 tracing::warn!(
908 "failed to cleanup rocksdb dir at {}: {}",
909 instance_path.display(),
910 e.display_with_causes(),
911 );
912 }
913}