use crate::{
DeviceReply, Request,
service::{ExchangeError, LinkClient, QueueId, RetryPolicy},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlanExpectation {
Success,
ResponseCodes(Vec<u8>),
DataPrefix(Vec<u8>),
}
#[derive(Debug, Clone)]
pub struct PlanStep {
pub name: String,
pub request: Request,
pub queue: QueueId,
pub retry: RetryPolicy,
pub expectation: PlanExpectation,
}
impl PlanStep {
pub fn new(name: impl Into<String>, request: Request) -> Self {
Self {
name: name.into(),
request,
queue: QueueId::DEFAULT,
retry: RetryPolicy::default(),
expectation: PlanExpectation::Success,
}
}
pub const fn with_queue(mut self, queue: QueueId) -> Self {
self.queue = queue;
self
}
pub const fn with_retry(mut self, retry: RetryPolicy) -> Self {
self.retry = retry;
self
}
pub fn expecting(mut self, expectation: PlanExpectation) -> Self {
self.expectation = expectation;
self
}
}
#[derive(Debug, Clone, Default)]
pub struct Plan {
pub steps: Vec<PlanStep>,
pub continue_after_failure: bool,
}
#[derive(Debug)]
pub struct StepReport {
pub name: String,
pub result: Result<DeviceReply, ExchangeError>,
pub expectation_met: bool,
}
#[derive(Debug, Default)]
pub struct PlanReport {
pub steps: Vec<StepReport>,
}
impl Plan {
pub const fn new() -> Self {
Self {
steps: Vec::new(),
continue_after_failure: false,
}
}
pub fn with_step(mut self, step: PlanStep) -> Self {
self.steps.push(step);
self
}
pub const fn continuing_after_failure(mut self, enabled: bool) -> Self {
self.continue_after_failure = enabled;
self
}
pub async fn execute(&self, link: &LinkClient) -> PlanReport {
let mut report = PlanReport::default();
for step in &self.steps {
let result = link
.request(step.request.clone(), step.queue, step.retry)
.await;
let expectation_met = result
.as_ref()
.is_ok_and(|reply| expectation_matches(&step.expectation, reply));
let exchange_failed = result.is_err();
report.steps.push(StepReport {
name: step.name.clone(),
result,
expectation_met,
});
if (exchange_failed || !expectation_met) && !self.continue_after_failure {
break;
}
}
report
}
}
fn expectation_matches(expectation: &PlanExpectation, reply: &DeviceReply) -> bool {
match expectation {
PlanExpectation::Success => reply.response_code == 0,
PlanExpectation::ResponseCodes(codes) => {
!reply.has_communication_error() && codes.contains(&reply.response_code)
}
PlanExpectation::DataPrefix(prefix) => {
reply.response_code == 0
&& !reply.has_communication_error()
&& reply.data.starts_with(prefix)
}
}
}