Skip to main content

common_function/
state.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 common_base::Plugins;
16
17use crate::handlers::{FlowServiceHandlerRef, ProcedureServiceHandlerRef, TableMutationHandlerRef};
18
19/// Shared state for SQL functions.
20/// The handlers in state may be `None` in cli command-line or test cases.
21#[derive(Clone, Default)]
22pub struct FunctionState {
23    /// Process plugins available to dynamically registered functions.
24    pub plugins: Plugins,
25    // The table mutation handler
26    pub table_mutation_handler: Option<TableMutationHandlerRef>,
27    // The procedure service handler
28    pub procedure_service_handler: Option<ProcedureServiceHandlerRef>,
29    // The flownode handler
30    pub flow_service_handler: Option<FlowServiceHandlerRef>,
31}
32
33impl FunctionState {
34    /// Create a mock [`FunctionState`] for test.
35    #[cfg(any(test, feature = "testing"))]
36    pub fn mock() -> Self {
37        Self::mock_with_procedure_state_counter(Default::default())
38    }
39
40    /// Creates a mock state that counts procedure state queries.
41    #[cfg(any(test, feature = "testing"))]
42    pub fn mock_with_procedure_state_counter(
43        calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
44    ) -> Self {
45        Self::mock_with_procedure_results(calls, Some("test_pid".to_string()))
46    }
47
48    #[cfg(any(test, feature = "testing"))]
49    pub(crate) fn mock_with_procedure_results(
50        calls: std::sync::Arc<std::sync::atomic::AtomicUsize>,
51        migration_pid: Option<String>,
52    ) -> Self {
53        use std::sync::Arc;
54        use std::sync::atomic::{AtomicUsize, Ordering};
55
56        use api::v1::meta::{ProcedureStatus, ReconcileRequest};
57        use async_trait::async_trait;
58        use catalog::CatalogManagerRef;
59        use common_base::AffectedRows;
60        use common_meta::rpc::procedure::{
61            GcRegionsRequest, GcResponse, GcTableRequest, ManageRegionFollowerRequest,
62            MigrateRegionRequest, ProcedureStateResponse,
63        };
64        use common_query::Output;
65        use common_query::error::Result;
66        use session::context::QueryContextRef;
67        use store_api::storage::RegionId;
68        use table::requests::{
69            BuildIndexTableRequest, CompactTableRequest, DeleteRequest, FlushTableRequest,
70            InsertRequest,
71        };
72        use table::table_name::TableName;
73
74        use crate::handlers::{FlowServiceHandler, ProcedureServiceHandler, TableMutationHandler};
75        struct MockProcedureServiceHandler {
76            calls: Arc<AtomicUsize>,
77            migration_pid: Option<String>,
78        }
79        struct MockTableMutationHandler;
80        struct MockFlowServiceHandler;
81        const ROWS: usize = 42;
82
83        #[async_trait]
84        impl ProcedureServiceHandler for MockProcedureServiceHandler {
85            async fn purge_table(
86                &self,
87                _query_ctx: QueryContextRef,
88                _table_name: table::table_name::TableName,
89            ) -> Result<()> {
90                Ok(())
91            }
92
93            async fn migrate_region(
94                &self,
95                _ctx: QueryContextRef,
96                _request: MigrateRegionRequest,
97            ) -> Result<Option<String>> {
98                Ok(self.migration_pid.clone())
99            }
100
101            async fn reconcile(&self, _request: ReconcileRequest) -> Result<Option<String>> {
102                Ok(Some("test_pid".to_string()))
103            }
104
105            async fn query_procedure_state(&self, _pid: &str) -> Result<ProcedureStateResponse> {
106                self.calls.fetch_add(1, Ordering::Relaxed);
107                Ok(ProcedureStateResponse {
108                    status: ProcedureStatus::Done.into(),
109                    error: "OK".to_string(),
110                    ..Default::default()
111                })
112            }
113
114            async fn manage_region_follower(
115                &self,
116                _query_ctx: QueryContextRef,
117                _request: ManageRegionFollowerRequest,
118            ) -> Result<()> {
119                Ok(())
120            }
121
122            async fn gc_regions(
123                &self,
124                _context: QueryContextRef,
125                _request: GcRegionsRequest,
126            ) -> Result<GcResponse> {
127                Ok(GcResponse {
128                    processed_regions: 1,
129                    need_retry_regions: vec![],
130                    deleted_files: 0,
131                    deleted_indexes: 0,
132                })
133            }
134
135            async fn gc_table(
136                &self,
137                _context: QueryContextRef,
138                _request: GcTableRequest,
139            ) -> Result<GcResponse> {
140                Ok(GcResponse {
141                    processed_regions: 1,
142                    need_retry_regions: vec![],
143                    deleted_files: 0,
144                    deleted_indexes: 0,
145                })
146            }
147
148            fn catalog_manager(&self) -> &CatalogManagerRef {
149                unimplemented!()
150            }
151        }
152
153        #[async_trait]
154        impl TableMutationHandler for MockTableMutationHandler {
155            async fn insert(
156                &self,
157                _request: InsertRequest,
158                _ctx: QueryContextRef,
159            ) -> Result<Output> {
160                Ok(Output::new_with_affected_rows(ROWS))
161            }
162
163            async fn delete(
164                &self,
165                _request: DeleteRequest,
166                _ctx: QueryContextRef,
167            ) -> Result<AffectedRows> {
168                Ok(ROWS)
169            }
170
171            async fn flush(
172                &self,
173                _request: FlushTableRequest,
174                _ctx: QueryContextRef,
175            ) -> Result<AffectedRows> {
176                Ok(ROWS)
177            }
178
179            async fn compact(
180                &self,
181                _request: CompactTableRequest,
182                _ctx: QueryContextRef,
183            ) -> Result<AffectedRows> {
184                Ok(ROWS)
185            }
186
187            async fn build_index(
188                &self,
189                _request: BuildIndexTableRequest,
190                _ctx: QueryContextRef,
191            ) -> Result<AffectedRows> {
192                Ok(ROWS)
193            }
194
195            async fn flush_region(
196                &self,
197                _region_id: RegionId,
198                _ctx: QueryContextRef,
199            ) -> Result<AffectedRows> {
200                Ok(ROWS)
201            }
202
203            async fn compact_region(
204                &self,
205                _region_id: RegionId,
206                _ctx: QueryContextRef,
207            ) -> Result<AffectedRows> {
208                Ok(ROWS)
209            }
210
211            async fn cancel_region_compaction(
212                &self,
213                _region_id: RegionId,
214                _task_id: String,
215                _ctx: QueryContextRef,
216            ) -> Result<AffectedRows> {
217                Ok(ROWS)
218            }
219
220            async fn discard_unflushed_data(
221                &self,
222                _region_id: RegionId,
223                _ctx: QueryContextRef,
224            ) -> Result<AffectedRows> {
225                Ok(ROWS)
226            }
227
228            async fn discard_unflushed_data_by_table(
229                &self,
230                _table_name: TableName,
231                _ctx: QueryContextRef,
232            ) -> Result<AffectedRows> {
233                Ok(ROWS)
234            }
235
236            /// Returns the node id; the table form adds ROWS, so tests can tell the forms apart.
237            async fn discard_pending_tails(
238                &self,
239                _region_id: RegionId,
240                node_id: u64,
241                _ctx: QueryContextRef,
242            ) -> Result<AffectedRows> {
243                Ok(node_id as AffectedRows)
244            }
245
246            async fn discard_pending_tails_by_table(
247                &self,
248                _table_name: TableName,
249                node_id: u64,
250                _ctx: QueryContextRef,
251            ) -> Result<AffectedRows> {
252                Ok(ROWS + node_id as AffectedRows)
253            }
254        }
255
256        #[async_trait]
257        impl FlowServiceHandler for MockFlowServiceHandler {
258            async fn flush(
259                &self,
260                _catalog: &str,
261                _flow: &str,
262                _ctx: QueryContextRef,
263            ) -> Result<api::v1::flow::FlowResponse> {
264                todo!()
265            }
266        }
267
268        Self {
269            plugins: Plugins::default(),
270            table_mutation_handler: Some(Arc::new(MockTableMutationHandler)),
271            procedure_service_handler: Some(Arc::new(MockProcedureServiceHandler {
272                calls,
273                migration_pid,
274            })),
275            flow_service_handler: Some(Arc::new(MockFlowServiceHandler)),
276        }
277    }
278}