use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use crate::error::FsError;
use crate::error::FsErrorKind;
use crate::error::FsOperation;
use crate::error::FsResult;
use crate::error::RecoveryCleanupState;
use crate::facade::internal::RecoveryCleanupGuard;
use crate::path::Path;
use crate::spi::FileWriterSpi;
use crate::write::WriteAbortOutcome;
#[must_use = "explicitly clean or retain the isolated recovery session"]
pub struct RejectedWriter {
session: Box<dyn FileWriterSpi>,
state: RecoveryCleanupState,
provider: Box<str>,
path: Option<Path>,
}
impl RejectedWriter {
pub(crate) fn new(session: Box<dyn FileWriterSpi>, provider: &str, path: Option<Path>) -> Self {
Self {
session,
state: RecoveryCleanupState::Pending,
provider: provider.into(),
path,
}
}
pub const fn cleanup_state(&self) -> RecoveryCleanupState {
self.state
}
pub fn abort(&mut self) -> FsResult<WriteAbortOutcome> {
if self.state == RecoveryCleanupState::Completed {
return Err(self.contextual_error(FsError::new(
FsErrorKind::InvalidState,
FsOperation::AbortWriter,
"isolated session cleanup already completed",
)));
}
let mut guard = RecoveryCleanupGuard::start(&mut self.state);
let result = self.session.abort();
guard.finish(matches!(
&result,
Ok(WriteAbortOutcome::NotPublished | WriteAbortOutcome::Published)
));
drop(guard);
result.map_err(|error| self.contextual_error(error))
}
fn contextual_error(&self, error: FsError) -> FsError {
error.with_trusted_cleanup_context(FsOperation::AbortWriter, self.path.as_ref(), &self.provider)
}
}
impl Debug for RejectedWriter {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.debug_struct("RejectedWriter")
.field("cleanup_state", &self.state)
.finish_non_exhaustive()
}
}