Skip to main content

common_meta/election/object_store/
store.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;
16
17use common_error::ext::BoxedError;
18use object_store::config::ObjectStoreConfig;
19use object_store::factory;
20use object_store::util;
21use object_store::{ErrorKind, Metadata, ObjectStore};
22use snafu::{IntoError, OptionExt, ResultExt};
23
24use crate::election::object_store::AuthorityHead;
25use crate::error::{self, Result};
26use crate::metrics::METRIC_AUTHORITY_STORAGE_EVENTS;
27
28/// A coherent read. Only this module can pair the payload and response metadata.
29#[derive(Debug, Clone)]
30pub struct AuthorityState {
31    head: AuthorityHead,
32    metadata: Metadata,
33    scope: Arc<StoreScope>,
34    path: String,
35}
36
37impl AuthorityState {
38    /// Payload observed by this read.
39    pub fn head(&self) -> &AuthorityHead {
40        &self.head
41    }
42    /// Complete metadata returned by the same read.
43    pub fn metadata(&self) -> &Metadata {
44        &self.metadata
45    }
46}
47
48/// Protocol-specific storage. Writes are never transparently retried.
49pub struct HeadStore {
50    pub(crate) operator: ObjectStore,
51    pub(crate) head_path: String,
52    pub(crate) probe_prefix: String,
53    scope: Arc<StoreScope>,
54}
55
56// A fresh allocation identifies the store instance that produced each state.
57#[derive(Debug)]
58struct StoreScope;
59
60enum ConditionIdentity<'a> {
61    Version(&'a str),
62    Etag(&'a str),
63}
64
65impl HeadStore {
66    /// Opens storage without creating or changing the official Head.
67    ///
68    /// Every call performs remote capability probes. Initialize once at node startup
69    /// and share this instance. An `AuthorityState` is bound to the instance that read
70    /// it; conditional replacement must use that same instance.
71    ///
72    /// `prefix` is relative to the configured storage root, which is applied once by
73    /// the operator. An empty prefix is for an exclusively owned root. Clusters sharing
74    /// a root must use non-empty, unique, stable prefixes. Path joining collapses
75    /// repeated `/` separators and preserves at most one leading `/`; that leading `/`
76    /// is still resolved within the operator root, not the host filesystem root.
77    pub async fn open(config: &ObjectStoreConfig, data_home: &str, prefix: &str) -> Result<Self> {
78        let operator = factory::new_raw_object_store(config, data_home)
79            .await
80            .context(error::AuthorityOpenSnafu)?;
81        let store = Self::new(operator, prefix);
82        store.check_capabilities()?;
83        store.probe_conditional_writes().await?;
84        Ok(store)
85    }
86
87    // The only Head operator layer assembly site, shared by open() and fault tests.
88    // The input must be raw: never add RetryLayer or clone a general-purpose operator.
89    fn new(operator: ObjectStore, prefix: &str) -> Self {
90        let operator = util::with_instrument_layers(operator, false);
91        Self {
92            operator,
93            head_path: util::join_path(prefix, "authority/head.json"),
94            probe_prefix: util::join_dir(prefix, "probes"),
95            scope: Arc::new(StoreScope),
96        }
97    }
98
99    #[cfg(test)]
100    pub(crate) fn new_for_test(operator: ObjectStore, prefix: &str) -> Self {
101        Self::new(operator, prefix)
102    }
103
104    /// Reads one full response and its metadata; absence requires operator recovery.
105    pub async fn read_head(&self) -> Result<AuthorityState> {
106        self.read_at(&self.head_path).await
107    }
108
109    /// Explicit create-only initialization. Normal reads never call this method.
110    /// Read back with [`Self::read_head`] when payload and metadata are needed.
111    pub async fn create_initial_head(&self) -> Result<()> {
112        self.create_at(&self.head_path, &AuthorityHead::initial())
113            .await
114    }
115
116    /// Replaces the observed version. Term and owner checks belong to the authority.
117    /// Success confirms the PUT only; a subsequent [`Self::read_head`] reports its own result.
118    pub async fn replace_head(
119        &self,
120        expected: &AuthorityState,
121        next: &AuthorityHead,
122    ) -> Result<()> {
123        self.replace_at(&self.head_path, expected, next).await
124    }
125
126    /// Compares opaque conditional identities. Equality does not resolve a timed-out write.
127    pub fn same_version(&self, left: &Metadata, right: &Metadata) -> Result<bool> {
128        let left = self.identity(left)?;
129        let right = self.identity(right)?;
130        match (left, right) {
131            (ConditionIdentity::Version(left), ConditionIdentity::Version(right))
132            | (ConditionIdentity::Etag(left), ConditionIdentity::Etag(right)) => Ok(left == right),
133            _ => error::AuthorityMetadataSnafu {
134                reason: "incomparable condition identities",
135            }
136            .fail(),
137        }
138    }
139
140    fn identity<'a>(&self, metadata: &'a Metadata) -> Result<ConditionIdentity<'a>> {
141        let capability = self.operator.info().capability();
142        if capability.write_with_if_version_match
143            && let Some(version) = metadata.version()
144        {
145            if version.is_empty() {
146                return error::AuthorityMetadataSnafu {
147                    reason: "empty native condition identity",
148                }
149                .fail();
150            }
151            return Ok(ConditionIdentity::Version(version));
152        }
153        if capability.write_with_if_match
154            && let Some(etag) = metadata.etag()
155            && !etag.is_empty()
156        {
157            return Ok(ConditionIdentity::Etag(etag));
158        }
159        error::AuthorityMetadataSnafu {
160            reason: "missing supported conditional identity",
161        }
162        .fail()
163    }
164
165    pub(crate) async fn read_at(&self, path: &str) -> Result<AuthorityState> {
166        let read = async {
167            let reader = self.operator.reader(path).await?;
168            let body = reader.read(..).await?;
169            Ok::<_, object_store::Error>((body, reader.metadata().cloned()))
170        }
171        .await;
172        let (body, metadata) = read.map_err(|error| {
173            if error.kind() == ErrorKind::NotFound {
174                error::AuthorityMissingSnafu { path }.into_error(error)
175            } else {
176                error::AuthorityStorageSnafu { operation: "read" }.into_error(error)
177            }
178        })?;
179        let metadata = metadata.context(error::AuthorityMetadataSnafu {
180            reason: "read returned no metadata",
181        })?;
182        self.identity(&metadata)?;
183        if metadata.last_modified().is_none() {
184            return error::AuthorityMetadataSnafu {
185                reason: "read returned no last_modified",
186            }
187            .fail();
188        }
189        let head = AuthorityHead::decode(&body.to_vec()).map_err(|source| {
190            error::AuthorityReadHeadSnafu { path }.into_error(BoxedError::new(source))
191        })?;
192        Ok(AuthorityState {
193            head,
194            metadata,
195            scope: self.scope.clone(),
196            path: path.into(),
197        })
198    }
199
200    pub(crate) async fn create_at(&self, path: &str, head: &AuthorityHead) -> Result<()> {
201        self.write_result(
202            self.operator
203                .write_with(path, head.encode()?)
204                .if_not_exists(true)
205                .await,
206        )
207    }
208
209    pub(crate) async fn replace_at(
210        &self,
211        path: &str,
212        expected: &AuthorityState,
213        next: &AuthorityHead,
214    ) -> Result<()> {
215        if !Arc::ptr_eq(&self.scope, &expected.scope) || expected.path != path {
216            return error::AuthorityMetadataSnafu {
217                reason: "state belongs to another storage instance or path",
218            }
219            .fail();
220        }
221        self.identity(&expected.metadata)?;
222        self.write_result(
223            self.operator
224                .write_with(path, next.encode()?)
225                .if_not_changed(&expected.metadata)
226                .await,
227        )
228    }
229
230    fn write_result(&self, result: object_store::Result<Metadata>) -> Result<()> {
231        result.map(|_| ()).map_err(|error| {
232            let outcome = match error.kind() {
233                ErrorKind::ConditionNotMatch | ErrorKind::AlreadyExists | ErrorKind::Conflict => {
234                    "conflict"
235                }
236                _ if error.is_temporary() || error.kind() == ErrorKind::Unexpected => {
237                    "unknown_write"
238                }
239                _ => "write_error",
240            };
241            METRIC_AUTHORITY_STORAGE_EVENTS
242                .with_label_values(&[outcome])
243                .inc();
244            error::AuthorityStorageSnafu { operation: "write" }.into_error(error)
245        })
246    }
247}