Skip to main content

operator/
utils.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, RwLock};
16
17use common_time::Timezone;
18use session::context::{QueryContextBuilder, QueryContextRef};
19use snafu::ResultExt;
20
21use crate::error::{Error, InvalidTimezoneSnafu};
22
23pub fn to_meta_query_context(
24    query_context: QueryContextRef,
25) -> common_meta::rpc::ddl::QueryContext {
26    common_meta::rpc::ddl::QueryContext {
27        current_catalog: query_context.current_catalog().to_string(),
28        current_schema: query_context.current_schema().clone(),
29        timezone: query_context.timezone().to_string(),
30        extensions: query_context.extensions(),
31        channel: query_context.channel() as u8,
32        snapshot_seqs: query_context.snapshots(),
33        sst_min_sequences: query_context.sst_min_sequences(),
34    }
35}
36
37pub fn to_meta_query_context_with_origin_frontend(
38    query_context: QueryContextRef,
39    origin_frontend_addr: &str,
40) -> common_meta::rpc::ddl::QueryContext {
41    let mut meta_query_context = to_meta_query_context(query_context);
42    meta_query_context.extensions.insert(
43        common_meta::rpc::ddl::ORIGIN_FRONTEND_ADDR_EXTENSION_KEY.to_string(),
44        origin_frontend_addr.to_string(),
45    );
46    meta_query_context
47}
48
49pub fn try_to_session_query_context(
50    value: common_meta::rpc::ddl::QueryContext,
51) -> Result<session::context::QueryContext, Error> {
52    Ok(QueryContextBuilder::default()
53        .current_catalog(value.current_catalog)
54        .current_schema(value.current_schema)
55        .timezone(
56            Timezone::from_tz_string(&value.timezone).context(InvalidTimezoneSnafu {
57                timezone: value.timezone,
58            })?,
59        )
60        .extensions(value.extensions)
61        .channel((value.channel as u32).into())
62        .snapshot_seqs(Arc::new(RwLock::new(value.snapshot_seqs)))
63        .sst_min_sequences(Arc::new(RwLock::new(value.sst_min_sequences)))
64        .build())
65}
66
67#[cfg(test)]
68mod tests {
69    use std::collections::HashMap;
70    use std::sync::{Arc, RwLock};
71
72    use common_meta::rpc::ddl::ORIGIN_FRONTEND_ADDR_EXTENSION_KEY;
73    use common_time::Timezone;
74    use session::context::QueryContextBuilder;
75
76    use super::{
77        to_meta_query_context, to_meta_query_context_with_origin_frontend,
78        try_to_session_query_context,
79    };
80
81    #[test]
82    fn test_query_context_meta_roundtrip_with_sequences() {
83        let session_ctx = Arc::new(
84            QueryContextBuilder::default()
85                .current_catalog("c1".to_string())
86                .current_schema("s1".to_string())
87                .timezone(Timezone::from_tz_string("UTC").unwrap())
88                .set_extension("flow.return_region_seq".to_string(), "true".to_string())
89                .snapshot_seqs(Arc::new(RwLock::new(HashMap::from([(10, 100)]))))
90                .sst_min_sequences(Arc::new(RwLock::new(HashMap::from([(10, 90)]))))
91                .build(),
92        );
93
94        let meta_ctx = to_meta_query_context(session_ctx);
95        let roundtrip = try_to_session_query_context(meta_ctx).unwrap();
96
97        assert_eq!(roundtrip.current_catalog(), "c1");
98        assert_eq!(roundtrip.current_schema(), "s1");
99        assert_eq!(roundtrip.snapshots(), HashMap::from([(10, 100)]));
100        assert_eq!(roundtrip.sst_min_sequences(), HashMap::from([(10, 90)]));
101        assert_eq!(roundtrip.extension("flow.return_region_seq"), Some("true"));
102    }
103
104    #[test]
105    fn test_meta_query_context_with_origin_frontend_overrides_reserved_key() {
106        let session_ctx = Arc::new(
107            QueryContextBuilder::default()
108                .set_extension(
109                    ORIGIN_FRONTEND_ADDR_EXTENSION_KEY.to_string(),
110                    "spoofed".to_string(),
111                )
112                .build(),
113        );
114
115        let meta_ctx = to_meta_query_context_with_origin_frontend(session_ctx, "127.0.0.1:4000");
116
117        assert_eq!(
118            meta_ctx
119                .extensions
120                .get(ORIGIN_FRONTEND_ADDR_EXTENSION_KEY)
121                .map(String::as_str),
122            Some("127.0.0.1:4000")
123        );
124    }
125}