Skip to main content

common_function/admin/
discard_pending_tails.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_error::ext::BoxedError;
17use common_macro::admin_fn;
18use common_query::error::{
19    InvalidFuncArgsSnafu, MissingTableMutationHandlerSnafu, Result, TableMutationSnafu,
20    UnsupportedInputDataTypeSnafu,
21};
22use datafusion_expr::Signature;
23use datatypes::data_type::DataType;
24use datatypes::prelude::*;
25use session::context::QueryContextRef;
26use session::table_name::table_name_to_full_name;
27use snafu::{ResultExt, ensure};
28use store_api::storage::RegionId;
29use table::table_name::TableName;
30
31use crate::handlers::TableMutationHandlerRef;
32use crate::helper::{cast_u64, one_of_sigs2};
33
34/// Discards the pending WAL tails that a datanode wrote from a region or from all regions
35/// of a table, without replaying them. Returns the number of discarded tails.
36///
37/// A region's flushed entry id is raised to the largest bound of the tails it discards. Where
38/// the WAL checks its history when a region opens, as the object-store WAL does after the
39/// datanode restarts, the region then opens only if the WAL of the datanode that leads the
40/// region holds history through that bound, unless the WAL is configured to accept missing
41/// history, which opens the region and loses its writes that were not flushed. The function
42/// does not check this: whoever records the tails ensures it.
43///
44/// - `region_id` or `table_name`: the region or the table.
45/// - `node_id`: the datanode that wrote the tails.
46#[admin_fn(
47    name = DiscardPendingTailsFunction,
48    display_name = discard_pending_tails,
49    sig_fn = signature,
50    ret = uint64,
51    single_row
52)]
53pub(crate) async fn discard_pending_tails(
54    table_mutation_handler: &TableMutationHandlerRef,
55    query_ctx: &QueryContextRef,
56    params: &[ValueRef<'_>],
57) -> Result<Value> {
58    ensure!(
59        params.len() == 2,
60        InvalidFuncArgsSnafu {
61            err_msg: format!(
62                "The length of the args is not correct, expect 2, have: {}",
63                params.len()
64            ),
65        }
66    );
67    let Some(node_id) = cast_u64(&params[1])? else {
68        return UnsupportedInputDataTypeSnafu {
69            function: "discard_pending_tails",
70            datatypes: params
71                .iter()
72                .map(|value| value.data_type())
73                .collect::<Vec<_>>(),
74        }
75        .fail();
76    };
77
78    let discarded = match params[0] {
79        ValueRef::String(table_name) => {
80            let (catalog_name, schema_name, table_name) =
81                table_name_to_full_name(table_name, query_ctx)
82                    .map_err(BoxedError::new)
83                    .context(TableMutationSnafu)?;
84            table_mutation_handler
85                .discard_pending_tails_by_table(
86                    TableName::new(catalog_name, schema_name, table_name),
87                    node_id,
88                    query_ctx.clone(),
89                )
90                .await?
91        }
92        _ => {
93            let Some(region_id) = cast_u64(&params[0])? else {
94                return UnsupportedInputDataTypeSnafu {
95                    function: "discard_pending_tails",
96                    datatypes: params
97                        .iter()
98                        .map(|value| value.data_type())
99                        .collect::<Vec<_>>(),
100                }
101                .fail();
102            };
103            table_mutation_handler
104                .discard_pending_tails(RegionId::from_u64(region_id), node_id, query_ctx.clone())
105                .await?
106        }
107    };
108
109    Ok(Value::from(discarded as u64))
110}
111
112fn signature() -> Signature {
113    let numerics = ConcreteDataType::numerics()
114        .into_iter()
115        .map(|data_type| data_type.as_arrow_type())
116        .collect::<Vec<_>>();
117    let mut targets = numerics.clone();
118    targets.push(ArrowDataType::Utf8);
119    one_of_sigs2(targets, numerics)
120}
121
122#[cfg(test)]
123mod tests {
124    use std::sync::Arc;
125
126    use arrow::array::{StringArray, UInt64Array};
127    use arrow::datatypes::{DataType, Field};
128    use datafusion_expr::ColumnarValue;
129
130    use super::*;
131    use crate::function::FunctionContext;
132    use crate::function_factory::ScalarFunctionFactory;
133    use crate::function_registry::{FUNCTION_REGISTRY, get_admin_function};
134
135    #[test]
136    fn test_discard_pending_tails_is_admin_only() {
137        assert!(get_admin_function("discard_pending_tails").is_some());
138        assert!(
139            FUNCTION_REGISTRY
140                .get_function("discard_pending_tails")
141                .is_none()
142        );
143    }
144
145    /// Calls the function with `args`; the mock handler returns the node id for a region and
146    /// 42 plus the node id for a table.
147    async fn call(args: Vec<(ColumnarValue, DataType)>) -> datafusion_common::Result<u64> {
148        let factory: ScalarFunctionFactory = DiscardPendingTailsFunction::factory().into();
149        let function = factory.provide(FunctionContext::mock());
150        let (args, arg_fields): (Vec<_>, Vec<_>) = args
151            .into_iter()
152            .enumerate()
153            .map(|(i, (arg, data_type))| {
154                (
155                    arg,
156                    Arc::new(Field::new(format!("arg_{i}"), data_type, false)),
157                )
158            })
159            .unzip();
160        let args = datafusion::logical_expr::ScalarFunctionArgs {
161            args,
162            arg_fields,
163            return_field: Arc::new(Field::new("result", DataType::UInt64, false)),
164            number_rows: 1,
165            config_options: Arc::new(datafusion_common::config::ConfigOptions::default()),
166        };
167        let ColumnarValue::Array(array) = function
168            .as_async()
169            .unwrap()
170            .invoke_async_with_args(args)
171            .await?
172        else {
173            panic!("expected array output");
174        };
175        Ok(array
176            .as_any()
177            .downcast_ref::<UInt64Array>()
178            .unwrap()
179            .value(0))
180    }
181
182    fn uint64(value: u64) -> (ColumnarValue, DataType) {
183        let array = Arc::new(UInt64Array::from(vec![value]));
184        (ColumnarValue::Array(array), DataType::UInt64)
185    }
186
187    fn string(value: &str) -> (ColumnarValue, DataType) {
188        let array = Arc::new(StringArray::from(vec![value]));
189        (ColumnarValue::Array(array), DataType::Utf8)
190    }
191
192    #[tokio::test]
193    async fn test_discard_pending_tails_of_region_or_table() {
194        assert_eq!(7, call(vec![uint64(99), uint64(7)]).await.unwrap());
195        assert_eq!(49, call(vec![string("my_table"), uint64(7)]).await.unwrap());
196    }
197
198    #[tokio::test]
199    async fn test_discard_pending_tails_requires_two_arguments() {
200        let error = call(vec![uint64(99)]).await.unwrap_err();
201        assert!(error.to_string().contains("expect 2, have: 1"), "{error}");
202    }
203}