Skip to main content

common_function/admin/
cancel_region_compaction.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 arrow::datatypes::DataType as ArrowDataType;
16use common_macro::admin_fn;
17use common_query::error::{
18    InvalidFuncArgsSnafu, MissingTableMutationHandlerSnafu, Result, UnsupportedInputDataTypeSnafu,
19};
20use datafusion_expr::Signature;
21use datatypes::data_type::DataType;
22use datatypes::prelude::{ConcreteDataType, Value, ValueRef};
23use session::context::QueryContextRef;
24use snafu::ensure;
25use store_api::storage::RegionId;
26
27use crate::handlers::TableMutationHandlerRef;
28use crate::helper;
29
30/// Cancels the region compaction identified by `(region_id, task_id)`.
31/// Returns one when cancellation is issued or already pending, and zero when absent.
32#[admin_fn(
33    name = CancelRegionCompactionFunction,
34    display_name = cancel_region_compaction,
35    sig_fn = signature,
36    ret = uint64
37)]
38pub(crate) async fn cancel_region_compaction(
39    table_mutation_handler: &TableMutationHandlerRef,
40    query_ctx: &QueryContextRef,
41    params: &[ValueRef<'_>],
42) -> Result<Value> {
43    ensure!(
44        params.len() == 2,
45        InvalidFuncArgsSnafu {
46            err_msg: format!(
47                "cancel_region_compaction expects 2 arguments, received {}",
48                params.len()
49            ),
50        }
51    );
52    let Some(region_id) = helper::cast_u64(&params[0])? else {
53        return UnsupportedInputDataTypeSnafu {
54            function: "cancel_region_compaction",
55            datatypes: params
56                .iter()
57                .map(|value| value.data_type())
58                .collect::<Vec<_>>(),
59        }
60        .fail();
61    };
62    let ValueRef::String(task_id) = params[1] else {
63        return InvalidFuncArgsSnafu {
64            err_msg: "task_id must be a non-empty string",
65        }
66        .fail();
67    };
68    ensure!(
69        !task_id.trim().is_empty(),
70        InvalidFuncArgsSnafu {
71            err_msg: "task_id must be a non-empty string"
72        }
73    );
74    let affected_rows = table_mutation_handler
75        .cancel_region_compaction(
76            RegionId::from_u64(region_id),
77            task_id.to_string(),
78            query_ctx.clone(),
79        )
80        .await?;
81    Ok(Value::from(affected_rows as u64))
82}
83
84fn signature() -> Signature {
85    // Matches COMPACT_REGION: primitive numerics without Decimal or Float16 overloads.
86    helper::one_of_sigs2(
87        ConcreteDataType::numerics()
88            .into_iter()
89            .map(|data_type| data_type.as_arrow_type())
90            .collect(),
91        vec![ArrowDataType::Utf8],
92    )
93}
94
95#[cfg(test)]
96mod tests {
97    use std::sync::Arc;
98
99    use arrow::datatypes::Field;
100    use datafusion_common::ScalarValue;
101    use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
102
103    use super::*;
104    use crate::function::FunctionContext;
105    use crate::function_registry;
106
107    #[tokio::test]
108    async fn test_cancel_region_compaction_arguments() {
109        let ctx = FunctionContext::mock();
110        let handler = ctx.state.table_mutation_handler.as_ref().unwrap();
111        for params in [
112            vec![],
113            vec![ValueRef::UInt64(42)],
114            vec![
115                ValueRef::UInt64(42),
116                ValueRef::String("task"),
117                ValueRef::Null,
118            ],
119            vec![ValueRef::Null, ValueRef::String("task")],
120            vec![ValueRef::UInt64(42), ValueRef::Null],
121            vec![ValueRef::UInt64(42), ValueRef::UInt64(1)],
122            vec![ValueRef::UInt64(42), ValueRef::String(" \t")],
123        ] {
124            assert!(
125                cancel_region_compaction(handler, &ctx.query_ctx, &params)
126                    .await
127                    .is_err(),
128                "{params:?}"
129            );
130        }
131        let error = cancel_region_compaction(
132            handler,
133            &ctx.query_ctx,
134            &[ValueRef::Null, ValueRef::String("cycle-id")],
135        )
136        .await
137        .unwrap_err();
138        assert!(matches!(
139            error,
140            common_query::error::Error::UnsupportedInputDataType { .. }
141        ));
142        assert_eq!(
143            cancel_region_compaction(
144                handler,
145                &ctx.query_ctx,
146                &[ValueRef::UInt64(u64::MAX), ValueRef::String("cycle-id")]
147            )
148            .await
149            .unwrap(),
150            Value::UInt64(42)
151        );
152    }
153
154    #[tokio::test]
155    async fn test_cancel_region_compaction_async_function() {
156        let factory = function_registry::FUNCTION_REGISTRY
157            .get_function("cancel_region_compaction")
158            .unwrap();
159        for (ctx, has_handler) in [
160            (FunctionContext::mock(), true),
161            (FunctionContext::default(), false),
162        ] {
163            let function = factory.provide(ctx);
164            let result = function
165                .as_async()
166                .unwrap()
167                .invoke_async_with_args(ScalarFunctionArgs {
168                    args: vec![
169                        ColumnarValue::Scalar(ScalarValue::UInt64(Some(u64::MAX))),
170                        ColumnarValue::Scalar(ScalarValue::Utf8(Some("cycle-id".into()))),
171                    ],
172                    arg_fields: vec![
173                        Arc::new(Field::new("region_id", ArrowDataType::UInt64, false)),
174                        Arc::new(Field::new("task_id", ArrowDataType::Utf8, false)),
175                    ],
176                    return_field: Arc::new(Field::new("result", ArrowDataType::UInt64, false)),
177                    number_rows: 1,
178                    config_options: Default::default(),
179                })
180                .await;
181            if has_handler {
182                let ColumnarValue::Array(array) = result.unwrap() else {
183                    panic!("expected array output");
184                };
185                assert_eq!(
186                    ScalarValue::try_from_array(&array, 0).unwrap(),
187                    ScalarValue::UInt64(Some(42))
188                );
189            } else {
190                assert!(
191                    result
192                        .unwrap_err()
193                        .to_string()
194                        .contains("Missing TableMutationHandler")
195                );
196            }
197        }
198    }
199
200    #[test]
201    fn test_cancel_region_compaction_registration_and_signature() {
202        let factory = function_registry::FUNCTION_REGISTRY
203            .get_function("cancel_region_compaction")
204            .unwrap();
205        let function = factory.provide(FunctionContext::mock());
206        assert_eq!(function.name(), "cancel_region_compaction");
207        assert_eq!(function.return_type(&[]).unwrap(), ArrowDataType::UInt64);
208        assert_eq!(function.signature(), &signature());
209    }
210}