Skip to main content

frontend/instance/
import_packed.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 auth::{
16    PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionTableTarget,
17    PermissionTableTargets,
18};
19use common_query::Output;
20use session::context::QueryContextRef;
21use snafu::ResultExt;
22use sql::statements::copy::CopyDatabaseArgument;
23use sql::statements::statement::Statement;
24use tokio_util::sync::CancellationToken;
25
26use crate::error::{PermissionSnafu, Result};
27use crate::instance::Instance;
28
29impl Instance {
30    pub(crate) async fn copy_packed_database(
31        &self,
32        arg: CopyDatabaseArgument,
33        stmt: &Statement,
34        ctx: QueryContextRef,
35    ) -> Result<Output> {
36        self.plugins
37            .get::<PermissionCheckerRef>()
38            .as_ref()
39            .check_permission_with_context(
40                ctx.current_user(),
41                PermissionReq::SqlStatement(stmt),
42                Some(&ctx.current_schema()),
43            )
44            .context(PermissionSnafu)?;
45        let req = operator::statement::to_copy_database_request(arg, &ctx)?;
46        let plan = self
47            .statement_executor
48            .prepare_packed_import(req, &ctx)
49            .await?;
50        let targets = PermissionTableTargets::resolved(
51            plan.tables
52                .iter()
53                .map(|t| {
54                    let info = t.table_info();
55                    PermissionTableTarget::new(&info.catalog_name, &info.schema_name, &info.name)
56                })
57                .collect(),
58        );
59        self.check_table_permission(&ctx, PermissionReq::SqlStatement(stmt), targets)
60            .context(PermissionSnafu)?;
61        let executor = self.statement_executor.clone();
62        run_packed_import(move |cancellation| async move {
63            executor.import_packed(plan, &cancellation, ctx).await
64        })
65        .await
66    }
67}
68
69async fn run_packed_import<F, Fut>(worker: F) -> Result<Output>
70where
71    F: FnOnce(CancellationToken) -> Fut,
72    Fut: std::future::Future<Output = operator::error::Result<Output>> + Send + 'static,
73{
74    let cancellation = CancellationToken::new();
75    let _guard = cancellation.clone().drop_guard();
76    // Transport timeout/drop signals cancellation; the worker retains ownership
77    // until its started inserts finish, even after the response is gone.
78    common_runtime::spawn_query(worker(cancellation))
79        .await
80        .context(operator::error::JoinTaskSnafu)?
81        .map_err(Into::into)
82}
83
84#[cfg(test)]
85mod tests {
86    use std::time::Duration;
87
88    use tokio::sync::oneshot;
89
90    use super::*;
91
92    #[tokio::test]
93    async fn packed_request_drop_keeps_worker_alive_until_cleanup() {
94        let (started_tx, started_rx) = oneshot::channel();
95        let (cancelled_tx, cancelled_rx) = oneshot::channel();
96        let (drain_tx, drain_rx) = oneshot::channel();
97        let (finished_tx, mut finished_rx) = oneshot::channel();
98        let mut request = Box::pin(run_packed_import(move |cancellation| async move {
99            started_tx.send(()).unwrap();
100            cancellation.cancelled().await;
101            cancelled_tx.send(()).unwrap();
102            // Model an already-started insert that must finish before worker exit.
103            drain_rx.await.unwrap();
104            finished_tx.send(()).unwrap();
105            Ok(Output::new_with_affected_rows(1))
106        }));
107        tokio::select! {
108            _ = started_rx => {}
109            _ = &mut request => panic!("worker must wait for cancellation"),
110        }
111        drop(request);
112        tokio::time::timeout(Duration::from_secs(5), cancelled_rx)
113            .await
114            .unwrap()
115            .unwrap();
116        assert!(matches!(
117            finished_rx.try_recv(),
118            Err(oneshot::error::TryRecvError::Empty)
119        ));
120        drain_tx.send(()).unwrap();
121        tokio::time::timeout(Duration::from_secs(5), finished_rx)
122            .await
123            .unwrap()
124            .unwrap();
125    }
126}