diff --git a/src/common/meta/Cargo.toml b/src/common/meta/Cargo.toml index 0c99d8d2c00..f99a6c569bb 100644 --- a/src/common/meta/Cargo.toml +++ b/src/common/meta/Cargo.toml @@ -104,3 +104,4 @@ common-procedure-test.workspace = true common-test-util.workspace = true common-wal = { workspace = true, features = ["testing"] } datatypes.workspace = true +object-store = { workspace = true, features = ["testing"] } diff --git a/src/common/meta/src/election.rs b/src/common/meta/src/election.rs index 12173beda80..a490876c498 100644 --- a/src/common/meta/src/election.rs +++ b/src/common/meta/src/election.rs @@ -13,6 +13,7 @@ // limitations under the License. pub mod etcd; +pub mod object_store; #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))] pub mod rds; diff --git a/src/common/meta/src/election/object_store.rs b/src/common/meta/src/election/object_store.rs new file mode 100644 index 00000000000..9c5b22dc591 --- /dev/null +++ b/src/common/meta/src/election/object_store.rs @@ -0,0 +1,24 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Authority Head v1 codec and non-retrying conditional object storage. + +mod head; +mod probe; +mod store; +#[cfg(test)] +mod tests; + +pub use head::{AuthorityHead, HEAD_FORMAT_VERSION, NodeIdentity}; +pub use store::{AuthorityState, HeadStore}; diff --git a/src/common/meta/src/election/object_store/head.rs b/src/common/meta/src/election/object_store/head.rs new file mode 100644 index 00000000000..6e2e4ac3b73 --- /dev/null +++ b/src/common/meta/src/election/object_store/head.rs @@ -0,0 +1,128 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use serde::{Deserialize, Deserializer, Serialize}; +use snafu::{OptionExt, ResultExt}; +use uuid::Uuid; + +use crate::error::{self, Result}; + +/// Persisted Authority Head format supported by this reader and writer. +pub const HEAD_FORMAT_VERSION: u32 = 1; + +/// A process identity, generated once at startup and retained by the caller. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NodeIdentity { + pub addr: String, + pub incarnation_id: Uuid, +} + +impl NodeIdentity { + /// Creates a fresh process incarnation, even when the address is reused. + pub fn new(addr: String) -> Self { + Self { + addr, + incarnation_id: Uuid::new_v4(), + } + } +} + +/// Version-one persisted authority payload. Lease deadline is diagnostic only. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AuthorityHead { + pub format_version: u32, + // Serde normally treats a missing Option as None. The design requires owner to + // be present while still allowing its value to be null. + #[serde(deserialize_with = "required_owner")] + pub owner: Option, + epoch: u64, + pub lease_deadline_ms: u64, + write_seq: u64, +} + +fn required_owner<'de, D: Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + Option::deserialize(deserializer) +} + +impl AuthorityHead { + /// Empty Head for explicit initialization of a new namespace. + pub fn initial() -> Self { + Self { + format_version: HEAD_FORMAT_VERSION, + owner: None, + epoch: 0, + lease_deadline_ms: 0, + write_seq: 0, + } + } + + /// Validates the format and encodes compact deterministic JSON. + pub fn encode(&self) -> Result> { + self.validate()?; + serde_json::to_vec(self).context(error::AuthorityFormatSnafu { + operation: "encode", + }) + } + + /// Decodes required fields and rejects unknown protocol versions. + pub fn decode(bytes: &[u8]) -> Result { + let head: Self = serde_json::from_slice(bytes).context(error::AuthorityFormatSnafu { + operation: "decode", + })?; + head.validate()?; + Ok(head) + } + + fn validate(&self) -> Result<()> { + if self.format_version != HEAD_FORMAT_VERSION { + return error::AuthorityVersionSnafu { + version: self.format_version, + } + .fail(); + } + Ok(()) + } + + /// Returns the logical epoch in this payload. + pub fn epoch(&self) -> u64 { + self.epoch + } + + /// Returns the write sequence in this payload. + pub fn write_seq(&self) -> u64 { + self.write_seq + } + + /// Returns a payload with its epoch advanced, rejecting overflow before mutation. + pub fn with_next_epoch(mut self) -> Result { + self.epoch = self + .epoch + .checked_add(1) + .context(error::AuthorityOverflowSnafu { counter: "epoch" })?; + Ok(self) + } + + /// Returns a payload with its write sequence advanced, rejecting overflow. + pub fn with_next_write_seq(mut self) -> Result { + self.write_seq = self + .write_seq + .checked_add(1) + .context(error::AuthorityOverflowSnafu { + counter: "write_seq", + })?; + Ok(self) + } +} diff --git a/src/common/meta/src/election/object_store/probe.rs b/src/common/meta/src/election/object_store/probe.rs new file mode 100644 index 00000000000..ff97bc7073d --- /dev/null +++ b/src/common/meta/src/election/object_store/probe.rs @@ -0,0 +1,167 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use common_telemetry::warn; +use object_store::util; +use object_store::{ErrorKind, Metadata}; +use snafu::{IntoError, ResultExt}; +use uuid::Uuid; + +use crate::election::object_store::{AuthorityHead, AuthorityState, HeadStore}; +use crate::error::{self, Result}; +use crate::metrics::METRIC_AUTHORITY_STORAGE_EVENTS; + +impl HeadStore { + pub(crate) fn check_capabilities(&self) -> Result<()> { + let info = self.operator.info(); + let scheme = info.scheme(); + // TODO(alorun): Replace the allow-list with capability-based admission after + // GCS passes real-endpoint generation-based conditional-write qualification. + let reason = match scheme { + "s3" | "azblob" => None, + "gcs" => { + Some("GCS generation-based conditional writes require real-endpoint validation") + } + "oss" => Some("OSS PutObject rejects If-Match and If-None-Match conditions"), + "fs" | "memory" => { + Some("backend lacks the required atomic conditional replacement semantics") + } + _ => Some("backend has not been qualified for Authority Head conditional replacement"), + }; + if let Some(reason) = reason { + return error::AuthorityCapabilitySnafu { scheme, reason }.fail(); + } + let c = info.capability(); + if !(c.read + && c.write + && c.list + && c.delete + && c.write_with_if_not_exists + && (c.write_with_if_version_match || c.write_with_if_match)) + { + return error::AuthorityCapabilitySnafu { + scheme, + reason: "read/write/list/delete and atomic conditional create/replace are required", + } + .fail(); + } + Ok(()) + } + + pub(crate) async fn probe_conditional_writes(&self) -> Result<()> { + let path = util::join_path(&self.probe_prefix, &format!("{}.json", Uuid::new_v4())); + let result = self.probe_at(&path).await; + let cleanup = self.cleanup_probe(&path).await; + if result.is_err() { + METRIC_AUTHORITY_STORAGE_EVENTS + .with_label_values(&["probe_failure"]) + .inc(); + if let Err(error) = cleanup { + warn!(error; "Authority probe cleanup also failed"); + } + return result; + } + cleanup + } + + async fn probe_at(&self, path: &str) -> Result<()> { + let initial = AuthorityHead::initial(); + self.create_at(path, &initial).await?; + let first = self.read_at(path).await?; + self.require_probe(first.head() == &initial, "initial contents differ")?; + let next = initial.clone().with_next_write_seq()?; + match self.create_at(path, &next).await { + Err(error) + if matches!( + error.authority_storage_error().map(|e| e.kind()), + Some(ErrorKind::ConditionNotMatch | ErrorKind::AlreadyExists) + ) => {} + Err(error) => return Err(error), + Ok(()) => { + return error::AuthorityProbeSnafu { + reason: "duplicate create was accepted", + } + .fail(); + } + } + let unchanged = self.read_at(path).await?; + self.verify_probe(&unchanged, &initial, first.metadata(), true)?; + self.replace_at(path, &first, &next).await?; + let current = self.read_at(path).await?; + self.verify_probe(¤t, &next, first.metadata(), false)?; + let stale = next.clone().with_next_write_seq()?; + match self.replace_at(path, &first, &stale).await { + Err(error) + if error.authority_storage_error().map(|e| e.kind()) + == Some(ErrorKind::ConditionNotMatch) => {} + Err(error) => return Err(error), + Ok(()) => { + return error::AuthorityProbeSnafu { + reason: "stale replacement was accepted", + } + .fail(); + } + } + let unchanged = self.read_at(path).await?; + self.verify_probe(&unchanged, &next, current.metadata(), true)?; + // Exercise plain PUT and listing permission, without using listing for authority. + self.operator + .write(path, stale.encode()?) + .await + .context(error::AuthorityStorageSnafu { + operation: "probe plain write", + })?; + let plain = self.read_at(path).await?; + self.verify_probe(&plain, &stale, current.metadata(), false)?; + self.operator + .list(&self.probe_prefix) + .await + .context(error::AuthorityStorageSnafu { + operation: "probe list", + })?; + Ok(()) + } + + fn verify_probe( + &self, + state: &AuthorityState, + expected: &AuthorityHead, + metadata: &Metadata, + same: bool, + ) -> Result<()> { + self.require_probe( + state.head() == expected && self.same_version(state.metadata(), metadata)? == same, + "contents or condition identity differ from expected", + ) + } + + fn require_probe(&self, valid: bool, reason: &'static str) -> Result<()> { + if !valid { + return error::AuthorityProbeSnafu { reason }.fail(); + } + Ok(()) + } + + pub(crate) async fn cleanup_probe(&self, path: &str) -> Result<()> { + self.operator.delete(path).await.map_err(|error| { + METRIC_AUTHORITY_STORAGE_EVENTS + .with_label_values(&["probe_cleanup_failure"]) + .inc(); + error::AuthorityStorageSnafu { + operation: "probe cleanup", + } + .into_error(error) + }) + } +} diff --git a/src/common/meta/src/election/object_store/store.rs b/src/common/meta/src/election/object_store/store.rs new file mode 100644 index 00000000000..b0dae355f58 --- /dev/null +++ b/src/common/meta/src/election/object_store/store.rs @@ -0,0 +1,247 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; + +use common_error::ext::BoxedError; +use object_store::config::ObjectStoreConfig; +use object_store::factory; +use object_store::util; +use object_store::{ErrorKind, Metadata, ObjectStore}; +use snafu::{IntoError, OptionExt, ResultExt}; + +use crate::election::object_store::AuthorityHead; +use crate::error::{self, Result}; +use crate::metrics::METRIC_AUTHORITY_STORAGE_EVENTS; + +/// A coherent read. Only this module can pair the payload and response metadata. +#[derive(Debug, Clone)] +pub struct AuthorityState { + head: AuthorityHead, + metadata: Metadata, + scope: Arc, + path: String, +} + +impl AuthorityState { + /// Payload observed by this read. + pub fn head(&self) -> &AuthorityHead { + &self.head + } + /// Complete metadata returned by the same read. + pub fn metadata(&self) -> &Metadata { + &self.metadata + } +} + +/// Protocol-specific storage. Writes are never transparently retried. +pub struct HeadStore { + pub(crate) operator: ObjectStore, + pub(crate) head_path: String, + pub(crate) probe_prefix: String, + scope: Arc, +} + +// A fresh allocation identifies the store instance that produced each state. +#[derive(Debug)] +struct StoreScope; + +enum ConditionIdentity<'a> { + Version(&'a str), + Etag(&'a str), +} + +impl HeadStore { + /// Opens storage without creating or changing the official Head. + /// + /// Every call performs remote capability probes. Initialize once at node startup + /// and share this instance. An `AuthorityState` is bound to the instance that read + /// it; conditional replacement must use that same instance. + /// + /// `prefix` is relative to the configured storage root, which is applied once by + /// the operator. An empty prefix is for an exclusively owned root. Clusters sharing + /// a root must use non-empty, unique, stable prefixes. Path joining collapses + /// repeated `/` separators and preserves at most one leading `/`; that leading `/` + /// is still resolved within the operator root, not the host filesystem root. + pub async fn open(config: &ObjectStoreConfig, data_home: &str, prefix: &str) -> Result { + let operator = factory::new_raw_object_store(config, data_home) + .await + .context(error::AuthorityOpenSnafu)?; + let store = Self::new(operator, prefix); + store.check_capabilities()?; + store.probe_conditional_writes().await?; + Ok(store) + } + + // The only Head operator layer assembly site, shared by open() and fault tests. + // The input must be raw: never add RetryLayer or clone a general-purpose operator. + fn new(operator: ObjectStore, prefix: &str) -> Self { + let operator = util::with_instrument_layers(operator, false); + Self { + operator, + head_path: util::join_path(prefix, "authority/head.json"), + probe_prefix: util::join_dir(prefix, "probes"), + scope: Arc::new(StoreScope), + } + } + + #[cfg(test)] + pub(crate) fn new_for_test(operator: ObjectStore, prefix: &str) -> Self { + Self::new(operator, prefix) + } + + /// Reads one full response and its metadata; absence requires operator recovery. + pub async fn read_head(&self) -> Result { + self.read_at(&self.head_path).await + } + + /// Explicit create-only initialization. Normal reads never call this method. + /// Read back with [`Self::read_head`] when payload and metadata are needed. + pub async fn create_initial_head(&self) -> Result<()> { + self.create_at(&self.head_path, &AuthorityHead::initial()) + .await + } + + /// Replaces the observed version. Term and owner checks belong to the authority. + /// Success confirms the PUT only; a subsequent [`Self::read_head`] reports its own result. + pub async fn replace_head( + &self, + expected: &AuthorityState, + next: &AuthorityHead, + ) -> Result<()> { + self.replace_at(&self.head_path, expected, next).await + } + + /// Compares opaque conditional identities. Equality does not resolve a timed-out write. + pub fn same_version(&self, left: &Metadata, right: &Metadata) -> Result { + let left = self.identity(left)?; + let right = self.identity(right)?; + match (left, right) { + (ConditionIdentity::Version(left), ConditionIdentity::Version(right)) + | (ConditionIdentity::Etag(left), ConditionIdentity::Etag(right)) => Ok(left == right), + _ => error::AuthorityMetadataSnafu { + reason: "incomparable condition identities", + } + .fail(), + } + } + + fn identity<'a>(&self, metadata: &'a Metadata) -> Result> { + let capability = self.operator.info().capability(); + if capability.write_with_if_version_match + && let Some(version) = metadata.version() + { + if version.is_empty() { + return error::AuthorityMetadataSnafu { + reason: "empty native condition identity", + } + .fail(); + } + return Ok(ConditionIdentity::Version(version)); + } + if capability.write_with_if_match + && let Some(etag) = metadata.etag() + && !etag.is_empty() + { + return Ok(ConditionIdentity::Etag(etag)); + } + error::AuthorityMetadataSnafu { + reason: "missing supported conditional identity", + } + .fail() + } + + pub(crate) async fn read_at(&self, path: &str) -> Result { + let read = async { + let reader = self.operator.reader(path).await?; + let body = reader.read(..).await?; + Ok::<_, object_store::Error>((body, reader.metadata().cloned())) + } + .await; + let (body, metadata) = read.map_err(|error| { + if error.kind() == ErrorKind::NotFound { + error::AuthorityMissingSnafu { path }.into_error(error) + } else { + error::AuthorityStorageSnafu { operation: "read" }.into_error(error) + } + })?; + let metadata = metadata.context(error::AuthorityMetadataSnafu { + reason: "read returned no metadata", + })?; + self.identity(&metadata)?; + if metadata.last_modified().is_none() { + return error::AuthorityMetadataSnafu { + reason: "read returned no last_modified", + } + .fail(); + } + let head = AuthorityHead::decode(&body.to_vec()).map_err(|source| { + error::AuthorityReadHeadSnafu { path }.into_error(BoxedError::new(source)) + })?; + Ok(AuthorityState { + head, + metadata, + scope: self.scope.clone(), + path: path.into(), + }) + } + + pub(crate) async fn create_at(&self, path: &str, head: &AuthorityHead) -> Result<()> { + self.write_result( + self.operator + .write_with(path, head.encode()?) + .if_not_exists(true) + .await, + ) + } + + pub(crate) async fn replace_at( + &self, + path: &str, + expected: &AuthorityState, + next: &AuthorityHead, + ) -> Result<()> { + if !Arc::ptr_eq(&self.scope, &expected.scope) || expected.path != path { + return error::AuthorityMetadataSnafu { + reason: "state belongs to another storage instance or path", + } + .fail(); + } + self.identity(&expected.metadata)?; + self.write_result( + self.operator + .write_with(path, next.encode()?) + .if_not_changed(&expected.metadata) + .await, + ) + } + + fn write_result(&self, result: object_store::Result) -> Result<()> { + result.map(|_| ()).map_err(|error| { + let outcome = match error.kind() { + ErrorKind::ConditionNotMatch | ErrorKind::AlreadyExists | ErrorKind::Conflict => { + "conflict" + } + _ if error.is_temporary() || error.kind() == ErrorKind::Unexpected => { + "unknown_write" + } + _ => "write_error", + }; + METRIC_AUTHORITY_STORAGE_EVENTS + .with_label_values(&[outcome]) + .inc(); + error::AuthorityStorageSnafu { operation: "write" }.into_error(error) + }) + } +} diff --git a/src/common/meta/src/election/object_store/tests.rs b/src/common/meta/src/election/object_store/tests.rs new file mode 100644 index 00000000000..9e857766078 --- /dev/null +++ b/src/common/meta/src/election/object_store/tests.rs @@ -0,0 +1,1021 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use common_error::ext::{ErrorExt, RetryHint}; +use common_error::status_code::StatusCode; +use object_store::layers::RetryLayer; +use object_store::layers::mock::{ + Buffer, BytesRange, Capability, Error, ErrorKind, Metadata, MetadataBuilder, OpCopy, + OpCreateDir, OpDelete, OpList, OpPresign, OpRead, OpRename, OpStat, OpWrite, OperationContext, + Result, RpCreateDir, RpPresign, RpRead, RpRename, RpStat, Service, Timestamp, oio, +}; +use object_store::{ObjectStore, ServiceInfo}; + +use super::*; + +// Explicitly supplies coherent response metadata. This is a protocol simulator, +// not a claim about memory-service or real-backend semantics. +#[derive(Debug, Default)] +struct Data { + objects: HashMap, Metadata)>, + seq: u64, + writes: usize, + ignore_conditions: bool, + ignore_replace: bool, + create_exists: bool, + missing_metadata: bool, + fail: Option<&'static str>, + delete_fail: bool, + deleted: Vec, + conflict_create: Option, + conflict_replace: Option, + corruptions: usize, + write_barrier: Option>, + write_arrivals: usize, + writes_in_flight: usize, + max_writes_in_flight: usize, + pause: Option<(Arc, Arc)>, +} + +#[derive(Debug, Clone, Copy)] +enum ConflictMutation { + Body, + Identity, +} + +#[derive(Debug, Clone)] +struct Backend { + data: Arc>, + scheme: &'static str, + capability: Capability, +} + +impl Default for Backend { + fn default() -> Self { + Self { + data: Arc::default(), + scheme: "s3", + capability: Capability { + read: true, + write: true, + list: true, + delete: true, + write_with_if_not_exists: true, + write_with_if_match: true, + ..Default::default() + }, + } + } +} + +impl Service for Backend { + async fn create_dir( + &self, + _: &OperationContext, + _: &str, + _: OpCreateDir, + ) -> Result { + unreachable!() + } + + async fn stat(&self, _: &OperationContext, _: &str, _: OpStat) -> Result { + unreachable!("Head must not stat") + } + + fn copy(&self, _: &OperationContext, _: &str, _: &str, _: OpCopy) -> Result<()> { + unreachable!() + } + + async fn rename( + &self, + _: &OperationContext, + _: &str, + _: &str, + _: OpRename, + ) -> Result { + unreachable!() + } + + async fn presign(&self, _: &OperationContext, _: &str, _: OpPresign) -> Result { + unreachable!() + } + + type Reader = TestReader; + type Writer = TestWriter; + type Lister = TestLister; + type Deleter = TestDeleter; + type Copier = (); + type Composer = (); + + fn info(&self) -> ServiceInfo { + ServiceInfo::new(self.scheme, "/", "authority-test") + } + + fn capability(&self) -> Capability { + self.capability + } + + fn read(&self, _: &OperationContext, path: &str, _: OpRead) -> Result { + Ok(TestReader { + data: self.data.clone(), + path: path.into(), + }) + } + + fn write(&self, _: &OperationContext, path: &str, args: OpWrite) -> Result { + Ok(TestWriter { + data: self.data.clone(), + path: path.into(), + args, + body: Vec::new(), + }) + } + + fn delete(&self, _: &OperationContext) -> Result { + Ok(TestDeleter(self.data.clone())) + } + + fn list(&self, _: &OperationContext, _: &str, _: OpList) -> Result { + if self.data.lock().unwrap().fail == Some("list") { + return Err(denied()); + } + Ok(TestLister) + } +} + +struct TestLister; + +impl oio::List for TestLister { + async fn next(&mut self) -> Result> { + Ok(None) + } +} + +fn denied() -> Error { + Error::new(ErrorKind::PermissionDenied, "injected permission failure") +} + +struct TestReader { + data: Arc>, + path: String, +} + +impl oio::Read for TestReader { + async fn open(&self, _: BytesRange) -> Result<(RpRead, Box)> { + let data = self.data.lock().unwrap(); + let (body, meta) = data + .objects + .get(&self.path) + .ok_or_else(|| Error::new(ErrorKind::NotFound, "missing"))?; + let rp = if data.missing_metadata { + RpRead::default() + } else { + RpRead::new(meta.clone()) + }; + Ok(( + rp, + Box::new(TestStream { + body: Buffer::from(body.clone()), + pause: data.pause.clone(), + }), + )) + } + + async fn read(&self, _: BytesRange) -> Result<(RpRead, Buffer)> { + unreachable!("full read must use one stream") + } +} + +struct TestStream { + body: Buffer, + pause: Option<(Arc, Arc)>, +} + +impl oio::ReadStream for TestStream { + async fn read(&mut self) -> Result { + if let Some((opened, release)) = self.pause.take() { + opened.notify_one(); + release.notified().await; + } + Ok(std::mem::take(&mut self.body)) + } +} + +struct TestWriter { + data: Arc>, + path: String, + args: OpWrite, + body: Vec, +} + +impl oio::Write for TestWriter { + async fn write(&mut self, bytes: Buffer) -> Result<()> { + self.body.extend(bytes.to_vec()); + Ok(()) + } + + async fn close(&mut self) -> Result { + let barrier = { + let mut data = self.data.lock().unwrap(); + let barrier = data.write_barrier.clone(); + if barrier.is_some() { + data.write_arrivals += 1; + data.writes_in_flight += 1; + data.max_writes_in_flight = data.max_writes_in_flight.max(data.writes_in_flight); + } + barrier + }; + if let Some(barrier) = barrier { + barrier.wait().await; + } + let mut data = self.data.lock().unwrap(); + if data.write_barrier.is_some() { + data.writes_in_flight -= 1; + } + data.writes += 1; + if data.fail == Some("write") { + return Err(Error::new(ErrorKind::Unexpected, "lost response").set_temporary()); + } + if data.fail == Some("plain") + && !self.args.if_not_exists() + && self.args.if_match().is_none() + { + return Err(denied()); + } + if !data.ignore_conditions { + if self.args.if_not_exists() && data.objects.contains_key(&self.path) { + let mutation = data.conflict_create; + corrupt_conflict(&mut data, &self.path, mutation); + return Err(Error::new( + if data.create_exists { + ErrorKind::AlreadyExists + } else { + ErrorKind::ConditionNotMatch + }, + "exists", + )); + } + if !data.ignore_replace + && let Some(version) = self.args.if_version_match() + && data.objects.get(&self.path).and_then(|(_, m)| m.version()) != Some(version) + { + let mutation = data.conflict_replace; + corrupt_conflict(&mut data, &self.path, mutation); + return Err(Error::new( + ErrorKind::ConditionNotMatch, + "stale native version", + )); + } + if !data.ignore_replace + && let Some(etag) = self.args.if_match() + && data.objects.get(&self.path).and_then(|(_, m)| m.etag()) != Some(etag) + { + let mutation = data.conflict_replace; + corrupt_conflict(&mut data, &self.path, mutation); + return Err(Error::new(ErrorKind::ConditionNotMatch, "stale")); + } + } + data.seq += 1; + let mut builder = MetadataBuilder::file(self.body.len() as u64); + builder + .etag(format!("\"{}\"", data.seq)) + .version(data.seq.to_string()) + .last_modified(Timestamp::now()); + let meta = builder.build(); + data.objects + .insert(self.path.clone(), (self.body.clone(), meta.clone())); + Ok(meta) + } + + async fn abort(&mut self) -> Result<()> { + Ok(()) + } +} + +fn corrupt_conflict(data: &mut Data, path: &str, mutation: Option) { + let Some(mutation) = mutation else { + return; + }; + let (body, metadata) = data.objects.get_mut(path).unwrap(); + match mutation { + ConflictMutation::Body => { + let mut head = AuthorityHead::decode(body).unwrap(); + head = head.with_next_write_seq().unwrap(); + *body = head.encode().unwrap(); + } + ConflictMutation::Identity => { + let mut builder = metadata.clone().into_builder(); + builder.etag("\"corrupt\"").version("corrupt"); + *metadata = builder.build(); + } + } + data.corruptions += 1; +} + +struct TestDeleter(Arc>); + +impl oio::Delete for TestDeleter { + async fn delete(&mut self, path: &str, _: OpDelete) -> Result<()> { + let mut data = self.0.lock().unwrap(); + data.deleted.push(path.into()); + if data.delete_fail { + return Err(denied()); + } + data.objects.remove(path); + Ok(()) + } + + async fn close(&mut self) -> Result<()> { + Ok(()) + } +} + +fn store(backend: &Backend) -> HeadStore { + HeadStore::new_for_test( + ObjectStore::from_parts(OperationContext::default(), Arc::new(backend.clone())), + "cluster", + ) +} + +#[tokio::test] +async fn test_head_conditional_create() { + let b = Backend::default(); + let s = store(&b); + s.create_initial_head().await.unwrap(); + let before = s.read_head().await.unwrap(); + assert!(s.create_initial_head().await.is_err()); + let after = s.read_head().await.unwrap(); + assert_eq!(before.head(), after.head()); + assert!(s.same_version(before.metadata(), after.metadata()).unwrap()); +} + +#[tokio::test] +async fn test_head_stale_replace() { + let b = Backend::default(); + let s = store(&b); + s.create_initial_head().await.unwrap(); + let old = s.read_head().await.unwrap(); + let next = old.head().clone().with_next_write_seq().unwrap(); + s.replace_head(&old, &next).await.unwrap(); + let before = s.read_head().await.unwrap(); + assert_eq!( + s.replace_head(&old, &next) + .await + .unwrap_err() + .authority_storage_error() + .unwrap() + .kind(), + ErrorKind::ConditionNotMatch + ); + let after = s.read_head().await.unwrap(); + assert_eq!(after.head(), &next); + assert!(s.same_version(before.metadata(), after.metadata()).unwrap()); +} + +#[tokio::test] +async fn test_head_concurrent_replace() { + let backend = Backend::default(); + let store = store(&backend); + store.create_initial_head().await.unwrap(); + let old = store.read_head().await.unwrap(); + let first = old.head().clone().with_next_write_seq().unwrap(); + let second = first.clone().with_next_write_seq().unwrap(); + backend.data.lock().unwrap().write_barrier = Some(Arc::new(tokio::sync::Barrier::new(2))); + let (left, right) = tokio::time::timeout(std::time::Duration::from_secs(5), async { + tokio::join!( + store.replace_head(&old, &first), + store.replace_head(&old, &second) + ) + }) + .await + .expect("both conditional writes must reach the barrier"); + { + let data = backend.data.lock().unwrap(); + assert_eq!(data.write_arrivals, 2); + assert_eq!(data.max_writes_in_flight, 2); + assert_eq!(data.writes_in_flight, 0); + } + let winner = match (left, right) { + (Ok(()), Err(error)) => { + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::ConditionNotMatch + ); + first + } + (Err(error), Ok(())) => { + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::ConditionNotMatch + ); + second + } + result => panic!("expected exactly one conditional winner: {result:?}"), + }; + assert_eq!(store.read_head().await.unwrap().head(), &winner); +} + +#[tokio::test] +async fn test_head_missing_no_create() { + let b = Backend::default(); + let s = store(&b); + let e = s.read_head().await.unwrap_err(); + assert_eq!( + e.authority_storage_error().unwrap().kind(), + ErrorKind::NotFound + ); + assert_eq!(b.data.lock().unwrap().writes, 0); +} + +#[tokio::test] +async fn test_head_missing_metadata() { + let b = Backend::default(); + let s = store(&b); + s.create_initial_head().await.unwrap(); + b.data.lock().unwrap().missing_metadata = true; + assert!(s.read_head().await.is_err()); +} + +#[tokio::test] +async fn test_head_write_error_not_replayed() { + for replace in [false, true] { + let backend = Backend::default(); + let store = store(&backend); + let error = failed_write(&store, &backend, replace).await; + assert_eq!( + error.authority_storage_error().unwrap().kind(), + ErrorKind::Unexpected + ); + assert!(error.authority_storage_error().unwrap().is_temporary()); + assert_eq!(error.retry_hint(), RetryHint::NonRetryable); + assert_eq!(backend.data.lock().unwrap().writes, 1); + } +} + +// A positive control proves the injected failure exposes transparent retries. +#[tokio::test] +async fn test_head_write_retry_detection_control() { + for replace in [false, true] { + let backend = Backend::default(); + let operator = + ObjectStore::from_parts(OperationContext::default(), Arc::new(backend.clone())).layer( + RetryLayer::new() + .with_max_times(1) + .with_min_delay(std::time::Duration::ZERO) + .with_max_delay(std::time::Duration::ZERO), + ); + let store = HeadStore::new_for_test(operator, "cluster"); + let _ = failed_write(&store, &backend, replace).await; + assert_eq!(backend.data.lock().unwrap().writes, 2); + } +} + +async fn failed_write(store: &HeadStore, backend: &Backend, replace: bool) -> crate::error::Error { + let expected = if replace { + store.create_initial_head().await.unwrap(); + Some(store.read_head().await.unwrap()) + } else { + None + }; + { + let mut data = backend.data.lock().unwrap(); + data.writes = 0; + data.fail = Some("write"); + } + if let Some(expected) = expected { + let next = expected.head().clone().with_next_write_seq().unwrap(); + store.replace_head(&expected, &next).await.unwrap_err() + } else { + store.create_initial_head().await.unwrap_err() + } +} + +#[test] +fn test_head_version_selection() { + let mut b = Backend::default(); + b.capability.write_with_if_version_match = true; + let s = store(&b); + let a = metadata_value(Some("a"), Some("v1"), true); + let c = metadata_value(Some("b"), Some("v1"), true); + assert!(s.same_version(&a, &c).unwrap()); + let etag = metadata_value(Some("a"), None, true); + assert!(s.same_version(&a, &etag).is_err()); + b.capability.write_with_if_version_match = false; + assert!(!store(&b).same_version(&a, &c).unwrap()); + assert!(store(&b).same_version(&etag, &etag).unwrap()); + assert!( + s.same_version(&metadata_value(None, None, true), &etag) + .is_err() + ); +} + +#[tokio::test] +async fn test_probe_conditional_writes() { + for exists in [false, true] { + let b = Backend::default(); + b.data.lock().unwrap().create_exists = exists; + store(&b).probe_conditional_writes().await.unwrap(); + assert!(b.data.lock().unwrap().objects.is_empty()); + } +} + +#[tokio::test] +async fn test_probe_rejects_ignored_conditions() { + let b = Backend::default(); + b.data.lock().unwrap().ignore_conditions = true; + assert!(store(&b).probe_conditional_writes().await.is_err()); + assert!(b.data.lock().unwrap().objects.is_empty()); +} + +#[tokio::test] +async fn test_probe_permissions() { + for fail in ["plain", "list"] { + let b = Backend::default(); + b.data.lock().unwrap().fail = Some(fail); + assert!(store(&b).probe_conditional_writes().await.is_err()); + assert!(b.data.lock().unwrap().objects.is_empty()); + } +} + +#[tokio::test] +async fn test_probe_cleanup() { + let b = Backend::default(); + b.data.lock().unwrap().delete_fail = true; + let e = store(&b).probe_conditional_writes().await.unwrap_err(); + assert_eq!( + e.authority_storage_error().unwrap().kind(), + ErrorKind::PermissionDenied + ); + b.data.lock().unwrap().fail = Some("write"); + let e = store(&b).probe_conditional_writes().await.unwrap_err(); + assert_eq!( + e.authority_storage_error().unwrap().kind(), + ErrorKind::Unexpected + ); + assert_eq!(b.data.lock().unwrap().deleted.len(), 2); +} + +#[tokio::test] +async fn test_probe_path_isolation() { + let b = Backend::default(); + let s = store(&b); + s.create_initial_head().await.unwrap(); + let before = s.read_head().await.unwrap(); + s.probe_conditional_writes().await.unwrap(); + let after = s.read_head().await.unwrap(); + assert!(s.same_version(before.metadata(), after.metadata()).unwrap()); + let data = b.data.lock().unwrap(); + assert!( + data.deleted + .iter() + .all(|p| p.starts_with("cluster/probes/") && p.ends_with(".json")) + ); + assert_eq!(data.objects.len(), 1); +} + +#[test] +fn test_backend_admission() { + let mut b = Backend::default(); + assert!(store(&b).check_capabilities().is_ok()); + for scheme in ["gcs", "oss", "fs", "memory"] { + b.scheme = scheme; + assert!(store(&b).check_capabilities().is_err()); + } + b.scheme = "azblob"; + assert!(store(&b).check_capabilities().is_ok()); + b.capability.list = false; + assert!(store(&b).check_capabilities().is_err()); +} + +#[tokio::test] +async fn test_head_read_coherent_metadata() { + let b = Backend::default(); + let s = Arc::new(store(&b)); + s.create_initial_head().await.unwrap(); + let initial = s.read_head().await.unwrap(); + let opened = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + b.data.lock().unwrap().pause = Some((opened.clone(), release.clone())); + let task = tokio::spawn({ + let s = s.clone(); + async move { s.read_head().await } + }); + opened.notified().await; + b.data.lock().unwrap().pause = None; + let next = initial.head().clone().with_next_write_seq().unwrap(); + s.replace_head(&initial, &next).await.unwrap(); + release.notify_one(); + let observed = task.await.unwrap().unwrap(); + assert_eq!(observed.head(), initial.head()); + assert!( + s.same_version(observed.metadata(), initial.metadata()) + .unwrap() + ); + let current = s.read_head().await.unwrap(); + assert_eq!(current.head(), &next); + assert!( + !s.same_version(observed.metadata(), current.metadata()) + .unwrap() + ); +} + +#[test] +fn test_head_empty_native_identity_rejected() { + let mut backend = Backend::default(); + backend.capability.write_with_if_version_match = true; + let metadata = metadata_value(Some("valid"), Some(""), true); + assert!(store(&backend).same_version(&metadata, &metadata).is_err()); +} + +#[tokio::test] +async fn test_head_incomplete_metadata() { + for missing_time in [false, true] { + let backend = Backend::default(); + let store = store(&backend); + store.create_initial_head().await.unwrap(); + { + let mut data = backend.data.lock().unwrap(); + let (_, metadata) = data.objects.values_mut().next().unwrap(); + *metadata = if missing_time { + metadata_value(Some("valid"), None, false) + } else { + metadata_value(None, None, true) + }; + } + assert!(store.read_head().await.is_err()); + } +} + +#[tokio::test] +async fn test_head_state_namespace_binding() { + let backend = Backend::default(); + let first = store(&backend); + let other = store(&backend); + first.create_initial_head().await.unwrap(); + let state = first.read_head().await.unwrap(); + assert!(other.replace_head(&state, state.head()).await.is_err()); + assert_eq!(backend.data.lock().unwrap().writes, 1); +} + +fn metadata_value(etag: Option<&str>, version: Option<&str>, time: bool) -> Metadata { + let mut builder = MetadataBuilder::file(0); + if let Some(etag) = etag { + builder.etag(etag); + } + if let Some(version) = version { + builder.version(version); + } + if time { + builder.last_modified(Timestamp::now()); + } + builder.build() +} + +#[tokio::test] +async fn test_head_native_version_replace() { + let mut backend = Backend::default(); + backend.capability.write_with_if_version_match = true; + let store = store(&backend); + store.create_initial_head().await.unwrap(); + let old = store.read_head().await.unwrap(); + let next = old.head().clone().with_next_write_seq().unwrap(); + store.replace_head(&old, &next).await.unwrap(); + let current = store.read_head().await.unwrap(); + assert!( + !store + .same_version(old.metadata(), current.metadata()) + .unwrap() + ); + assert_eq!( + store + .replace_head(&old, &next) + .await + .unwrap_err() + .authority_storage_error() + .unwrap() + .kind(), + ErrorKind::ConditionNotMatch + ); +} + +#[tokio::test] +async fn test_probe_rejects_ignored_replace() { + let backend = Backend::default(); + backend.data.lock().unwrap().ignore_replace = true; + assert!(store(&backend).probe_conditional_writes().await.is_err()); + assert!(backend.data.lock().unwrap().objects.is_empty()); +} + +#[tokio::test] +async fn test_probe_metadata_cleanup() { + let backend = Backend::default(); + backend.data.lock().unwrap().missing_metadata = true; + assert!(store(&backend).probe_conditional_writes().await.is_err()); + let data = backend.data.lock().unwrap(); + assert!(data.objects.is_empty()); + assert_eq!(data.deleted.len(), 1); +} + +#[test] +fn test_backend_required_capabilities() { + for missing in 0..6 { + let mut backend = Backend::default(); + match missing { + 0 => backend.capability.read = false, + 1 => backend.capability.write = false, + 2 => backend.capability.list = false, + 3 => backend.capability.delete = false, + 4 => backend.capability.write_with_if_not_exists = false, + _ => backend.capability.write_with_if_match = false, + } + assert!(store(&backend).check_capabilities().is_err()); + } +} + +#[tokio::test] +async fn test_probe_rejects_mutation_despite_conflict() { + for mutation in [ConflictMutation::Body, ConflictMutation::Identity] { + for create in [true, false] { + for already_exists in [false, true] { + let backend = Backend::default(); + { + let mut data = backend.data.lock().unwrap(); + data.create_exists = already_exists; + if create { + data.conflict_create = Some(mutation); + } else { + data.conflict_replace = Some(mutation); + } + } + let error = store(&backend) + .probe_conditional_writes() + .await + .unwrap_err(); + assert!( + matches!(error, crate::error::Error::AuthorityProbe { .. }), + "{error:?}" + ); + let data = backend.data.lock().unwrap(); + assert_eq!(data.corruptions, 1); + assert_eq!(data.deleted.len(), 1); + assert!(data.objects.is_empty()); + } + } + } +} + +const INITIAL: &str = + r#"{"format_version":1,"owner":null,"epoch":0,"lease_deadline_ms":0,"write_seq":0}"#; +const OWNED: &str = r#"{"format_version":1,"owner":{"addr":"127.0.0.1:3002","incarnation_id":"550e8400-e29b-41d4-a716-446655440000"},"epoch":1,"lease_deadline_ms":1794528010000,"write_seq":1}"#; + +#[test] +fn test_head_v1_fixtures() { + assert_eq!( + AuthorityHead::decode(INITIAL.as_bytes()).unwrap(), + AuthorityHead::initial() + ); + for fixture in [INITIAL, OWNED] { + let head = AuthorityHead::decode(fixture.as_bytes()).unwrap(); + assert_eq!(head.encode().unwrap(), fixture.trim_end().as_bytes()); + } + let owner = AuthorityHead::decode(OWNED.as_bytes()) + .unwrap() + .owner + .unwrap(); + assert_eq!(owner.addr, "127.0.0.1:3002"); + assert_eq!( + owner.incarnation_id.to_string(), + "550e8400-e29b-41d4-a716-446655440000" + ); + let identity = NodeIdentity::new(owner.addr.clone()); + assert_ne!(NodeIdentity::new(owner.addr), identity); +} + +#[test] +fn test_head_v1_unknown_fields() { + let mut value: serde_json::Value = serde_json::from_str(OWNED).unwrap(); + value["extra"] = true.into(); + value["owner"]["extra"] = 42.into(); + assert_eq!( + AuthorityHead::decode(&serde_json::to_vec(&value).unwrap()).unwrap(), + AuthorityHead::decode(OWNED.as_bytes()).unwrap() + ); +} + +#[test] +fn test_head_required_owner() { + assert!(AuthorityHead::decode(INITIAL.as_bytes()).is_ok()); + let mut value: serde_json::Value = serde_json::from_str(INITIAL).unwrap(); + value.as_object_mut().unwrap().remove("owner"); + assert!(AuthorityHead::decode(&serde_json::to_vec(&value).unwrap()).is_err()); +} + +#[test] +fn test_head_invalid_fields_and_version() { + let value: serde_json::Value = serde_json::from_str(OWNED).unwrap(); + for field in [ + "format_version", + "owner", + "epoch", + "lease_deadline_ms", + "write_seq", + ] { + let mut missing = value.clone(); + missing.as_object_mut().unwrap().remove(field); + assert!(AuthorityHead::decode(&serde_json::to_vec(&missing).unwrap()).is_err()); + let mut wrong = value.clone(); + wrong[field] = true.into(); + assert!(AuthorityHead::decode(&serde_json::to_vec(&wrong).unwrap()).is_err()); + } + for field in ["addr", "incarnation_id"] { + let mut missing = value.clone(); + missing["owner"].as_object_mut().unwrap().remove(field); + assert!(AuthorityHead::decode(&serde_json::to_vec(&missing).unwrap()).is_err()); + } + let mut invalid = value.clone(); + invalid["owner"]["incarnation_id"] = "invalid".into(); + assert!(AuthorityHead::decode(&serde_json::to_vec(&invalid).unwrap()).is_err()); + invalid = value; + invalid["format_version"] = 2.into(); + assert!(AuthorityHead::decode(&serde_json::to_vec(&invalid).unwrap()).is_err()); + let mut head = AuthorityHead::initial(); + head.format_version = 2; + assert!(head.encode().is_err()); + assert!(AuthorityHead::decode(b"{").is_err()); +} + +#[test] +fn test_head_counter_overflow() { + let head = AuthorityHead::initial(); + let next = head + .clone() + .with_next_epoch() + .unwrap() + .with_next_write_seq() + .unwrap(); + assert_eq!((head.epoch(), head.write_seq()), (0, 0)); + assert_eq!((next.epoch(), next.write_seq()), (1, 1)); + for field in ["epoch", "write_seq"] { + let mut value = serde_json::to_value(&head).unwrap(); + value[field] = u64::MAX.into(); + let max = AuthorityHead::decode(&serde_json::to_vec(&value).unwrap()).unwrap(); + let error = if field == "epoch" { + max.clone().with_next_epoch().unwrap_err() + } else { + max.clone().with_next_write_seq().unwrap_err() + }; + assert_eq!(error.status_code(), StatusCode::IllegalState); + assert_eq!(serde_json::to_value(&max).unwrap()[field], u64::MAX); + } +} + +#[test] +fn test_authority_error_status_codes() { + let mut head = AuthorityHead::initial(); + head.format_version = 2; + assert_eq!( + head.encode().unwrap_err().status_code(), + StatusCode::IllegalState + ); + assert_eq!( + AuthorityHead::decode(b"{").unwrap_err().status_code(), + StatusCode::IllegalState + ); + assert_eq!( + crate::error::AuthorityProbeSnafu { + reason: "ignored condition" + } + .build() + .status_code(), + StatusCode::Unsupported + ); + assert_eq!( + crate::error::AuthorityMetadataSnafu { + reason: "missing timestamp" + } + .build() + .status_code(), + StatusCode::StorageUnavailable + ); + assert_eq!( + crate::error::AuthorityCapabilitySnafu { + scheme: "gcs", + reason: "pending qualification" + } + .build() + .status_code(), + StatusCode::Unsupported + ); +} + +#[tokio::test] +async fn test_head_decode_error_context() { + let backend = Backend::default(); + let store = store(&backend); + store.create_initial_head().await.unwrap(); + for invalid in [b"{".as_slice(), br#"{"format_version":1}"#.as_slice()] { + { + let mut data = backend.data.lock().unwrap(); + let (body, metadata) = data.objects.values_mut().next().unwrap(); + *body = invalid.to_vec(); + let mut builder = metadata.clone().into_builder(); + builder.set_file(invalid.len() as u64); + *metadata = builder.build(); + } + let error = store.read_head().await.unwrap_err(); + assert_eq!(error.status_code(), StatusCode::IllegalState); + assert!(error.to_string().contains("cluster/authority/head.json")); + let mut source = std::error::Error::source(&error); + let mut found = false; + while let Some(cause) = source { + if let Some(json) = cause.downcast_ref::() { + assert!(json.line() > 0); + assert!(json.column() > 0); + found = true; + } + source = cause.source(); + } + assert!(found, "serde_json error source must be retained"); + } +} + +#[test] +fn test_head_prefix_normalization() { + let backend = Backend::default(); + for (prefix, head, probes) in [ + ( + "///cluster//nested/", + "/cluster/nested/authority/head.json", + "/cluster/nested/probes/", + ), + ("", "/authority/head.json", "/probes/"), + ] { + let store = HeadStore::new_for_test( + ObjectStore::from_parts(OperationContext::default(), Arc::new(backend.clone())), + prefix, + ); + assert_eq!(store.head_path, head); + assert_eq!(store.probe_prefix, probes); + } +} + +#[test] +fn test_backend_admission_diagnostics() { + for (scheme, text) in [ + ("gcs", "generation"), + ("oss", "PutObject"), + ("fs", "atomic"), + ("memory", "atomic"), + ] { + let backend = Backend { + scheme, + ..Default::default() + }; + let error = store(&backend).check_capabilities().unwrap_err(); + match error { + crate::error::Error::AuthorityCapability { + scheme: actual, + reason, + .. + } => { + assert_eq!(actual, scheme); + assert!(reason.contains(text), "{reason}"); + } + other => panic!("unexpected error: {other:?}"), + } + } +} + +#[tokio::test] +async fn test_head_write_success_does_not_require_readback() { + let backend = Backend::default(); + let store = store(&backend); + backend.data.lock().unwrap().missing_metadata = true; + store.create_initial_head().await.unwrap(); + assert!(store.read_head().await.is_err()); + backend.data.lock().unwrap().missing_metadata = false; + let expected = store.read_head().await.unwrap(); + backend.data.lock().unwrap().missing_metadata = true; + store + .replace_head( + &expected, + &expected.head().clone().with_next_write_seq().unwrap(), + ) + .await + .unwrap(); + assert!(store.read_head().await.is_err()); +} diff --git a/src/common/meta/src/error.rs b/src/common/meta/src/error.rs index f5ef827f311..2befbc3520c 100644 --- a/src/common/meta/src/error.rs +++ b/src/common/meta/src/error.rs @@ -1066,6 +1066,89 @@ pub enum Error { reason: String, }, + #[snafu(display("Failed to {} Authority Head JSON", operation))] + AuthorityFormat { + operation: &'static str, + #[snafu(source)] + error: serde_json::Error, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Failed to decode Authority Head at {}", path))] + AuthorityReadHead { + path: String, + source: BoxedError, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Unsupported Authority Head format version: {}", version))] + AuthorityVersion { + version: u32, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority Head counter overflow: {}", counter))] + AuthorityOverflow { + counter: &'static str, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority Head is missing at {}; operator recovery is required", path))] + AuthorityMissing { + path: String, + #[snafu(source)] + error: object_store::Error, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority Head metadata is unusable: {}", reason))] + AuthorityMetadata { + reason: &'static str, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display( + "Object store {} is not admitted for Authority Head: {}", + scheme, + reason + ))] + AuthorityCapability { + scheme: &'static str, + reason: &'static str, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority storage probe failed: {}", reason))] + AuthorityProbe { + reason: &'static str, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Authority storage request failed: {}", operation))] + AuthorityStorage { + operation: &'static str, + #[snafu(source)] + error: object_store::Error, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("Failed to open Authority storage"))] + AuthorityOpen { + #[snafu(source)] + error: object_store::error::Error, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Failed to write object, file path: {}", file_path))] WriteObject { #[snafu(implicit)] @@ -1243,6 +1326,15 @@ impl ErrorExt for Error { | ElectionLeaderLeaseExpired { .. } | ElectionLeaderLeaseChanged { .. } => StatusCode::Internal, + AuthorityFormat { .. } | AuthorityVersion { .. } | AuthorityOverflow { .. } => { + StatusCode::IllegalState + } + AuthorityReadHead { source, .. } => source.status_code(), + AuthorityCapability { .. } | AuthorityProbe { .. } => StatusCode::Unsupported, + AuthorityMissing { .. } + | AuthorityMetadata { .. } + | AuthorityStorage { .. } + | AuthorityOpen { .. } => StatusCode::StorageUnavailable, NoLeader { .. } => StatusCode::TableUnavailable, ValueNotExist { .. } | ProcedurePoisonConflict { .. } @@ -1459,6 +1551,16 @@ impl ErrorExt for Error { } impl Error { + /// Returns the original Authority request error without inviting write replay. + pub fn authority_storage_error(&self) -> Option<&object_store::Error> { + match self { + Self::AuthorityStorage { error, .. } | Self::AuthorityMissing { error, .. } => { + Some(error) + } + _ => None, + } + } + #[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))] /// Check if the error is a serialization error. pub fn is_serialization_error(&self) -> bool { diff --git a/src/common/meta/src/metrics.rs b/src/common/meta/src/metrics.rs index a977c3ed1c5..f989d9f09ec 100644 --- a/src/common/meta/src/metrics.rs +++ b/src/common/meta/src/metrics.rs @@ -23,6 +23,9 @@ pub const STATS_TYPE_NO_REGION_METADATA: &str = "no_region_metadata"; pub const STATS_TYPE_REGION_NOT_OPEN: &str = "region_not_open"; lazy_static! { + pub static ref METRIC_AUTHORITY_STORAGE_EVENTS: IntCounterVec = register_int_counter_vec!( + "greptime_meta_authority_storage_events", "Authority storage failures and conflicts", &["outcome"] + ).unwrap(); pub static ref METRIC_META_TXN_REQUEST: HistogramVec = register_histogram_vec!( "greptime_meta_txn_request", "meta txn request", diff --git a/src/object-store/src/layers/mock.rs b/src/object-store/src/layers/mock.rs index 3f8f8904a66..16a8ffe1bb9 100644 --- a/src/object-store/src/layers/mock.rs +++ b/src/object-store/src/layers/mock.rs @@ -20,9 +20,13 @@ use std::sync::{Arc, Mutex}; use derive_builder::Builder; pub use oio::*; pub use opendal::raw::{ - Layer, OpCopy, OpDelete, OpList, OpRead, OpWrite, RpRead, Service, Servicer, oio, + Layer, OpCopy, OpCreateDir, OpDelete, OpList, OpPresign, OpRead, OpRename, OpStat, OpWrite, + RpCreateDir, RpPresign, RpRead, RpRename, RpStat, Service, Servicer, Timestamp, oio, +}; +pub use opendal::{ + Buffer, BytesRange, Capability, Error, ErrorKind, Metadata, MetadataBuilder, OperationContext, + Result, }; -pub use opendal::{Buffer, BytesRange, Error, ErrorKind, Metadata, OperationContext, Result}; pub type MockWriterFactory = Arc oio::Writer + Send + Sync>; pub type MockReaderFactory = Arc oio::Reader + Send + Sync>; diff --git a/src/object-store/src/lib.rs b/src/object-store/src/lib.rs index e1c421797da..67588538054 100644 --- a/src/object-store/src/lib.rs +++ b/src/object-store/src/lib.rs @@ -15,8 +15,8 @@ pub use opendal::raw::{Service, ServiceInfo, Servicer}; pub use opendal::{ Buffer, Builder as ObjectStoreBuilder, Entry, EntryMode, Error, ErrorKind, FuturesAsyncReader, - FuturesAsyncWriter, HttpTransporter, Lister, OperationContext, Operator as ObjectStore, Reader, - Result, Writer, services, + FuturesAsyncWriter, HttpTransporter, Lister, Metadata, OperationContext, + Operator as ObjectStore, Reader, Result, Writer, services, }; pub mod config; diff --git a/tests-integration/tests/main.rs b/tests-integration/tests/main.rs index 12d8dddbb81..cd9088637ee 100644 --- a/tests-integration/tests/main.rs +++ b/tests-integration/tests/main.rs @@ -42,6 +42,7 @@ mod repartition_expr_version; mod export_logical_tables; mod mysql; mod native_prefix; +mod object_store_authority; mod object_store_wal; mod reconciliation_event; mod view_ddl_event; diff --git a/tests-integration/tests/object_store_authority.rs b/tests-integration/tests/object_store_authority.rs new file mode 100644 index 00000000000..5e06897c66e --- /dev/null +++ b/tests-integration/tests/object_store_authority.rs @@ -0,0 +1,91 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use common_meta::election::object_store::{AuthorityHead, HeadStore}; +use object_store::ErrorKind; +use tests_integration::test_util::{StorageType, get_test_store_config}; + +/// Requires an explicitly configured S3-compatible endpoint (MinIO for PR1 qualification). +#[tokio::test] +async fn test_minio_head_storage() { + if !StorageType::S3.test_on() { + common_telemetry::init_default_ut_logging(); + common_telemetry::warn!( + "NOT RUN: Authority storage qualification requires configured S3/MinIO" + ); + return; + } + for name in [ + "GT_S3_BUCKET", + "GT_S3_ACCESS_KEY_ID", + "GT_S3_ACCESS_KEY", + "GT_S3_REGION", + ] { + assert!( + std::env::var_os(name).is_some(), + "Missing {name}; this test requires real storage" + ); + } + let (config, _guard) = get_test_store_config(&StorageType::S3); + let store = HeadStore::open(&config, "", "authority-test") + .await + .unwrap(); + assert_eq!( + store + .read_head() + .await + .unwrap_err() + .authority_storage_error() + .unwrap() + .kind(), + ErrorKind::NotFound + ); + store.create_initial_head().await.unwrap(); + let initial = store.read_head().await.unwrap(); + assert_eq!(initial.head(), &AuthorityHead::initial()); + assert!(initial.metadata().last_modified().is_some()); + assert!(initial.metadata().etag().unwrap().starts_with('"')); + let e = store.create_initial_head().await.unwrap_err(); + assert!(matches!( + e.authority_storage_error().unwrap().kind(), + ErrorKind::ConditionNotMatch | ErrorKind::AlreadyExists + )); + let next = initial.head().clone().with_next_write_seq().unwrap(); + store.replace_head(&initial, &next).await.unwrap(); + let current = store.read_head().await.unwrap(); + assert_eq!(current.head(), &next); + assert!(current.metadata().last_modified().is_some()); + assert!( + !store + .same_version(initial.metadata(), current.metadata()) + .unwrap() + ); + assert_eq!( + store + .replace_head(&initial, &next) + .await + .unwrap_err() + .authority_storage_error() + .unwrap() + .kind(), + ErrorKind::ConditionNotMatch + ); + let after = store.read_head().await.unwrap(); + assert_eq!(after.head(), &next); + assert!( + store + .same_version(after.metadata(), current.metadata()) + .unwrap() + ); +}