use serde_json::Value;
use super::answer::{Answer, said};
use super::state::{ACTOR_CHANGED, MISMATCH, REFUSED, Reason};
use crate::conversation::Error;
use crate::conversation::turn_records::{Header, State as DraftState, Written};
use crate::remote::records::Refusal;
const CONFLICT: &str = "agent_conversation_conflict";
const CONFIGURATION: &str = "agent_configuration_error";
const FORMAT: &str = "agent_conversation_format_unsupported";
const STORAGE: &str = "storage_exceeded";
pub const RETRY_SECONDS: u64 = 10;
pub const WAIT_SECONDS: u64 = 60;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Route {
Records,
Whole,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Action {
Took(DraftState, u64),
Stored(Header),
Probe,
Hold(Reason),
HoldAside(Reason),
Fresh(Reason),
Restart,
Reread(String),
Whole,
Keep(Stop),
}
#[derive(Debug, PartialEq, Eq)]
pub enum Stop {
Conversation(String),
Retry { seconds: u64, message: String },
Wait {
seconds: u64,
failing: bool,
message: String,
},
Block {
block: Block,
message: String,
status: Option<u16>,
code: Option<String>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Block {
Storage,
Forbidden,
Credential,
}
impl Block {
pub fn name(self) -> &'static str {
match self {
Self::Storage => "storage",
Self::Forbidden => "forbidden",
Self::Credential => "credential",
}
}
}
impl Stop {
pub fn destination(&self) -> bool {
!matches!(self, Self::Conversation(_))
}
pub fn message(&self) -> &str {
match self {
Self::Conversation(message)
| Self::Retry { message, .. }
| Self::Wait { message, .. }
| Self::Block { message, .. } => message,
}
}
}
fn failing(message: String) -> Action {
Action::Keep(Stop::Wait {
seconds: WAIT_SECONDS,
failing: true,
message,
})
}
fn block(block: Block, message: String) -> Action {
Action::Keep(Stop::Block {
block,
message,
status: None,
code: None,
})
}
fn refused_by(block: Block, refusal: &Refusal, message: String) -> Action {
Action::Keep(Stop::Block {
block,
message,
status: Some(refusal.status),
code: refusal.code.clone(),
})
}
const CREDENTIAL_REFUSED: [&str; 4] = [
"rejected the bearer token",
"rejected this machine credential",
"run neosian login",
"requires a credential",
];
pub fn unopened(error: &Error) -> Stop {
let message = error.text();
let credential = matches!(error, Error::Memory(_))
&& CREDENTIAL_REFUSED.iter().any(|mark| message.contains(mark));
match credential {
true => Stop::Block {
block: Block::Credential,
message,
status: None,
code: None,
},
false => Stop::Wait {
seconds: WAIT_SECONDS,
failing: true,
message,
},
}
}
fn reason(reason: &'static str, refusal: &Refusal, said: String) -> Reason {
let message = match refusal.message.is_empty() {
true => said,
false => refusal.message.clone(),
};
Reason::answered(reason, Some(refusal.status), refusal.code.clone(), message)
}
fn own_draft(refusal: &Refusal) -> bool {
let reason = refusal.details.get("reason").and_then(Value::as_str);
let reason = reason.unwrap_or_default();
reason.contains("draft's")
|| reason.starts_with("record ")
|| reason.starts_with("records line ")
|| reason.starts_with("the requested range of stored records")
}
fn written(written: &Written) -> Action {
match (written.state, &written.turn) {
(DraftState::Sealed, Some(header)) => Action::Stored(header.clone()),
(DraftState::Sealed, None) => failing(format!(
"draft {} answered sealed without its turn",
written.draft
)),
(state, _) => Action::Took(state, written.next_seq),
}
}
pub fn decide(route: Route, answer: &Answer) -> Action {
let refusal = match answer {
Answer::Written(answered) => return written(answered),
Answer::Refused(refusal) => refusal,
Answer::Lost(_) | Answer::Unreadable(_) => return failing(said(answer)),
Answer::Unasked { credential, .. } if *credential => {
return block(Block::Credential, said(answer));
}
Answer::Unasked { .. } => return failing(said(answer)),
Answer::Unsupported => return Action::Whole,
};
let said = said(answer);
let code = refusal.code.as_deref();
let conflict = match code {
Some(CONFLICT) => refusal.details.get("reason").and_then(Value::as_str),
_ => None,
};
match (refusal.status, code, conflict) {
(429, ..) => match refusal.retry_after {
Some(seconds) if seconds <= RETRY_SECONDS => Action::Keep(Stop::Retry {
seconds,
message: said,
}),
seconds => Action::Keep(Stop::Wait {
seconds: seconds.unwrap_or(WAIT_SECONDS),
failing: false,
message: said,
}),
},
(413, Some(STORAGE), _) => refused_by(Block::Storage, refusal, said),
(401, ..) => refused_by(Block::Credential, refusal, said),
(403, ..) | (300..=399, ..) => refused_by(Block::Forbidden, refusal, said),
(_, _, Some("draft_sealed")) => match refusal.details.get("turn").map(Header::from_json) {
Some(Ok(header)) => Action::Stored(header),
_ => Action::Probe,
},
(_, _, Some("draft_mismatch" | "draft_size")) => {
Action::Fresh(reason(MISMATCH, refusal, said))
}
(400, Some(FORMAT), _) if route == Route::Records && own_draft(refusal) => {
Action::Fresh(reason(MISMATCH, refusal, said))
}
(_, _, Some("draft_gap")) => Action::Restart,
(_, _, Some("drafts_open")) => Action::Keep(Stop::Conversation(said)),
(_, _, Some("draft_actor")) => Action::HoldAside(reason(ACTOR_CHANGED, refusal, said)),
(410, ..) if route == Route::Records => Action::Restart,
(404, ..) if route == Route::Records => Action::Whole,
(404, ..) => refused_by(Block::Forbidden, refusal, said),
(400, Some(CONFIGURATION), _) if route == Route::Records => Action::Reread(said),
(400..=499, ..) => Action::Hold(reason(REFUSED, refusal, said)),
_ => failing(said),
}
}