Skip to main content

risingwave_storage/
store_impl.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashSet;
16use std::fmt::Debug;
17use std::sync::{Arc, LazyLock};
18use std::time::Duration;
19
20use enum_as_inner::EnumAsInner;
21use foyer::{
22    BlockEngineConfig, CacheBuilder, DeviceBuilder, FifoPicker, FsDeviceBuilder, HybridCacheBuilder,
23};
24use futures::FutureExt;
25use futures::future::BoxFuture;
26use mixtrics::registry::prometheus::PrometheusMetricsRegistry;
27use risingwave_common::catalog::TableId;
28use risingwave_common::config::Role;
29use risingwave_common::config::storage::FileCacheRuntimeConfig;
30use risingwave_common::license::Feature;
31use risingwave_common::monitor::GLOBAL_METRICS_REGISTRY;
32use risingwave_common_service::RpcNotificationClient;
33use risingwave_hummock_sdk::{HummockEpoch, HummockSstableObjectId, SyncResult};
34use risingwave_object_store::object::build_remote_object_store;
35use thiserror_ext::AsReport;
36
37use crate::StateStore;
38use crate::compaction_catalog_manager::{CompactionCatalogManager, RemoteTableAccessor};
39use crate::error::StorageResult;
40use crate::hummock::all::AllRecentFilter;
41use crate::hummock::hummock_meta_client::MonitoredHummockMetaClient;
42use crate::hummock::none::NoneRecentFilter;
43use crate::hummock::sharded::ShardedRecentFilter;
44use crate::hummock::simple::SimpleRecentFilter;
45use crate::hummock::{
46    Block, BlockCacheEventListener, HummockError, HummockStorage, SstableBlockIndex,
47    SstableMetaCacheValue, SstableStore, SstableStoreConfig,
48};
49use crate::memory::MemoryStateStore;
50use crate::memory::sled::SledStateStore;
51use crate::monitor::{
52    CompactorMetrics, HummockStateStoreMetrics, MonitoredStateStore, MonitoredStorageMetrics,
53    ObjectStoreMetrics,
54};
55use crate::opts::StorageOpts;
56
57fn build_file_cache_spawner(
58    name: &str,
59    config: &FileCacheRuntimeConfig,
60) -> StorageResult<foyer::Spawner> {
61    let config = match config {
62        FileCacheRuntimeConfig::Disabled => return Ok(foyer::Spawner::current()),
63        FileCacheRuntimeConfig::Unified(config) => config.clone(),
64        FileCacheRuntimeConfig::Separated { .. } => {
65            return Err(HummockError::other(format!(
66                "{name} runtime_config.Separated is unsupported with Foyer 0.22; use runtime_config.Unified instead"
67            ))
68            .into());
69        }
70    };
71
72    let mut builder = tokio::runtime::Builder::new_multi_thread();
73    #[cfg(madsim)]
74    let _ = &config;
75    #[cfg(not(madsim))]
76    if config.worker_threads != 0 {
77        builder.worker_threads(config.worker_threads);
78    }
79    #[cfg(not(madsim))]
80    if config.max_blocking_threads != 0 {
81        builder.max_blocking_threads(config.max_blocking_threads);
82    }
83    builder.thread_name(format!("{name}-unified"));
84    let runtime = builder.enable_all().build().map_err(|error| {
85        HummockError::other(format!(
86            "failed to build {name} dedicated runtime: {}",
87            error.as_report()
88        ))
89    })?;
90    Ok(runtime.into())
91}
92
93#[cfg(test)]
94mod tests {
95    use risingwave_common::config::storage::FileCacheTokioRuntimeConfig;
96
97    use super::*;
98
99    #[test]
100    fn test_build_file_cache_spawner_rejects_separated_runtime() {
101        let runtime_options = FileCacheTokioRuntimeConfig {
102            worker_threads: 1,
103            max_blocking_threads: 1,
104        };
105        let error = build_file_cache_spawner(
106            "foyer.test",
107            &FileCacheRuntimeConfig::Separated {
108                read_runtime_options: runtime_options.clone(),
109                write_runtime_options: runtime_options,
110            },
111        )
112        .unwrap_err()
113        .to_string();
114
115        assert!(error.contains("foyer.test runtime_config.Separated"));
116        assert!(error.contains("use runtime_config.Unified instead"));
117    }
118
119    #[cfg(not(madsim))]
120    #[tokio::test]
121    async fn test_build_file_cache_spawner_runtime_modes() {
122        let current_runtime_id = tokio::runtime::Handle::current().id();
123
124        let disabled =
125            build_file_cache_spawner("foyer.test", &FileCacheRuntimeConfig::Disabled).unwrap();
126        let disabled_runtime_id = disabled
127            .spawn(async { tokio::runtime::Handle::current().id() })
128            .await
129            .unwrap();
130        assert_eq!(disabled_runtime_id, current_runtime_id);
131
132        let unified = build_file_cache_spawner(
133            "foyer.test",
134            &FileCacheRuntimeConfig::Unified(FileCacheTokioRuntimeConfig {
135                worker_threads: 1,
136                max_blocking_threads: 1,
137            }),
138        )
139        .unwrap();
140        let (unified_runtime_id, thread_name) = unified
141            .spawn(async {
142                (
143                    tokio::runtime::Handle::current().id(),
144                    std::thread::current().name().map(str::to_owned),
145                )
146            })
147            .await
148            .unwrap();
149
150        assert_ne!(unified_runtime_id, current_runtime_id);
151        assert_eq!(thread_name.as_deref(), Some("foyer.test-unified"));
152    }
153}
154
155static FOYER_METRICS_REGISTRY: LazyLock<Box<PrometheusMetricsRegistry>> = LazyLock::new(|| {
156    Box::new(PrometheusMetricsRegistry::new(
157        GLOBAL_METRICS_REGISTRY.clone(),
158    ))
159});
160
161mod opaque_type {
162    use super::*;
163
164    pub type HummockStorageType = impl StateStore + AsHummock;
165    pub type MemoryStateStoreType = impl StateStore + AsHummock;
166    pub type SledStateStoreType = impl StateStore + AsHummock;
167
168    #[define_opaque(MemoryStateStoreType)]
169    pub fn in_memory(state_store: MemoryStateStore) -> MemoryStateStoreType {
170        may_dynamic_dispatch(state_store)
171    }
172
173    #[define_opaque(HummockStorageType)]
174    pub fn hummock(state_store: HummockStorage) -> HummockStorageType {
175        may_dynamic_dispatch(may_verify(state_store))
176    }
177
178    #[define_opaque(SledStateStoreType)]
179    pub fn sled(state_store: SledStateStore) -> SledStateStoreType {
180        may_dynamic_dispatch(state_store)
181    }
182}
183pub use opaque_type::{HummockStorageType, MemoryStateStoreType, SledStateStoreType};
184use opaque_type::{hummock, in_memory, sled};
185
186#[cfg(feature = "hm-trace")]
187type Monitored<S> = MonitoredStateStore<crate::monitor::traced_store::TracedStateStore<S>>;
188
189#[cfg(not(feature = "hm-trace"))]
190type Monitored<S> = MonitoredStateStore<S>;
191
192fn monitored<S: StateStore>(
193    state_store: S,
194    storage_metrics: Arc<MonitoredStorageMetrics>,
195) -> Monitored<S> {
196    let inner = {
197        #[cfg(feature = "hm-trace")]
198        {
199            crate::monitor::traced_store::TracedStateStore::new_global(state_store)
200        }
201        #[cfg(not(feature = "hm-trace"))]
202        {
203            state_store
204        }
205    };
206    inner.monitored(storage_metrics)
207}
208
209fn inner<S>(state_store: &Monitored<S>) -> &S {
210    let inner = state_store.inner();
211    {
212        #[cfg(feature = "hm-trace")]
213        {
214            inner.inner()
215        }
216        #[cfg(not(feature = "hm-trace"))]
217        {
218            inner
219        }
220    }
221}
222
223/// The type erased [`StateStore`].
224#[derive(Clone, EnumAsInner)]
225#[expect(clippy::enum_variant_names)]
226pub enum StateStoreImpl {
227    /// The Hummock state store, which operates on an S3-like service. URLs beginning with
228    /// `hummock` will be automatically recognized as Hummock state store.
229    ///
230    /// Example URLs:
231    ///
232    /// * `hummock+s3://bucket`
233    /// * `hummock+minio://KEY:SECRET@minio-ip:port`
234    /// * `hummock+memory` (should only be used in 1 compute node mode)
235    HummockStateStore(Monitored<HummockStorageType>),
236    /// In-memory B-Tree state store. Should only be used in unit and integration tests. If you
237    /// want speed up e2e test, you should use Hummock in-memory mode instead. Also, this state
238    /// store misses some critical implementation to ensure the correctness of persisting streaming
239    /// state. (e.g., no `read_epoch` support, no async checkpoint)
240    MemoryStateStore(Monitored<MemoryStateStoreType>),
241    SledStateStore(Monitored<SledStateStoreType>),
242}
243
244fn may_dynamic_dispatch(state_store: impl StateStore + AsHummock) -> impl StateStore + AsHummock {
245    #[cfg(not(debug_assertions))]
246    {
247        state_store
248    }
249    #[cfg(debug_assertions)]
250    {
251        use crate::store_impl::dyn_state_store::StateStorePointer;
252        StateStorePointer(Arc::new(state_store) as _)
253    }
254}
255
256fn may_verify(state_store: impl StateStore + AsHummock) -> impl StateStore + AsHummock {
257    #[cfg(not(debug_assertions))]
258    {
259        state_store
260    }
261    #[cfg(debug_assertions)]
262    {
263        use std::marker::PhantomData;
264
265        use risingwave_common::util::env_var::env_var_is_true;
266        use tracing::info;
267
268        use crate::store_impl::verify::VerifyStateStore;
269
270        let expected = if env_var_is_true("ENABLE_STATE_STORE_VERIFY") {
271            info!("enable verify state store");
272            Some(SledStateStore::new_temp())
273        } else {
274            info!("verify state store is not enabled");
275            None
276        };
277        VerifyStateStore {
278            actual: state_store,
279            expected,
280            _phantom: PhantomData::<()>,
281        }
282    }
283}
284
285impl StateStoreImpl {
286    fn in_memory(
287        state_store: MemoryStateStore,
288        storage_metrics: Arc<MonitoredStorageMetrics>,
289    ) -> Self {
290        // The specific type of MemoryStateStoreType in deducted here.
291        Self::MemoryStateStore(monitored(in_memory(state_store), storage_metrics))
292    }
293
294    pub fn hummock(
295        state_store: HummockStorage,
296        storage_metrics: Arc<MonitoredStorageMetrics>,
297    ) -> Self {
298        // The specific type of HummockStateStoreType in deducted here.
299        Self::HummockStateStore(monitored(hummock(state_store), storage_metrics))
300    }
301
302    pub fn sled(
303        state_store: SledStateStore,
304        storage_metrics: Arc<MonitoredStorageMetrics>,
305    ) -> Self {
306        Self::SledStateStore(monitored(sled(state_store), storage_metrics))
307    }
308
309    pub fn shared_in_memory_store(storage_metrics: Arc<MonitoredStorageMetrics>) -> Self {
310        Self::in_memory(MemoryStateStore::shared(), storage_metrics)
311    }
312
313    pub fn for_test() -> Self {
314        Self::in_memory(
315            MemoryStateStore::new(),
316            Arc::new(MonitoredStorageMetrics::unused()),
317        )
318    }
319
320    pub fn as_hummock(&self) -> Option<&HummockStorage> {
321        match self {
322            StateStoreImpl::HummockStateStore(hummock) => {
323                Some(inner(hummock).as_hummock().expect("should be hummock"))
324            }
325            _ => None,
326        }
327    }
328}
329
330impl Debug for StateStoreImpl {
331    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332        match self {
333            StateStoreImpl::HummockStateStore(_) => write!(f, "HummockStateStore"),
334            StateStoreImpl::MemoryStateStore(_) => write!(f, "MemoryStateStore"),
335            StateStoreImpl::SledStateStore(_) => write!(f, "SledStateStore"),
336        }
337    }
338}
339
340#[macro_export]
341macro_rules! dispatch_state_store {
342    ($impl:expr, $store:ident, $body:tt) => {{
343        use $crate::store_impl::StateStoreImpl;
344
345        match $impl {
346            StateStoreImpl::MemoryStateStore($store) => {
347                // WARNING: don't change this. Enabling memory backend will cause monomorphization
348                // explosion and thus slow compile time in release mode.
349                #[cfg(debug_assertions)]
350                {
351                    $body
352                }
353                #[cfg(not(debug_assertions))]
354                {
355                    let _store = $store;
356                    unimplemented!("memory state store should never be used in release mode");
357                }
358            }
359
360            StateStoreImpl::SledStateStore($store) => {
361                // WARNING: don't change this. Enabling memory backend will cause monomorphization
362                // explosion and thus slow compile time in release mode.
363                #[cfg(debug_assertions)]
364                {
365                    $body
366                }
367                #[cfg(not(debug_assertions))]
368                {
369                    let _store = $store;
370                    unimplemented!("sled state store should never be used in release mode");
371                }
372            }
373
374            StateStoreImpl::HummockStateStore($store) => $body,
375        }
376    }};
377}
378
379#[cfg(any(debug_assertions, test, feature = "test"))]
380pub mod verify {
381    use std::fmt::Debug;
382    use std::future::Future;
383    use std::marker::PhantomData;
384    use std::ops::Deref;
385    use std::sync::Arc;
386
387    use bytes::Bytes;
388    use risingwave_common::array::VectorRef;
389    use risingwave_common::bitmap::Bitmap;
390    use risingwave_common::hash::VirtualNode;
391    use risingwave_hummock_sdk::HummockReadEpoch;
392    use risingwave_hummock_sdk::key::{FullKey, TableKey, TableKeyRange};
393    use tracing::log::warn;
394
395    use crate::error::StorageResult;
396    use crate::hummock::HummockStorage;
397    use crate::store::*;
398    use crate::store_impl::AsHummock;
399
400    #[expect(dead_code)]
401    fn assert_result_eq<Item: PartialEq + Debug, E>(
402        first: &std::result::Result<Item, E>,
403        second: &std::result::Result<Item, E>,
404    ) {
405        match (first, second) {
406            (Ok(first), Ok(second)) => {
407                if first != second {
408                    warn!("result different: {:?} {:?}", first, second);
409                }
410                assert_eq!(first, second);
411            }
412            (Err(_), Err(_)) => {}
413            _ => {
414                warn!("one success and one failed");
415                panic!("result not equal");
416            }
417        }
418    }
419
420    #[derive(Clone)]
421    pub struct VerifyStateStore<A, E, T = ()> {
422        pub actual: A,
423        pub expected: Option<E>,
424        pub _phantom: PhantomData<T>,
425    }
426
427    impl<A: AsHummock, E: AsHummock> AsHummock for VerifyStateStore<A, E> {
428        fn as_hummock(&self) -> Option<&HummockStorage> {
429            self.actual.as_hummock()
430        }
431    }
432
433    impl<A: StateStoreGet, E: StateStoreGet> StateStoreGet for VerifyStateStore<A, E> {
434        async fn on_key_value<'a, O: Send + 'a>(
435            &'a self,
436            key: TableKey<Bytes>,
437            read_options: ReadOptions,
438            on_key_value_fn: impl KeyValueFn<'a, O>,
439        ) -> StorageResult<Option<O>> {
440            let actual: Option<(FullKey<Bytes>, Bytes)> = self
441                .actual
442                .on_key_value(key.clone(), read_options.clone(), |key, value| {
443                    Ok((key.copy_into(), Bytes::copy_from_slice(value)))
444                })
445                .await?;
446            if let Some(expected) = &self.expected {
447                let expected: Option<(FullKey<Bytes>, Bytes)> = expected
448                    .on_key_value(key, read_options, |key, value| {
449                        Ok((key.copy_into(), Bytes::copy_from_slice(value)))
450                    })
451                    .await?;
452                assert_eq!(
453                    actual
454                        .as_ref()
455                        .map(|item| (item.0.epoch_with_gap.pure_epoch(), item)),
456                    expected
457                        .as_ref()
458                        .map(|item| (item.0.epoch_with_gap.pure_epoch(), item))
459                );
460            }
461
462            actual
463                .map(|(key, value)| on_key_value_fn(key.to_ref(), value.as_ref()))
464                .transpose()
465        }
466    }
467
468    impl<A: StateStoreReadVector, E: StateStoreReadVector> StateStoreReadVector
469        for VerifyStateStore<A, E>
470    {
471        fn nearest<'a, O: Send + 'a>(
472            &'a self,
473            vec: VectorRef<'a>,
474            options: VectorNearestOptions,
475            on_nearest_item_fn: impl OnNearestItemFn<'a, O>,
476        ) -> impl StorageFuture<'a, Vec<O>> {
477            self.actual.nearest(vec, options, on_nearest_item_fn)
478        }
479    }
480
481    impl<A: StateStoreRead, E: StateStoreRead> StateStoreRead for VerifyStateStore<A, E> {
482        type Iter = impl StateStoreReadIter;
483        type RevIter = impl StateStoreReadIter;
484
485        // TODO: may avoid manual async fn when the bug of rust compiler is fixed. Currently it will
486        // fail to compile.
487        #[expect(clippy::manual_async_fn)]
488        fn iter(
489            &self,
490            key_range: TableKeyRange,
491
492            read_options: ReadOptions,
493        ) -> impl Future<Output = StorageResult<Self::Iter>> + '_ {
494            async move {
495                let actual = self
496                    .actual
497                    .iter(key_range.clone(), read_options.clone())
498                    .await?;
499                let expected = if let Some(expected) = &self.expected {
500                    Some(expected.iter(key_range, read_options).await?)
501                } else {
502                    None
503                };
504
505                Ok(verify_iter::<StateStoreKeyedRow>(actual, expected))
506            }
507        }
508
509        #[expect(clippy::manual_async_fn)]
510        fn rev_iter(
511            &self,
512            key_range: TableKeyRange,
513
514            read_options: ReadOptions,
515        ) -> impl Future<Output = StorageResult<Self::RevIter>> + '_ {
516            async move {
517                let actual = self
518                    .actual
519                    .rev_iter(key_range.clone(), read_options.clone())
520                    .await?;
521                let expected = if let Some(expected) = &self.expected {
522                    Some(expected.rev_iter(key_range, read_options).await?)
523                } else {
524                    None
525                };
526
527                Ok(verify_iter::<StateStoreKeyedRow>(actual, expected))
528            }
529        }
530    }
531
532    impl<A: StateStoreReadLog, E: StateStoreReadLog> StateStoreReadLog for VerifyStateStore<A, E> {
533        type ChangeLogIter = impl StateStoreReadChangeLogIter;
534
535        async fn next_epoch(&self, epoch: u64, options: NextEpochOptions) -> StorageResult<u64> {
536            let actual = self.actual.next_epoch(epoch, options.clone()).await?;
537            if let Some(expected) = &self.expected {
538                assert_eq!(actual, expected.next_epoch(epoch, options).await?);
539            }
540            Ok(actual)
541        }
542
543        async fn iter_log(
544            &self,
545            epoch_range: (u64, u64),
546            key_range: TableKeyRange,
547            options: ReadLogOptions,
548        ) -> StorageResult<Self::ChangeLogIter> {
549            let actual = self
550                .actual
551                .iter_log(epoch_range, key_range.clone(), options.clone())
552                .await?;
553            let expected = if let Some(expected) = &self.expected {
554                Some(expected.iter_log(epoch_range, key_range, options).await?)
555            } else {
556                None
557            };
558
559            Ok(verify_iter::<StateStoreReadLogItem>(actual, expected))
560        }
561    }
562
563    impl<A: StateStoreIter<T>, E: StateStoreIter<T>, T: IterItem> StateStoreIter<T>
564        for VerifyStateStore<A, E, T>
565    where
566        for<'a> T::ItemRef<'a>: PartialEq + Debug,
567    {
568        async fn try_next(&mut self) -> StorageResult<Option<T::ItemRef<'_>>> {
569            let actual = self.actual.try_next().await?;
570            if let Some(expected) = self.expected.as_mut() {
571                let expected = expected.try_next().await?;
572                assert_eq!(actual, expected);
573            }
574            Ok(actual)
575        }
576    }
577
578    fn verify_iter<T: IterItem>(
579        actual: impl StateStoreIter<T>,
580        expected: Option<impl StateStoreIter<T>>,
581    ) -> impl StateStoreIter<T>
582    where
583        for<'a> T::ItemRef<'a>: PartialEq + Debug,
584    {
585        VerifyStateStore {
586            actual,
587            expected,
588            _phantom: PhantomData::<T>,
589        }
590    }
591
592    impl<A: LocalStateStore, E: LocalStateStore> LocalStateStore for VerifyStateStore<A, E> {
593        type FlushedSnapshotReader =
594            VerifyStateStore<A::FlushedSnapshotReader, E::FlushedSnapshotReader>;
595
596        type Iter<'a> = impl StateStoreIter + 'a;
597        type RevIter<'a> = impl StateStoreIter + 'a;
598
599        #[expect(clippy::manual_async_fn)]
600        fn iter(
601            &self,
602            key_range: TableKeyRange,
603            read_options: ReadOptions,
604        ) -> impl Future<Output = StorageResult<Self::Iter<'_>>> + Send + '_ {
605            async move {
606                let actual = self
607                    .actual
608                    .iter(key_range.clone(), read_options.clone())
609                    .await?;
610                let expected = if let Some(expected) = &self.expected {
611                    Some(expected.iter(key_range, read_options).await?)
612                } else {
613                    None
614                };
615
616                Ok(verify_iter::<StateStoreKeyedRow>(actual, expected))
617            }
618        }
619
620        #[expect(clippy::manual_async_fn)]
621        fn rev_iter(
622            &self,
623            key_range: TableKeyRange,
624            read_options: ReadOptions,
625        ) -> impl Future<Output = StorageResult<Self::RevIter<'_>>> + Send + '_ {
626            async move {
627                let actual = self
628                    .actual
629                    .rev_iter(key_range.clone(), read_options.clone())
630                    .await?;
631                let expected = if let Some(expected) = &self.expected {
632                    Some(expected.rev_iter(key_range, read_options).await?)
633                } else {
634                    None
635                };
636
637                Ok(verify_iter::<StateStoreKeyedRow>(actual, expected))
638            }
639        }
640
641        fn insert(
642            &mut self,
643            key: TableKey<Bytes>,
644            new_val: Bytes,
645            old_val: Option<Bytes>,
646        ) -> StorageResult<()> {
647            if let Some(expected) = &mut self.expected {
648                expected.insert(key.clone(), new_val.clone(), old_val.clone())?;
649            }
650            self.actual.insert(key, new_val, old_val)?;
651
652            Ok(())
653        }
654
655        fn delete(&mut self, key: TableKey<Bytes>, old_val: Bytes) -> StorageResult<()> {
656            if let Some(expected) = &mut self.expected {
657                expected.delete(key.clone(), old_val.clone())?;
658            }
659            self.actual.delete(key, old_val)?;
660            Ok(())
661        }
662
663        async fn update_vnode_bitmap(&mut self, vnodes: Arc<Bitmap>) -> StorageResult<Arc<Bitmap>> {
664            let ret = self.actual.update_vnode_bitmap(vnodes.clone()).await?;
665            if let Some(expected) = &mut self.expected {
666                assert_eq!(ret, expected.update_vnode_bitmap(vnodes).await?);
667            }
668            Ok(ret)
669        }
670
671        fn get_table_watermark(&self, vnode: VirtualNode) -> Option<Bytes> {
672            let ret = self.actual.get_table_watermark(vnode);
673            if let Some(expected) = &self.expected {
674                assert_eq!(ret, expected.get_table_watermark(vnode));
675            }
676            ret
677        }
678
679        fn new_flushed_snapshot_reader(&self) -> Self::FlushedSnapshotReader {
680            VerifyStateStore {
681                actual: self.actual.new_flushed_snapshot_reader(),
682                expected: self.expected.as_ref().map(E::new_flushed_snapshot_reader),
683                _phantom: Default::default(),
684            }
685        }
686    }
687
688    impl<A: StateStoreWriteEpochControl, E: StateStoreWriteEpochControl> StateStoreWriteEpochControl
689        for VerifyStateStore<A, E>
690    {
691        async fn flush(&mut self) -> StorageResult<usize> {
692            if let Some(expected) = &mut self.expected {
693                expected.flush().await?;
694            }
695            self.actual.flush().await
696        }
697
698        async fn try_flush(&mut self) -> StorageResult<()> {
699            if let Some(expected) = &mut self.expected {
700                expected.try_flush().await?;
701            }
702            self.actual.try_flush().await
703        }
704
705        async fn init(&mut self, options: InitOptions) -> StorageResult<()> {
706            self.actual.init(options.clone()).await?;
707            if let Some(expected) = &mut self.expected {
708                expected.init(options).await?;
709            }
710            Ok(())
711        }
712
713        fn seal_current_epoch(&mut self, next_epoch: u64, opts: SealCurrentEpochOptions) {
714            if let Some(expected) = &mut self.expected {
715                expected.seal_current_epoch(next_epoch, opts.clone());
716            }
717            self.actual.seal_current_epoch(next_epoch, opts);
718        }
719    }
720
721    impl<A: StateStore, E: StateStore> StateStore for VerifyStateStore<A, E> {
722        type Local = VerifyStateStore<A::Local, E::Local>;
723        type ReadSnapshot = VerifyStateStore<A::ReadSnapshot, E::ReadSnapshot>;
724        type VectorWriter = A::VectorWriter;
725
726        fn try_wait_epoch(
727            &self,
728            epoch: HummockReadEpoch,
729            options: TryWaitEpochOptions,
730        ) -> impl Future<Output = StorageResult<()>> + Send + '_ {
731            self.actual.try_wait_epoch(epoch, options)
732        }
733
734        async fn new_local(&self, option: NewLocalOptions) -> Self::Local {
735            let expected = if let Some(expected) = &self.expected {
736                Some(expected.new_local(option.clone()).await)
737            } else {
738                None
739            };
740            VerifyStateStore {
741                actual: self.actual.new_local(option).await,
742                expected,
743                _phantom: PhantomData::<()>,
744            }
745        }
746
747        async fn new_read_snapshot(
748            &self,
749            epoch: HummockReadEpoch,
750            options: NewReadSnapshotOptions,
751        ) -> StorageResult<Self::ReadSnapshot> {
752            let expected = if let Some(expected) = &self.expected {
753                Some(expected.new_read_snapshot(epoch, options).await?)
754            } else {
755                None
756            };
757            Ok(VerifyStateStore {
758                actual: self.actual.new_read_snapshot(epoch, options).await?,
759                expected,
760                _phantom: PhantomData::<()>,
761            })
762        }
763
764        fn new_vector_writer(
765            &self,
766            options: NewVectorWriterOptions,
767        ) -> impl Future<Output = Self::VectorWriter> + Send + '_ {
768            self.actual.new_vector_writer(options)
769        }
770    }
771
772    impl<A, E> Deref for VerifyStateStore<A, E> {
773        type Target = A;
774
775        fn deref(&self) -> &Self::Target {
776            &self.actual
777        }
778    }
779}
780
781impl StateStoreImpl {
782    #[cfg_attr(not(target_os = "linux"), allow(unused_variables))]
783    #[expect(clippy::borrowed_box)]
784    pub async fn new(
785        s: &str,
786        role: Role,
787        opts: Arc<StorageOpts>,
788        hummock_meta_client: Arc<MonitoredHummockMetaClient>,
789        state_store_metrics: Arc<HummockStateStoreMetrics>,
790        object_store_metrics: Arc<ObjectStoreMetrics>,
791        storage_metrics: Arc<MonitoredStorageMetrics>,
792        compactor_metrics: Arc<CompactorMetrics>,
793        await_tree_config: Option<await_tree::Config>,
794        use_new_object_prefix_strategy: bool,
795    ) -> StorageResult<Self> {
796        const KB: usize = 1 << 10;
797        const MB: usize = 1 << 20;
798
799        let meta_cache = {
800            let mut builder = HybridCacheBuilder::new()
801                .with_name("foyer.meta")
802                .with_metrics_registry(FOYER_METRICS_REGISTRY.clone())
803                .memory(opts.meta_cache_capacity_mb * MB)
804                .with_shards(opts.meta_cache_shard_num)
805                .with_eviction_config(opts.meta_cache_eviction_config.clone())
806                .with_weighter(
807                    |_: &HummockSstableObjectId, value: &SstableMetaCacheValue| {
808                        std::mem::size_of::<HummockSstableObjectId>()
809                            + value.estimated_meta_cache_memory_weight()
810                    },
811                )
812                .storage();
813
814            if !opts.meta_file_cache_dir.is_empty() {
815                if let Err(e) = Feature::ElasticDiskCache.check_available() {
816                    tracing::warn!(error = %e.as_report(), "ElasticDiskCache is not available.");
817                } else {
818                    let device_builder = FsDeviceBuilder::new(&opts.meta_file_cache_dir)
819                        .with_capacity(opts.meta_file_cache_capacity_mb * MB)
820                        .with_throttle(opts.meta_file_cache_throttle.clone());
821                    #[cfg(target_os = "linux")]
822                    let device_builder = device_builder.with_direct(opts.meta_file_cache_direct_io);
823                    let device = device_builder.build().map_err(HummockError::foyer_error)?;
824                    let engine_builder = BlockEngineConfig::new(device)
825                        .with_block_size(opts.meta_file_cache_file_capacity_mb * MB)
826                        .with_indexer_shards(opts.meta_file_cache_indexer_shards)
827                        .with_flushers(opts.meta_file_cache_flushers)
828                        .with_reclaimers(opts.meta_file_cache_reclaimers)
829                        .with_buffer_pool_size(opts.meta_file_cache_flush_buffer_threshold_mb * MB)
830                        .with_submit_queue_size_threshold(
831                            opts.meta_file_cache_submit_queue_size_threshold_mb * MB,
832                        )
833                        .with_clean_block_threshold(
834                            opts.meta_file_cache_reclaimers + opts.meta_file_cache_reclaimers / 2,
835                        )
836                        .with_recover_concurrency(opts.meta_file_cache_recover_concurrency)
837                        .with_blob_index_size(opts.meta_file_cache_blob_index_size_kb * KB)
838                        .with_eviction_pickers(vec![Box::new(FifoPicker::new(
839                            opts.meta_file_cache_fifo_probation_ratio,
840                        ))]);
841                    builder = builder
842                        .with_engine_config(engine_builder)
843                        .with_recover_mode(opts.meta_file_cache_recover_mode)
844                        .with_compression(opts.meta_file_cache_compression);
845                    builder = builder.with_spawner(build_file_cache_spawner(
846                        "foyer.meta",
847                        &opts.meta_file_cache_runtime_config,
848                    )?);
849                }
850            }
851
852            builder.build().await.map_err(HummockError::foyer_error)?
853        };
854
855        let block_cache = {
856            let mut builder = HybridCacheBuilder::new()
857                .with_name("foyer.data")
858                .with_metrics_registry(FOYER_METRICS_REGISTRY.clone())
859                .with_event_listener(Arc::new(BlockCacheEventListener::new(
860                    state_store_metrics.clone(),
861                )))
862                .memory(opts.block_cache_capacity_mb * MB)
863                .with_shards(opts.block_cache_shard_num)
864                .with_eviction_config(opts.block_cache_eviction_config.clone())
865                .with_weighter(|_: &SstableBlockIndex, value: &Box<Block>| {
866                    std::mem::size_of::<SstableBlockIndex>() + value.estimated_memory_weight()
867                })
868                .storage();
869
870            if !opts.data_file_cache_dir.is_empty() {
871                if let Err(e) = Feature::ElasticDiskCache.check_available() {
872                    tracing::warn!(error = %e.as_report(), "ElasticDiskCache is not available.");
873                } else {
874                    let device_builder = FsDeviceBuilder::new(&opts.data_file_cache_dir)
875                        .with_capacity(opts.data_file_cache_capacity_mb * MB)
876                        .with_throttle(opts.data_file_cache_throttle.clone());
877                    #[cfg(target_os = "linux")]
878                    let device_builder = device_builder.with_direct(opts.data_file_cache_direct_io);
879                    let device = device_builder.build().map_err(HummockError::foyer_error)?;
880                    let engine_builder = BlockEngineConfig::new(device)
881                        .with_block_size(opts.data_file_cache_file_capacity_mb * MB)
882                        .with_indexer_shards(opts.data_file_cache_indexer_shards)
883                        .with_flushers(opts.data_file_cache_flushers)
884                        .with_reclaimers(opts.data_file_cache_reclaimers)
885                        .with_buffer_pool_size(opts.data_file_cache_flush_buffer_threshold_mb * MB)
886                        .with_submit_queue_size_threshold(
887                            opts.data_file_cache_submit_queue_size_threshold_mb * MB,
888                        )
889                        .with_clean_block_threshold(
890                            opts.data_file_cache_reclaimers + opts.data_file_cache_reclaimers / 2,
891                        )
892                        .with_recover_concurrency(opts.data_file_cache_recover_concurrency)
893                        .with_blob_index_size(opts.data_file_cache_blob_index_size_kb * KB)
894                        .with_eviction_pickers(vec![Box::new(FifoPicker::new(
895                            opts.data_file_cache_fifo_probation_ratio,
896                        ))]);
897                    builder = builder
898                        .with_engine_config(engine_builder)
899                        .with_recover_mode(opts.data_file_cache_recover_mode)
900                        .with_compression(opts.data_file_cache_compression);
901                    builder = builder.with_spawner(build_file_cache_spawner(
902                        "foyer.data",
903                        &opts.data_file_cache_runtime_config,
904                    )?);
905                }
906            }
907
908            builder.build().await.map_err(HummockError::foyer_error)?
909        };
910
911        let vector_meta_cache = CacheBuilder::new(opts.vector_meta_cache_capacity_mb * MB)
912            .with_shards(opts.vector_meta_cache_shard_num)
913            .with_eviction_config(opts.vector_meta_cache_eviction_config.clone())
914            .build();
915
916        let vector_block_cache = CacheBuilder::new(opts.vector_block_cache_capacity_mb * MB)
917            .with_shards(opts.vector_block_cache_shard_num)
918            .with_eviction_config(opts.vector_block_cache_eviction_config.clone())
919            .build();
920
921        let recent_filter = if opts.data_file_cache_dir.is_empty() {
922            Arc::new(NoneRecentFilter::default().into())
923        } else if opts.cache_refill_recent_filter_shards == 1 {
924            Arc::new(
925                SimpleRecentFilter::new(
926                    opts.cache_refill_recent_filter_layers,
927                    Duration::from_millis(
928                        opts.cache_refill_recent_filter_rotate_interval_ms as u64,
929                    ),
930                )
931                .into(),
932            )
933        } else if opts.cache_refill_skip_recent_filter {
934            Arc::new(AllRecentFilter::default().into())
935        } else {
936            Arc::new(
937                ShardedRecentFilter::new(
938                    opts.cache_refill_recent_filter_layers,
939                    Duration::from_millis(
940                        opts.cache_refill_recent_filter_rotate_interval_ms as u64,
941                    ),
942                    opts.cache_refill_recent_filter_shards,
943                )
944                .into(),
945            )
946        };
947
948        let store = match s {
949            hummock if hummock.starts_with("hummock+") => {
950                let object_store = build_remote_object_store(
951                    hummock.strip_prefix("hummock+").unwrap(),
952                    object_store_metrics.clone(),
953                    "Hummock",
954                    Arc::new(opts.object_store_config.clone()),
955                )
956                .await;
957
958                let sstable_store = Arc::new(SstableStore::new(SstableStoreConfig {
959                    store: Arc::new(object_store),
960                    path: opts.data_directory.clone(),
961                    prefetch_buffer_capacity: opts.prefetch_buffer_capacity_mb * (1 << 20),
962                    max_prefetch_block_number: opts.max_prefetch_block_number,
963                    recent_filter,
964                    state_store_metrics: state_store_metrics.clone(),
965                    use_new_object_prefix_strategy,
966                    skip_bloom_filter_in_serde: opts.sst_skip_bloom_filter_in_serde,
967
968                    meta_cache,
969                    block_cache,
970                    vector_meta_cache,
971                    vector_block_cache,
972                }));
973                let notification_client =
974                    RpcNotificationClient::new(hummock_meta_client.get_inner().clone());
975                let compaction_catalog_manager_ref =
976                    Arc::new(CompactionCatalogManager::new(Box::new(
977                        RemoteTableAccessor::new(hummock_meta_client.get_inner().clone()),
978                    )));
979
980                let inner = HummockStorage::new(
981                    role,
982                    opts.clone(),
983                    sstable_store,
984                    hummock_meta_client.clone(),
985                    notification_client,
986                    compaction_catalog_manager_ref,
987                    state_store_metrics.clone(),
988                    compactor_metrics.clone(),
989                    await_tree_config,
990                )
991                .await?;
992
993                StateStoreImpl::hummock(inner, storage_metrics)
994            }
995
996            "in_memory" | "in-memory" => {
997                tracing::warn!(
998                    "In-memory state store should never be used in end-to-end benchmarks or production environment. Scaling and recovery are not supported."
999                );
1000                StateStoreImpl::shared_in_memory_store(storage_metrics.clone())
1001            }
1002
1003            sled if sled.starts_with("sled://") => {
1004                tracing::warn!(
1005                    "sled state store should never be used in end-to-end benchmarks or production environment. Scaling and recovery are not supported."
1006                );
1007                let path = sled.strip_prefix("sled://").unwrap();
1008                StateStoreImpl::sled(SledStateStore::new(path), storage_metrics.clone())
1009            }
1010
1011            other => unimplemented!("{} state store is not supported", other),
1012        };
1013
1014        Ok(store)
1015    }
1016}
1017
1018pub trait AsHummock: Send + Sync {
1019    fn as_hummock(&self) -> Option<&HummockStorage>;
1020
1021    fn sync(
1022        &self,
1023        sync_table_epochs: Vec<(HummockEpoch, HashSet<TableId>)>,
1024    ) -> BoxFuture<'_, StorageResult<SyncResult>> {
1025        async move {
1026            if let Some(hummock) = self.as_hummock() {
1027                hummock.sync(sync_table_epochs).await
1028            } else {
1029                Ok(SyncResult::default())
1030            }
1031        }
1032        .boxed()
1033    }
1034}
1035
1036impl AsHummock for HummockStorage {
1037    fn as_hummock(&self) -> Option<&HummockStorage> {
1038        Some(self)
1039    }
1040}
1041
1042impl AsHummock for MemoryStateStore {
1043    fn as_hummock(&self) -> Option<&HummockStorage> {
1044        None
1045    }
1046}
1047
1048impl AsHummock for SledStateStore {
1049    fn as_hummock(&self) -> Option<&HummockStorage> {
1050        None
1051    }
1052}
1053
1054#[cfg(debug_assertions)]
1055mod dyn_state_store {
1056    use std::future::Future;
1057    use std::ops::DerefMut;
1058    use std::sync::Arc;
1059
1060    use bytes::Bytes;
1061    use risingwave_common::array::VectorRef;
1062    use risingwave_common::bitmap::Bitmap;
1063    use risingwave_common::hash::VirtualNode;
1064    use risingwave_hummock_sdk::HummockReadEpoch;
1065    use risingwave_hummock_sdk::key::{TableKey, TableKeyRange};
1066
1067    use crate::error::StorageResult;
1068    use crate::hummock::HummockStorage;
1069    use crate::store::*;
1070    use crate::store_impl::AsHummock;
1071    use crate::vector::VectorDistance;
1072
1073    #[async_trait::async_trait]
1074    pub trait DynStateStoreIter<T: IterItem>: Send {
1075        async fn try_next(&mut self) -> StorageResult<Option<T::ItemRef<'_>>>;
1076    }
1077
1078    #[async_trait::async_trait]
1079    impl<T: IterItem, I: StateStoreIter<T>> DynStateStoreIter<T> for I {
1080        async fn try_next(&mut self) -> StorageResult<Option<T::ItemRef<'_>>> {
1081            self.try_next().await
1082        }
1083    }
1084
1085    pub type BoxStateStoreIter<'a, T> = Box<dyn DynStateStoreIter<T> + 'a>;
1086    impl<T: IterItem> StateStoreIter<T> for BoxStateStoreIter<'_, T> {
1087        fn try_next(
1088            &mut self,
1089        ) -> impl Future<Output = StorageResult<Option<T::ItemRef<'_>>>> + Send + '_ {
1090            self.deref_mut().try_next()
1091        }
1092    }
1093
1094    // For StateStoreRead
1095
1096    pub type BoxStateStoreReadIter = BoxStateStoreIter<'static, StateStoreKeyedRow>;
1097    pub type BoxStateStoreReadChangeLogIter = BoxStateStoreIter<'static, StateStoreReadLogItem>;
1098
1099    #[async_trait::async_trait]
1100    pub trait DynStateStoreGet: StaticSendSync {
1101        async fn get_keyed_row(
1102            &self,
1103            key: TableKey<Bytes>,
1104            read_options: ReadOptions,
1105        ) -> StorageResult<Option<StateStoreKeyedRow>>;
1106    }
1107
1108    #[async_trait::async_trait]
1109    pub trait DynStateStoreRead: DynStateStoreGet + StaticSendSync {
1110        async fn iter(
1111            &self,
1112            key_range: TableKeyRange,
1113
1114            read_options: ReadOptions,
1115        ) -> StorageResult<BoxStateStoreReadIter>;
1116
1117        async fn rev_iter(
1118            &self,
1119            key_range: TableKeyRange,
1120
1121            read_options: ReadOptions,
1122        ) -> StorageResult<BoxStateStoreReadIter>;
1123    }
1124
1125    #[async_trait::async_trait]
1126    pub trait DynStateStoreReadLog: StaticSendSync {
1127        async fn next_epoch(&self, epoch: u64, options: NextEpochOptions) -> StorageResult<u64>;
1128        async fn iter_log(
1129            &self,
1130            epoch_range: (u64, u64),
1131            key_range: TableKeyRange,
1132            options: ReadLogOptions,
1133        ) -> StorageResult<BoxStateStoreReadChangeLogIter>;
1134    }
1135
1136    pub type StateStoreReadDynRef = StateStorePointer<Arc<dyn DynStateStoreRead>>;
1137
1138    #[async_trait::async_trait]
1139    impl<S: StateStoreGet> DynStateStoreGet for S {
1140        async fn get_keyed_row(
1141            &self,
1142            key: TableKey<Bytes>,
1143            read_options: ReadOptions,
1144        ) -> StorageResult<Option<StateStoreKeyedRow>> {
1145            self.on_key_value(key, read_options, move |key, value| {
1146                Ok((key.copy_into(), Bytes::copy_from_slice(value)))
1147            })
1148            .await
1149        }
1150    }
1151
1152    #[async_trait::async_trait]
1153    impl<S: StateStoreRead> DynStateStoreRead for S {
1154        async fn iter(
1155            &self,
1156            key_range: TableKeyRange,
1157
1158            read_options: ReadOptions,
1159        ) -> StorageResult<BoxStateStoreReadIter> {
1160            Ok(Box::new(self.iter(key_range, read_options).await?))
1161        }
1162
1163        async fn rev_iter(
1164            &self,
1165            key_range: TableKeyRange,
1166
1167            read_options: ReadOptions,
1168        ) -> StorageResult<BoxStateStoreReadIter> {
1169            Ok(Box::new(self.rev_iter(key_range, read_options).await?))
1170        }
1171    }
1172
1173    #[async_trait::async_trait]
1174    impl<S: StateStoreReadLog> DynStateStoreReadLog for S {
1175        async fn next_epoch(&self, epoch: u64, options: NextEpochOptions) -> StorageResult<u64> {
1176            self.next_epoch(epoch, options).await
1177        }
1178
1179        async fn iter_log(
1180            &self,
1181            epoch_range: (u64, u64),
1182            key_range: TableKeyRange,
1183            options: ReadLogOptions,
1184        ) -> StorageResult<BoxStateStoreReadChangeLogIter> {
1185            Ok(Box::new(
1186                self.iter_log(epoch_range, key_range, options).await?,
1187            ))
1188        }
1189    }
1190
1191    // For LocalStateStore
1192    pub type BoxLocalStateStoreIterStream<'a> = BoxStateStoreIter<'a, StateStoreKeyedRow>;
1193    #[async_trait::async_trait]
1194    pub trait DynLocalStateStore:
1195        DynStateStoreGet + DynStateStoreWriteEpochControl + StaticSendSync
1196    {
1197        async fn iter(
1198            &self,
1199            key_range: TableKeyRange,
1200            read_options: ReadOptions,
1201        ) -> StorageResult<BoxLocalStateStoreIterStream<'_>>;
1202
1203        async fn rev_iter(
1204            &self,
1205            key_range: TableKeyRange,
1206            read_options: ReadOptions,
1207        ) -> StorageResult<BoxLocalStateStoreIterStream<'_>>;
1208
1209        fn new_flushed_snapshot_reader(&self) -> StateStoreReadDynRef;
1210
1211        fn insert(
1212            &mut self,
1213            key: TableKey<Bytes>,
1214            new_val: Bytes,
1215            old_val: Option<Bytes>,
1216        ) -> StorageResult<()>;
1217
1218        fn delete(&mut self, key: TableKey<Bytes>, old_val: Bytes) -> StorageResult<()>;
1219
1220        async fn update_vnode_bitmap(&mut self, vnodes: Arc<Bitmap>) -> StorageResult<Arc<Bitmap>>;
1221
1222        fn get_table_watermark(&self, vnode: VirtualNode) -> Option<Bytes>;
1223    }
1224
1225    #[async_trait::async_trait]
1226    pub trait DynStateStoreWriteEpochControl: StaticSendSync {
1227        async fn flush(&mut self) -> StorageResult<usize>;
1228
1229        async fn try_flush(&mut self) -> StorageResult<()>;
1230
1231        async fn init(&mut self, epoch: InitOptions) -> StorageResult<()>;
1232
1233        fn seal_current_epoch(&mut self, next_epoch: u64, opts: SealCurrentEpochOptions);
1234    }
1235
1236    #[async_trait::async_trait]
1237    impl<S: LocalStateStore> DynLocalStateStore for S {
1238        async fn iter(
1239            &self,
1240            key_range: TableKeyRange,
1241            read_options: ReadOptions,
1242        ) -> StorageResult<BoxLocalStateStoreIterStream<'_>> {
1243            Ok(Box::new(self.iter(key_range, read_options).await?))
1244        }
1245
1246        async fn rev_iter(
1247            &self,
1248            key_range: TableKeyRange,
1249            read_options: ReadOptions,
1250        ) -> StorageResult<BoxLocalStateStoreIterStream<'_>> {
1251            Ok(Box::new(self.rev_iter(key_range, read_options).await?))
1252        }
1253
1254        fn new_flushed_snapshot_reader(&self) -> StateStoreReadDynRef {
1255            StateStorePointer(Arc::new(self.new_flushed_snapshot_reader()) as _)
1256        }
1257
1258        fn insert(
1259            &mut self,
1260            key: TableKey<Bytes>,
1261            new_val: Bytes,
1262            old_val: Option<Bytes>,
1263        ) -> StorageResult<()> {
1264            self.insert(key, new_val, old_val)
1265        }
1266
1267        fn delete(&mut self, key: TableKey<Bytes>, old_val: Bytes) -> StorageResult<()> {
1268            self.delete(key, old_val)
1269        }
1270
1271        async fn update_vnode_bitmap(&mut self, vnodes: Arc<Bitmap>) -> StorageResult<Arc<Bitmap>> {
1272            self.update_vnode_bitmap(vnodes).await
1273        }
1274
1275        fn get_table_watermark(&self, vnode: VirtualNode) -> Option<Bytes> {
1276            self.get_table_watermark(vnode)
1277        }
1278    }
1279
1280    #[async_trait::async_trait]
1281    impl<S: StateStoreWriteEpochControl> DynStateStoreWriteEpochControl for S {
1282        async fn flush(&mut self) -> StorageResult<usize> {
1283            self.flush().await
1284        }
1285
1286        async fn try_flush(&mut self) -> StorageResult<()> {
1287            self.try_flush().await
1288        }
1289
1290        async fn init(&mut self, options: InitOptions) -> StorageResult<()> {
1291            self.init(options).await
1292        }
1293
1294        fn seal_current_epoch(&mut self, next_epoch: u64, opts: SealCurrentEpochOptions) {
1295            self.seal_current_epoch(next_epoch, opts)
1296        }
1297    }
1298
1299    pub type BoxDynLocalStateStore = StateStorePointer<Box<dyn DynLocalStateStore>>;
1300
1301    impl LocalStateStore for BoxDynLocalStateStore {
1302        type FlushedSnapshotReader = StateStoreReadDynRef;
1303        type Iter<'a> = BoxLocalStateStoreIterStream<'a>;
1304        type RevIter<'a> = BoxLocalStateStoreIterStream<'a>;
1305
1306        fn iter(
1307            &self,
1308            key_range: TableKeyRange,
1309            read_options: ReadOptions,
1310        ) -> impl Future<Output = StorageResult<Self::Iter<'_>>> + Send + '_ {
1311            (*self.0).iter(key_range, read_options)
1312        }
1313
1314        fn rev_iter(
1315            &self,
1316            key_range: TableKeyRange,
1317            read_options: ReadOptions,
1318        ) -> impl Future<Output = StorageResult<Self::RevIter<'_>>> + Send + '_ {
1319            (*self.0).rev_iter(key_range, read_options)
1320        }
1321
1322        fn new_flushed_snapshot_reader(&self) -> Self::FlushedSnapshotReader {
1323            (*self.0).new_flushed_snapshot_reader()
1324        }
1325
1326        fn get_table_watermark(&self, vnode: VirtualNode) -> Option<Bytes> {
1327            (*self.0).get_table_watermark(vnode)
1328        }
1329
1330        fn insert(
1331            &mut self,
1332            key: TableKey<Bytes>,
1333            new_val: Bytes,
1334            old_val: Option<Bytes>,
1335        ) -> StorageResult<()> {
1336            (*self.0).insert(key, new_val, old_val)
1337        }
1338
1339        fn delete(&mut self, key: TableKey<Bytes>, old_val: Bytes) -> StorageResult<()> {
1340            (*self.0).delete(key, old_val)
1341        }
1342
1343        async fn update_vnode_bitmap(&mut self, vnodes: Arc<Bitmap>) -> StorageResult<Arc<Bitmap>> {
1344            (*self.0).update_vnode_bitmap(vnodes).await
1345        }
1346    }
1347
1348    impl<P> StateStoreWriteEpochControl for StateStorePointer<P>
1349    where
1350        StateStorePointer<P>: AsMut<dyn DynStateStoreWriteEpochControl> + StaticSendSync,
1351    {
1352        fn flush(&mut self) -> impl Future<Output = StorageResult<usize>> + Send + '_ {
1353            self.as_mut().flush()
1354        }
1355
1356        fn try_flush(&mut self) -> impl Future<Output = StorageResult<()>> + Send + '_ {
1357            self.as_mut().try_flush()
1358        }
1359
1360        fn init(
1361            &mut self,
1362            options: InitOptions,
1363        ) -> impl Future<Output = StorageResult<()>> + Send + '_ {
1364            self.as_mut().init(options)
1365        }
1366
1367        fn seal_current_epoch(&mut self, next_epoch: u64, opts: SealCurrentEpochOptions) {
1368            self.as_mut().seal_current_epoch(next_epoch, opts)
1369        }
1370    }
1371
1372    #[async_trait::async_trait]
1373    pub trait DynStateStoreWriteVector: DynStateStoreWriteEpochControl + StaticSendSync {
1374        fn insert(&mut self, vec: VectorRef<'_>, info: Bytes) -> StorageResult<()>;
1375    }
1376
1377    #[async_trait::async_trait]
1378    impl<S: StateStoreWriteVector> DynStateStoreWriteVector for S {
1379        fn insert(&mut self, vec: VectorRef<'_>, info: Bytes) -> StorageResult<()> {
1380            self.insert(vec, info)
1381        }
1382    }
1383
1384    pub type BoxDynStateStoreWriteVector = StateStorePointer<Box<dyn DynStateStoreWriteVector>>;
1385
1386    impl StateStoreWriteVector for BoxDynStateStoreWriteVector {
1387        fn insert(&mut self, vec: VectorRef<'_>, info: Bytes) -> StorageResult<()> {
1388            self.0.insert(vec, info)
1389        }
1390    }
1391
1392    // For global StateStore
1393
1394    #[async_trait::async_trait]
1395    pub trait DynStateStoreReadVector: StaticSendSync {
1396        async fn nearest(
1397            &self,
1398            vec: VectorRef<'_>,
1399            options: VectorNearestOptions,
1400        ) -> StorageResult<Vec<(Vector, VectorDistance, Bytes)>>;
1401    }
1402
1403    #[async_trait::async_trait]
1404    impl<S: StateStoreReadVector> DynStateStoreReadVector for S {
1405        async fn nearest(
1406            &self,
1407            vec: VectorRef<'_>,
1408            options: VectorNearestOptions,
1409        ) -> StorageResult<Vec<(Vector, VectorDistance, Bytes)>> {
1410            use risingwave_common::types::ScalarRef;
1411            self.nearest(vec, options, |vec, distance, info| {
1412                (
1413                    vec.to_owned_scalar(),
1414                    distance,
1415                    Bytes::copy_from_slice(info),
1416                )
1417            })
1418            .await
1419        }
1420    }
1421
1422    impl<P> StateStoreReadVector for StateStorePointer<P>
1423    where
1424        StateStorePointer<P>: AsRef<dyn DynStateStoreReadVector> + StaticSendSync,
1425    {
1426        async fn nearest<'a, O: Send + 'a>(
1427            &'a self,
1428            vec: VectorRef<'a>,
1429            options: VectorNearestOptions,
1430            on_nearest_item_fn: impl OnNearestItemFn<'a, O>,
1431        ) -> StorageResult<Vec<O>> {
1432            let output = self.as_ref().nearest(vec, options).await?;
1433            Ok(output
1434                .into_iter()
1435                .map(|(vec, distance, info)| {
1436                    on_nearest_item_fn(vec.to_ref(), distance, info.as_ref())
1437                })
1438                .collect())
1439        }
1440    }
1441
1442    pub trait DynStateStoreReadSnapshot:
1443        DynStateStoreRead + DynStateStoreReadVector + StaticSendSync
1444    {
1445    }
1446
1447    impl<S: DynStateStoreRead + DynStateStoreReadVector + StaticSendSync> DynStateStoreReadSnapshot
1448        for S
1449    {
1450    }
1451
1452    pub type StateStoreReadSnapshotDynRef = StateStorePointer<Arc<dyn DynStateStoreReadSnapshot>>;
1453    #[async_trait::async_trait]
1454    pub trait DynStateStoreExt: StaticSendSync {
1455        async fn try_wait_epoch(
1456            &self,
1457            epoch: HummockReadEpoch,
1458            options: TryWaitEpochOptions,
1459        ) -> StorageResult<()>;
1460
1461        async fn new_local(&self, option: NewLocalOptions) -> BoxDynLocalStateStore;
1462        async fn new_read_snapshot(
1463            &self,
1464            epoch: HummockReadEpoch,
1465            options: NewReadSnapshotOptions,
1466        ) -> StorageResult<StateStoreReadSnapshotDynRef>;
1467        async fn new_vector_writer(
1468            &self,
1469            options: NewVectorWriterOptions,
1470        ) -> BoxDynStateStoreWriteVector;
1471    }
1472
1473    #[async_trait::async_trait]
1474    impl<S: StateStore> DynStateStoreExt for S {
1475        async fn try_wait_epoch(
1476            &self,
1477            epoch: HummockReadEpoch,
1478            options: TryWaitEpochOptions,
1479        ) -> StorageResult<()> {
1480            self.try_wait_epoch(epoch, options).await
1481        }
1482
1483        async fn new_local(&self, option: NewLocalOptions) -> BoxDynLocalStateStore {
1484            StateStorePointer(Box::new(self.new_local(option).await))
1485        }
1486
1487        async fn new_read_snapshot(
1488            &self,
1489            epoch: HummockReadEpoch,
1490            options: NewReadSnapshotOptions,
1491        ) -> StorageResult<StateStoreReadSnapshotDynRef> {
1492            Ok(StateStorePointer(Arc::new(
1493                self.new_read_snapshot(epoch, options).await?,
1494            )))
1495        }
1496
1497        async fn new_vector_writer(
1498            &self,
1499            options: NewVectorWriterOptions,
1500        ) -> BoxDynStateStoreWriteVector {
1501            StateStorePointer(Box::new(self.new_vector_writer(options).await))
1502        }
1503    }
1504
1505    pub type StateStoreDynRef = StateStorePointer<Arc<dyn DynStateStore>>;
1506
1507    macro_rules! state_store_pointer_dyn_as_ref {
1508        ($pointer:ident < dyn $source_dyn_trait:ident > , $target_dyn_trait:ident) => {
1509            impl AsRef<dyn $target_dyn_trait>
1510                for StateStorePointer<$pointer<dyn $source_dyn_trait>>
1511            {
1512                fn as_ref(&self) -> &dyn $target_dyn_trait {
1513                    (&*self.0) as _
1514                }
1515            }
1516        };
1517    }
1518
1519    state_store_pointer_dyn_as_ref!(Arc<dyn DynStateStoreReadSnapshot>, DynStateStoreRead);
1520    state_store_pointer_dyn_as_ref!(Arc<dyn DynStateStoreReadSnapshot>, DynStateStoreGet);
1521    state_store_pointer_dyn_as_ref!(Arc<dyn DynStateStoreReadSnapshot>, DynStateStoreReadVector);
1522    state_store_pointer_dyn_as_ref!(Arc<dyn DynStateStoreRead>, DynStateStoreRead);
1523    state_store_pointer_dyn_as_ref!(Arc<dyn DynStateStoreRead>, DynStateStoreGet);
1524    state_store_pointer_dyn_as_ref!(Box<dyn DynLocalStateStore>, DynStateStoreGet);
1525
1526    macro_rules! state_store_pointer_dyn_as_mut {
1527        ($pointer:ident < dyn $source_dyn_trait:ident > , $target_dyn_trait:ident) => {
1528            impl AsMut<dyn $target_dyn_trait>
1529                for StateStorePointer<$pointer<dyn $source_dyn_trait>>
1530            {
1531                fn as_mut(&mut self) -> &mut dyn $target_dyn_trait {
1532                    (&mut *self.0) as _
1533                }
1534            }
1535        };
1536    }
1537
1538    state_store_pointer_dyn_as_mut!(Box<dyn DynLocalStateStore>, DynStateStoreWriteEpochControl);
1539    state_store_pointer_dyn_as_mut!(
1540        Box<dyn DynStateStoreWriteVector>,
1541        DynStateStoreWriteEpochControl
1542    );
1543
1544    #[derive(Clone)]
1545    pub struct StateStorePointer<P>(pub(crate) P);
1546
1547    impl<P> StateStoreGet for StateStorePointer<P>
1548    where
1549        StateStorePointer<P>: AsRef<dyn DynStateStoreGet> + StaticSendSync,
1550    {
1551        async fn on_key_value<'a, O: Send + 'a>(
1552            &'a self,
1553            key: TableKey<Bytes>,
1554            read_options: ReadOptions,
1555            on_key_value_fn: impl KeyValueFn<'a, O>,
1556        ) -> StorageResult<Option<O>> {
1557            let option = self.as_ref().get_keyed_row(key, read_options).await?;
1558            option
1559                .map(|(key, value)| on_key_value_fn(key.to_ref(), value.as_ref()))
1560                .transpose()
1561        }
1562    }
1563
1564    impl<P> StateStoreRead for StateStorePointer<P>
1565    where
1566        StateStorePointer<P>: AsRef<dyn DynStateStoreRead> + StateStoreGet + StaticSendSync,
1567    {
1568        type Iter = BoxStateStoreReadIter;
1569        type RevIter = BoxStateStoreReadIter;
1570
1571        fn iter(
1572            &self,
1573            key_range: TableKeyRange,
1574
1575            read_options: ReadOptions,
1576        ) -> impl Future<Output = StorageResult<Self::Iter>> + '_ {
1577            self.as_ref().iter(key_range, read_options)
1578        }
1579
1580        fn rev_iter(
1581            &self,
1582            key_range: TableKeyRange,
1583
1584            read_options: ReadOptions,
1585        ) -> impl Future<Output = StorageResult<Self::RevIter>> + '_ {
1586            self.as_ref().rev_iter(key_range, read_options)
1587        }
1588    }
1589
1590    impl StateStoreReadLog for StateStoreDynRef {
1591        type ChangeLogIter = BoxStateStoreReadChangeLogIter;
1592
1593        async fn next_epoch(&self, epoch: u64, options: NextEpochOptions) -> StorageResult<u64> {
1594            (*self.0).next_epoch(epoch, options).await
1595        }
1596
1597        fn iter_log(
1598            &self,
1599            epoch_range: (u64, u64),
1600            key_range: TableKeyRange,
1601            options: ReadLogOptions,
1602        ) -> impl Future<Output = StorageResult<Self::ChangeLogIter>> + Send + '_ {
1603            (*self.0).iter_log(epoch_range, key_range, options)
1604        }
1605    }
1606
1607    pub trait DynStateStore: DynStateStoreReadLog + DynStateStoreExt + AsHummock {}
1608
1609    impl AsHummock for StateStoreDynRef {
1610        fn as_hummock(&self) -> Option<&HummockStorage> {
1611            (*self.0).as_hummock()
1612        }
1613    }
1614
1615    impl<S: DynStateStoreReadLog + DynStateStoreExt + AsHummock> DynStateStore for S {}
1616
1617    impl StateStore for StateStoreDynRef {
1618        type Local = BoxDynLocalStateStore;
1619        type ReadSnapshot = StateStoreReadSnapshotDynRef;
1620        type VectorWriter = BoxDynStateStoreWriteVector;
1621
1622        fn try_wait_epoch(
1623            &self,
1624            epoch: HummockReadEpoch,
1625            options: TryWaitEpochOptions,
1626        ) -> impl Future<Output = StorageResult<()>> + Send + '_ {
1627            (*self.0).try_wait_epoch(epoch, options)
1628        }
1629
1630        fn new_local(
1631            &self,
1632            option: NewLocalOptions,
1633        ) -> impl Future<Output = Self::Local> + Send + '_ {
1634            (*self.0).new_local(option)
1635        }
1636
1637        async fn new_read_snapshot(
1638            &self,
1639            epoch: HummockReadEpoch,
1640            options: NewReadSnapshotOptions,
1641        ) -> StorageResult<Self::ReadSnapshot> {
1642            (*self.0).new_read_snapshot(epoch, options).await
1643        }
1644
1645        fn new_vector_writer(
1646            &self,
1647            options: NewVectorWriterOptions,
1648        ) -> impl Future<Output = Self::VectorWriter> + Send + '_ {
1649            (*self.0).new_vector_writer(options)
1650        }
1651    }
1652}