Skip to main content

common_meta/ddl/drop_database/
cursor.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::any::Any;
16use std::collections::HashSet;
17use std::pin::Pin;
18
19use common_base::readable_size::ReadableSize;
20use common_catalog::format_full_table_name;
21use common_procedure::Status;
22use futures::{StreamExt, TryStreamExt};
23use serde::{Deserialize, Serialize};
24use snafu::{OptionExt, ensure};
25use table::metadata::{TableId, TableType};
26use table::table_name::TableName;
27
28use crate::cache_invalidator::Context;
29use crate::ddl::DdlContext;
30use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
31use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
32use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
33use crate::error::{Result, TableInfoNotFoundSnafu, UnexpectedSnafu};
34use crate::instruction::CacheIdent;
35use crate::key::table_route::TableRouteValue;
36
37#[derive(Debug, Serialize, Deserialize)]
38pub(crate) struct DropDatabaseCursor {
39    pub(crate) target: DropTableTarget,
40}
41
42impl DropDatabaseCursor {
43    /// Returns a new [DropDatabaseCursor].
44    pub fn new(target: DropTableTarget) -> Self {
45        Self { target }
46    }
47
48    /// Collects a bounded page without mutating metadata. Only the executor's batch is durable.
49    async fn collect_logical_tables(
50        &mut self,
51        ddl_ctx: &DdlContext,
52        ctx: &mut DropDatabaseContext,
53    ) -> Result<(Box<dyn State>, Status)> {
54        let page = Self::collect_page(ctx).await?;
55        if page.is_empty() {
56            return self.handle_reach_end(ctx);
57        }
58        let tables = Self::logical_tables(ddl_ctx, ctx, page).await?;
59        if tables.is_empty() {
60            return Ok((Box::new(Self::new(self.target)), Status::executing(false)));
61        }
62        Ok((
63            Box::new(DropDatabaseBatchExecutor { tables }),
64            Status::executing(true),
65        ))
66    }
67
68    // Leave headroom below etcd's default 1.5 MiB request limit.
69    const MAX_BATCH_BYTES: usize = ReadableSize::mb(1).as_bytes() as usize;
70
71    fn estimated_table_bytes(catalog: &str, schema: &str, name: &str) -> usize {
72        // A control byte can expand to 6 JSON bytes, then 7 inside ProcedureMessage's
73        // JSON string. Round up to 8x and allow 128 bytes for fixed per-table JSON/key overhead.
74        128 + 8 * (catalog.len() + schema.len() + name.len())
75    }
76
77    async fn collect_page(ctx: &mut DropDatabaseContext) -> Result<Vec<(String, TableId)>> {
78        let mut page = Vec::new();
79        let mut bytes: usize = 0;
80        let tables = ctx.tables.as_mut().unwrap();
81        loop {
82            match Pin::new(&mut *tables).peek().await {
83                Some(Ok((name, _))) => {
84                    let size = Self::estimated_table_bytes(&ctx.catalog, &ctx.schema, name);
85                    if !page.is_empty() && bytes.saturating_add(size) > Self::MAX_BATCH_BYTES {
86                        break;
87                    }
88                    // A single oversized name must still make progress. Procedure storage
89                    // already splits oversized values; never strand an existing table here.
90                    bytes = bytes.saturating_add(size);
91                }
92                Some(Err(_)) => {} // Consume below to propagate the owned error.
93                None => break,
94            }
95            let (name, value) = tables.try_next().await?.unwrap();
96            page.push((name, value.table_id()));
97        }
98        Ok(page)
99    }
100
101    async fn logical_tables(
102        ddl_ctx: &DdlContext,
103        ctx: &mut DropDatabaseContext,
104        page: Vec<(String, TableId)>,
105    ) -> Result<Vec<(TableId, TableName)>> {
106        let manager = &ddl_ctx.table_metadata_manager;
107        let ids = page.iter().map(|(_, id)| *id).collect::<Vec<_>>();
108        let infos = manager.table_info_manager().batch_get(&ids).await?;
109        let routes = manager
110            .table_route_manager()
111            .table_route_storage()
112            .batch_get(&ids)
113            .await?;
114        let physical_ids = routes
115            .iter()
116            .filter_map(|route| match route {
117                Some(TableRouteValue::Logical(route)) => Some(route.physical_table_id()),
118                _ => None,
119            })
120            .collect::<HashSet<_>>()
121            .into_iter()
122            .collect::<Vec<_>>();
123        let physical_infos = manager
124            .table_info_manager()
125            .batch_get(&physical_ids)
126            .await?;
127        let mut tables = Vec::new();
128        for ((name, id), route) in page.into_iter().zip(routes) {
129            let info = infos.get(&id).with_context(|| TableInfoNotFoundSnafu {
130                table: format_full_table_name(&ctx.catalog, &ctx.schema, &name),
131            })?;
132            if info.table_info.table_type == TableType::View {
133                // Views are handled in the physical phase so collecting a batch has no side effects.
134                continue;
135            }
136            if let Some(TableRouteValue::Logical(route)) = route {
137                let physical = physical_infos
138                    .get(&route.physical_table_id())
139                    .with_context(|| TableInfoNotFoundSnafu {
140                        table: route.physical_table_id().to_string(),
141                    })?;
142                // Metadata-only deletion is safe only when the backing table is dropped with us.
143                ensure!(
144                    physical.table_info.catalog_name == ctx.catalog
145                        && physical.table_info.schema_name == ctx.schema,
146                    UnexpectedSnafu {
147                        err_msg: format!(
148                            "Logical table {} references physical table {} (id {}) outside the dropped database",
149                            format_full_table_name(&ctx.catalog, &ctx.schema, &name),
150                            format_full_table_name(
151                                &physical.table_info.catalog_name,
152                                &physical.table_info.schema_name,
153                                &physical.table_info.name,
154                            ),
155                            route.physical_table_id(),
156                        ),
157                    }
158                );
159                tables.push((id, TableName::new(&ctx.catalog, &ctx.schema, name)));
160            }
161        }
162        Ok(tables)
163    }
164
165    fn handle_reach_end(
166        &mut self,
167        ctx: &mut DropDatabaseContext,
168    ) -> Result<(Box<dyn State>, Status)> {
169        // Consumes the tables stream.
170        ctx.tables.take();
171        match self.target {
172            DropTableTarget::Logical => Ok((
173                Box::new(DropDatabaseCursor::new(DropTableTarget::Physical)),
174                Status::executing(true),
175            )),
176            DropTableTarget::Physical => Ok((
177                Box::new(DropDatabaseRemoveMetadata),
178                Status::executing(true),
179            )),
180        }
181    }
182
183    async fn handle_table(
184        &mut self,
185        ctx: &mut DropDatabaseContext,
186        table_name: String,
187        table_id: TableId,
188        table_route_value: TableRouteValue,
189    ) -> Result<(Box<dyn State>, Status)> {
190        match (self.target, table_route_value) {
191            (DropTableTarget::Physical, TableRouteValue::Physical(table_route)) => Ok((
192                Box::new(DropDatabaseExecutor::new(
193                    table_id,
194                    table_id,
195                    TableName::new(&ctx.catalog, &ctx.schema, &table_name),
196                    table_route.region_routes,
197                    self.target,
198                )),
199                Status::executing(true),
200            )),
201            _ => Ok((
202                Box::new(DropDatabaseCursor::new(self.target)),
203                Status::executing(false),
204            )),
205        }
206    }
207    async fn handle_view(
208        &self,
209        ddl_ctx: &DdlContext,
210        ctx: &mut DropDatabaseContext,
211        table_name: String,
212        table_id: TableId,
213    ) -> Result<(Box<dyn State>, Status)> {
214        let view_name = TableName::new(&ctx.catalog, &ctx.schema, &table_name);
215        ddl_ctx
216            .table_metadata_manager
217            .destroy_view_info(table_id, &view_name)
218            .await?;
219
220        let cache_invalidator = &ddl_ctx.cache_invalidator;
221        let ctx = Context {
222            subject: Some("Invalidate table cache by dropping table".to_string()),
223        };
224
225        cache_invalidator
226            .invalidate(
227                &ctx,
228                &[
229                    CacheIdent::TableName(view_name),
230                    CacheIdent::TableId(table_id),
231                ],
232            )
233            .await?;
234
235        Ok((
236            Box::new(DropDatabaseCursor::new(self.target)),
237            Status::executing(false),
238        ))
239    }
240}
241
242#[async_trait::async_trait]
243#[typetag::serde]
244impl State for DropDatabaseCursor {
245    async fn next(
246        &mut self,
247        ddl_ctx: &DdlContext,
248        ctx: &mut DropDatabaseContext,
249    ) -> Result<(Box<dyn State>, Status)> {
250        if ctx.tables.is_none() {
251            let tables = ddl_ctx
252                .table_metadata_manager
253                .table_name_manager()
254                .tables(&ctx.catalog, &ctx.schema);
255            ctx.tables = Some(tables.peekable());
256        }
257        let result = async {
258            if self.target == DropTableTarget::Logical {
259                return self.collect_logical_tables(ddl_ctx, ctx).await;
260            }
261            // Safety: must exist
262            match ctx.tables.as_mut().unwrap().try_next().await? {
263                Some((table_name, table_name_value)) => {
264                    let table_id = table_name_value.table_id();
265
266                    let table_info_value = ddl_ctx
267                        .table_metadata_manager
268                        .table_info_manager()
269                        .get(table_id)
270                        .await?
271                        .with_context(|| TableInfoNotFoundSnafu {
272                            table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name),
273                        })?;
274
275                    if table_info_value.table_info.table_type == TableType::View {
276                        return self.handle_view(ddl_ctx, ctx, table_name, table_id).await;
277                    }
278
279                    match ddl_ctx
280                        .table_metadata_manager
281                        .table_route_manager()
282                        .table_route_storage()
283                        .get(table_id)
284                        .await?
285                    {
286                        Some(table_route_value) => {
287                            self.handle_table(ctx, table_name, table_id, table_route_value)
288                                .await
289                        }
290                        None => Ok((
291                            Box::new(DropDatabaseCursor::new(self.target)),
292                            Status::executing(false),
293                        )),
294                    }
295                }
296                None => self.handle_reach_end(ctx),
297            }
298        }
299        .await;
300        if result.is_err() {
301            // The entry was consumed but no deletion plan was persisted. Rescan on retry.
302            ctx.tables.take();
303        }
304        result
305    }
306
307    fn as_any(&self) -> &dyn Any {
308        self
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use std::sync::Arc;
315
316    use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
317
318    use crate::ddl::drop_database::cursor::DropDatabaseCursor;
319    use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
320    use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
321    use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
322    use crate::ddl::test_util::{create_logical_table, create_physical_table};
323    use crate::test_util::{MockDatanodeManager, new_ddl_context};
324
325    #[tokio::test]
326    async fn test_cursor_read_failure_rescans() {
327        use crate::key::table_name::TableNameValue;
328        use futures::StreamExt;
329        for target in [DropTableTarget::Logical, DropTableTarget::Physical] {
330            let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
331            let physical = create_physical_table(&ddl, "physical").await;
332            let mut ctx = DropDatabaseContext {
333                catalog: DEFAULT_CATALOG_NAME.into(),
334                schema: DEFAULT_SCHEMA_NAME.into(),
335                drop_if_exists: false,
336                retrying: false,
337                tables: Some(
338                    futures::stream::iter(vec![Ok(("missing".into(), TableNameValue::new(99999)))])
339                        .boxed()
340                        .peekable(),
341                ),
342            };
343            let mut cursor = DropDatabaseCursor::new(target);
344            assert!(cursor.next(&ddl, &mut ctx).await.is_err());
345            assert!(ctx.tables.is_none());
346            let (state, _) = cursor.next(&ddl, &mut ctx).await.unwrap();
347            if target == DropTableTarget::Physical {
348                assert!(state.as_any().is::<DropDatabaseExecutor>());
349            } else {
350                assert!(state.as_any().is::<DropDatabaseCursor>());
351            }
352            assert!(
353                ddl.table_metadata_manager
354                    .table_info_manager()
355                    .get(physical)
356                    .await
357                    .unwrap()
358                    .is_some()
359            );
360        }
361    }
362
363    #[tokio::test]
364    async fn test_collect_page_oversized_singleton_makes_progress() {
365        use crate::key::table_name::TableNameValue;
366        use futures::StreamExt;
367        let mut ctx = DropDatabaseContext {
368            catalog: DEFAULT_CATALOG_NAME.into(),
369            schema: DEFAULT_SCHEMA_NAME.into(),
370            drop_if_exists: false,
371            retrying: false,
372            tables: Some(
373                futures::stream::iter(vec![
374                    Ok((
375                        "x".repeat(DropDatabaseCursor::MAX_BATCH_BYTES),
376                        TableNameValue::new(1),
377                    )),
378                    Ok(("small".into(), TableNameValue::new(2))),
379                ])
380                .boxed()
381                .peekable(),
382            ),
383        };
384        let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
385        assert_eq!(page.len(), 1);
386        assert_eq!(page[0].1, 1);
387        assert_eq!(
388            DropDatabaseCursor::collect_page(&mut ctx).await.unwrap(),
389            vec![("small".into(), 2)]
390        );
391        assert!(
392            DropDatabaseCursor::collect_page(&mut ctx)
393                .await
394                .unwrap()
395                .is_empty()
396        );
397    }
398
399    #[tokio::test]
400    async fn test_collect_page_limits_and_request_headroom() {
401        use common_procedure::store::ProcedureMessage;
402        use futures::StreamExt;
403        use table::table_name::TableName;
404
405        use crate::ddl::drop_database::DropDatabaseProcedure;
406        use crate::key::TableMetadataManager;
407        use crate::key::table_name::TableNameValue;
408        for name in [
409            "short".to_string(),
410            "x".repeat(64 * 1024),
411            "\"\\\n\u{0001}中文".repeat(4096),
412        ] {
413            let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
414            let count = if name.len() < 1024 { 5000 } else { 65 };
415            let entries = (0..count)
416                .map(|id| Ok((name.clone(), TableNameValue::new(id))))
417                .collect::<Vec<_>>();
418            let mut ctx = DropDatabaseContext {
419                catalog: DEFAULT_CATALOG_NAME.into(),
420                schema: DEFAULT_SCHEMA_NAME.into(),
421                drop_if_exists: false,
422                tables: Some(futures::stream::iter(entries).boxed().peekable()),
423                retrying: false,
424            };
425            let mut collected = Vec::new();
426            loop {
427                let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
428                if page.is_empty() {
429                    break;
430                }
431                let estimated = page
432                    .iter()
433                    .map(|(name, _)| {
434                        DropDatabaseCursor::estimated_table_bytes(&ctx.catalog, &ctx.schema, name)
435                    })
436                    .sum::<usize>();
437                assert!(estimated <= DropDatabaseCursor::MAX_BATCH_BYTES);
438                let tables = page
439                    .iter()
440                    .map(|(name, id)| (*id, TableName::new(&ctx.catalog, &ctx.schema, name)))
441                    .collect::<Vec<_>>();
442                // Each delete has one bytes field nested in two messages. Allow
443                // 32 bytes per key for tags and length varints, plus a txn envelope.
444                let delete_bytes = 64
445                    + tables
446                        .iter()
447                        .flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name))
448                        .map(|key| key.len() + 32)
449                        .sum::<usize>();
450                assert!(delete_bytes <= estimated);
451                let mut procedure = DropDatabaseProcedure::new(
452                    ctx.catalog.clone(),
453                    ctx.schema.clone(),
454                    false,
455                    ddl.clone(),
456                );
457                procedure.state = Box::new(DropDatabaseBatchExecutor { tables });
458                let message = ProcedureMessage {
459                    type_name: DropDatabaseProcedure::TYPE_NAME.into(),
460                    data: common_procedure::Procedure::dump(&procedure).unwrap(),
461                    parent_id: None,
462                    subprocedure_recovery: common_procedure::SubprocedureRecovery::Discard,
463                    step: u32::MAX,
464                    error: None,
465                    context: Default::default(),
466                };
467                let serialized = serde_json::to_vec(&message).unwrap();
468                assert!(serialized.len() <= estimated);
469                assert!(serialized.len() + 512 * 1024 < 1536 * 1024);
470                collected.extend(page.into_iter().map(|(_, id)| id));
471            }
472            assert_eq!(collected, (0..count).collect::<Vec<_>>());
473        }
474    }
475
476    #[tokio::test]
477    async fn test_next_without_logical_tables() {
478        let node_manager = Arc::new(MockDatanodeManager::new(()));
479        let ddl_context = new_ddl_context(node_manager);
480        create_physical_table(&ddl_context, "phy").await;
481        // It always starts from Logical
482        let mut state = DropDatabaseCursor::new(DropTableTarget::Logical);
483        let mut ctx = DropDatabaseContext {
484            catalog: DEFAULT_CATALOG_NAME.to_string(),
485            schema: DEFAULT_SCHEMA_NAME.to_string(),
486            drop_if_exists: false,
487            tables: None,
488            retrying: false,
489        };
490        // Ticks
491        let (mut state, status) = state.next(&ddl_context, &mut ctx).await.unwrap();
492        assert!(!status.need_persist());
493        let cursor = state.as_any().downcast_ref::<DropDatabaseCursor>().unwrap();
494        assert_eq!(cursor.target, DropTableTarget::Logical);
495        // Ticks
496        let (mut state, status) = state.next(&ddl_context, &mut ctx).await.unwrap();
497        assert!(status.need_persist());
498        assert!(ctx.tables.is_none());
499        let cursor = state.as_any().downcast_ref::<DropDatabaseCursor>().unwrap();
500        assert_eq!(cursor.target, DropTableTarget::Physical);
501        // Ticks
502        let (state, status) = state.next(&ddl_context, &mut ctx).await.unwrap();
503        assert!(status.need_persist());
504        let executor = state
505            .as_any()
506            .downcast_ref::<DropDatabaseExecutor>()
507            .unwrap();
508        assert_eq!(executor.target, DropTableTarget::Physical);
509    }
510
511    #[tokio::test]
512    async fn test_next_with_logical_tables() {
513        let node_manager = Arc::new(MockDatanodeManager::new(()));
514        let ddl_context = new_ddl_context(node_manager);
515        let physical_table_id = create_physical_table(&ddl_context, "phy").await;
516        create_logical_table(ddl_context.clone(), physical_table_id, "metric_0").await;
517        // It always starts from Logical
518        let mut state = DropDatabaseCursor::new(DropTableTarget::Logical);
519        let mut ctx = DropDatabaseContext {
520            catalog: DEFAULT_CATALOG_NAME.to_string(),
521            schema: DEFAULT_SCHEMA_NAME.to_string(),
522            drop_if_exists: false,
523            tables: None,
524            retrying: false,
525        };
526        // Ticks
527        let (state, status) = state.next(&ddl_context, &mut ctx).await.unwrap();
528        assert!(status.need_persist());
529        let executor = state
530            .as_any()
531            .downcast_ref::<DropDatabaseBatchExecutor>()
532            .unwrap();
533        assert_eq!(executor.tables.len(), 1);
534        assert_eq!(executor.tables[0].1.table_name, "metric_0");
535    }
536
537    #[tokio::test]
538    async fn test_reach_the_end() {
539        let node_manager = Arc::new(MockDatanodeManager::new(()));
540        let ddl_context = new_ddl_context(node_manager);
541        let mut state = DropDatabaseCursor::new(DropTableTarget::Physical);
542        let mut ctx = DropDatabaseContext {
543            catalog: DEFAULT_CATALOG_NAME.to_string(),
544            schema: DEFAULT_SCHEMA_NAME.to_string(),
545            drop_if_exists: false,
546            tables: None,
547            retrying: false,
548        };
549        // Ticks
550        let (state, status) = state.next(&ddl_context, &mut ctx).await.unwrap();
551        assert!(status.need_persist());
552        state
553            .as_any()
554            .downcast_ref::<DropDatabaseRemoveMetadata>()
555            .unwrap();
556        assert!(ctx.tables.is_none());
557    }
558}