Skip to main content

sim_lib_auto_order/
conformance.rs

1//! Modeled work-order conformance runner.
2
3use std::{collections::BTreeSet, sync::Arc};
4
5use sim_kernel::{
6    CapabilityName, Consistency, Cx, Error, EvalFabric, EvalMode, EvalRequest, Expr, Result, Symbol,
7};
8use sim_lib_auto_core::{
9    AUTO_DIAGNOSTICS_READ, AUTO_FLASH, AUTO_ORDER, AUTO_SERVICE_WRITE, SiteManifest, VehicleId,
10};
11use sim_lib_auto_parts::{OrderStatus, Supplier};
12use sim_lib_auto_vendor::{
13    ModeledVendorBridge, VendorEffectClass, VendorGateLedger, VendorSiteFabric, autotuner_manifest,
14    biluppgifter_se_manifest, esitronic_manifest, flash_site_cassettes, haynespro_manifest,
15    ista_manifest, manifest_operation, mekonomen_pro_manifest, odis_manifest, oem_site_cassettes,
16    supplier_site_cassettes, vendor_irreversible_request_expr, vendor_request_expr, vida_manifest,
17    xentry_manifest,
18};
19
20use crate::{
21    ConformanceReport, LedgerInvoiceExport, WorkOrder, WorkOrderEvent, model::WorkOrderEventInput,
22};
23
24/// Runs the public modeled automotive work-order conformance story.
25pub fn run_modeled_conformance(cx: &mut Cx) -> Result<ConformanceReport> {
26    run_modeled_conformance_with_parent_grants(cx, default_parent_grants())
27}
28
29/// Runs conformance with an explicit parent grant set.
30pub fn run_modeled_conformance_with_parent_grants(
31    cx: &mut Cx,
32    parent_grants: Vec<CapabilityName>,
33) -> Result<ConformanceReport> {
34    ModeledWorkOrderEngine::new(parent_grants).run(cx)
35}
36
37/// Returns the site labels covered by the modeled conformance story.
38pub fn expected_modeled_sites() -> Vec<&'static str> {
39    vec![
40        "xentry",
41        "ista",
42        "vida",
43        "odis",
44        "esitronic",
45        "haynespro",
46        "biluppgifter-se",
47        "mekonomen-pro",
48        "autotuner",
49    ]
50}
51
52/// Manifest-driven engine for a modeled work-order conformance story.
53#[derive(Clone, Debug)]
54pub struct ModeledWorkOrderEngine {
55    parent_grants: Vec<CapabilityName>,
56}
57
58impl ModeledWorkOrderEngine {
59    /// Builds an engine with the parent session grants.
60    pub fn new(parent_grants: Vec<CapabilityName>) -> Self {
61        Self { parent_grants }
62    }
63
64    /// Runs the conformance story.
65    pub fn run(&self, cx: &mut Cx) -> Result<ConformanceReport> {
66        cx.require_all(&self.parent_grants)?;
67        let mut work_order = WorkOrder::new(
68            "SIM-WO-MBTECH-1",
69            VehicleId::new("modeled-se", "vehicle-alpha"),
70            self.parent_grants.clone(),
71        );
72        let mut issues = Vec::new();
73        let mut delegation_violations = Vec::new();
74        let expected_sites = expected_modeled_sites();
75
76        for story in site_stories() {
77            self.run_story(
78                cx,
79                story,
80                &mut work_order,
81                &mut issues,
82                &mut delegation_violations,
83            )?;
84        }
85
86        if let Some(order) = &work_order.order_status {
87            work_order.invoice = Some(LedgerInvoiceExport::for_work_order(
88                &work_order.id,
89                order,
90                &work_order.parts,
91                90,
92            ));
93        } else {
94            issues.push("mekonomen-pro order/place did not produce an order status".to_owned());
95        }
96
97        let seen_sites = work_order.ledger.sites();
98        for expected in &expected_sites {
99            if !seen_sites.contains(*expected) {
100                issues.push(format!("missing modeled site {expected}"));
101            }
102        }
103        if !has_denial(&work_order, "xentry", "code/sca", AUTO_SERVICE_WRITE) {
104            issues.push("missing denied xentry code/sca event".to_owned());
105        }
106        if !has_denial(&work_order, "autotuner", "flash/write", AUTO_FLASH) {
107            issues.push("missing denied autotuner flash/write event".to_owned());
108        }
109
110        Ok(ConformanceReport::new(
111            work_order,
112            expected_sites.len(),
113            delegation_violations,
114            issues,
115        ))
116    }
117
118    fn run_story(
119        &self,
120        cx: &mut Cx,
121        story: SiteStory,
122        work_order: &mut WorkOrder,
123        issues: &mut Vec<String>,
124        delegation_violations: &mut Vec<String>,
125    ) -> Result<()> {
126        let bridge = Arc::new(ModeledVendorBridge::with_cassettes(all_cassettes()));
127        let gate_ledger = Arc::new(VendorGateLedger::new());
128        let fabric = VendorSiteFabric::with_gate_ledger(
129            story.manifest.clone(),
130            bridge,
131            Arc::clone(&gate_ledger),
132        );
133        for operation in story.operations {
134            let operation_policy = manifest_operation(&story.manifest, operation)?;
135            let delegated = self.delegated_grants(&operation_policy.capability);
136            let before = gate_ledger.records()?.len();
137            let outcome = fabric.realize(
138                cx,
139                request(operation, &operation_policy.effect, delegated.clone()),
140            );
141            let event = match outcome {
142                Ok(_) => {
143                    if let Some(violation) =
144                        delegated_violation(&delegated, &self.parent_grants, operation)
145                    {
146                        delegation_violations.push(violation);
147                    }
148                    if operation == "order/place" {
149                        work_order.order_status = Some(OrderStatus::accepted(
150                            "SIM-ORDER-MBTECH-1",
151                            Supplier::MekonomenProModeled,
152                            work_order.parts.len() as u32,
153                        ));
154                    }
155                    WorkOrderEvent::from_input(WorkOrderEventInput {
156                        site: story.manifest.site.clone(),
157                        operation: operation.to_owned(),
158                        lane: operation_policy.lane.name,
159                        capability: operation_policy.capability,
160                        effect: operation_policy.effect.as_str().to_owned(),
161                        outcome: "accepted".to_owned(),
162                        note: gate_note(&gate_ledger, before)?,
163                        delegated_capabilities: delegated,
164                    })
165                }
166                Err(Error::CapabilityDenied { capability }) => {
167                    WorkOrderEvent::from_input(WorkOrderEventInput {
168                        site: story.manifest.site.clone(),
169                        operation: operation.to_owned(),
170                        lane: operation_policy.lane.name,
171                        capability: operation_policy.capability,
172                        effect: operation_policy.effect.as_str().to_owned(),
173                        outcome: "denied".to_owned(),
174                        note: format!("denied missing {}", capability.as_str()),
175                        delegated_capabilities: delegated,
176                    })
177                }
178                Err(err) => {
179                    issues.push(format!(
180                        "{} {} failed: {err}",
181                        story.manifest.site, operation
182                    ));
183                    WorkOrderEvent::from_input(WorkOrderEventInput {
184                        site: story.manifest.site.clone(),
185                        operation: operation.to_owned(),
186                        lane: operation_policy.lane.name,
187                        capability: operation_policy.capability,
188                        effect: operation_policy.effect.as_str().to_owned(),
189                        outcome: "failed".to_owned(),
190                        note: err.to_string(),
191                        delegated_capabilities: delegated,
192                    })
193                }
194            };
195            work_order.ledger.push(event);
196        }
197        Ok(())
198    }
199
200    fn delegated_grants(&self, required: &CapabilityName) -> Vec<CapabilityName> {
201        if self.parent_grants.iter().any(|grant| grant == required) {
202            vec![required.clone()]
203        } else {
204            Vec::new()
205        }
206    }
207}
208
209fn default_parent_grants() -> Vec<CapabilityName> {
210    vec![
211        CapabilityName::new(AUTO_DIAGNOSTICS_READ),
212        CapabilityName::new(AUTO_ORDER),
213    ]
214}
215
216#[derive(Clone, Debug)]
217struct SiteStory {
218    manifest: SiteManifest,
219    operations: Vec<&'static str>,
220}
221
222impl SiteStory {
223    fn new(manifest: SiteManifest, operations: Vec<&'static str>) -> Self {
224        Self {
225            manifest,
226            operations,
227        }
228    }
229}
230
231fn site_stories() -> Vec<SiteStory> {
232    vec![
233        SiteStory::new(
234            xentry_manifest(),
235            vec![
236                "read/dtc",
237                "info/wis-procedure",
238                "parts/epc-lookup",
239                "code/sca",
240            ],
241        ),
242        SiteStory::new(
243            ista_manifest(),
244            vec!["read/dtc", "info/test-plan", "code/coding"],
245        ),
246        SiteStory::new(vida_manifest(), vec!["read/dtc", "info/procedure"]),
247        SiteStory::new(odis_manifest(), vec!["service/guided-function"]),
248        SiteStory::new(esitronic_manifest(), vec!["read/dtc", "info/procedure"]),
249        SiteStory::new(
250            haynespro_manifest(),
251            vec!["read/identity", "info/procedure"],
252        ),
253        SiteStory::new(biluppgifter_se_manifest(), vec!["read/plate-lookup"]),
254        SiteStory::new(
255            mekonomen_pro_manifest(),
256            vec!["parts/catalog-lookup", "order/status", "order/place"],
257        ),
258        SiteStory::new(autotuner_manifest(), vec!["flash/write"]),
259    ]
260}
261
262fn all_cassettes() -> Vec<sim_lib_auto_vendor::ModeledVendorCassette> {
263    oem_site_cassettes()
264        .into_iter()
265        .chain(supplier_site_cassettes())
266        .chain(flash_site_cassettes())
267        .collect()
268}
269
270fn request(
271    operation: &str,
272    effect: &VendorEffectClass,
273    required_capabilities: Vec<CapabilityName>,
274) -> EvalRequest {
275    let expr = if *effect == VendorEffectClass::Irreversible {
276        vendor_irreversible_request_expr(
277            operation,
278            story_args(),
279            reversal_artifact(operation),
280            "modeled-work-order-warrant",
281        )
282    } else {
283        vendor_request_expr(operation, story_args())
284    };
285    EvalRequest {
286        expr,
287        result_shape: None,
288        required_capabilities,
289        deadline: None,
290        consistency: Consistency::LocalFirst,
291        mode: EvalMode::Eval,
292        answer_limit: None,
293        stream_buffer: None,
294        stream: false,
295        trace: false,
296    }
297}
298
299fn story_args() -> Expr {
300    Expr::Map(vec![
301        string_field("work-order", "SIM-WO-MBTECH-1"),
302        string_field("vehicle", "modeled-se/vehicle-alpha"),
303    ])
304}
305
306fn reversal_artifact(operation: &str) -> Expr {
307    Expr::Map(vec![
308        (
309            Expr::Symbol(Symbol::new("content-key")),
310            Expr::String(format!("stock-map-before-{operation}")),
311        ),
312        (
313            Expr::Symbol(Symbol::new("bytes")),
314            Expr::Bytes(operation.as_bytes().to_vec()),
315        ),
316    ])
317}
318
319fn string_field(name: &str, value: &str) -> (Expr, Expr) {
320    (
321        Expr::Symbol(Symbol::new(name.to_owned())),
322        Expr::String(value.to_owned()),
323    )
324}
325
326fn gate_note(ledger: &VendorGateLedger, before: usize) -> Result<String> {
327    let records = ledger.records()?;
328    if records.len() > before {
329        Ok(format!("vendor gate recorded {}", records.len() - before))
330    } else {
331        Ok("pure manifest reply".to_owned())
332    }
333}
334
335fn delegated_violation(
336    delegated: &[CapabilityName],
337    parent_grants: &[CapabilityName],
338    operation: &str,
339) -> Option<String> {
340    let parent = parent_grants.iter().collect::<BTreeSet<_>>();
341    delegated
342        .iter()
343        .find(|capability| !parent.contains(*capability))
344        .map(|capability| {
345            format!(
346                "{operation} delegated {} outside parent grant set",
347                capability.as_str()
348            )
349        })
350}
351
352fn has_denial(work_order: &WorkOrder, site: &str, operation: &str, capability: &str) -> bool {
353    work_order.ledger.events.iter().any(|event| {
354        event.site == site
355            && event.operation == operation
356            && event.capability == capability
357            && event.denied()
358    })
359}