use core::fmt;
use jiff::Timestamp;
use crate::deadline::{self, DeadlineKind};
use crate::process::{Direction, Message, Open, Process, Refusal, State};
use crate::pruefung::{self, Bestand};
use crate::validate::Severity;
use crate::xml::ReadError;
use crate::{
Abbm, AbbmTr, Anfrage, Calendar, Control, Erlm, Freitext, Geschaeftsfall, Meldung, Meldungscode, Meldungstyp,
Payload, Role, RuemVa, SignaturId, Teq, Vorabstimmung,
};
#[doc(inline)]
pub use carrier_core::sim::Latency;
pub use jiff::SignedDuration;
const MAX_ACTS: usize = 1_000;
const RECEIPT_MAX: SignedDuration = SignedDuration::from_hours(2);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Antwort {
Pruefung(Box<Bestand>),
Zustimmung,
Ablehnung(Meldungscode),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outbound {
pub at: Timestamp,
pub payload: Payload,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Rejection {
Unreadable(ReadError),
Refused(Refusal),
}
impl fmt::Display for Rejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unreadable(e) => write!(f, "unreadable: {e} (TEQ {})", e.teq_code().as_str()),
Self::Refused(r) => write!(f, "refused: {r}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Reply {
pub outbound: Vec<Outbound>,
pub rejection: Option<Rejection>,
}
#[derive(Clone, PartialEq, Eq)]
pub struct Ekpabg {
antwort: Antwort,
signatur: SignaturId,
latency: Latency,
calendar: Calendar,
process: Option<Process>,
stopped: Option<Refusal>,
}
impl fmt::Debug for Ekpabg {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let antwort = match &self.antwort {
Antwort::Pruefung(_) => "Pruefung".to_owned(),
Antwort::Zustimmung => "Zustimmung".to_owned(),
Antwort::Ablehnung(c) => format!("Ablehnung({})", c.as_str()),
};
f.debug_struct("Ekpabg")
.field("antwort", &antwort)
.field("latency", &self.latency)
.field("state", &self.process.as_ref().map(|p| p.state().to_string()))
.field("events", &self.process.as_ref().map_or(0, |p| p.history().len()))
.field("stopped", &self.stopped)
.finish_non_exhaustive()
}
}
impl Ekpabg {
#[must_use]
pub fn new(antwort: Antwort, signatur: SignaturId) -> Self {
Self {
antwort,
signatur,
latency: Latency::default(),
calendar: Calendar::wbci(),
process: None,
stopped: None,
}
}
#[must_use]
pub const fn with_latency(mut self, latency: Latency) -> Self {
self.latency = latency;
self
}
#[must_use]
pub fn with_calendar(mut self, calendar: Calendar) -> Self {
self.calendar = calendar;
self
}
#[must_use]
pub const fn process(&self) -> Option<&Process> {
self.process.as_ref()
}
#[must_use]
pub const fn stopped(&self) -> Option<&Refusal> {
self.stopped.as_ref()
}
#[must_use]
pub fn next_due(&self) -> Option<Timestamp> {
self.plan().map(|(at, _)| at)
}
pub fn advance(&mut self, now: Timestamp) -> Vec<Outbound> {
let mut out = Vec::new();
for _ in 0..MAX_ACTS {
let Some((at, meldung)) = self.plan().filter(|(at, _)| *at <= now) else { break };
let Some(process) = self.process.as_mut() else { break };
match process.apply(Direction::Sent, at, meldung.clone()) {
Ok(()) => out.push(self.meldung_out(at, meldung)),
Err(e) => {
self.stopped = Some(e);
break;
}
}
}
out
}
pub fn receive(&mut self, payload: &Payload, at: Timestamp) -> Reply {
let mut reply = Reply { outbound: self.advance(at), rejection: None };
let receipt_at = at.saturating_add(self.latency.receipt_within(RECEIPT_MAX)).unwrap_or(at);
let rejection = match payload {
Payload::AnfrageRequest { anfrage, .. } => self.anfrage(anfrage, at, receipt_at, &mut reply.outbound),
Payload::MeldungRequest { meldung, .. } => self.meldung(meldung, at, receipt_at, &mut reply.outbound),
Payload::AnfrageResponse { quittung, .. } | Payload::MeldungResponse { quittung, .. } => {
self.teq(quittung, at)
}
};
reply.rejection = rejection;
reply
}
pub fn receive_xml(&mut self, xml: &[u8], at: Timestamp) -> Reply {
match Payload::from_xml(xml) {
Ok(payload) => self.receive(&payload, at),
Err(e) => Reply { outbound: self.advance(at), rejection: Some(Rejection::Unreadable(e)) },
}
}
fn control(&self, at: Timestamp) -> Control {
Control::new(at, self.signatur.clone())
}
fn meldung_out(&self, at: Timestamp, meldung: Meldung) -> Outbound {
Outbound { at, payload: Payload::MeldungRequest { control: self.control(at), meldung } }
}
fn answer_at(&self, at: Timestamp) -> Timestamp {
at.saturating_add(self.latency.answer()).unwrap_or(at)
}
fn anfrage(
&mut self,
anfrage: &Anfrage,
at: Timestamp,
receipt_at: Timestamp,
out: &mut Vec<Outbound>,
) -> Option<Rejection> {
let receipt = Teq::for_anfrage(anfrage, Meldungscode::Ok);
let receipt_out = Outbound {
at: receipt_at,
payload: Payload::AnfrageResponse { control: self.control(receipt_at), quittung: receipt.clone() },
};
let accepted = match (&mut self.process, anfrage) {
(None, Anfrage::Vorabstimmung(va)) => {
Process::new(Role::EkpAbg, va.clone(), Direction::Received, at).map(|p| {
self.process = Some(p.with_calendar(self.calendar.clone()));
})
}
(None, _) => Err(Refusal {
code: if matches!(anfrage, Anfrage::Storno(_)) {
Meldungscode::VorabstimmungsIdUnbekannt
} else {
Meldungscode::Sonstiges
},
reason: "no pre-agreement with this Vorabstimmungs-ID was received".to_owned(),
}),
(Some(p), _) => p.apply(Direction::Received, at, anfrage.clone()),
};
match accepted {
Ok(()) => {
self.own_receipt(receipt_at, receipt);
out.push(receipt_out);
None
}
Err(refusal) => {
out.push(receipt_out);
let mut abbm = refusal_abbm(anfrage, &refusal);
if let (Anfrage::Terminverschiebung(_), Some(State::Agreed { wechseltermin })) =
(anfrage, self.process.as_ref().map(Process::state))
{
abbm.wechseltermin = Some(*wechseltermin);
}
out.push(self.meldung_out(self.answer_at(at), abbm.into()));
Some(Rejection::Refused(refusal))
}
}
}
fn meldung(
&mut self,
meldung: &Meldung,
at: Timestamp,
receipt_at: Timestamp,
out: &mut Vec<Outbound>,
) -> Option<Rejection> {
let receipt = Teq::for_meldung(meldung, Meldungscode::Ok);
out.push(Outbound {
at: receipt_at,
payload: Payload::MeldungResponse { control: self.control(receipt_at), quittung: receipt.clone() },
});
let result = match &mut self.process {
None => Err(Refusal {
code: Meldungscode::VorabstimmungsIdUnbekannt,
reason: "no pre-agreement with this Vorabstimmungs-ID was received".to_owned(),
}),
Some(p) => p.apply(Direction::Received, at, meldung.clone()),
};
match result {
Ok(()) => {
self.own_receipt(receipt_at, receipt);
None
}
Err(refusal) => {
if let Meldung::AkmTr(t) = meldung
&& refusal.code.applies(Meldungstyp::AbbmTr, t.kopf.geschaeftsfall)
{
let abbm_tr = AbbmTr::ablehnung(t, refusal.code.clone());
out.push(self.meldung_out(self.answer_at(at), abbm_tr.into()));
}
Some(Rejection::Refused(refusal))
}
}
}
fn teq(&mut self, teq: &Teq, at: Timestamp) -> Option<Rejection> {
let result = match &mut self.process {
None => Err(Refusal {
code: Meldungscode::VorabstimmungsIdUnbekannt,
reason: "a receipt, but no pre-agreement was received".to_owned(),
}),
Some(p) => p.apply(Direction::Received, at, teq.clone()),
};
result.err().map(Rejection::Refused)
}
fn own_receipt(&mut self, at: Timestamp, receipt: Teq) {
if let Some(p) = self.process.as_mut()
&& let Err(e) = p.apply(Direction::Sent, at, receipt)
{
self.stopped = Some(e);
}
}
fn plan(&self) -> Option<(Timestamp, Meldung)> {
if self.stopped.is_some() {
return None;
}
let p = self.process.as_ref()?;
let last = p.history().last()?.at;
let deadlines = p.deadlines();
let due = |kind: DeadlineKind| {
deadlines.iter().filter(|d| d.kind == kind && d.party == Role::EkpAbg).map(|d| d.due).min()
};
let when = |deadline: Option<Timestamp>| {
let at = self.answer_at(last);
match deadline.and_then(|d| d.checked_sub(SignedDuration::from_secs(1)).ok()) {
Some(latest) if latest < at => latest.max(last),
_ => at,
}
};
if *p.state() == State::Requested {
let deadline = due(DeadlineKind::VaAnswer)?;
return Some((when(Some(deadline)), self.va_answer(p.vorabstimmung(), p)));
}
for open in p.open() {
match open {
Open::Storno { id, sender: Role::EkpAuf, teq_at: Some(_), .. } => {
let storno = p.history().iter().find_map(|e| match &e.message {
Message::Anfrage(Anfrage::Storno(s)) if s.storno_id == *id => Some(s),
_ => None,
})?;
return Some((when(due(DeadlineKind::Answer24h)), Erlm::storno_ok(storno).into()));
}
Open::Terminverschiebung { id, teq_at: Some(_), .. } => {
let tvs = p.history().iter().find_map(|e| match &e.message {
Message::Anfrage(Anfrage::Terminverschiebung(t)) if t.aenderungs_id == *id => Some(t),
_ => None,
})?;
return Some((when(due(DeadlineKind::Answer24h)), Erlm::terminverschiebung_ok(tvs).into()));
}
Open::Storno { .. } | Open::Terminverschiebung { .. } => {}
}
}
None
}
fn va_answer(&self, va: &Vorabstimmung, p: &Process) -> Meldung {
let received = p.history().first().map_or(Timestamp::UNIX_EPOCH, |e| e.at);
let answered = p.history().last().map_or(received, |e| e.at);
let anfrage = Anfrage::Vorabstimmung(va.clone());
match &self.antwort {
Antwort::Pruefung(bestand) => pruefung::check(va, bestand, received, &self.calendar).antwort,
Antwort::Zustimmung => {
let codes: Vec<Meldungscode> = anfrage
.issues_at(received, &self.calendar)
.into_iter()
.filter(|i| i.severity == Severity::Error)
.filter_map(|i| i.code)
.filter(|c| c.applies(Meldungstyp::Abbm, va.geschaeftsfall()))
.collect();
if let Some((first, rest)) = codes.split_first() {
let mut abbm = Abbm::ablehnung(&anfrage, first.clone());
for c in rest {
abbm = abbm.with_position(crate::Position::new(c.clone()));
}
return with_reason(abbm, "the request does not meet the validation rules").into();
}
let date = if va.geschaeftsfall() == Geschaeftsfall::VaRrnp {
va.kundenwunschtermin
} else {
let at = self.answer_at(answered);
deadline::earliest_wechseltermin(at, va.kundenwunschtermin, &self.calendar).date
};
RuemVa::zustimmung(va, date).into()
}
Antwort::Ablehnung(code) => {
with_reason(Abbm::ablehnung(&anfrage, code.clone()), "refused by the simulated losing provider").into()
}
}
}
}
fn refusal_abbm(anfrage: &Anfrage, refusal: &Refusal) -> Abbm {
let fall = anfrage.geschaeftsfall();
if refusal.code.applies(Meldungstyp::Abbm, fall) {
with_reason(Abbm::ablehnung(anfrage, refusal.code.clone()), &refusal.reason)
} else {
with_reason(Abbm::ablehnung(anfrage, Meldungscode::Sonstiges), &refusal.reason)
}
}
fn with_reason(abbm: Abbm, reason: &str) -> Abbm {
if abbm.positionen.iter().any(|p| p.position.code == Meldungscode::Sonstiges) {
let text = Freitext::new(reason).or_else(|_| Freitext::new("Abgelehnt"));
match text {
Ok(t) => abbm.with_begruendung(t),
Err(_) => abbm,
}
} else {
abbm
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_receipt_never_leaves_its_deadline() {
let slow = Latency { receipt: SignedDuration::from_hours(5), answer: SignedDuration::from_hours(1) };
assert_eq!(slow.receipt_within(RECEIPT_MAX), RECEIPT_MAX);
}
#[test]
fn a_new_peer_plans_nothing() {
let signatur = SignaturId {
issuer: crate::SignaturText::new("CN=Sandbox").unwrap(),
serial: crate::SignaturText::new("1").unwrap(),
};
let mut peer = Ekpabg::new(Antwort::Zustimmung, signatur);
assert_eq!(peer.next_due(), None);
assert!(peer.advance(Timestamp::MAX).is_empty());
assert!(peer.process().is_none() && peer.stopped().is_none());
}
}