common_meta/election/object_store/
store.rs1use 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#[derive(Debug, Clone)]
30pub struct AuthorityState {
31 head: AuthorityHead,
32 metadata: Metadata,
33 scope: Arc<StoreScope>,
34 path: String,
35}
36
37impl AuthorityState {
38 pub fn head(&self) -> &AuthorityHead {
40 &self.head
41 }
42 pub fn metadata(&self) -> &Metadata {
44 &self.metadata
45 }
46}
47
48pub 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#[derive(Debug)]
58struct StoreScope;
59
60enum ConditionIdentity<'a> {
61 Version(&'a str),
62 Etag(&'a str),
63}
64
65impl HeadStore {
66 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 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 pub async fn read_head(&self) -> Result<AuthorityState> {
106 self.read_at(&self.head_path).await
107 }
108
109 pub async fn create_initial_head(&self) -> Result<()> {
112 self.create_at(&self.head_path, &AuthorityHead::initial())
113 .await
114 }
115
116 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 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}