use super::editor::ValueEditor;
use super::external::ExternalDraft;
use super::state::RequestId;
use super::tree::{MaskPath, NodePath};
use crate::errors::{FsqError, FsqResult, NoUpdateTime};
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::{MapValue, Value};
use firestore::gcloud_sdk::prost_types::Timestamp;
use firestore::timestamp_utils::from_timestamp;
use firestore::{FirestoreDocument, FirestoreWritePrecondition};
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq)]
pub enum Change {
Field {
path: MaskPath,
value: Option<Value>,
},
Document(Option<HashMap<String, Value>>),
NewDocument {
name: String,
fields: HashMap<String, Value>,
},
}
impl Change {
fn needs_document(&self) -> bool {
!matches!(self, Self::Document(Some(_)) | Self::NewDocument { .. })
}
fn operation(&self) -> WriteOperation {
match self {
Self::Field { path, value } => WriteOperation::Update {
fields: path.fields_with(value.clone()),
mask: Some(path.clone()),
},
Self::Document(Some(fields)) | Self::NewDocument { fields, .. } => {
WriteOperation::Update {
fields: fields.clone(),
mask: None,
}
}
Self::Document(None) => WriteOperation::Delete,
}
}
}
#[derive(Debug)]
pub struct Edit {
document: Option<String>,
read: Option<FirestoreDocument>,
step: Step,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Step {
Editing(Draft),
Confirming(Confirmation),
}
#[derive(Debug)]
pub enum Draft {
Value(ValueEditor),
External(ExternalDraft),
}
impl Draft {
fn submit(&mut self) -> Option<Change> {
match self {
Self::Value(editor) => editor.submit(),
Self::External(draft) => draft.submit(),
}
}
}
#[derive(Debug)]
pub struct Confirmation {
change: Change,
draft: Option<Draft>,
stage: Stage,
}
impl Confirmation {
pub fn change(&self) -> &Change {
&self.change
}
pub fn has_draft(&self) -> bool {
self.draft.is_some()
}
pub fn stage(&self) -> &Stage {
&self.stage
}
}
#[derive(Debug)]
pub enum Stage {
Asking(Option<Note>),
Writing(RequestId),
DeletingRecursively(RecursiveProgress),
DeletedPartly(PartialDelete),
Reading(RequestId),
Failed(FsqError),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Note {
Changed,
WriteStopped,
ReadStopped,
Exists,
}
#[derive(Debug, PartialEq)]
pub struct ValueChange {
pub before: Option<Value>,
pub after: Option<Value>,
}
impl ValueChange {
pub fn changes_nothing(&self) -> bool {
self.before == self.after
}
}
impl Edit {
pub fn editing(document: &FirestoreDocument, draft: Draft) -> Self {
Self::new(document, Step::Editing(draft))
}
pub fn confirming(document: &FirestoreDocument, change: Change) -> Self {
let confirmation = Confirmation {
change,
draft: None,
stage: Stage::Asking(None),
};
Self::new(document, Step::Confirming(confirmation))
}
pub fn creating(draft: ExternalDraft) -> Self {
Self {
document: None,
read: None,
step: Step::Editing(Draft::External(draft)),
}
}
fn new(document: &FirestoreDocument, step: Step) -> Self {
Self {
document: Some(document.name.clone()),
read: Some(document.clone()),
step,
}
}
pub fn document(&self) -> Option<&str> {
match self.confirmation().map(Confirmation::change) {
Some(Change::NewDocument { name, .. }) => Some(name),
_ => self.document.as_deref(),
}
}
pub fn creates(&self) -> bool {
matches!(
self.confirmation().map(Confirmation::change),
Some(Change::NewDocument { .. })
)
}
pub fn exists_already(&self) -> bool {
matches!(
self.confirmation().map(Confirmation::stage),
Some(Stage::Asking(Some(Note::Exists)))
)
}
pub fn last_read(&self) -> Option<&FirestoreDocument> {
self.read.as_ref()
}
pub fn created(&self, stored: &FirestoreDocument) -> bool {
matches!(
self.confirmation().map(Confirmation::change),
Some(Change::NewDocument { fields, .. }) if *fields == stored.fields
)
}
pub fn step(&self) -> &Step {
&self.step
}
pub fn confirmation(&self) -> Option<&Confirmation> {
match &self.step {
Step::Confirming(confirmation) => Some(confirmation),
Step::Editing(_) => None,
}
}
pub fn value_editor(&self) -> Option<&ValueEditor> {
match &self.step {
Step::Editing(Draft::Value(editor)) => Some(editor),
Step::Editing(Draft::External(_)) | Step::Confirming(_) => None,
}
}
pub fn value_editor_mut(&mut self) -> Option<&mut ValueEditor> {
match &mut self.step {
Step::Editing(Draft::Value(editor)) => Some(editor),
Step::Editing(Draft::External(_)) | Step::Confirming(_) => None,
}
}
pub fn external_draft(&self) -> Option<&ExternalDraft> {
match &self.step {
Step::Editing(Draft::External(draft)) => Some(draft),
Step::Editing(Draft::Value(_)) | Step::Confirming(_) => None,
}
}
pub fn external_draft_mut(&mut self) -> Option<&mut ExternalDraft> {
match &mut self.step {
Step::Editing(Draft::External(draft)) => Some(draft),
Step::Editing(Draft::Value(_)) | Step::Confirming(_) => None,
}
}
pub fn is_waiting(&self) -> bool {
matches!(
self.confirmation().map(Confirmation::stage),
Some(Stage::Writing(_) | Stage::DeletingRecursively(_) | Stage::Reading(_))
)
}
pub fn waits_for(&self, request: RequestId) -> bool {
match self.confirmation().map(Confirmation::stage) {
Some(Stage::Writing(waited) | Stage::Reading(waited)) => *waited == request,
Some(Stage::DeletingRecursively(progress)) => progress.request == request,
_ => false,
}
}
pub fn deletes_document(&self) -> bool {
matches!(
self.confirmation().map(Confirmation::change),
Some(Change::Document(None))
)
}
pub fn can_write(&self) -> bool {
let answered = matches!(
self.confirmation().map(Confirmation::stage),
Some(Stage::Asking(_) | Stage::Failed(_))
);
answered && !self.is_gone() && !self.exists_already()
}
pub fn is_gone(&self) -> bool {
self.read.is_none()
&& self
.confirmation()
.is_some_and(|confirmation| confirmation.change.needs_document())
}
pub fn submitted(self) -> Option<Self> {
let step = match self.step {
Step::Editing(mut draft) => match draft.submit() {
Some(change) => Step::Confirming(Confirmation {
change,
draft: Some(draft),
stage: Stage::Asking(None),
}),
None => Step::Editing(draft),
},
confirming @ Step::Confirming(_) => confirming,
};
let edit = Self { step, ..self };
let changes_nothing = edit
.value_change()
.is_some_and(|values| values.changes_nothing());
(!changes_nothing).then_some(edit)
}
pub fn reopened(self) -> Self {
let step = match self.step {
Step::Confirming(Confirmation {
draft: Some(draft),
stage: Stage::Asking(_) | Stage::Failed(_),
..
}) => Step::Editing(draft),
step => step,
};
Self { step, ..self }
}
pub fn value_change(&self) -> Option<ValueChange> {
let confirmation = self.confirmation()?;
let read = self.read.as_ref();
Some(match &confirmation.change {
Change::Field { path, value } => ValueChange {
before: read.and_then(|read| NodePath::from(path).value_in(read).cloned()),
after: value.clone(),
},
Change::Document(fields) => ValueChange {
before: read.map(|read| map_value(read.fields.clone())),
after: fields.clone().map(map_value),
},
Change::NewDocument { fields, .. } => ValueChange {
before: None,
after: Some(map_value(fields.clone())),
},
})
}
pub fn write(&mut self, request: RequestId) -> Option<DocumentWrite> {
let precondition = self.precondition()?;
let document = self.document()?.to_string();
let Step::Confirming(confirmation) = &mut self.step else {
return None;
};
confirmation.stage = Stage::Writing(request);
Some(DocumentWrite {
request,
document,
operation: confirmation.change.operation(),
precondition,
})
}
pub fn delete_recursively(&mut self, request: RequestId) -> Option<RecursiveDelete> {
if !self.deletes_document() || !self.can_write() {
return None;
}
let update_time = self.update_time()?;
let document = self.document.clone()?;
self.set_stage(Stage::DeletingRecursively(RecursiveProgress {
request,
deleted: 0,
stopping: false,
}));
Some(RecursiveDelete {
request,
document,
update_time,
})
}
fn precondition(&mut self) -> Option<FirestoreWritePrecondition> {
if !self.can_write() {
return None;
}
if self.read.is_none() || self.creates() {
return Some(FirestoreWritePrecondition::Exists(false));
}
match from_timestamp(self.update_time()?) {
Ok(update_time) => Some(FirestoreWritePrecondition::UpdateTime(update_time)),
Err(error) => {
self.fail(error.into());
None
}
}
}
fn update_time(&mut self) -> Option<Timestamp> {
let read = self.read.as_ref()?;
let Some(update_time) = read.update_time else {
let document = read.name.clone();
self.fail(FsqError::NoUpdateTime(NoUpdateTime { document }));
return None;
};
Some(update_time)
}
pub fn count_deleted(&mut self, deleted: usize) {
if let Some(Stage::DeletingRecursively(progress)) = self.stage_mut() {
progress.deleted = deleted;
}
}
pub fn end_partly(&mut self, partial: FsqResult<PartialDelete>) {
let Some(Stage::DeletingRecursively(progress)) = self.stage_mut() else {
return;
};
let partial = partial.unwrap_or_else(|error| PartialDelete {
deleted: progress.deleted,
halt: Halt::Failed(error),
});
self.set_stage(Stage::DeletedPartly(partial));
}
pub fn wait_for_read(&mut self, request: RequestId) {
self.set_stage(Stage::Reading(request));
}
pub fn read_again(&mut self, read: Option<FirestoreDocument>) {
self.read = read;
self.set_stage(Stage::Asking(Some(Note::Changed)));
}
pub fn fail(&mut self, error: FsqError) {
self.set_stage(Stage::Failed(error));
}
pub fn refuse_existing(&mut self) {
self.set_stage(Stage::Asking(Some(Note::Exists)));
}
pub fn stop_waiting(&mut self) -> bool {
if !self.is_waiting() {
return false;
}
match self.stage_mut() {
Some(Stage::DeletingRecursively(progress)) => progress.stopping = true,
Some(Stage::Reading(_)) => self.set_stage(Stage::Asking(Some(Note::ReadStopped))),
_ => self.set_stage(Stage::Asking(Some(Note::WriteStopped))),
}
true
}
pub fn abandon(&mut self) -> bool {
let Some(Stage::DeletingRecursively(progress)) = self.stage_mut() else {
return false;
};
if !progress.stopping {
return false;
}
let deleted = progress.deleted;
self.set_stage(Stage::DeletedPartly(PartialDelete {
deleted,
halt: Halt::Abandoned,
}));
true
}
fn stage_mut(&mut self) -> Option<&mut Stage> {
match &mut self.step {
Step::Confirming(confirmation) => Some(&mut confirmation.stage),
Step::Editing(_) => None,
}
}
fn set_stage(&mut self, stage: Stage) {
if let Some(current) = self.stage_mut() {
*current = stage;
}
}
}
fn map_value(fields: HashMap<String, Value>) -> Value {
Value {
value_type: Some(ValueType::MapValue(MapValue { fields })),
}
}
#[derive(Debug, PartialEq)]
pub struct DocumentWrite {
pub request: RequestId,
pub document: String,
pub operation: WriteOperation,
pub precondition: FirestoreWritePrecondition,
}
#[derive(Debug, PartialEq)]
pub enum WriteOperation {
Update {
fields: HashMap<String, Value>,
mask: Option<MaskPath>,
},
Delete,
}
#[derive(Debug)]
pub enum WriteOutcome {
Written(FirestoreDocument),
Deleted,
Stale,
}
#[derive(Debug, PartialEq)]
pub struct RecursiveDelete {
pub request: RequestId,
pub document: String,
pub update_time: Timestamp,
}
#[derive(Debug)]
pub struct RecursiveProgress {
pub request: RequestId,
pub deleted: usize,
pub stopping: bool,
}
#[derive(Debug)]
pub enum RecursiveOutcome {
Deleted,
Partial(PartialDelete),
}
#[derive(Debug)]
pub struct PartialDelete {
pub deleted: usize,
pub halt: Halt,
}
#[derive(Debug)]
pub enum Halt {
Stopped,
Stale,
Failed(FsqError),
Abandoned,
}
impl From<FsqError> for Halt {
fn from(error: FsqError) -> Self {
Self::Failed(error)
}
}