Skip to main content

api/
region.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::collections::HashMap;
16
17use common_base::AffectedRows;
18use greptime_proto::v1::region::{RegionRequestHeader, RegionResponse as RegionResponseV1};
19
20/// Request extension advertising support for per-entry write failures.
21pub const ACCEPT_PARTIAL_RESULT: &str = "accept_partial_result";
22
23/// Advertises support for per-entry write failures in the request header.
24pub fn set_accept_partial_result(header: &mut RegionRequestHeader) {
25    header
26        .query_context
27        .get_or_insert_with(Default::default)
28        .extensions
29        .insert(ACCEPT_PARTIAL_RESULT.to_string(), "true".to_string());
30}
31
32/// This result struct is derived from [RegionResponseV1]
33#[derive(Debug)]
34pub struct RegionResponse {
35    pub affected_rows: AffectedRows,
36    pub extensions: HashMap<String, Vec<u8>>,
37    pub metadata: Vec<u8>,
38}
39
40/// Successful entries and failed-entry errors indexed by input order.
41#[derive(Debug)]
42pub struct BatchRegionResponse<E> {
43    pub affected_rows: AffectedRows,
44    pub extensions: HashMap<String, Vec<u8>>,
45    pub failures: Vec<(usize, E)>,
46}
47
48impl<E> BatchRegionResponse<E> {
49    /// Returns the failure with the smallest original request index.
50    pub fn first_failure(&self) -> Option<&(usize, E)> {
51        self.failures.iter().min_by_key(|(index, _)| *index)
52    }
53}
54
55impl RegionResponse {
56    pub fn from_region_response(region_response: RegionResponseV1) -> Self {
57        Self {
58            affected_rows: region_response.affected_rows as _,
59            extensions: region_response.extensions,
60            metadata: region_response.metadata,
61        }
62    }
63
64    /// Creates one response without extension
65    pub fn new(affected_rows: AffectedRows) -> Self {
66        Self {
67            affected_rows,
68            extensions: Default::default(),
69            metadata: Vec::new(),
70        }
71    }
72
73    /// Creates one response with metadata.
74    pub fn from_metadata(metadata: Vec<u8>) -> Self {
75        Self {
76            affected_rows: 0,
77            extensions: Default::default(),
78            metadata,
79        }
80    }
81}