Skip to main content

index/
target.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;
16
17use common_error::ext::ErrorExt;
18use common_error::status_code::StatusCode;
19use common_macro::stack_trace_debug;
20use datatypes::json::JSON2_REMAINDER_FIELD_NAME;
21use serde::{Deserialize, Serialize};
22use snafu::{OptionExt, Snafu, ensure};
23use store_api::storage::ColumnId;
24
25/// Identifies a column or a JSON object path within a column.
26///
27/// # Encoding
28///
29/// - Columns are encoded as decimal IDs, e.g. `1`.
30/// - JSON path targets use `json-{column_id}:` followed by path segments encoded
31///   as `{UTF-8 byte length}:{segment}`, e.g. `json-1:7:service4:name`.
32///   IDs and lengths are unsigned decimal integers without leading zeros.
33///   Segments are read by byte length, so their contents need no escaping.
34///
35/// This persisted encoding is independent of the serde representation of these types.
36///
37/// Note: Columns retain decimal ID encoding because existing index files use
38/// these IDs as lookup keys. Changing the encoding would prevent queries from
39/// finding those indexes.
40#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
41pub enum IndexTarget {
42    ColumnId(ColumnId),
43    JsonPath(JsonPathTarget),
44}
45
46/// An index target for a JSON object path.
47#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
48pub struct JsonPathTarget {
49    column_id: ColumnId,
50    #[serde(deserialize_with = "deserialize_json_path")]
51    path: Vec<String>,
52}
53
54impl JsonPathTarget {
55    /// Returns the ID of the root column containing this JSON path.
56    pub fn column_id(&self) -> ColumnId {
57        self.column_id
58    }
59
60    /// Returns the JSON object path.
61    pub fn path(&self) -> &[String] {
62        &self.path
63    }
64}
65
66impl IndexTarget {
67    /// Estimates the memory used by this target, including JSON path strings.
68    pub fn approx_mem_size(&self) -> usize {
69        std::mem::size_of::<Self>()
70            + match self {
71                Self::ColumnId(_) => 0,
72                Self::JsonPath(target) => target
73                    .path
74                    .iter()
75                    .map(|part| std::mem::size_of::<String>() + part.len())
76                    .sum::<usize>(),
77            }
78    }
79
80    /// Creates an index target for a JSON object path.
81    pub fn new_json_path(column_id: ColumnId, path: Vec<String>) -> Result<Self, TargetKeyError> {
82        validate_json_path(&path)?;
83        let target = JsonPathTarget { column_id, path };
84        Ok(Self::JsonPath(target))
85    }
86
87    /// Encodes this target using the format described in [`IndexTarget`].
88    pub fn encode(&self) -> String {
89        let target = match self {
90            Self::ColumnId(id) => return id.to_string(),
91            Self::JsonPath(target) => target,
92        };
93        let mut key = format!("json-{}:", target.column_id);
94        for part in &target.path {
95            key.push_str(&part.len().to_string());
96            key.push(':');
97            key.push_str(part);
98        }
99        key
100    }
101
102    /// Decodes an index name using the format described in [`IndexTarget`].
103    pub fn decode(key: &str) -> Result<Self, TargetKeyError> {
104        ensure!(!key.is_empty(), EmptySnafu);
105        if key.bytes().all(|byte| byte.is_ascii_digit()) {
106            let id = key
107                .parse::<ColumnId>()
108                .map_err(|_| InvalidColumnIdSnafu { value: key }.build())?;
109            return Ok(Self::ColumnId(id));
110        }
111
112        let invalid_key = || InvalidJsonTargetSnafu { target_key: key };
113        // JSON target IDs and lengths use decimal digits without signs or leading zeros.
114        let is_canonical_decimal = |value: &str| {
115            !value.is_empty()
116                && value.bytes().all(|byte| byte.is_ascii_digit())
117                && (value.len() == 1 || !value.starts_with('0'))
118        };
119
120        // The prefix contains the root column ID; the remainder contains path segments.
121        let (column_id, mut rest) = key
122            .strip_prefix("json-")
123            .and_then(|rest| rest.split_once(':'))
124            .with_context(invalid_key)?;
125        ensure!(is_canonical_decimal(column_id), invalid_key());
126        let column_id = column_id.parse().ok().with_context(invalid_key)?;
127
128        let mut path = Vec::new();
129        while !rest.is_empty() {
130            let (length, content) = rest.split_once(':').with_context(invalid_key)?;
131            ensure!(is_canonical_decimal(length), invalid_key());
132            let length = length.parse::<usize>().ok().with_context(invalid_key)?;
133            // Read exactly this many bytes, including any delimiters in the segment.
134            // Check bounds and the UTF-8 boundary before allocating the segment string.
135            let (part, remaining) = content.split_at_checked(length).with_context(invalid_key)?;
136            path.push(part.to_string());
137            rest = remaining;
138        }
139        Self::new_json_path(column_id, path)
140    }
141}
142
143/// Errors that can occur when working with index target keys.
144#[derive(Snafu, Clone, PartialEq, Eq)]
145#[stack_trace_debug]
146pub enum TargetKeyError {
147    #[snafu(display("target key cannot be empty"))]
148    Empty,
149
150    #[snafu(display("target key must contain digits only: {key}"))]
151    InvalidCharacters { key: String },
152
153    #[snafu(display("failed to parse column id from '{value}'"))]
154    InvalidColumnId { value: String },
155
156    #[snafu(display("invalid JSON index target key: {target_key}"))]
157    InvalidJsonTarget { target_key: String },
158
159    #[snafu(display("invalid JSON index path: {detail}"))]
160    InvalidJsonPath { detail: String },
161}
162
163fn deserialize_json_path<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
164where
165    D: serde::Deserializer<'de>,
166{
167    let path = Vec::<String>::deserialize(deserializer)?;
168    validate_json_path(&path).map_err(serde::de::Error::custom)?;
169    Ok(path)
170}
171
172fn validate_json_path(path: &[String]) -> Result<(), TargetKeyError> {
173    ensure!(
174        !path.is_empty(),
175        InvalidJsonPathSnafu {
176            detail: "path must not be empty",
177        }
178    );
179    for (index, part) in path.iter().enumerate() {
180        ensure!(
181            !part.is_empty(),
182            InvalidJsonPathSnafu {
183                detail: format!("path segment at index {index} must not be empty"),
184            }
185        );
186        ensure!(
187            part != JSON2_REMAINDER_FIELD_NAME,
188            InvalidJsonPathSnafu {
189                detail: format!("path segment at index {index} uses reserved name '{part}'"),
190            }
191        );
192    }
193    Ok(())
194}
195
196impl ErrorExt for TargetKeyError {
197    fn status_code(&self) -> StatusCode {
198        StatusCode::InvalidArguments
199    }
200
201    fn as_any(&self) -> &dyn Any {
202        self
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    fn encode_decode_column() {
212        let target = IndexTarget::ColumnId(42);
213        let key = target.encode();
214        assert_eq!(key, "42");
215        assert_eq!(IndexTarget::decode("42").unwrap(), target);
216        let decoded = IndexTarget::decode(&key).unwrap();
217        assert_eq!(decoded, target);
218    }
219
220    #[test]
221    fn encode_decode_column_id_bounds() {
222        for id in [0, 1, ColumnId::MAX] {
223            let target = IndexTarget::ColumnId(id);
224            let key = id.to_string();
225            assert_eq!(target.encode(), key);
226            assert_eq!(IndexTarget::decode(&key).unwrap(), target);
227        }
228        for key in ["-1", "4294967296", "1.5", "\"1\"", "null"] {
229            assert!(IndexTarget::decode(key).is_err(), "{key}");
230        }
231    }
232
233    #[test]
234    fn decode_rejects_empty() {
235        let err = IndexTarget::decode("").unwrap_err();
236        assert!(matches!(err, TargetKeyError::Empty));
237    }
238
239    #[test]
240    fn decode_rejects_invalid_digits() {
241        let err = IndexTarget::decode("1a2").unwrap_err();
242        assert!(matches!(err, TargetKeyError::InvalidJsonTarget { .. }));
243    }
244
245    #[test]
246    fn json_target_encoding_is_stable() {
247        let target =
248            IndexTarget::new_json_path(7, vec!["resource".into(), "service.name".into()]).unwrap();
249        let key = "json-7:8:resource12:service.name";
250        assert_eq!(target.encode(), key);
251        assert_eq!(IndexTarget::decode(key).unwrap(), target);
252        let json = r#"{"JsonPath":{"column_id":7,"path":["resource","service.name"]}}"#;
253        assert_eq!(serde_json::to_string(&target).unwrap(), json);
254        assert_eq!(serde_json::from_str::<IndexTarget>(json).unwrap(), target);
255        let target = IndexTarget::new_json_path(42, vec!["引号\".:[]".into()]).unwrap();
256        assert_eq!(IndexTarget::decode(&target.encode()).unwrap(), target);
257        assert_eq!(
258            serde_json::to_string(&IndexTarget::ColumnId(42)).unwrap(),
259            r#"{"ColumnId":42}"#
260        );
261    }
262
263    #[test]
264    fn json_target_encode_decode_segments() {
265        let cases: &[(ColumnId, &[&str], &str)] = &[
266            (42, &["service", "name"], "json-42:7:service4:name"),
267            (0, &["a"], "json-0:1:a"),
268            (ColumnId::MAX, &["a"], "json-4294967295:1:a"),
269            (42, &["a.b"], "json-42:3:a.b"),
270            (42, &["a", "b"], "json-42:1:a1:b"),
271            (42, &["a:b", "12:xyz"], "json-42:3:a:b6:12:xyz"),
272            (42, &["中文", "😀"], "json-42:6:中文4:😀"),
273            (42, &["\"\\\n\0"], "json-42:4:\"\\\n\0"),
274            (42, &["abcdefghijkl"], "json-42:12:abcdefghijkl"),
275        ];
276        for &(column_id, path, key) in cases {
277            let target = IndexTarget::new_json_path(
278                column_id,
279                path.iter().map(|part| (*part).to_string()).collect(),
280            )
281            .unwrap();
282            assert_eq!(target.encode(), key);
283            assert_eq!(IndexTarget::decode(key).unwrap(), target);
284        }
285    }
286
287    #[test]
288    fn json_target_rejects_malformed_framing() {
289        for key in [
290            "json-",
291            "json-42",
292            "json-:1:a",
293            "json-+42:1:a",
294            "json-042:1:a",
295            "json-4294967296:1:a",
296            "json-42:",
297            "json-42:0:",
298            "json-42:1:a0:",
299            "json-42::a",
300            "json-42:+1:a",
301            "json-42:-1:a",
302            "json-42:01:a",
303            "json-42:1",
304            "json-42:2:a",
305            "json-42:1:中",
306            "json-42:3:中x",
307            "json-42:1:a1:",
308            "json-42:999999999999999999999999999999999999:a",
309        ] {
310            assert!(IndexTarget::decode(key).is_err(), "{key}");
311        }
312        for path in [
313            vec![JSON2_REMAINDER_FIELD_NAME],
314            vec!["nested", JSON2_REMAINDER_FIELD_NAME],
315        ] {
316            let mut key = "json-42:".to_string();
317            for part in path {
318                key.push_str(&format!("{}:{part}", part.len()));
319            }
320            assert!(matches!(
321                IndexTarget::decode(&key),
322                Err(TargetKeyError::InvalidJsonPath { .. })
323            ));
324        }
325    }
326
327    #[test]
328    fn json_target_rejects_invalid_paths_and_keys() {
329        for path in [
330            vec![],
331            vec![String::new()],
332            vec!["a".into(), String::new()],
333            vec![JSON2_REMAINDER_FIELD_NAME.into()],
334            vec!["a".into(), JSON2_REMAINDER_FIELD_NAME.into()],
335            vec!["a".into(), JSON2_REMAINDER_FIELD_NAME.into(), "b".into()],
336        ] {
337            assert!(matches!(
338                IndexTarget::new_json_path(7, path.clone()),
339                Err(TargetKeyError::InvalidJsonPath { .. })
340            ));
341            let json = serde_json::json!({
342                "column_id": 7,
343                "path": path,
344            });
345            assert!(
346                serde_json::from_value::<IndexTarget>(serde_json::json!({"JsonPath": json}))
347                    .is_err()
348            );
349            let key = serde_json::json!({"JsonPath": {"column_id": 7, "path": path}}).to_string();
350            assert!(IndexTarget::decode(&key).is_err());
351        }
352        assert!(
353            serde_json::from_value::<JsonPathTarget>(serde_json::json!({
354                "column_id": 7,
355                "path": [],
356            }))
357            .is_err()
358        );
359        for key in ["j.2.7.e30", "j.1.7", "j.1.7.!", "j.1.x.e30", "j.1.7.e30"] {
360            assert!(IndexTarget::decode(key).is_err(), "{key}");
361        }
362    }
363}