Skip to main content

operator/
request.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::helper::to_pb_time_unit;
18use api::v1::region::region_request::Body as RegionRequestBody;
19use api::v1::region::{
20    BuildIndexRequest, CancelCompactionRequest, CompactRequest, CompactionTimeRange,
21    DiscardPendingTailsRequest, FlushRequest, RegionRequestHeader, TruncateRequest, Unflushed,
22    build_index_request, truncate_request,
23};
24use catalog::CatalogManagerRef;
25use common_catalog::build_db_string;
26use common_catalog::consts::METRIC_ENGINE;
27use common_meta::node_manager::{AffectedRows, NodeManagerRef};
28use common_meta::peer::Peer;
29use common_telemetry::tracing_context::TracingContext;
30use common_telemetry::{debug, error, info, warn};
31use common_time::range::TimestampRange;
32use common_time::timestamp::TimeUnit as TimestampUnit;
33use futures_util::future;
34use partition::cache::PhysicalPartitionInfo;
35use partition::manager::PartitionRuleManagerRef;
36use session::context::QueryContextRef;
37use snafu::prelude::*;
38use store_api::metric_engine_consts;
39use store_api::storage::RegionId;
40use table::metadata::{TableId, TableInfoRef};
41use table::requests::{BuildIndexTableRequest, CompactTableRequest, FlushTableRequest};
42use table::table_name::TableName;
43
44use crate::error::{
45    CatalogSnafu, FindRegionLeaderSnafu, FindTablePartitionRuleSnafu, JoinTaskSnafu,
46    NotSupportedSnafu, RequestRegionSnafu, Result, TableNotFoundSnafu,
47    UnsupportedRegionRequestSnafu,
48};
49use crate::region_req_factory::RegionRequestFactory;
50
51/// Region requester which processes flush, compact requests etc.
52pub struct Requester {
53    catalog_manager: CatalogManagerRef,
54    partition_manager: PartitionRuleManagerRef,
55    node_manager: NodeManagerRef,
56}
57
58pub type RequesterRef = Arc<Requester>;
59
60impl Requester {
61    pub fn new(
62        catalog_manager: CatalogManagerRef,
63        partition_manager: PartitionRuleManagerRef,
64        node_manager: NodeManagerRef,
65    ) -> Self {
66        Self {
67            catalog_manager,
68            partition_manager,
69            node_manager,
70        }
71    }
72
73    /// Handle the request to flush table.
74    pub async fn handle_table_flush(
75        &self,
76        request: FlushTableRequest,
77        ctx: QueryContextRef,
78    ) -> Result<AffectedRows> {
79        let partitions = &self
80            .get_table_partition_info(
81                &request.catalog_name,
82                &request.schema_name,
83                &request.table_name,
84            )
85            .await?
86            .partitions;
87
88        let requests = partitions
89            .iter()
90            .map(|partition| {
91                RegionRequestBody::Flush(FlushRequest {
92                    region_id: partition.id.into(),
93                })
94            })
95            .collect();
96
97        info!("Handle table manual flush request: {:?}", request);
98
99        self.do_request(
100            requests,
101            Some(build_db_string(&request.catalog_name, &request.schema_name)),
102            &ctx,
103        )
104        .await
105    }
106
107    /// Handle the request to build index for table.
108    pub async fn handle_table_build_index(
109        &self,
110        request: BuildIndexTableRequest,
111        ctx: QueryContextRef,
112    ) -> Result<AffectedRows> {
113        if matches!(
114            request.options,
115            Some(build_index_request::Options::SeriesIndex(_))
116        ) {
117            let table = self
118                .catalog_manager
119                .table(
120                    &request.catalog_name,
121                    &request.schema_name,
122                    &request.table_name,
123                    None,
124                )
125                .await
126                .context(CatalogSnafu)?;
127            let table = table.with_context(|| TableNotFoundSnafu {
128                table_name: common_catalog::format_full_table_name(
129                    &request.catalog_name,
130                    &request.schema_name,
131                    &request.table_name,
132                ),
133            })?;
134            let info = table.table_info();
135            ensure_build_series_index_supported(&info.meta.engine, info.is_physical_table())?;
136        }
137        let partitions = &self
138            .get_table_partition_info(
139                &request.catalog_name,
140                &request.schema_name,
141                &request.table_name,
142            )
143            .await?
144            .partitions;
145
146        let requests = partitions
147            .iter()
148            .map(|partition| {
149                RegionRequestBody::BuildIndex(BuildIndexRequest {
150                    region_id: partition.id.into(),
151                    options: request.options,
152                })
153            })
154            .collect();
155
156        info!(
157            "Handle table manual build index for table {}",
158            request.table_name
159        );
160        debug!("Request details: {:?}", request);
161
162        self.do_request(
163            requests,
164            Some(build_db_string(&request.catalog_name, &request.schema_name)),
165            &ctx,
166        )
167        .await
168    }
169
170    /// Handle the request to compact table.
171    pub async fn handle_table_compaction(
172        &self,
173        request: CompactTableRequest,
174        ctx: QueryContextRef,
175    ) -> Result<AffectedRows> {
176        let partitions = &self
177            .get_table_partition_info(
178                &request.catalog_name,
179                &request.schema_name,
180                &request.table_name,
181            )
182            .await?
183            .partitions;
184
185        let time_range = request
186            .time_range
187            .map(to_pb_compaction_time_range)
188            .transpose()?;
189        let requests = partitions
190            .iter()
191            .map(|partition| {
192                RegionRequestBody::Compact(CompactRequest {
193                    region_id: partition.id.into(),
194                    parallelism: request.parallelism,
195                    options: Some(request.compact_options),
196                    time_range,
197                })
198            })
199            .collect();
200
201        info!("Handle table manual compaction request: {:?}", request);
202
203        self.do_request(
204            requests,
205            Some(build_db_string(&request.catalog_name, &request.schema_name)),
206            &ctx,
207        )
208        .await
209    }
210
211    /// Handle the request to flush the region.
212    pub async fn handle_region_flush(
213        &self,
214        region_id: RegionId,
215        ctx: QueryContextRef,
216    ) -> Result<AffectedRows> {
217        let request = RegionRequestBody::Flush(FlushRequest {
218            region_id: region_id.into(),
219        });
220
221        info!("Handle region manual flush request: {region_id}");
222        self.do_request(vec![request], None, &ctx).await
223    }
224
225    /// Handle the request to compact the region.
226    pub async fn handle_region_compaction(
227        &self,
228        region_id: RegionId,
229        ctx: QueryContextRef,
230    ) -> Result<AffectedRows> {
231        let request = RegionRequestBody::Compact(CompactRequest {
232            region_id: region_id.into(),
233            parallelism: 1,
234            options: None, // todo(hl): maybe also support parameters in region compaction.
235            time_range: None,
236        });
237
238        info!("Handle region manual compaction request: {region_id}");
239        self.do_request(vec![request], None, &ctx).await
240    }
241
242    /// Cancels one identified compaction task through the region leader.
243    pub async fn handle_cancel_region_compaction(
244        &self,
245        region_id: RegionId,
246        task_id: String,
247        ctx: QueryContextRef,
248    ) -> Result<AffectedRows> {
249        ensure!(
250            region_id.region_group() != metric_engine_consts::METRIC_METADATA_REGION_GROUP,
251            NotSupportedSnafu {
252                feat: "cancelling compaction for an internal metric metadata region",
253            }
254        );
255
256        let request = RegionRequestBody::CancelCompaction(CancelCompactionRequest {
257            region_id: region_id.into(),
258            task_id,
259        });
260        self.do_request(vec![request], None, &ctx).await
261    }
262
263    /// Discard all unflushed data from the region.
264    pub async fn handle_discard_unflushed_data(
265        &self,
266        region_id: RegionId,
267        ctx: QueryContextRef,
268    ) -> Result<AffectedRows> {
269        let request = RegionRequestBody::Truncate(TruncateRequest {
270            region_id: region_id.into(),
271            kind: Some(truncate_request::Kind::Unflushed(Unflushed {})),
272        });
273
274        info!("Handle region discard unflushed data request: {region_id}");
275        self.do_request(vec![request], None, &ctx).await
276    }
277
278    /// Discard all unflushed data from all regions of the table.
279    pub async fn handle_discard_unflushed_data_by_table(
280        &self,
281        table_name: TableName,
282        ctx: QueryContextRef,
283    ) -> Result<AffectedRows> {
284        let table_info = self.table_info(&table_name).await?;
285        ensure_discard_supported(
286            &table_info.meta.engine,
287            table_info.is_physical_table(),
288            "discarding unflushed data from a Metric Engine logical table",
289        )?;
290        let requests = self
291            .physical_region_ids(&table_name, table_info.ident.table_id)
292            .await?
293            .into_iter()
294            .map(|region_id| {
295                RegionRequestBody::Truncate(TruncateRequest {
296                    region_id: region_id.into(),
297                    kind: Some(truncate_request::Kind::Unflushed(Unflushed {})),
298                })
299            })
300            .collect();
301
302        info!("Handle table discard unflushed data request: {table_name}");
303        self.do_request(
304            requests,
305            Some(build_db_string(
306                &table_name.catalog_name,
307                &table_name.schema_name,
308            )),
309            &ctx,
310        )
311        .await
312    }
313
314    /// Discards the region's pending WAL tails that datanode `node_id` wrote.
315    pub(crate) async fn handle_discard_pending_tails(
316        &self,
317        region_id: RegionId,
318        node_id: u64,
319        ctx: QueryContextRef,
320    ) -> Result<AffectedRows> {
321        let request = RegionRequestBody::DiscardPendingTails(DiscardPendingTailsRequest {
322            region_id: region_id.into(),
323            datanode_id: node_id,
324        });
325
326        info!(
327            user = ctx.current_user().username(),
328            "Handle region discard pending tails request: {region_id}, node: {node_id}"
329        );
330        let discarded = self.do_request(vec![request], None, &ctx).await?;
331        if discarded == 0 {
332            info!("No pending tails from node {node_id} in region {region_id}");
333        }
334        Ok(discarded)
335    }
336
337    /// Discards the pending WAL tails that datanode `node_id` wrote in every region of the
338    /// table. Each failed region is logged with its error, and the first error is returned
339    /// after a warning with the number of tails the regions that succeeded discarded.
340    pub(crate) async fn handle_discard_pending_tails_by_table(
341        &self,
342        table_name: TableName,
343        node_id: u64,
344        ctx: QueryContextRef,
345    ) -> Result<AffectedRows> {
346        let table_info = self.table_info(&table_name).await?;
347        ensure_discard_supported(
348            &table_info.meta.engine,
349            table_info.is_physical_table(),
350            "discarding pending WAL tails from a Metric Engine logical table",
351        )?;
352        let region_ids = self
353            .physical_region_ids(&table_name, table_info.ident.table_id)
354            .await?;
355        let requests = region_ids
356            .iter()
357            .map(|region_id| {
358                RegionRequestBody::DiscardPendingTails(DiscardPendingTailsRequest {
359                    region_id: (*region_id).into(),
360                    datanode_id: node_id,
361                })
362            })
363            .collect();
364
365        info!(
366            user = ctx.current_user().username(),
367            "Handle table discard pending tails request: {table_name}, node: {node_id}"
368        );
369        let results = self
370            .do_requests(
371                requests,
372                Some(build_db_string(
373                    &table_name.catalog_name,
374                    &table_name.schema_name,
375                )),
376                &ctx,
377            )
378            .await?;
379        let discarded = results.iter().flatten().sum::<AffectedRows>();
380        let mut first_error = None;
381        for (region_id, result) in region_ids.into_iter().zip(results) {
382            if let Err(e) = result {
383                error!(e; "Failed to discard the pending tails from node {node_id} in region {region_id} of table {table_name}");
384                first_error.get_or_insert(e);
385            }
386        }
387        if let Some(e) = first_error {
388            warn!(
389                "Discarded {discarded} pending tails from node {node_id} in the regions of table {table_name} that succeeded"
390            );
391            return Err(e);
392        }
393        if discarded == 0 {
394            info!("No pending tails from node {node_id} in table {table_name}");
395        }
396        Ok(discarded)
397    }
398
399    /// Returns the info of the table, or a [TableNotFound](crate::error::Error::TableNotFound)
400    /// error if the catalog has no such table.
401    async fn table_info(&self, table_name: &TableName) -> Result<TableInfoRef> {
402        let table = self
403            .catalog_manager
404            .table(
405                &table_name.catalog_name,
406                &table_name.schema_name,
407                &table_name.table_name,
408                None,
409            )
410            .await
411            .context(CatalogSnafu)?;
412        let table = table.with_context(|| TableNotFoundSnafu {
413            table_name: table_name.to_string(),
414        })?;
415        Ok(table.table_info())
416    }
417
418    /// Returns the region ids of the physical table behind `table_id`, from its physical
419    /// partition info. For a Metric Engine logical table these are the regions of its physical
420    /// table, so a caller that must not act on them rejects a logical table first.
421    async fn physical_region_ids(
422        &self,
423        table_name: &TableName,
424        table_id: TableId,
425    ) -> Result<Vec<RegionId>> {
426        Ok(self
427            .partition_manager
428            .find_physical_partition_info(table_id)
429            .await
430            .with_context(|_| FindTablePartitionRuleSnafu {
431                table_name: table_name.to_string(),
432            })?
433            .partitions
434            .iter()
435            .map(|partition| partition.id)
436            .collect())
437    }
438}
439
440fn to_pb_compaction_time_range(range: TimestampRange) -> Result<CompactionTimeRange> {
441    let (Some(start), Some(end)) = (*range.start(), *range.end()) else {
442        return crate::error::InvalidTimestampRangeSnafu {
443            start: format!("{:?}", range.start()),
444            end: format!("{:?}", range.end()),
445        }
446        .fail();
447    };
448    let original_start = start;
449    let original_end = end;
450    let start = start.convert_to(TimestampUnit::Second).with_context(|| {
451        crate::error::InvalidTimestampRangeSnafu {
452            start: format!("{original_start:?}"),
453            end: format!("{original_end:?}"),
454        }
455    })?;
456    let end = end
457        .convert_to_ceil(TimestampUnit::Second)
458        .with_context(|| crate::error::InvalidTimestampRangeSnafu {
459            start: format!("{original_start:?}"),
460            end: format!("{original_end:?}"),
461        })?;
462    ensure!(
463        start < end,
464        crate::error::InvalidTimestampRangeSnafu {
465            start: format!("{original_start:?}"),
466            end: format!("{original_end:?}"),
467        }
468    );
469
470    Ok(CompactionTimeRange {
471        start: start.value(),
472        end: end.value(),
473        time_unit: to_pb_time_unit(TimestampUnit::Second) as i32,
474    })
475}
476
477impl Requester {
478    async fn do_request(
479        &self,
480        requests: Vec<RegionRequestBody>,
481        db_string: Option<String>,
482        ctx: &QueryContextRef,
483    ) -> Result<AffectedRows> {
484        self.do_requests(requests, db_string, ctx)
485            .await?
486            .into_iter()
487            .sum()
488    }
489
490    /// Sends `requests` to their region leaders and returns the result of each.
491    async fn do_requests(
492        &self,
493        requests: Vec<RegionRequestBody>,
494        db_string: Option<String>,
495        ctx: &QueryContextRef,
496    ) -> Result<Vec<Result<AffectedRows>>> {
497        let request_factory = RegionRequestFactory::new(RegionRequestHeader {
498            tracing_context: TracingContext::from_current_span().to_w3c(),
499            dbname: db_string.unwrap_or_else(|| ctx.get_db_string()),
500            ..Default::default()
501        });
502
503        let tasks = requests.into_iter().map(|req_body| {
504            let request = request_factory.build_request(req_body.clone());
505            let partition_manager = self.partition_manager.clone();
506            let node_manager = self.node_manager.clone();
507            common_runtime::spawn_global(async move {
508                let peer =
509                    Self::find_region_leader_by_request(partition_manager, &req_body).await?;
510                node_manager
511                    .datanode(&peer)
512                    .await
513                    .handle(request)
514                    .await
515                    .context(RequestRegionSnafu)
516            })
517        });
518        let results = future::try_join_all(tasks).await.context(JoinTaskSnafu)?;
519
520        Ok(results
521            .into_iter()
522            .map(|resp| resp.map(|r| r.affected_rows))
523            .collect())
524    }
525
526    async fn find_region_leader_by_request(
527        partition_manager: PartitionRuleManagerRef,
528        req: &RegionRequestBody,
529    ) -> Result<Peer> {
530        let region_id = match req {
531            RegionRequestBody::Flush(req) => req.region_id,
532            RegionRequestBody::Compact(req) => req.region_id,
533            RegionRequestBody::CancelCompaction(req) => req.region_id,
534            RegionRequestBody::DiscardPendingTails(req) => req.region_id,
535            RegionRequestBody::BuildIndex(req) => req.region_id,
536            RegionRequestBody::Truncate(req) => req.region_id,
537            _ => {
538                error!("Unsupported region request: {:?}", req);
539                return UnsupportedRegionRequestSnafu {}.fail();
540            }
541        };
542
543        partition_manager
544            .find_region_leader(region_id.into())
545            .await
546            .context(FindRegionLeaderSnafu)
547    }
548
549    async fn get_table_partition_info(
550        &self,
551        catalog: &str,
552        schema: &str,
553        table_name: &str,
554    ) -> Result<Arc<PhysicalPartitionInfo>> {
555        let table = self
556            .catalog_manager
557            .table(catalog, schema, table_name, None)
558            .await
559            .context(CatalogSnafu)?;
560
561        let table = table.with_context(|| TableNotFoundSnafu {
562            table_name: common_catalog::format_full_table_name(catalog, schema, table_name),
563        })?;
564        let table_info = table.table_info();
565
566        self.partition_manager
567            .find_physical_partition_info(table_info.ident.table_id)
568            .await
569            .with_context(|_| FindTablePartitionRuleSnafu {
570                table_name: common_catalog::format_full_table_name(catalog, schema, table_name),
571            })
572    }
573}
574
575fn ensure_build_series_index_supported(engine: &str, is_physical_table: bool) -> Result<()> {
576    ensure!(
577        engine == METRIC_ENGINE && is_physical_table,
578        NotSupportedSnafu {
579            feat: "building series indexes requires a physical metric table",
580        }
581    );
582    Ok(())
583}
584
585fn ensure_discard_supported(
586    engine: &str,
587    is_physical_table: bool,
588    feat: &'static str,
589) -> Result<()> {
590    ensure!(
591        engine != METRIC_ENGINE || is_physical_table,
592        NotSupportedSnafu { feat }
593    );
594    Ok(())
595}
596
597#[cfg(test)]
598mod tests {
599    use api::region::RegionResponse;
600    use api::v1::TimeUnit;
601    use common_error::ext::ErrorExt;
602    use common_error::status_code::StatusCode;
603    use common_meta::ddl::test_util::datanode_handler::DatanodeWatcher;
604    use common_meta::test_util::MockDatanodeManager;
605    use common_time::Timestamp;
606    use common_time::range::TimestampRange;
607    use session::context::QueryContext;
608
609    use super::*;
610    use crate::test_util;
611
612    #[tokio::test]
613    async fn test_cancel_region_compaction_routes_to_region_leader() {
614        let backend = test_util::prepare_mocked_backend().await;
615        let partition_manager = test_util::create_partition_rule_manager(backend).await;
616        let (sender, mut requests) = tokio::sync::mpsc::channel(4);
617        let watcher = DatanodeWatcher::new(sender).with_handler(|_, request| {
618            let Some(RegionRequestBody::CancelCompaction(request)) = request.body else {
619                panic!("expected cancellation through Handle");
620            };
621            Ok(RegionResponse::new(usize::from(
622                request.task_id == "live-cycle",
623            )))
624        });
625        let requester = Requester::new(
626            catalog::memory::MemoryCatalogManager::new(),
627            partition_manager,
628            Arc::new(MockDatanodeManager::new(watcher)),
629        );
630        let ctx = Arc::new(QueryContext::with("greptime", "cancel_test"));
631        for (region_number, task_id, affected_rows) in
632            [(1, "live-cycle", 1), (3, "absent-cycle", 0)]
633        {
634            let region_id = RegionId::new(1, region_number);
635            assert_eq!(
636                requester
637                    .handle_cancel_region_compaction(region_id, task_id.into(), ctx.clone())
638                    .await
639                    .unwrap(),
640                affected_rows
641            );
642            let (peer, request) = requests.try_recv().unwrap();
643            assert_eq!(peer.id, u64::from(region_number));
644            assert_eq!(request.header.unwrap().dbname, ctx.get_db_string());
645            assert_eq!(
646                request.body,
647                Some(RegionRequestBody::CancelCompaction(
648                    CancelCompactionRequest {
649                        region_id: region_id.as_u64(),
650                        task_id: task_id.into(),
651                    }
652                ))
653            );
654        }
655        // Metadata regions are rejected before routing, even without a table route.
656        for table_id in [1, u32::MAX] {
657            let region_id = RegionId::with_group_and_seq(
658                table_id,
659                metric_engine_consts::METRIC_METADATA_REGION_GROUP,
660                1,
661            );
662            let error = requester
663                .handle_cancel_region_compaction(region_id, "live-cycle".into(), ctx.clone())
664                .await
665                .unwrap_err();
666            assert_eq!(error.status_code(), StatusCode::Unsupported);
667            assert!(matches!(error, crate::error::Error::NotSupported { .. }));
668            assert!(
669                error
670                    .to_string()
671                    .contains("internal metric metadata region")
672            );
673        }
674        assert!(requests.try_recv().is_err());
675    }
676
677    #[tokio::test]
678    async fn test_discard_pending_tails_routes_by_node_and_sums_regions() {
679        use catalog::RegisterTableRequest;
680        use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
681        use table::dist_table::DummyDataSource;
682
683        let backend = test_util::prepare_mocked_backend().await;
684        let partition_manager = test_util::create_partition_rule_manager(backend).await;
685        let (sender, mut requests) = tokio::sync::mpsc::channel(8);
686        // Region `n` discards `n` tails, except that region 3 fails for node 7.
687        let watcher = DatanodeWatcher::new(sender).with_handler(|peer, request| {
688            let Some(RegionRequestBody::DiscardPendingTails(DiscardPendingTailsRequest {
689                datanode_id: node_id,
690                ..
691            })) = request.body
692            else {
693                panic!("expected a pending tails discard");
694            };
695            if peer.id == 3 && node_id == 7 {
696                return common_meta::error::UnexpectedSnafu {
697                    err_msg: "mock error",
698                }
699                .fail();
700            }
701            Ok(RegionResponse::new(peer.id as usize))
702        });
703        let catalog = catalog::memory::MemoryCatalogManager::with_default_setup();
704        let table = Arc::new(table::Table::new(
705            Arc::new(test_util::new_test_table_info(1, "table_1", [].into_iter())),
706            table::metadata::FilterPushDownType::Unsupported,
707            Arc::new(DummyDataSource),
708        ));
709        catalog
710            .register_table_sync(RegisterTableRequest {
711                catalog: DEFAULT_CATALOG_NAME.to_string(),
712                schema: DEFAULT_SCHEMA_NAME.to_string(),
713                table_name: "table_1".to_string(),
714                table_id: 1,
715                table,
716            })
717            .unwrap();
718        let requester = Requester::new(
719            catalog,
720            partition_manager,
721            Arc::new(MockDatanodeManager::new(watcher)),
722        );
723        let ctx = Arc::new(QueryContext::with(
724            DEFAULT_CATALOG_NAME,
725            DEFAULT_SCHEMA_NAME,
726        ));
727        let expected = |region_number, node_id| {
728            Some(RegionRequestBody::DiscardPendingTails(
729                DiscardPendingTailsRequest {
730                    region_id: RegionId::new(1, region_number).as_u64(),
731                    datanode_id: node_id,
732                },
733            ))
734        };
735
736        let discarded = requester
737            .handle_discard_pending_tails(RegionId::new(1, 1), 7, ctx.clone())
738            .await
739            .unwrap();
740        assert_eq!(1, discarded);
741        let (peer, request) = requests.try_recv().unwrap();
742        assert_eq!(1, peer.id);
743        assert_eq!(expected(1, 7), request.body);
744        assert!(requests.try_recv().is_err());
745
746        let table_name = TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "table_1");
747        let mut sent_to_regions = |node_id| {
748            let mut sent = Vec::new();
749            while let Ok((peer, request)) = requests.try_recv() {
750                assert_eq!(expected(peer.id as u32, node_id), request.body);
751                sent.push(peer.id);
752            }
753            sent.sort();
754            sent
755        };
756        let error = requester
757            .handle_discard_pending_tails_by_table(table_name.clone(), 7, ctx.clone())
758            .await
759            .unwrap_err();
760        assert!(matches!(error, crate::error::Error::RequestRegion { .. }));
761        assert_eq!(vec![1, 2, 3], sent_to_regions(7));
762
763        let discarded = requester
764            .handle_discard_pending_tails_by_table(table_name, 8, ctx)
765            .await
766            .unwrap();
767        assert_eq!(1 + 2 + 3, discarded);
768        assert_eq!(vec![1, 2, 3], sent_to_regions(8));
769    }
770
771    #[test]
772    fn test_build_series_index_requires_physical_metric_table() {
773        ensure_build_series_index_supported(METRIC_ENGINE, true).unwrap();
774        assert!(ensure_build_series_index_supported(METRIC_ENGINE, false).is_err());
775        assert!(ensure_build_series_index_supported("mito", false).is_err());
776        assert!(ensure_build_series_index_supported("mito", true).is_err());
777    }
778
779    #[test]
780    fn test_to_pb_compaction_time_range_normalizes_mixed_units() {
781        let range = TimestampRange::new(
782            Timestamp::new_millisecond(1_500),
783            Timestamp::new_microsecond(2_500_000),
784        )
785        .unwrap();
786
787        let pb_range = to_pb_compaction_time_range(range).unwrap();
788        assert_eq!(1, pb_range.start);
789        assert_eq!(3, pb_range.end);
790        assert_eq!(TimeUnit::Second as i32, pb_range.time_unit);
791    }
792
793    #[test]
794    fn test_ensure_discard_supported() {
795        let feat = "discarding pending WAL tails from a Metric Engine logical table";
796        let error = ensure_discard_supported(METRIC_ENGINE, false, feat).unwrap_err();
797        assert!(matches!(error, crate::error::Error::NotSupported { .. }));
798
799        ensure_discard_supported(METRIC_ENGINE, true, feat).unwrap();
800        ensure_discard_supported("mito", false, feat).unwrap();
801    }
802
803    #[test]
804    fn test_to_pb_compaction_time_range() {
805        let range = TimestampRange::new(
806            Timestamp::new_microsecond(1_000),
807            Timestamp::new_microsecond(2_000),
808        )
809        .unwrap();
810
811        let pb_range = to_pb_compaction_time_range(range).unwrap();
812        assert_eq!(0, pb_range.start);
813        assert_eq!(1, pb_range.end);
814        assert_eq!(TimeUnit::Second as i32, pb_range.time_unit);
815    }
816}