mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
feat(meta): add object-store authority state machine and single writer (#10588)
* feat: add object-store authority state machine and single writer Signed-off-by: hahaha <a310608318@gmail.com> * fix: validate conditional resignations and retry renewal reads Signed-off-by: hahaha <a310608318@gmail.com> * refactor: clarify object-store authority naming Signed-off-by: hahaha <a310608318@gmail.com> --------- Signed-off-by: hahaha <a310608318@gmail.com>
This commit is contained in:
@@ -106,3 +106,4 @@ common-test-util.workspace = true
|
||||
common-wal = { workspace = true, features = ["testing"] }
|
||||
datatypes.workspace = true
|
||||
object-store = { workspace = true, features = ["testing"] }
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
@@ -12,13 +12,18 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Authority Head v1 codec and non-retrying conditional object storage.
|
||||
//! Object-store Authority election, Head v1 codec and conditional storage.
|
||||
|
||||
mod authority;
|
||||
mod head;
|
||||
mod probe;
|
||||
mod store;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use authority::{
|
||||
Authority, AuthorityMutation, AuthorityPrecondition, AuthorityStatus, FencingToken,
|
||||
TakeoverOutcome,
|
||||
};
|
||||
pub use head::{AuthorityHead, HEAD_FORMAT_VERSION, NodeIdentity};
|
||||
pub use store::{AuthorityState, HeadStore};
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
// 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.
|
||||
|
||||
//! Object-store Authority with one writer per node and monotonic local leases.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod writer;
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Utc;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{Instant, sleep_until};
|
||||
|
||||
use crate::election::object_store::authority::writer::{Request, Resignation, Writer};
|
||||
use crate::election::object_store::{AuthorityHead, AuthorityState, HeadStore, NodeIdentity};
|
||||
use crate::error::{self, Error, Result};
|
||||
|
||||
const LEASE: Duration = Duration::from_secs(10);
|
||||
const RENEW_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const CLOCK_GUARD: Duration = Duration::from_secs(2);
|
||||
const GET_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
const QUEUE_CAPACITY: usize = 32;
|
||||
|
||||
/// A token authorizes mutations only in its original local term.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FencingToken {
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
impl FencingToken {
|
||||
/// The logical epoch won by the takeover.
|
||||
pub fn epoch(&self) -> u64 {
|
||||
self.epoch
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of one takeover attempt.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum TakeoverOutcome {
|
||||
/// The Head PUT applied and the node can lead in this term.
|
||||
Acquired(FencingToken),
|
||||
/// The Head PUT applied after local eligibility was lost.
|
||||
AppliedButInactive,
|
||||
/// The observed Head still has a live owner.
|
||||
NotEligible,
|
||||
}
|
||||
|
||||
/// The local lifecycle of the Authority writer.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AuthorityStatus {
|
||||
/// Has no active local term and can attempt takeover.
|
||||
#[default]
|
||||
Follower,
|
||||
/// Holds a local term that can admit writes before its deadline.
|
||||
Leader { epoch: u64, deadline: Instant },
|
||||
/// Stops admitting new writes for the term while resignation is resolved.
|
||||
Resigning { epoch: u64, deadline: Instant },
|
||||
/// The official Head is missing and requires operator recovery.
|
||||
RecoveryRequired,
|
||||
/// Rejects new operations after shutdown begins.
|
||||
Closed,
|
||||
}
|
||||
|
||||
impl AuthorityStatus {
|
||||
fn term(self) -> Option<(u64, Instant)> {
|
||||
match self {
|
||||
Self::Leader { epoch, deadline } | Self::Resigning { epoch, deadline } => {
|
||||
Some((epoch, deadline))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional condition on the Head for a fenced mutation.
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub enum AuthorityPrecondition {
|
||||
/// Accepts any current Head write sequence.
|
||||
#[default]
|
||||
Any,
|
||||
/// Requires an exact match with the current Head write sequence.
|
||||
WriteSeq(u64),
|
||||
}
|
||||
|
||||
impl AuthorityPrecondition {
|
||||
fn check(self, head: &AuthorityHead) -> Result<()> {
|
||||
let actual = head.write_seq();
|
||||
if let Self::WriteSeq(expected) = self
|
||||
&& actual != expected
|
||||
{
|
||||
return error::AuthorityWriteSeqMismatchSnafu { expected, actual }.fail();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fenced Head updates supported by Head v1.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum AuthorityMutation {
|
||||
/// Renews the current lease while preserving the owner and epoch.
|
||||
Renew,
|
||||
/// Clears the current owner while preserving the epoch.
|
||||
Resign,
|
||||
}
|
||||
|
||||
/// Node-local Authority. Share one instance and its writer across callers.
|
||||
pub struct Authority {
|
||||
inner: Arc<Inner>,
|
||||
request_tx: mpsc::Sender<Request>,
|
||||
writer_task: tokio::sync::Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
impl Authority {
|
||||
/// Starts the writer with the process identity generated once at startup.
|
||||
pub fn new(store: Arc<HeadStore>, identity: NodeIdentity) -> Self {
|
||||
Self::start(
|
||||
store,
|
||||
identity,
|
||||
|| {
|
||||
let now = Utc::now();
|
||||
i128::from(now.timestamp()) * 1_000_000_000
|
||||
+ i128::from(now.timestamp_subsec_nanos())
|
||||
},
|
||||
QUEUE_CAPACITY,
|
||||
common_runtime::spawn_global,
|
||||
)
|
||||
}
|
||||
|
||||
fn start(
|
||||
store: Arc<HeadStore>,
|
||||
identity: NodeIdentity,
|
||||
wall_now_ns: impl Fn() -> i128 + Send + Sync + 'static,
|
||||
capacity: usize,
|
||||
spawn: impl FnOnce(Pin<Box<dyn Future<Output = ()> + Send>>) -> JoinHandle<()>,
|
||||
) -> Self {
|
||||
let (status_tx, _) = watch::channel(AuthorityStatus::Follower);
|
||||
let inner = Arc::new(Inner {
|
||||
store,
|
||||
identity,
|
||||
wall_now_ns: Box::new(wall_now_ns),
|
||||
control: Mutex::default(),
|
||||
status_tx,
|
||||
});
|
||||
let (request_tx, request_rx) = mpsc::channel(capacity);
|
||||
let writer_task = spawn(Box::pin(Writer::new(inner.clone(), request_rx).run()));
|
||||
Self {
|
||||
inner,
|
||||
request_tx,
|
||||
writer_task: tokio::sync::Mutex::new(Some(writer_task)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a coherent Head and its complete metadata in a single storage operation.
|
||||
pub async fn head(&self) -> Result<AuthorityState> {
|
||||
self.inner.read(Admission::Read, None).await
|
||||
}
|
||||
|
||||
/// Returns the local state, accounting for any elapsed monotonic deadline.
|
||||
pub fn status(&self) -> AuthorityStatus {
|
||||
self.inner.update(|control, _| control.status)
|
||||
}
|
||||
|
||||
/// Attempts a single conditional takeover.
|
||||
pub async fn takeover(&self) -> Result<TakeoverOutcome> {
|
||||
let (response, result) = oneshot::channel();
|
||||
self.submit(Admission::Takeover, Request::Takeover(response))
|
||||
.await?;
|
||||
result.await.unwrap_or_else(|_| Err(closed()))
|
||||
}
|
||||
|
||||
/// Requests a fenced Head update. Success confirms its PUT.
|
||||
pub async fn mutate(
|
||||
&self,
|
||||
token: &FencingToken,
|
||||
precondition: AuthorityPrecondition,
|
||||
mutation: AuthorityMutation,
|
||||
) -> Result<()> {
|
||||
let epoch = token.epoch;
|
||||
let (response, result) = oneshot::channel();
|
||||
match (mutation, precondition) {
|
||||
(AuthorityMutation::Resign, AuthorityPrecondition::Any) => {
|
||||
self.inner.update(|control, _| {
|
||||
Admission::Renew(epoch).check(control.status)?;
|
||||
let AuthorityStatus::Leader { deadline, .. } = control.status else {
|
||||
return Err(rejected("term is inactive"));
|
||||
};
|
||||
control.status = AuthorityStatus::Resigning { epoch, deadline };
|
||||
control.resignation = Some(Resignation { epoch, response });
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
(mutation, precondition) => {
|
||||
let admission = match mutation {
|
||||
AuthorityMutation::Renew => Admission::Renew(epoch),
|
||||
AuthorityMutation::Resign => Admission::ConditionalResign(epoch),
|
||||
};
|
||||
self.submit(
|
||||
admission,
|
||||
Request::Mutate {
|
||||
epoch,
|
||||
mutation,
|
||||
precondition,
|
||||
response,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
result.await.unwrap_or_else(|_| Err(closed()))
|
||||
}
|
||||
|
||||
/// Stops term admission and attempts to clear the owner before the frozen deadline.
|
||||
pub async fn resign(&self, token: &FencingToken) -> Result<()> {
|
||||
self.mutate(token, AuthorityPrecondition::Any, AuthorityMutation::Resign)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stops the local term, cancels I/O waits and joins the writer.
|
||||
pub async fn shutdown(&self) {
|
||||
self.inner.close();
|
||||
let mut writer_task = self.writer_task.lock().await;
|
||||
if let Some(task) = writer_task.as_mut()
|
||||
&& let Err(error) = task.await
|
||||
{
|
||||
common_telemetry::warn!("Authority writer exited with error: {error}");
|
||||
}
|
||||
writer_task.take();
|
||||
}
|
||||
|
||||
async fn submit(&self, admission: Admission, request: Request) -> Result<()> {
|
||||
admission.check(self.status())?;
|
||||
tokio::select! {
|
||||
permit = self.request_tx.reserve() => {
|
||||
let permit = permit.map_err(|_| closed())?;
|
||||
self.inner.update(|control, _| {
|
||||
admission.check(control.status)?;
|
||||
permit.send(request);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
_ = self.inner.wait_until(|status| admission.check(status).is_err()) => {
|
||||
admission.check(self.status()).and_then(|()| Err(rejected("admission changed")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Authority {
|
||||
fn drop(&mut self) {
|
||||
self.inner.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Admission {
|
||||
Read,
|
||||
Takeover,
|
||||
Renew(u64),
|
||||
ConditionalResign(u64),
|
||||
Resign(u64),
|
||||
}
|
||||
|
||||
impl Admission {
|
||||
fn check(self, status: AuthorityStatus) -> Result<()> {
|
||||
match (self, status) {
|
||||
(_, AuthorityStatus::Closed) => Err(closed()),
|
||||
(_, AuthorityStatus::RecoveryRequired) => error::AuthorityRecoveryRequiredSnafu.fail(),
|
||||
(Self::Read, _) | (Self::Takeover, AuthorityStatus::Follower) => Ok(()),
|
||||
(
|
||||
Self::Renew(expected) | Self::ConditionalResign(expected),
|
||||
AuthorityStatus::Leader { epoch, .. },
|
||||
)
|
||||
| (Self::Resign(expected), AuthorityStatus::Resigning { epoch, .. })
|
||||
if expected == epoch =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(rejected(
|
||||
"local state or fencing token does not authorize the operation",
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Control {
|
||||
status: AuthorityStatus,
|
||||
resignation: Option<Resignation>,
|
||||
snapshot: Option<SnapshotFloor>,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
fn expire(&mut self, now: Instant) {
|
||||
if self
|
||||
.status
|
||||
.term()
|
||||
.is_some_and(|(_, deadline)| now >= deadline)
|
||||
{
|
||||
self.status = AuthorityStatus::Follower;
|
||||
}
|
||||
}
|
||||
|
||||
fn retire(&mut self, epoch: u64) {
|
||||
if self
|
||||
.status
|
||||
.term()
|
||||
.is_some_and(|(current, _)| current == epoch)
|
||||
{
|
||||
self.status = AuthorityStatus::Follower;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A confirmed PUT no longer has usable Metadata. Its base is retained solely
|
||||
/// to rule out a stale conditional version when the next snapshot arrives.
|
||||
enum SnapshotFloor {
|
||||
Observed(AuthorityState),
|
||||
Applied {
|
||||
head: AuthorityHead,
|
||||
base: AuthorityState,
|
||||
},
|
||||
}
|
||||
|
||||
impl SnapshotFloor {
|
||||
fn head(&self) -> &AuthorityHead {
|
||||
match self {
|
||||
Self::Observed(state) => state.head(),
|
||||
Self::Applied { head, .. } => head,
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(&self, store: &HeadStore, state: &AuthorityState) -> Result<()> {
|
||||
let head = state.head();
|
||||
let floor = self.head();
|
||||
if head.epoch() < floor.epoch()
|
||||
|| head.write_seq() < floor.write_seq()
|
||||
|| (head.write_seq() == floor.write_seq() && head != floor)
|
||||
{
|
||||
return Err(invalid_snapshot(
|
||||
"Head moved behind an observed or applied write",
|
||||
));
|
||||
}
|
||||
let (metadata, expect_same_version) = match self {
|
||||
Self::Observed(previous) => {
|
||||
(previous.metadata(), head.write_seq() == floor.write_seq())
|
||||
}
|
||||
Self::Applied { base, .. } => (base.metadata(), false),
|
||||
};
|
||||
if store.same_version(metadata, state.metadata())? != expect_same_version {
|
||||
return Err(invalid_snapshot(
|
||||
"conditional version disagrees with Head write sequence",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
store: Arc<HeadStore>,
|
||||
identity: NodeIdentity,
|
||||
wall_now_ns: Box<dyn Fn() -> i128 + Send + Sync>,
|
||||
control: Mutex<Control>,
|
||||
status_tx: watch::Sender<AuthorityStatus>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
/// Runs the short state transitions and PUT authorization under the same lock.
|
||||
fn update<T>(&self, f: impl FnOnce(&mut Control, Instant) -> T) -> T {
|
||||
let mut control = self.control.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let before = control.status;
|
||||
let now = Instant::now();
|
||||
control.expire(now);
|
||||
let result = f(&mut control, now);
|
||||
if control.status != before {
|
||||
self.status_tx.send_replace(control.status);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn wait_until(&self, predicate: impl Fn(AuthorityStatus) -> bool) {
|
||||
let mut status = self.status_tx.subscribe();
|
||||
let _ = status.wait_for(|status| predicate(*status)).await;
|
||||
}
|
||||
|
||||
fn close(&self) {
|
||||
self.update(|control, _| control.status = AuthorityStatus::Closed);
|
||||
}
|
||||
|
||||
async fn read(
|
||||
&self,
|
||||
admission: Admission,
|
||||
deadline: Option<Instant>,
|
||||
) -> Result<AuthorityState> {
|
||||
self.update(|control, _| admission.check(control.status))?;
|
||||
let now = Instant::now();
|
||||
let stop = deadline.map_or(now + GET_TIMEOUT, |end| end.min(now + GET_TIMEOUT));
|
||||
if now >= stop {
|
||||
return Err(timeout("read"));
|
||||
}
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = self.wait_until(|status| admission.check(status).is_err()) => {
|
||||
return self.update(|control, _| {
|
||||
admission.check(control.status)?;
|
||||
Err(rejected("read admission changed"))
|
||||
});
|
||||
}
|
||||
result = self.store.read_head() => result,
|
||||
_ = sleep_until(stop) => return Err(timeout("read")),
|
||||
};
|
||||
if matches!(result, Err(Error::AuthorityMissing { .. })) {
|
||||
self.update(|control, _| {
|
||||
if control.status != AuthorityStatus::Closed {
|
||||
control.status = AuthorityStatus::RecoveryRequired;
|
||||
}
|
||||
});
|
||||
}
|
||||
let state = result?;
|
||||
if Instant::now() >= stop {
|
||||
return Err(timeout("read"));
|
||||
}
|
||||
self.observe(admission, &state)?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn observe(&self, admission: Admission, state: &AuthorityState) -> Result<()> {
|
||||
self.update(|control, _| {
|
||||
let head = state.head();
|
||||
if let Some(floor) = &control.snapshot {
|
||||
// A concurrent reader can observe a newer Head while this response
|
||||
// is in flight. Historical evidence is usable for readback, but
|
||||
// it cannot replace the floor or supply a new CAS condition.
|
||||
if matches!(admission, Admission::Read)
|
||||
&& head.write_seq() < floor.head().write_seq()
|
||||
&& head.epoch() <= floor.head().epoch()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
floor.validate(&self.store, state)?;
|
||||
}
|
||||
if let Some((epoch, _)) = control.status.term()
|
||||
&& head.epoch() >= epoch
|
||||
&& (head.epoch() != epoch || head.owner.as_ref() != Some(&self.identity))
|
||||
{
|
||||
control.retire(epoch);
|
||||
}
|
||||
control.snapshot = Some(SnapshotFloor::Observed(state.clone()));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn diagnostic_deadline(&self) -> u64 {
|
||||
let ns = (self.wall_now_ns)().saturating_add(LEASE.as_nanos() as i128);
|
||||
u64::try_from(ns / 1_000_000).unwrap_or(if ns < 0 { 0 } else { u64::MAX })
|
||||
}
|
||||
}
|
||||
|
||||
fn closed() -> Error {
|
||||
error::AuthorityClosedSnafu.build()
|
||||
}
|
||||
|
||||
fn rejected(reason: &'static str) -> Error {
|
||||
error::AuthorityRejectedSnafu { reason }.build()
|
||||
}
|
||||
|
||||
fn invalid_snapshot(reason: &'static str) -> Error {
|
||||
error::AuthorityMetadataSnafu { reason }.build()
|
||||
}
|
||||
|
||||
fn timeout(operation: &'static str) -> Error {
|
||||
error::AuthorityTimeoutSnafu { operation }.build()
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,596 @@
|
||||
// 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 std::time::Duration;
|
||||
|
||||
use object_store::ErrorKind;
|
||||
use snafu::{IntoError, OptionExt};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::time::{Instant, sleep_until};
|
||||
|
||||
use crate::election::object_store::authority::{
|
||||
Admission, AuthorityMutation, AuthorityPrecondition, AuthorityStatus, CLOCK_GUARD,
|
||||
FencingToken, Inner, LEASE, RENEW_INTERVAL, SnapshotFloor, TakeoverOutcome, closed, rejected,
|
||||
timeout,
|
||||
};
|
||||
use crate::election::object_store::{AuthorityHead, AuthorityState};
|
||||
use crate::error::{self, Error, Result};
|
||||
|
||||
const PUT_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const READBACK_RESERVE: Duration = Duration::from_secs(1);
|
||||
const INITIAL_BACKOFF: Duration = Duration::from_millis(50);
|
||||
const MAX_BACKOFF: Duration = Duration::from_millis(400);
|
||||
|
||||
pub(crate) enum Request {
|
||||
Takeover(oneshot::Sender<Result<TakeoverOutcome>>),
|
||||
Mutate {
|
||||
epoch: u64,
|
||||
mutation: AuthorityMutation,
|
||||
precondition: AuthorityPrecondition,
|
||||
response: oneshot::Sender<Result<()>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Request {
|
||||
fn reject(self, error: Error) {
|
||||
match self {
|
||||
Self::Takeover(response) => {
|
||||
let _ = response.send(Err(error));
|
||||
}
|
||||
Self::Mutate { response, .. } => {
|
||||
let _ = response.send(Err(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Resignation {
|
||||
pub(crate) epoch: u64,
|
||||
pub(crate) response: oneshot::Sender<Result<()>>,
|
||||
}
|
||||
|
||||
pub(crate) struct Writer {
|
||||
inner: Arc<Inner>,
|
||||
request_rx: mpsc::Receiver<Request>,
|
||||
ambiguous_takeover: Option<AuthorityState>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
pub(crate) fn new(inner: Arc<Inner>, request_rx: mpsc::Receiver<Request>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
request_rx,
|
||||
ambiguous_takeover: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run(mut self) {
|
||||
let mut changes = self.inner.status_tx.subscribe();
|
||||
loop {
|
||||
let (status, resignation) = self
|
||||
.inner
|
||||
.update(|control, _| (control.status, control.resignation.take()));
|
||||
if status == AuthorityStatus::Closed {
|
||||
if let Some(request) = resignation {
|
||||
let _ = request.response.send(Err(closed()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some(request) = resignation {
|
||||
self.drain_resigning(request.epoch);
|
||||
let result = self.resign(request.epoch).await;
|
||||
let _ = request.response.send(result);
|
||||
continue;
|
||||
}
|
||||
let term = match status {
|
||||
AuthorityStatus::Leader { epoch, deadline } => Some((epoch, deadline)),
|
||||
_ => None,
|
||||
};
|
||||
let deadline = term.map_or_else(Instant::now, |(_, deadline)| deadline);
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = changes.changed() => {}
|
||||
_ = sleep_until(deadline), if term.is_some() => {}
|
||||
_ = sleep_until(renew_at(deadline)), if term.is_some() => {
|
||||
if let Some((epoch, _)) = term {
|
||||
self.renew(epoch).await;
|
||||
}
|
||||
}
|
||||
request = self.request_rx.recv() => match request {
|
||||
Some(request) => self.process(request).await,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
self.request_rx.close();
|
||||
self.drain(closed);
|
||||
}
|
||||
|
||||
fn drain_resigning(&mut self, epoch: u64) {
|
||||
// Once the term retires, the FIFO can also contain a new takeover.
|
||||
while let Some(request) = self.inner.update(|control, _| {
|
||||
Admission::Resign(epoch).check(control.status).ok()?;
|
||||
self.request_rx.try_recv().ok()
|
||||
}) {
|
||||
request.reject(rejected("resignation stopped admission before PUT"));
|
||||
}
|
||||
}
|
||||
|
||||
fn drain(&mut self, error: impl Fn() -> Error) {
|
||||
while let Ok(request) = self.request_rx.try_recv() {
|
||||
request.reject(error());
|
||||
}
|
||||
}
|
||||
|
||||
async fn process(&mut self, request: Request) {
|
||||
match request {
|
||||
Request::Takeover(response) => {
|
||||
let _ = response.send(self.takeover().await);
|
||||
}
|
||||
Request::Mutate {
|
||||
epoch,
|
||||
mutation,
|
||||
precondition,
|
||||
response,
|
||||
} => {
|
||||
let result = loop {
|
||||
let put = match mutation {
|
||||
AuthorityMutation::Renew => {
|
||||
self.prepare_renewal(epoch, precondition, false).await
|
||||
}
|
||||
AuthorityMutation::Resign => {
|
||||
self.prepare_term(
|
||||
Admission::ConditionalResign(epoch),
|
||||
precondition,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
match put {
|
||||
Ok(Some(put)) => {
|
||||
if matches!(mutation, AuthorityMutation::Resign) {
|
||||
self.drain_resigning(epoch);
|
||||
}
|
||||
break self.write(&put).await.map(|_| ());
|
||||
}
|
||||
Ok(None) => self.renew(epoch).await,
|
||||
Err(error) => break Err(error),
|
||||
}
|
||||
};
|
||||
let _ = response.send(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn takeover(&mut self) -> Result<TakeoverOutcome> {
|
||||
let base = self.inner.read(Admission::Takeover, None).await?;
|
||||
let ambiguous = if let Some(previous) = &self.ambiguous_takeover {
|
||||
self.inner
|
||||
.store
|
||||
.same_version(previous.metadata(), base.metadata())?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !ambiguous {
|
||||
self.ambiguous_takeover = None;
|
||||
}
|
||||
|
||||
if base.head().owner.is_some() {
|
||||
let modified = base
|
||||
.metadata()
|
||||
.last_modified()
|
||||
.context(error::AuthorityMetadataSnafu {
|
||||
reason: "read returned no last_modified",
|
||||
})?
|
||||
.into_inner()
|
||||
.as_nanosecond();
|
||||
if (self.inner.wall_now_ns)() <= modified + (LEASE + CLOCK_GUARD).as_nanos() as i128 {
|
||||
return Ok(TakeoverOutcome::NotEligible);
|
||||
}
|
||||
}
|
||||
let mut next = base
|
||||
.head()
|
||||
.clone()
|
||||
.with_next_epoch()?
|
||||
.with_next_write_seq()?;
|
||||
next.owner = Some(self.inner.identity.clone());
|
||||
next.lease_deadline_ms = self.inner.diagnostic_deadline();
|
||||
let put = self.inner.update(|control, now| {
|
||||
Admission::Takeover.check(control.status)?;
|
||||
if let Some(floor) = &control.snapshot {
|
||||
floor.validate(&self.inner.store, &base)?;
|
||||
}
|
||||
Ok(Put {
|
||||
admission: Admission::Takeover,
|
||||
base,
|
||||
next,
|
||||
sent_at: now,
|
||||
deadline: now + LEASE,
|
||||
ambiguous,
|
||||
})
|
||||
})?;
|
||||
|
||||
match self.write(&put).await {
|
||||
Ok(true) => Ok(TakeoverOutcome::Acquired(FencingToken {
|
||||
epoch: put.next.epoch(),
|
||||
})),
|
||||
Ok(false) => Ok(TakeoverOutcome::AppliedButInactive),
|
||||
Err(error) => {
|
||||
if matches!(error, Error::AuthorityUnknown { .. }) {
|
||||
let base_unresolved = self.inner.update(|control, _| {
|
||||
control.snapshot.as_ref().is_none_or(|observed| {
|
||||
observed.head().write_seq() <= put.base.head().write_seq()
|
||||
})
|
||||
});
|
||||
self.ambiguous_takeover = base_unresolved.then_some(put.base);
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn renew(&self, epoch: u64) {
|
||||
if let Ok(Some(put)) = self
|
||||
.prepare_renewal(epoch, AuthorityPrecondition::Any, true)
|
||||
.await
|
||||
&& let Err(error) = self.write(&put).await
|
||||
{
|
||||
common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed");
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare_renewal(
|
||||
&self,
|
||||
epoch: u64,
|
||||
precondition: AuthorityPrecondition,
|
||||
scheduled: bool,
|
||||
) -> Result<Option<Put>> {
|
||||
let admission = Admission::Renew(epoch);
|
||||
let result = self.prepare_term(admission, precondition, !scheduled).await;
|
||||
if let Err(error) = &result
|
||||
&& !matches!(error, Error::AuthorityWriteSeqMismatch { .. })
|
||||
{
|
||||
// Resignation or shutdown can take over while the preparation GET is in flight.
|
||||
let retired = self.inner.update(|control, _| {
|
||||
if admission.check(control.status).is_ok() {
|
||||
control.retire(epoch);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
if scheduled && retired {
|
||||
common_telemetry::warn!(error; "Authority renewal of epoch {epoch} failed");
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn resign(&self, epoch: u64) -> Result<()> {
|
||||
let result = match self
|
||||
.prepare_term(Admission::Resign(epoch), AuthorityPrecondition::Any, false)
|
||||
.await
|
||||
{
|
||||
Ok(Some(put)) => self.write(&put).await.map(|_| ()),
|
||||
Ok(None) => Err(rejected("resignation could not be authorized")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
self.inner.update(|control, _| control.retire(epoch));
|
||||
result
|
||||
}
|
||||
|
||||
/// An empty result keeps the FIFO request in hand while we perform a due renewal.
|
||||
async fn prepare_term(
|
||||
&self,
|
||||
admission: Admission,
|
||||
precondition: AuthorityPrecondition,
|
||||
defer_for_renewal: bool,
|
||||
) -> Result<Option<Put>> {
|
||||
let (epoch, deadline) = self.inner.update(|control, _| {
|
||||
admission.check(control.status)?;
|
||||
control
|
||||
.status
|
||||
.term()
|
||||
.ok_or_else(|| rejected("term is inactive"))
|
||||
})?;
|
||||
let read = match admission {
|
||||
Admission::Renew(_) => {
|
||||
self.read_renewal_head(admission, deadline, defer_for_renewal)
|
||||
.await
|
||||
}
|
||||
_ => self.inner.read(admission, Some(deadline)).await,
|
||||
};
|
||||
let base = match read {
|
||||
Ok(base) => base,
|
||||
Err(error) => {
|
||||
let renew_due = defer_for_renewal
|
||||
&& self.inner.update(|control, now| {
|
||||
admission.check(control.status).is_ok() && now >= renew_at(deadline)
|
||||
});
|
||||
return if renew_due { Ok(None) } else { Err(error) };
|
||||
}
|
||||
};
|
||||
let next = base.head().clone().with_next_write_seq().map(|mut next| {
|
||||
if matches!(
|
||||
admission,
|
||||
Admission::Resign(_) | Admission::ConditionalResign(_)
|
||||
) {
|
||||
next.owner = None;
|
||||
next.lease_deadline_ms = 0;
|
||||
} else {
|
||||
next.lease_deadline_ms = self.inner.diagnostic_deadline();
|
||||
}
|
||||
next
|
||||
});
|
||||
self.inner.update(|control, now| {
|
||||
admission.check(control.status)?;
|
||||
if defer_for_renewal && now >= renew_at(deadline) {
|
||||
return Ok(None);
|
||||
}
|
||||
if now + READBACK_RESERVE >= deadline {
|
||||
control.retire(epoch);
|
||||
return Err(timeout("write budget"));
|
||||
}
|
||||
if base.head().epoch() != epoch
|
||||
|| base.head().owner.as_ref() != Some(&self.inner.identity)
|
||||
{
|
||||
return Err(rejected("Head is not owned by this term"));
|
||||
}
|
||||
if let Some(floor) = &control.snapshot {
|
||||
floor.validate(&self.inner.store, &base)?;
|
||||
}
|
||||
precondition.check(base.head())?;
|
||||
let next = next?;
|
||||
let admission = if matches!(admission, Admission::ConditionalResign(_)) {
|
||||
// Close admission and authorize the CAS against this read under one lock.
|
||||
control.status = AuthorityStatus::Resigning { epoch, deadline };
|
||||
Admission::Resign(epoch)
|
||||
} else {
|
||||
admission
|
||||
};
|
||||
Ok(Some(Put {
|
||||
admission,
|
||||
base,
|
||||
next,
|
||||
sent_at: now,
|
||||
deadline,
|
||||
ambiguous: false,
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_renewal_head(
|
||||
&self,
|
||||
admission: Admission,
|
||||
deadline: Instant,
|
||||
defer_for_renewal: bool,
|
||||
) -> Result<AuthorityState> {
|
||||
let prepare_deadline = deadline - READBACK_RESERVE;
|
||||
// A queued renewal yields to the scheduled renewal during read backoff.
|
||||
let retry_until = if defer_for_renewal {
|
||||
prepare_deadline.min(renew_at(deadline))
|
||||
} else {
|
||||
prepare_deadline
|
||||
};
|
||||
let mut backoff = INITIAL_BACKOFF;
|
||||
loop {
|
||||
let error = match self.inner.read(admission, Some(prepare_deadline)).await {
|
||||
Ok(head) => return Ok(head),
|
||||
Err(error) => error,
|
||||
};
|
||||
let retryable = matches!(
|
||||
error,
|
||||
Error::AuthorityTimeout {
|
||||
operation: "read",
|
||||
..
|
||||
}
|
||||
) || error.authority_storage_error().is_some_and(|source| {
|
||||
source.is_temporary()
|
||||
&& !matches!(
|
||||
source.kind(),
|
||||
ErrorKind::PermissionDenied | ErrorKind::NotFound
|
||||
)
|
||||
});
|
||||
let now = Instant::now();
|
||||
if !retryable || now >= retry_until {
|
||||
return Err(error);
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.inner.wait_until(|status| admission.check(status).is_err()) => {}
|
||||
_ = sleep_until((now + backoff).min(retry_until)) => {}
|
||||
}
|
||||
self.inner
|
||||
.update(|control, _| admission.check(control.status))?;
|
||||
if Instant::now() >= retry_until {
|
||||
return Err(error);
|
||||
}
|
||||
backoff = (backoff * 2).min(MAX_BACKOFF);
|
||||
}
|
||||
}
|
||||
|
||||
async fn write(&self, put: &Put) -> Result<bool> {
|
||||
let response = self.send(put).await;
|
||||
match response {
|
||||
PutResponse::Applied => Ok(self.confirm(put, true)),
|
||||
PutResponse::Unsent(error) | PutResponse::Failed(error) => {
|
||||
self.retire(put);
|
||||
Err(error)
|
||||
}
|
||||
PutResponse::Conflict(error) => {
|
||||
self.retire(put);
|
||||
// Re-evaluate the observed version and term without replaying the CAS.
|
||||
let _ = self.inner.read(Admission::Read, Some(put.deadline)).await;
|
||||
Err(error)
|
||||
}
|
||||
PutResponse::Unknown(error) => {
|
||||
self.retire(put);
|
||||
if self.resolve(put).await {
|
||||
Ok(self.confirm(put, false))
|
||||
} else {
|
||||
Err(error::AuthorityUnknownSnafu.into_error(Box::new(error)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(&self, put: &Put) -> PutResponse {
|
||||
let stop = (put.sent_at + PUT_TIMEOUT).min(put.deadline - READBACK_RESERVE);
|
||||
let request = async {
|
||||
if let Err(error) =
|
||||
Admission::Read.check(self.inner.update(|control, _| control.status))
|
||||
{
|
||||
return PutResponse::Unsent(error);
|
||||
}
|
||||
if Instant::now() >= stop {
|
||||
return PutResponse::Unsent(timeout("write budget"));
|
||||
}
|
||||
match self.inner.store.replace_head(&put.base, &put.next).await {
|
||||
Ok(()) => PutResponse::Applied,
|
||||
Err(error) => match error.authority_storage_error() {
|
||||
Some(storage)
|
||||
if matches!(
|
||||
storage.kind(),
|
||||
ErrorKind::ConditionNotMatch
|
||||
| ErrorKind::AlreadyExists
|
||||
| ErrorKind::Conflict
|
||||
| ErrorKind::NotFound
|
||||
) =>
|
||||
{
|
||||
PutResponse::Conflict(error)
|
||||
}
|
||||
Some(storage)
|
||||
if storage.is_temporary() || storage.kind() == ErrorKind::Unexpected =>
|
||||
{
|
||||
PutResponse::Unknown(error)
|
||||
}
|
||||
_ => PutResponse::Failed(error),
|
||||
},
|
||||
}
|
||||
};
|
||||
// A response already available when the task wakes still determines the PUT
|
||||
// result. The state transition separately checks the clock under the lock.
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = request => result,
|
||||
_ = self.inner.wait_until(|status| status == AuthorityStatus::Closed) => PutResponse::Unknown(closed()),
|
||||
_ = sleep_until(stop) => PutResponse::Unknown(timeout("write")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve(&self, put: &Put) -> bool {
|
||||
let mut backoff = INITIAL_BACKOFF;
|
||||
while Instant::now() < put.deadline {
|
||||
match self.inner.read(Admission::Read, Some(put.deadline)).await {
|
||||
Ok(state) => {
|
||||
let advanced = self
|
||||
.inner
|
||||
.store
|
||||
.same_version(put.base.metadata(), state.metadata());
|
||||
if matches!(advanced, Ok(false))
|
||||
&& state.head().write_seq() >= put.next.write_seq()
|
||||
{
|
||||
// A later or competing write may have overwritten our evidence.
|
||||
// With an older ambiguous takeover, even an exact match is inconclusive.
|
||||
return !put.ambiguous && state.head() == &put.next;
|
||||
}
|
||||
}
|
||||
Err(
|
||||
Error::AuthorityClosed { .. }
|
||||
| Error::AuthorityMissing { .. }
|
||||
| Error::AuthorityRecoveryRequired { .. },
|
||||
) => return false,
|
||||
Err(_) => {}
|
||||
}
|
||||
let retry_at = (Instant::now() + backoff).min(put.deadline);
|
||||
tokio::select! {
|
||||
_ = self.inner.wait_until(|status| Admission::Read.check(status).is_err()) => return false,
|
||||
_ = sleep_until(retry_at) => {}
|
||||
}
|
||||
backoff = (backoff * 2).min(MAX_BACKOFF);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn confirm(&self, put: &Put, direct: bool) -> bool {
|
||||
self.inner.update(|control, now| {
|
||||
let current = control.snapshot.as_ref().map(SnapshotFloor::head);
|
||||
let still_current = current
|
||||
.is_none_or(|head| head.write_seq() < put.next.write_seq() || head == &put.next);
|
||||
if current.is_none_or(|head| head.write_seq() < put.next.write_seq()) {
|
||||
control.snapshot = Some(SnapshotFloor::Applied {
|
||||
head: put.next.clone(),
|
||||
base: put.base.clone(),
|
||||
});
|
||||
}
|
||||
let epoch = put.next.epoch();
|
||||
if matches!(put.admission, Admission::Resign(_)) {
|
||||
control.retire(epoch);
|
||||
return false;
|
||||
}
|
||||
if still_current && now < put.deadline {
|
||||
match put.admission {
|
||||
Admission::Takeover if control.status == AuthorityStatus::Follower => {
|
||||
control.status = AuthorityStatus::Leader {
|
||||
epoch,
|
||||
deadline: put.deadline,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
Admission::Renew(_)
|
||||
if direct && Admission::Renew(epoch).check(control.status).is_ok() =>
|
||||
{
|
||||
control.status = AuthorityStatus::Leader {
|
||||
epoch,
|
||||
deadline: put.sent_at + LEASE,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
fn retire(&self, put: &Put) {
|
||||
if let Admission::Renew(epoch) | Admission::Resign(epoch) = put.admission {
|
||||
self.inner.update(|control, _| control.retire(epoch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn renew_at(deadline: Instant) -> Instant {
|
||||
deadline - (LEASE - RENEW_INTERVAL)
|
||||
}
|
||||
|
||||
/// The writer obtains this single-use authorization under the state lock and
|
||||
/// owns it until the PUT outcome is classified. No other code sends a Head PUT.
|
||||
struct Put {
|
||||
admission: Admission,
|
||||
base: AuthorityState,
|
||||
next: AuthorityHead,
|
||||
sent_at: Instant,
|
||||
deadline: Instant,
|
||||
ambiguous: bool,
|
||||
}
|
||||
|
||||
enum PutResponse {
|
||||
Applied,
|
||||
Unsent(Error),
|
||||
Conflict(Error),
|
||||
Failed(Error),
|
||||
Unknown(Error),
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use common_error::ext::{ErrorExt, RetryHint};
|
||||
@@ -24,14 +24,20 @@ use object_store::layers::mock::{
|
||||
Result, RpCreateDir, RpPresign, RpRead, RpRename, RpStat, Service, Timestamp, oio,
|
||||
};
|
||||
use object_store::{ObjectStore, ServiceInfo};
|
||||
use tokio::sync::{Notify, oneshot};
|
||||
use tokio::time::Instant;
|
||||
|
||||
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<String, (Vec<u8>, Metadata)>,
|
||||
pub(crate) struct Data {
|
||||
pub(crate) calls: Vec<Call>,
|
||||
read_actions: VecDeque<ReadAction>,
|
||||
write_actions: VecDeque<WriteAction>,
|
||||
next_write_error: Option<Error>,
|
||||
pub(crate) objects: HashMap<String, (Vec<u8>, Metadata)>,
|
||||
seq: u64,
|
||||
writes: usize,
|
||||
ignore_conditions: bool,
|
||||
@@ -58,8 +64,8 @@ enum ConflictMutation {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Backend {
|
||||
data: Arc<Mutex<Data>>,
|
||||
pub(crate) struct Backend {
|
||||
pub(crate) data: Arc<Mutex<Data>>,
|
||||
scheme: &'static str,
|
||||
capability: Capability,
|
||||
}
|
||||
@@ -82,6 +88,116 @@ impl Default for Backend {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Call {
|
||||
Get(Instant),
|
||||
Put(AuthorityHead),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ReadAction {
|
||||
Pause(DeferredRead),
|
||||
PauseResponse(DeferredRead),
|
||||
Fail(Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct DeferredRead {
|
||||
pub(crate) arrived: Arc<Notify>,
|
||||
pub(crate) release: Arc<Notify>,
|
||||
}
|
||||
|
||||
type WriteReceipt = (Result<Metadata>, oneshot::Sender<Result<Metadata>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WriteAction {
|
||||
arrived: Arc<Notify>,
|
||||
commit: oneshot::Receiver<bool>,
|
||||
committed: oneshot::Sender<WriteReceipt>,
|
||||
}
|
||||
|
||||
pub(crate) struct DeferredWrite {
|
||||
pub(crate) arrived: Arc<Notify>,
|
||||
commit: Option<oneshot::Sender<bool>>,
|
||||
committed: oneshot::Receiver<WriteReceipt>,
|
||||
receipt: Option<WriteReceipt>,
|
||||
}
|
||||
|
||||
impl DeferredWrite {
|
||||
pub(crate) async fn commit(&mut self, apply: bool) -> bool {
|
||||
self.commit.take().unwrap().send(apply).unwrap();
|
||||
let receipt = (&mut self.committed).await.unwrap();
|
||||
let applied = receipt.0.is_ok();
|
||||
self.receipt = Some(receipt);
|
||||
applied
|
||||
}
|
||||
|
||||
pub(crate) fn respond(mut self) -> bool {
|
||||
let (result, response) = self.receipt.take().unwrap();
|
||||
response.send(result).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
pub(crate) fn pause_next_read(&self) -> DeferredRead {
|
||||
self.pause_read(ReadAction::Pause)
|
||||
}
|
||||
|
||||
pub(crate) fn pause_next_read_response(&self) -> DeferredRead {
|
||||
self.pause_read(ReadAction::PauseResponse)
|
||||
}
|
||||
|
||||
fn pause_read(&self, action: impl FnOnce(DeferredRead) -> ReadAction) -> DeferredRead {
|
||||
let gate = DeferredRead {
|
||||
arrived: Arc::new(Notify::new()),
|
||||
release: Arc::new(Notify::new()),
|
||||
};
|
||||
self.data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.read_actions
|
||||
.push_back(action(gate.clone()));
|
||||
gate
|
||||
}
|
||||
|
||||
pub(crate) fn fail_next_read(&self) {
|
||||
self.fail_next_read_with(denied());
|
||||
}
|
||||
|
||||
pub(crate) fn fail_next_read_with(&self, error: Error) {
|
||||
self.data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.read_actions
|
||||
.push_back(ReadAction::Fail(error));
|
||||
}
|
||||
|
||||
pub(crate) fn fail_next_write(&self, error: Error) {
|
||||
self.data.lock().unwrap().next_write_error = Some(error);
|
||||
}
|
||||
|
||||
pub(crate) fn defer_next_write(&self) -> DeferredWrite {
|
||||
let arrived = Arc::new(Notify::new());
|
||||
let (commit_tx, commit) = oneshot::channel();
|
||||
let (committed, committed_rx) = oneshot::channel();
|
||||
self.data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.write_actions
|
||||
.push_back(WriteAction {
|
||||
arrived: arrived.clone(),
|
||||
commit,
|
||||
committed,
|
||||
});
|
||||
DeferredWrite {
|
||||
arrived,
|
||||
commit: Some(commit_tx),
|
||||
committed: committed_rx,
|
||||
receipt: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Service for Backend {
|
||||
async fn create_dir(
|
||||
&self,
|
||||
@@ -157,7 +273,7 @@ impl Service for Backend {
|
||||
}
|
||||
}
|
||||
|
||||
struct TestLister;
|
||||
pub(crate) struct TestLister;
|
||||
|
||||
impl oio::List for TestLister {
|
||||
async fn next(&mut self) -> Result<Option<oio::Entry>> {
|
||||
@@ -169,13 +285,28 @@ fn denied() -> Error {
|
||||
Error::new(ErrorKind::PermissionDenied, "injected permission failure")
|
||||
}
|
||||
|
||||
struct TestReader {
|
||||
pub(crate) struct TestReader {
|
||||
data: Arc<Mutex<Data>>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl oio::Read for TestReader {
|
||||
async fn open(&self, _: BytesRange) -> Result<(RpRead, Box<dyn oio::ReadStreamDyn>)> {
|
||||
let action = {
|
||||
let mut data = self.data.lock().unwrap();
|
||||
data.calls.push(Call::Get(Instant::now()));
|
||||
data.read_actions.pop_front()
|
||||
};
|
||||
let pause_response = match action {
|
||||
Some(ReadAction::Pause(gate)) => {
|
||||
gate.arrived.notify_one();
|
||||
gate.release.notified().await;
|
||||
None
|
||||
}
|
||||
Some(ReadAction::PauseResponse(gate)) => Some((gate.arrived, gate.release)),
|
||||
Some(ReadAction::Fail(error)) => return Err(error),
|
||||
None => None,
|
||||
};
|
||||
let data = self.data.lock().unwrap();
|
||||
let (body, meta) = data
|
||||
.objects
|
||||
@@ -190,7 +321,7 @@ impl oio::Read for TestReader {
|
||||
rp,
|
||||
Box::new(TestStream {
|
||||
body: Buffer::from(body.clone()),
|
||||
pause: data.pause.clone(),
|
||||
pause: pause_response.or_else(|| data.pause.clone()),
|
||||
}),
|
||||
))
|
||||
}
|
||||
@@ -215,7 +346,8 @@ impl oio::ReadStream for TestStream {
|
||||
}
|
||||
}
|
||||
|
||||
struct TestWriter {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TestWriter {
|
||||
data: Arc<Mutex<Data>>,
|
||||
path: String,
|
||||
args: OpWrite,
|
||||
@@ -242,11 +374,47 @@ impl oio::Write for TestWriter {
|
||||
if let Some(barrier) = barrier {
|
||||
barrier.wait().await;
|
||||
}
|
||||
let action = {
|
||||
let mut data = self.data.lock().unwrap();
|
||||
if data.write_barrier.is_some() {
|
||||
data.writes_in_flight -= 1;
|
||||
}
|
||||
data.writes += 1;
|
||||
data.calls
|
||||
.push(Call::Put(AuthorityHead::decode(&self.body).unwrap()));
|
||||
data.write_actions.pop_front()
|
||||
};
|
||||
if let Some(action) = action {
|
||||
let writer = self.clone();
|
||||
let (response, result) = oneshot::channel();
|
||||
// The server owns the conditional update even after the client stops waiting.
|
||||
tokio::spawn(async move {
|
||||
action.arrived.notify_one();
|
||||
let outcome = match action.commit.await {
|
||||
Ok(true) => writer.commit(),
|
||||
Ok(false) => Err(denied()),
|
||||
Err(_) => return,
|
||||
};
|
||||
let _ = action.committed.send((outcome, response));
|
||||
});
|
||||
return result.await.unwrap_or_else(|_| {
|
||||
Err(Error::new(ErrorKind::Unexpected, "lost response").set_temporary())
|
||||
});
|
||||
}
|
||||
self.commit()
|
||||
}
|
||||
|
||||
async fn abort(&mut self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TestWriter {
|
||||
fn commit(&self) -> Result<Metadata> {
|
||||
let mut data = self.data.lock().unwrap();
|
||||
if data.write_barrier.is_some() {
|
||||
data.writes_in_flight -= 1;
|
||||
if let Some(error) = data.next_write_error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
data.writes += 1;
|
||||
if data.fail == Some("write") {
|
||||
return Err(Error::new(ErrorKind::Unexpected, "lost response").set_temporary());
|
||||
}
|
||||
@@ -300,10 +468,6 @@ impl oio::Write for TestWriter {
|
||||
.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<ConflictMutation>) {
|
||||
@@ -326,7 +490,7 @@ fn corrupt_conflict(data: &mut Data, path: &str, mutation: Option<ConflictMutati
|
||||
data.corruptions += 1;
|
||||
}
|
||||
|
||||
struct TestDeleter(Arc<Mutex<Data>>);
|
||||
pub(crate) struct TestDeleter(Arc<Mutex<Data>>);
|
||||
|
||||
impl oio::Delete for TestDeleter {
|
||||
async fn delete(&mut self, path: &str, _: OpDelete) -> Result<()> {
|
||||
@@ -344,7 +508,7 @@ impl oio::Delete for TestDeleter {
|
||||
}
|
||||
}
|
||||
|
||||
fn store(backend: &Backend) -> HeadStore {
|
||||
pub(crate) fn store(backend: &Backend) -> HeadStore {
|
||||
HeadStore::new_for_test(
|
||||
ObjectStore::from_parts(OperationContext::default(), Arc::new(backend.clone())),
|
||||
"cluster",
|
||||
|
||||
@@ -1141,6 +1141,51 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority is closed"))]
|
||||
AuthorityClosed {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority Head requires operator recovery"))]
|
||||
AuthorityRecoveryRequired {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority operation was not executed: {}", reason))]
|
||||
AuthorityRejected {
|
||||
reason: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display(
|
||||
"Authority Head write sequence mismatch: expected {}, actual {}",
|
||||
expected,
|
||||
actual
|
||||
))]
|
||||
AuthorityWriteSeqMismatch {
|
||||
expected: u64,
|
||||
actual: u64,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority {} timed out", operation))]
|
||||
AuthorityTimeout {
|
||||
operation: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority PUT outcome is unknown"))]
|
||||
AuthorityUnknown {
|
||||
source: Box<Error>,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to open Authority storage"))]
|
||||
AuthorityOpen {
|
||||
#[snafu(source)]
|
||||
@@ -1334,7 +1379,13 @@ impl ErrorExt for Error {
|
||||
AuthorityMissing { .. }
|
||||
| AuthorityMetadata { .. }
|
||||
| AuthorityStorage { .. }
|
||||
| AuthorityOpen { .. } => StatusCode::StorageUnavailable,
|
||||
| AuthorityOpen { .. }
|
||||
| AuthorityClosed { .. }
|
||||
| AuthorityRecoveryRequired { .. }
|
||||
| AuthorityTimeout { .. }
|
||||
| AuthorityUnknown { .. } => StatusCode::StorageUnavailable,
|
||||
AuthorityRejected { .. } => StatusCode::IllegalState,
|
||||
AuthorityWriteSeqMismatch { .. } => StatusCode::RequestOutdated,
|
||||
NoLeader { .. } => StatusCode::TableUnavailable,
|
||||
ValueNotExist { .. }
|
||||
| ProcedurePoisonConflict { .. }
|
||||
@@ -1557,6 +1608,7 @@ impl Error {
|
||||
Self::AuthorityStorage { error, .. } | Self::AuthorityMissing { error, .. } => {
|
||||
Some(error)
|
||||
}
|
||||
Self::AuthorityUnknown { source, .. } => source.authority_storage_error(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user