Skip to main content

query/
region_query.rs

1// Copyright 2023 Greptime Team
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::sync::Arc;
16
17use api::v1::region::{RemoteDynFilterUnregister, RemoteDynFilterUpdate};
18use async_trait::async_trait;
19use common_meta::node_manager::NodeManagerRef;
20use common_meta::peer::Peer;
21use common_query::request::QueryRequest;
22use common_recordbatch::SendableRecordBatchStream;
23use partition::manager::PartitionRuleManagerRef;
24use session::ReadPreference;
25use tokio::sync::{Semaphore, SemaphorePermit};
26
27use crate::error::Result;
28
29/// Caps the region reads one query keeps in flight.
30///
31/// A region read is a `DoGet` whose body streams until that region is drained, so a query
32/// reading several sources would otherwise run one body per source and partition at once.
33/// The bound belongs to the query, not to one scan: its permit count is the query's target
34/// partitions, so two scans of three regions no longer read four bodies at once.
35pub(crate) struct RegionReadLimiter {
36    permits: Semaphore,
37}
38
39impl RegionReadLimiter {
40    pub(crate) fn new(permits: usize) -> Self {
41        Self {
42            permits: Semaphore::new(permits.max(1)),
43        }
44    }
45
46    /// Waits for one region read to be allowed; the read stays counted until the permit drops.
47    pub(crate) async fn acquire(&self) -> SemaphorePermit<'_> {
48        self.permits
49            .acquire()
50            .await
51            .expect("the region read limiter is never closed")
52    }
53}
54
55/// The peer selected to serve a region query.
56///
57/// The target is frozen when the query is dispatched. Follow-up controls must
58/// reuse it instead of resolving the region route again.
59#[derive(Clone, Debug, PartialEq, Eq, Hash)]
60pub struct RegionQueryTarget(Peer);
61
62impl RegionQueryTarget {
63    pub fn new(peer: Peer) -> Self {
64        Self(peer)
65    }
66
67    pub fn peer(&self) -> &Peer {
68        &self.0
69    }
70}
71
72/// A factory to create a [`RegionQueryHandler`].
73pub trait RegionQueryHandlerFactory: Send + Sync {
74    /// Build a [`RegionQueryHandler`] with the given partition manager and node manager.
75    fn build(
76        &self,
77        partition_manager: PartitionRuleManagerRef,
78        node_manager: NodeManagerRef,
79    ) -> RegionQueryHandlerRef;
80}
81
82pub type RegionQueryHandlerFactoryRef = Arc<dyn RegionQueryHandlerFactory>;
83
84#[async_trait]
85pub trait RegionQueryHandler: Send + Sync {
86    async fn select_target(
87        &self,
88        read_preference: ReadPreference,
89        region_id: store_api::storage::RegionId,
90    ) -> Result<RegionQueryTarget>;
91
92    async fn do_get(
93        &self,
94        target: &RegionQueryTarget,
95        request: QueryRequest,
96    ) -> Result<SendableRecordBatchStream>;
97
98    async fn handle_remote_dyn_filter_update(
99        &self,
100        target: &RegionQueryTarget,
101        query_id: String,
102        update: RemoteDynFilterUpdate,
103    ) -> Result<()>;
104
105    async fn handle_remote_dyn_filter_unregister(
106        &self,
107        target: &RegionQueryTarget,
108        query_id: String,
109        unregister: RemoteDynFilterUnregister,
110    ) -> Result<()>;
111}
112
113pub type RegionQueryHandlerRef = Arc<dyn RegionQueryHandler>;
114
115#[cfg(test)]
116pub(crate) mod tests {
117    use async_trait::async_trait;
118    use common_meta::peer::Peer;
119    use session::ReadPreference;
120    use store_api::storage::RegionId;
121
122    use super::{RegionQueryHandler, RegionQueryTarget};
123
124    pub(crate) struct PlanningOnlyRegionQueryHandler;
125
126    #[async_trait]
127    impl RegionQueryHandler for PlanningOnlyRegionQueryHandler {
128        async fn select_target(
129            &self,
130            _read_preference: ReadPreference,
131            _region_id: RegionId,
132        ) -> crate::error::Result<RegionQueryTarget> {
133            unimplemented!("planning test does not dispatch regions")
134        }
135
136        async fn do_get(
137            &self,
138            _target: &RegionQueryTarget,
139            _request: common_query::request::QueryRequest,
140        ) -> crate::error::Result<common_recordbatch::SendableRecordBatchStream> {
141            unimplemented!("planning test does not dispatch regions")
142        }
143
144        async fn handle_remote_dyn_filter_update(
145            &self,
146            _target: &RegionQueryTarget,
147            _query_id: String,
148            _update: api::v1::region::RemoteDynFilterUpdate,
149        ) -> crate::error::Result<()> {
150            unimplemented!("planning test does not dispatch regions")
151        }
152
153        async fn handle_remote_dyn_filter_unregister(
154            &self,
155            _target: &RegionQueryTarget,
156            _query_id: String,
157            _unregister: api::v1::region::RemoteDynFilterUnregister,
158        ) -> crate::error::Result<()> {
159            unimplemented!("planning test does not dispatch regions")
160        }
161    }
162
163    #[test]
164    fn region_query_target_exposes_immutable_peer() {
165        let peer = Peer {
166            id: 42,
167            addr: "127.0.0.1:3001".to_string(),
168        };
169        let target = RegionQueryTarget::new(peer.clone());
170
171        assert_eq!(target.peer(), &peer);
172    }
173}