diff --git a/contract/CONTRACT.md b/contract/CONTRACT.md index f098028..a6625de 100644 --- a/contract/CONTRACT.md +++ b/contract/CONTRACT.md @@ -349,50 +349,13 @@ incl. Pyfa's mass / capacity / volume / radius attributes), `effects` [{id, name (Pyfa Traits tab HTML), `required_skills` {skill id: level} (cases `type_*`; MKT-003, ENG-SHIP-006, CHR-008; a case's `_fields` param lists the fields it scores). -## `compute` (unified entry, `exfa/compute@1`) - -One input object produces one output object; the engine stays workspace/group-agnostic and only sees fully -resolved fits (no host-side `fit_id` / `character_id` references). Available as the `compute` RPC method -(`params` = the request envelope), the `exfa compute [FILE]` CLI (file or stdin → one JSON line on stdout, -exit 2 on an error envelope), and `exfa_core::compute_json` / `exfa_core::compute::compute` (WASM gets the RPC -method for free). - -```jsonc -// request -{"format": "exfa/compute@1", "operation": "calc", "fit": { /* FitSpec */ }} -{"format": "exfa/compute@1", "operation": "batch", "batch": { /* BatchSpec */ }} -// response -{"format": "exfa/compute-result@1", "operation": "calc", "result": { /* FitStats */ }} -{"format": "exfa/compute-result@1", "operation": "batch", "result": { /* BatchResponse */ }} -{"format": "exfa/compute-result@1", "operation": "calc", "error": {"code": "...", "message": "...", "path": "..."}} -``` - -- A missing or non-`"exfa/compute@1"` `format` → `UNSUPPORTED_FORMAT`; a missing or non-`"calc"`/`"batch"` - `operation` → `BAD_REQUEST`; inner calc/batch failures keep their `code`/`message`/`path` inside the error - envelope. A top-level JSON parse failure still answers with the error envelope (`BAD_JSON`; `operation` - echoed when recoverable from the raw text, else `"calc"`). `compute_json` never panics. -- `batch` is exactly the docs/23 BatchRequest (`batch_version`, exactly one of `fits`/`variants`/`product`/ - `sweep`, `fields`, `deltas`, `delta_ref`, `filter`, `sort_by`, `top_n`, `max_combinations`, price layers); - expansion, per-item errors and the `fits[]` item `id`/`label` echo behave as before. - -**FitSpec = FitRequest + stable ids + shorthand normalization.** +## Item ids and `select` - `modules[]`, `drones[]` and `fighters[]` entries take an optional string `id` (a stable caller-chosen id; ignored everywhere except `select`, below). -- Shorthand defaults (applied by the `compute` entry point only — `calc`/`batch`/`graph` keep the existing - FitRequest defaults; explicit values always win, so `default_level: 0` stays 0): - - `character.skills.default_level` omitted → `5` (an omitted `character` is the same); - - `modules[].state` omitted → `"active"` when the type can be activated (has an active or target effect and - `activationBlocked` ≤ 0 — the `type` RPC `allowed_states` rule), else `"online"`; an unknown type is left - alone so the usual error reports it; - - `drones[].active` omitted → `quantity` (every drone active); `fighters[].active` already defaults true; - - everything else uses the existing FitRequest defaults at build time. -- Normalization recurses into every nested FitRequest (`projected[kind=fit].fit`, `fleet.booster_fits[]`, - `scenarios[].target.fit`). Under `operation=calc` each defaulted category is reported once as an - `adjustments[]` entry `{"code": "DEFAULTED", "path": "/character/skills/default_level" | "/modules/*/state" | - "/drones/*/active", "from": null, "to": , "message": "compute shorthand - default applied"}` (top-level fit only). Under `operation=batch` the `base` and each `fits[].fit` are - normalized silently *before* expansion, so patches act on a fully normalized base. +- The engine applies no input shorthand: an omitted `character.skills.default_level` is 0, an omitted module + `state` is `online`. Defaults, groups and other host-side conveniences are the caller's (EXFA Format) + concern; the engine only ever sees fully resolved fits. **`select` on `projected[kind=fit]`** chooses which of the source fit's items project onto this fit: @@ -470,3 +433,5 @@ method for free). FIGHTER_TUBES for resource-bar overloads (Pyfa shows these as red bars, not fit problems). - v1.5.0: add top-level `adjustments[]` for silent request normalization and optional `scenarios[]` / `scenario_results[]` for fixed-target effective damage; scenario failures are isolated per result. +- 2026-11-08: the `exfa/compute@1` envelope, the `compute` RPC method and the `exfa compute` CLI command are + removed (they only added shorthand defaults, now the caller's job). `select` and item `id`s are unchanged. diff --git a/crates/exfa-cli/src/main.rs b/crates/exfa-cli/src/main.rs index a4606df..64fb083 100644 --- a/crates/exfa-cli/src/main.rs +++ b/crates/exfa-cli/src/main.rs @@ -9,11 +9,10 @@ const USAGE: &str = "exfa [args] (dataset compiled in; --dataset PAT Commands: calc [FILE] FitRequest JSON (file or stdin) -> FitStats JSON - compute [FILE] exfa/compute@1 envelope (file or stdin) -> one exfa/compute-result@1 JSON line batch JSONL FitRequests on stdin -> JSONL FitStats on stdout (a BatchRequest line -> one BatchResponse line) batch --request FILE|- BatchRequest JSON (docs/23: fits / variants / product / sweep) -> BatchResponse JSON optimize [FILE] OptimizeRequest JSON (docs/21) -> ranked fits - serve-stdio JSONL RPC: {\"id\":..,\"method\":\"calc|batch|compute|prices_load|version|sde_override|optimize|graph|search|type|meta|eft_parse|eft_export|format_import|format_export|fits.backup|item.variations|item.compare|market.group|market.search|implant_sets.list|character.import_evemon|names.resolve|pyfa_data_load|pyfa_data_status\",\"params\":..} + serve-stdio JSONL RPC: {\"id\":..,\"method\":\"calc|batch|prices_load|version|sde_override|optimize|graph|search|type|meta|eft_parse|eft_export|format_import|format_export|fits.backup|item.variations|item.compare|market.group|market.search|implant_sets.list|character.import_evemon|names.resolve|pyfa_data_load|pyfa_data_status\",\"params\":..} eft [FILE] EFT text (file or stdin) -> FitRequest JSON (add --calc to compute, --skills N) search QUERY [--limit N] [--kinds ship,module,..] search types by name (exact > prefix > substring) type ID|NAME show type with base attributes @@ -120,15 +119,6 @@ fn main() { std::process::exit(2); } } - "compute" => { - let s = read_input(args.get(1)); - let res = exfa_core::compute_json(&s); - writeln!(out, "{res}").or_pipe(); - out.flush().or_pipe(); - if serde_json::from_str::(&res).ok().and_then(|v| v.get("error").cloned()).is_some() { - std::process::exit(2); - } - } "batch" => { if let Some(f) = take_flag(&mut args, "--request") { let res = exfa_core::batch_json(&read_input(Some(&f))); diff --git a/crates/exfa-core/src/compute.rs b/crates/exfa-core/src/compute.rs deleted file mode 100644 index 845dd1e..0000000 --- a/crates/exfa-core/src/compute.rs +++ /dev/null @@ -1,212 +0,0 @@ -//! Unified compute envelope `exfa/compute@1` -> `exfa/compute-result@1` (docs/27 §5.3): ONE input object, -//! ONE output object. `operation=calc` takes a `FitSpec` and returns FitStats; `operation=batch` takes a -//! `BatchSpec` (the existing BatchRequest) and returns the BatchResponse. The workspace/group semantics and -//! host-side references stay outside; the engine only sees fully resolved fits. -//! -//! FitSpec = FitRequest + stable equipment `id`s (modules/drones/fighters, used by -//! `projected[kind=fit].select`) + shorthand normalization, applied by this entry point only: omitted -//! `character.skills.default_level` = 5, omitted module `state` = `active` when the type can activate else -//! `online`, omitted drone `active` = `quantity` (fighters already default active). Explicit values win -//! (`default_level: 0` stays 0). Normalization recurses into every nested FitRequest (`projected[kind=fit].fit`, -//! `fleet.booster_fits[]`, `scenarios[].target.fit`); for `operation=calc` the top-level defaults are reported -//! as `DEFAULTED` adjustments, for `operation=batch` the same rules apply silently before expansion. -use crate::data::{self as d, a}; -use crate::j::J; -use crate::jv; -use crate::request::{FitRequest, State}; -use serde_json::{json, Value}; -use std::ops::IndexMut; - -pub const FORMAT: &str = "exfa/compute@1"; -pub const RESULT_FORMAT: &str = "exfa/compute-result@1"; - -fn err_env(op: &str, code: &str, message: impl Into, path: &str) -> Value { - json!({"format": RESULT_FORMAT, "operation": op, "error": {"code": code, "message": message.into(), "path": path}}) -} - -/// Best-effort `operation` for the error envelope of an unparseable request. -fn recover_op(s: &str) -> Option { - let k = s.find("\"operation\"")? + "\"operation\"".len(); - let rest = s[k..].trim_start().strip_prefix(':')?.trim_start().strip_prefix('"')?; - rest.find('"').map(|e| rest[..e].to_string()) -} - -/// The engine-side `state` shorthand default (Pyfa isValidState, same rule as `type` RPC `allowed_states`): -/// `active` when the type has an activatable effect (category 1|2) and `activationBlocked` <= 0, else `online`. -/// Unknown types stay `None` so the existing error path reports them. -fn state_default(type_id: u32) -> Option { - let ty = d::type_index(type_id)?; - let can_active = d::type_effects(ty).iter().any(|&x| matches!(d::EFF_META[(x >> 1) as usize].cat, 1 | 2)) - && d::type_attr(ty, a::activationBlocked).unwrap_or(0.0) <= 0.0; - Some(if can_active { State::Active } else { State::Online }) -} - -/// Defaults applied to the top-level fit (calc reports them as `DEFAULTED` adjustments). -#[derive(Default)] -struct Notes { - default_level: bool, - module_states: Vec, - drone_actives: Vec, -} - -/// Normalize a FitSpec in place, recursing into every nested FitRequest. Notes are recorded for the -/// top-level fit only (the existing convention: `adjustments` reports the top-level request). -fn normalize(req: &mut FitRequest, top: bool, notes: &mut Notes) { - if req.character.skills.default_level.is_none() { - req.character.skills.default_level = Some(5); - if top { - notes.default_level = true; - } - } - for m in &mut req.modules { - if m.state.is_none() { - if let Some(st) = state_default(m.type_id) { - m.state = Some(st); - if top { - notes.module_states.push(st); - } - } - } - } - for dr in &mut req.drones { - if dr.active.is_none() { - dr.active = Some(dr.quantity); - if top { - notes.drone_actives.push(dr.quantity); - } - } - } - for bf in &mut req.fleet.booster_fits { - normalize(bf, false, notes); - } - for p in &mut req.projected { - if p.kind == "fit" { - if let Some(f) = p.fit.as_deref_mut() { - normalize(f, false, notes); - } - } - } - if let Some(Value::Array(list)) = req.scenarios.as_mut() { - for s in list.iter_mut() { - if let Some(v) = s.get_mut("target").and_then(|t| t.get_mut("fit")).filter(|v| v.is_object()) { - normalize_fit_json(v); - } - } - } -} - -/// Normalize a FitSpec held as JSON (batch base / fits[].fit / scenario target.fit); on a shape error the -/// value is left as-is so the downstream path reports it. -fn normalize_fit_json(v: &mut Value) { - if let Ok(mut req) = serde_json::from_value::(v.clone()) { - normalize(&mut req, false, &mut Notes::default()); - if let Ok(nv) = serde_json::to_value(&req) { - *v = nv; - } - } -} - -/// One `DEFAULTED` adjustment per defaulted category (wildcard paths cover every defaulted item; `to` lists -/// the applied values in request order). -fn defaulted_adjustments(n: &Notes) -> Vec { - let mut v = Vec::new(); - if n.default_level { - v.push(jv!({"code": "DEFAULTED", "path": "/character/skills/default_level", "from": J::Null, "to": 5u8, "message": "compute shorthand default applied"})); - } - if !n.module_states.is_empty() { - v.push(jv!({"code": "DEFAULTED", "path": "/modules/*/state", "from": J::Null, "to": n.module_states.clone(), "message": "compute shorthand default applied"})); - } - if !n.drone_actives.is_empty() { - v.push(jv!({"code": "DEFAULTED", "path": "/drones/*/active", "from": J::Null, "to": n.drone_actives.clone(), "message": "compute shorthand default applied"})); - } - v -} - -/// Wrap an inner `{"error": {...}}` output (calc or batch) into the error envelope, keeping its code/message/path. -fn inner_error(op: &str, e: &Value) -> Value { - let mut e = e.clone(); - if let Some(m) = e.as_object_mut() { - m.entry("path").or_insert(json!("")); - } - json!({"format": RESULT_FORMAT, "operation": op, "error": e}) -} - -fn calc_op(input: &Value) -> Value { - let fit_v = match input.get("fit") { - Some(v) if v.is_object() => v.clone(), - _ => return err_env("calc", "BAD_REQUEST", "fit must be a FitRequest object", "/fit"), - }; - let mut req: FitRequest = match serde_json::from_value(fit_v) { - Ok(r) => r, - Err(e) => return err_env("calc", "BAD_REQUEST", e.to_string(), "/fit"), - }; - let mut notes = Notes::default(); - normalize(&mut req, true, &mut notes); - let mut out = crate::calc(&req); - if let J::O(o) = &out { - if let Some((_, e)) = o.iter().find(|(k, _)| k.as_ref() == "error") { - return inner_error("calc", &e.to_value_raw()); - } - } - if let J::O(_) = &out { - let adj = out.index_mut("adjustments"); - if !matches!(adj, J::A(_)) { - *adj = J::A(Vec::new()); - } - if let J::A(a) = adj { - a.extend(defaulted_adjustments(¬es)); - } - } - let result = if req.options.full_precision { out.to_value_raw() } else { serde_json::to_value(&out).unwrap_or(Value::Null) }; - json!({"format": RESULT_FORMAT, "operation": "calc", "result": result}) -} - -fn batch_op(input: &Value) -> Value { - let mut b = match input.get("batch") { - Some(v) if v.is_object() => v.clone(), - _ => return err_env("batch", "BAD_REQUEST", "batch must be a BatchRequest object", "/batch"), - }; - // FitSpec shorthand applies to the base and every explicit fit BEFORE expansion, so patches act on a - // fully normalized base and there is no shorthand-vs-normalized ambiguity downstream. - if let Some(v) = b.get_mut("base").filter(|v| v.is_object()) { - normalize_fit_json(v); - } - if let Some(fits) = b.get_mut("fits").and_then(Value::as_array_mut) { - for it in fits.iter_mut() { - if let Some(v) = it.get_mut("fit").filter(|v| v.is_object()) { - normalize_fit_json(v); - } - } - } - let r = crate::batch::run(&b); - match r.get("error") { - Some(e) => inner_error("batch", e), - None => json!({"format": RESULT_FORMAT, "operation": "batch", "result": r}), - } -} - -/// `compute` params (`exfa/compute@1`) -> `exfa/compute-result@1`. -pub fn compute(input: &Value) -> Value { - if input.get("format").and_then(Value::as_str) != Some(FORMAT) { - let op = input.get("operation").and_then(Value::as_str).unwrap_or("calc"); - return err_env(op, "UNSUPPORTED_FORMAT", "format must be \"exfa/compute@1\"", "/format"); - } - let op = input.get("operation").and_then(Value::as_str).unwrap_or(""); - match op { - "calc" => calc_op(input), - "batch" => batch_op(input), - _ => err_env(if op.is_empty() { "calc" } else { op }, "BAD_REQUEST", "operation must be \"calc\" or \"batch\"", "/operation"), - } -} - -/// JSON string in, JSON string out; never panics and always answers with the result envelope. -pub fn compute_json(input: &str) -> String { - let v = match serde_json::from_str::(input) { - Ok(v) => compute(&v), - Err(e) => { - let op = recover_op(input).unwrap_or_else(|| "calc".into()); - err_env(&op, "BAD_JSON", e.to_string(), "") - } - }; - serde_json::to_string(&v).unwrap_or_default() -} diff --git a/crates/exfa-core/src/engine.rs b/crates/exfa-core/src/engine.rs index cad1bdf..ee1e8b9 100644 --- a/crates/exfa-core/src/engine.rs +++ b/crates/exfa-core/src/engine.rs @@ -120,7 +120,7 @@ pub struct Item { pub distance: Option, /// mutated (rolled) attributes: request overrides do not replace them (Pyfa reads mutators after overrides) pub rolled: Vec, - /// stable caller-chosen id (FitSpec `id` on modules/drones/fighters; projected-fit `select` refers to it) + /// stable caller-chosen id (`id` on modules/drones/fighters; projected-fit `select` refers to it) pub id: Option, } @@ -1509,7 +1509,7 @@ impl Fit { } } for (sf, amount, dist, select) in &self.ext { - // `select` = explicit whitelist of source items by their FitSpec id: a kind whose list is absent + // `select` = explicit whitelist of source items by their `id`: a kind whose list is absent // contributes nothing, a present list contributes only its active items whose id is in it. The // source fit itself was built completely, so unselected items still shape the source's attributes. let mut unmatched: Vec<(&'static str, &str)> = Vec::new(); diff --git a/crates/exfa-core/src/lib.rs b/crates/exfa-core/src/lib.rs index dbd2d89..a91879b 100644 --- a/crates/exfa-core/src/lib.rs +++ b/crates/exfa-core/src/lib.rs @@ -6,7 +6,6 @@ //! The SDE dataset is compiled into this crate by `build.rs`: the `sde` static tables plus the generated //! Rust code for every effect's modifiers. `calc(request) -> stats` is pure: no I/O, no clocks, no global state, no data loading. pub mod capsim; -pub mod compute; pub mod model; pub mod sde; pub mod data; @@ -243,12 +242,6 @@ pub fn batch_json(s: &str) -> String { batch::run_json(s) } -/// Unified compute envelope `exfa/compute@1` (docs/27 §5.3): JSON string in, one -/// `exfa/compute-result@1` JSON line out; never panics (any failure is the error envelope). -pub fn compute_json(input: &str) -> String { - compute::compute_json(input) -} - /// JSONL RPC line: {"id","method","params"} -> {"id","result"} pub fn rpc(line: &str) -> Value { let v: Value = match serde_json::from_str(line) { @@ -264,7 +257,6 @@ pub fn rpc(line: &str) -> Value { Err(e) => json!({"error": {"code": "BAD_REQUEST", "message": e.to_string()}}), }, "batch" | "calc_batch" => batch::run(&p), - "compute" => compute::compute(&p), "prices_load" => prices_load(&p), "version" => prov::version(), "sde_override" => prov::sde_override(&p), diff --git a/crates/exfa-core/src/model.rs b/crates/exfa-core/src/model.rs index bcf3352..dafcca4 100644 --- a/crates/exfa-core/src/model.rs +++ b/crates/exfa-core/src/model.rs @@ -53,7 +53,7 @@ pub struct Mutation { #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct ModuleReq { pub type_id: u32, - /// Stable caller-chosen id (exfa/compute@1 FitSpec): `projected[kind=fit].select.module_ids` refers to it. + /// Stable caller-chosen id: `projected[kind=fit].select.module_ids` refers to it. #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option, #[serde(default)] @@ -71,7 +71,7 @@ pub struct ModuleReq { #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct DroneReq { pub type_id: u32, - /// Stable caller-chosen id (FitSpec): `projected[kind=fit].select.drone_ids` refers to it. + /// Stable caller-chosen id: `projected[kind=fit].select.drone_ids` refers to it. #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option, #[serde(default = "one")] @@ -88,7 +88,7 @@ fn one() -> u32 { #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct FighterReq { pub type_id: u32, - /// Stable caller-chosen id (FitSpec): `projected[kind=fit].select.fighter_ids` refers to it. + /// Stable caller-chosen id: `projected[kind=fit].select.fighter_ids` refers to it. #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option, #[serde(default)] @@ -153,7 +153,7 @@ pub struct Fleet { pub booster_fits: Vec, } -/// Whitelist of source items a `projected[kind=fit]` entry projects (FitSpec): present = explicit selection, +/// Whitelist of source items a `projected[kind=fit]` entry projects: present = explicit selection, /// so a kind whose id list is absent contributes nothing. The source fit is still computed in full. #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct Select { diff --git a/crates/exfa-core/tests/compute.rs b/crates/exfa-core/tests/compute.rs deleted file mode 100644 index e1b3e7e..0000000 --- a/crates/exfa-core/tests/compute.rs +++ /dev/null @@ -1,196 +0,0 @@ -//! exfa/compute@1 -> exfa/compute-result@1 (docs/27 §5.3): envelope, FitSpec shorthand normalization, -//! batch normalization-first, projected-fit `select`, and error envelopes. -use serde_json::{json, Value}; - -fn compute(req: Value) -> Value { - serde_json::from_str(&exfa_core::compute_json(&req.to_string())).unwrap() -} -fn calc_result(fit: Value) -> Value { - compute(json!({"format": "exfa/compute@1", "operation": "calc", "fit": fit})) -} -fn calc_raw(fit: &Value) -> Value { - let r: exfa_core::FitRequest = serde_json::from_value(fit.clone()).unwrap(); - serde_json::to_value(exfa_core::calc(&r)).unwrap() -} -/// Stats equality ignoring `adjustments` (compute calc may append DEFAULTED entries). -fn stats_eq(a: &Value, b: &Value) -> bool { - let (mut a, mut b) = (a.clone(), b.clone()); - for v in [&mut a, &mut b] { - v.as_object_mut().unwrap().remove("adjustments"); - } - a == b -} -fn velocity(r: &Value) -> f64 { - r["result"]["navigation"]["max_velocity"].as_f64().unwrap() -} - -#[test] -fn shorthand_equals_explicit_and_defaulted_adjustments() { - // 439 = 1MN Afterburner I (activatable): omitted state -> "active", omitted skills -> all 5. - let short = calc_result(json!({"ship": {"type_id": 587}, "modules": [{"type_id": 439}]})); - let explicit = calc_result( - json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, "modules": [{"type_id": 439, "state": "active"}]}), - ); - assert!(stats_eq(&short["result"], &explicit["result"]), "shorthand == explicit {}", short); - let adj = short["result"]["adjustments"].as_array().unwrap(); - assert!(adj.iter().any(|a| a["code"] == "DEFAULTED" && a["path"] == "/character/skills/default_level" && a["to"] == 5)); - assert!(adj.iter().any(|a| a["code"] == "DEFAULTED" && a["path"] == "/modules/*/state" && a["to"] == json!(["active"]))); - assert_eq!(explicit["result"]["adjustments"].as_array().unwrap().len(), 0); - // a module that cannot activate (519 = Gyrostabilizer II) defaults to "online", not "active" - let passive = calc_result(json!({"ship": {"type_id": 587}, "modules": [{"type_id": 519}]})); - assert_eq!(passive["result"]["modules"][0]["state"], "online"); - assert_eq!(velocity(&short), velocity(&explicit)); -} - -#[test] -fn explicit_values_always_win() { - let v_short = velocity(&calc_result(json!({"ship": {"type_id": 587}, "modules": [{"type_id": 439}]}))); - // explicit all-0 / online is preserved (not upgraded to 5 / active) - let zero = calc_result( - json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 0}}, "modules": [{"type_id": 439, "state": "online"}]}), - ); - assert_eq!(zero["result"]["adjustments"].as_array().unwrap().len(), 0); - assert_eq!(zero["result"]["modules"][0]["state"], "online"); - assert!(velocity(&zero) < v_short, "online+0 skills is slower than active+5"); - // and equals the raw calc of the same explicit request - assert!(stats_eq( - &zero["result"], - &calc_raw(&json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 0}}, "modules": [{"type_id": 439, "state": "online"}]})) - )); -} - -#[test] -fn drone_active_defaults_to_quantity() { - // 2185 = Hammerhead II - let short = calc_result(json!({"ship": {"type_id": 587}, "drones": [{"type_id": 2185, "quantity": 5}]})); - let explicit = calc_result(json!({"ship": {"type_id": 587}, "drones": [{"type_id": 2185, "quantity": 5, "active": 5}]})); - assert_eq!(short["result"]["drones"]["active"], 5); - assert!(stats_eq(&short["result"], &explicit["result"])); - assert!(short["result"]["adjustments"].as_array().unwrap().iter().any(|a| a["path"] == "/drones/*/active")); - let parked = calc_result(json!({"ship": {"type_id": 587}, "drones": [{"type_id": 2185, "quantity": 5, "active": 0}]})); - assert_eq!(parked["result"]["drones"]["active"], 0, "explicit active:0 preserved"); -} - -#[test] -fn batch_fits_normalize_and_echo_ids() { - let fit_a = json!({"ship": {"type_id": 587}, "modules": [{"type_id": 439}]}); - let fit_b = json!({"ship": {"type_id": 585}}); - let r = compute(json!({"format": "exfa/compute@1", "operation": "batch", "batch": { - "batch_version": 1, "fits": [{"id": "a", "label": "A", "fit": fit_a}, {"id": "b", "fit": fit_b}]}})); - assert_eq!(r["operation"], "batch"); - let res = r["result"]["results"].as_array().unwrap(); - assert_eq!(res.len(), 2); - assert_eq!(res[0]["id"], "a"); - assert_eq!(res[0]["label"], "A"); - assert_eq!(res[1]["id"], "b"); - assert_eq!(res[1]["label"], "b"); - // each untrimmed stats equals calc of the same normalized fit (with the shorthand defaults applied) - let norm_a = json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, "modules": [{"type_id": 439, "state": "active"}]}); - let norm_b = json!({"ship": {"type_id": 585}, "character": {"skills": {"default_level": 5}}}); - assert_eq!(res[0]["stats"], calc_raw(&norm_a)); - assert_eq!(res[1]["stats"], calc_raw(&norm_b)); - // normalization is silent inside batch: no DEFAULTED adjustments on item stats - assert_eq!(res[0]["stats"]["adjustments"].as_array().unwrap().len(), 0); -} - -#[test] -fn batch_variants_on_normalized_base() { - let r = compute(json!({"format": "exfa/compute@1", "operation": "batch", "batch": { - "batch_version": 1, "base": {"ship": {"type_id": 587}, "modules": [{"type_id": 439}]}, - "variants": [ - {"id": "kept", "patch": []}, - {"id": "down", "patch": [{"op": "replace", "path": "/modules/0/state", "value": "online"}]} - ]}})); - let res = r["result"]["results"].as_array().unwrap(); - assert_eq!(res.len(), 2); - let norm = json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, "modules": [{"type_id": 439, "state": "active"}]}); - let mut down = norm.clone(); - down["modules"][0]["state"] = json!("online"); - assert_eq!(res[0]["stats"], calc_raw(&norm)); - assert_eq!(res[1]["stats"], calc_raw(&down)); - assert!(res[0]["stats"]["navigation"]["max_velocity"].as_f64() > res[1]["stats"]["navigation"]["max_velocity"].as_f64()); -} - -/// Source fit: two active Stasis Webifier I (526), stable ids m1/m2. -fn web_source() -> Value { - json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, - "modules": [{"id": "m1", "type_id": 526, "state": "active"}, {"id": "m2", "type_id": 526, "state": "active"}]}) -} -fn projected(select: Value) -> Value { - let mut e = json!({"kind": "fit", "fit": web_source()}); - if !select.is_null() { - e["select"] = select; - } - calc_result(json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, "projected": [e]})) -} - -#[test] -fn projected_fit_select_whitelist() { - let v_none = velocity(&projected(Value::Null)); - let v_m1 = velocity(&projected(json!({"module_ids": ["m1"]}))); - let v_both = velocity(&projected(json!({"module_ids": ["m1", "m2"]}))); - let v_empty = velocity(&projected(json!({"module_ids": []}))); - assert!(v_none < v_m1 && v_m1 < v_empty, "one web slows less than two, none slows not at all: {v_none} {v_m1} {v_empty}"); - assert_eq!(v_both, v_none, "selecting both == no select"); - // select m1 == a source that only carries m1 - let only_m1 = calc_result(json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, - "projected": [{"kind": "fit", "fit": {"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, - "modules": [{"id": "m1", "type_id": 526, "state": "active"}]}}]})); - assert_eq!(v_m1, velocity(&only_m1), "select m1 == source with only m1"); - // unselected kinds contribute nothing: drone list present-but-empty + no module list -> no modules - let v_drones_only = velocity(&projected(json!({"drone_ids": []}))); - assert_eq!(v_drones_only, v_empty, "absent module_ids contributes no modules"); - // unmatched id -> one deduplicated warning, the matched id still projects - let miss = projected(json!({"module_ids": ["m1", "nope"]})); - assert_eq!(velocity(&miss), v_m1); - let w = miss["result"]["warnings"].as_array().unwrap(); - assert_eq!(w.iter().filter(|x| **x == "projected fit select: no module item with id 'nope'").count(), 1); - // select on kind != fit is ignored (warning, no error) - let other = calc_result(json!({"ship": {"type_id": 587}, "projected": [ - {"kind": "module", "module": {"type_id": 526, "state": "active"}, "select": {"module_ids": ["x"]}}]})); - assert!(other["result"]["error"].is_null()); - assert!(other["result"]["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap_or("").contains("select"))); -} - -#[test] -fn error_envelopes() { - let bad_format = compute(json!({"format": "nope", "operation": "calc", "fit": {}})); - assert_eq!(bad_format["format"], "exfa/compute-result@1"); - assert_eq!(bad_format["error"]["code"], "UNSUPPORTED_FORMAT"); - for op in [json!("bogus"), json!(null)] { - let r = compute(json!({"format": "exfa/compute@1", "operation": op})); - assert_eq!(r["error"]["code"], "BAD_REQUEST", "{op}"); - } - // inner fit error propagates with its code/message/path - let inner = calc_result(json!({"ship": {"type_id": 999999999}})); - assert_eq!(inner["operation"], "calc"); - assert_eq!(inner["error"]["code"], "UNKNOWN_TYPE"); - assert_eq!(inner["error"]["path"], "/ship/type_id"); - // missing fit / batch payloads - assert_eq!(compute(json!({"format": "exfa/compute@1", "operation": "calc"}))["error"]["code"], "BAD_REQUEST"); - assert_eq!(compute(json!({"format": "exfa/compute@1", "operation": "batch"}))["error"]["code"], "BAD_REQUEST"); - // malformed JSON still returns the error envelope (operation recovered when possible) - let malformed: Value = serde_json::from_str(&exfa_core::compute_json("{bad \"operation\":\"batch\"}")).unwrap(); - assert_eq!(malformed["format"], "exfa/compute-result@1"); - assert_eq!(malformed["operation"], "batch"); - assert!(malformed["error"]["code"].is_string()); - let no_op: Value = serde_json::from_str(&exfa_core::compute_json("{bad")).unwrap(); - assert_eq!(no_op["operation"], "calc"); -} - -#[test] -fn rpc_method_and_full_precision() { - let p = json!({"format": "exfa/compute@1", "operation": "calc", "fit": {"ship": {"type_id": 587}, "modules": [{"type_id": 439}]}}); - let r = exfa_core::rpc(&json!({"id": 7, "method": "compute", "params": p}).to_string()); - assert_eq!(r["id"], 7); - assert_eq!(r["result"]["format"], "exfa/compute-result@1"); - assert!(r["result"]["result"]["navigation"]["max_velocity"].is_number()); - // options.full_precision inside the FitSpec still takes the raw path: unrounded floats - let p = json!({"format": "exfa/compute@1", "operation": "calc", "fit": {"ship": {"type_id": 587}, "options": {"full_precision": true}}}); - let v = compute(p)["result"]["capacitor"]["peak_recharge_gj_s"].as_f64().unwrap(); - let rounded = compute(json!({"format": "exfa/compute@1", "operation": "calc", "fit": {"ship": {"type_id": 587}}}))["result"]["capacitor"]["peak_recharge_gj_s"] - .as_f64() - .unwrap(); - assert_eq!(rounded, (v * 1e6).round() / 1e6, "raw path keeps >6 decimals: {v} vs {rounded}"); - assert!(v != rounded, "full_precision bypasses the 6-decimal rounding"); -} diff --git a/crates/exfa-core/tests/select.rs b/crates/exfa-core/tests/select.rs new file mode 100644 index 0000000..28a6449 --- /dev/null +++ b/crates/exfa-core/tests/select.rs @@ -0,0 +1,67 @@ +//! `projected[kind=fit].select` (item-id whitelist) and `options.full_precision` through `calc` / the `calc` RPC. +use serde_json::{json, Value}; + +fn calc(fit: Value) -> Value { + let r: exfa_core::FitRequest = serde_json::from_value(fit).unwrap(); + if r.options.full_precision { + exfa_core::calc(&r).to_value_raw() + } else { + serde_json::to_value(exfa_core::calc(&r)).unwrap() + } +} +fn velocity(r: &Value) -> f64 { + r["navigation"]["max_velocity"].as_f64().unwrap() +} + +/// Source fit: two active Stasis Webifier I (526), stable ids m1/m2. +fn web_source() -> Value { + json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, + "modules": [{"id": "m1", "type_id": 526, "state": "active"}, {"id": "m2", "type_id": 526, "state": "active"}]}) +} +fn projected(select: Value) -> Value { + let mut e = json!({"kind": "fit", "fit": web_source()}); + if !select.is_null() { + e["select"] = select; + } + calc(json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, "projected": [e]})) +} + +#[test] +fn projected_fit_select_whitelist() { + let v_none = velocity(&projected(Value::Null)); + let v_m1 = velocity(&projected(json!({"module_ids": ["m1"]}))); + let v_both = velocity(&projected(json!({"module_ids": ["m1", "m2"]}))); + let v_empty = velocity(&projected(json!({"module_ids": []}))); + assert!(v_none < v_m1 && v_m1 < v_empty, "one web slows less than two, none slows not at all: {v_none} {v_m1} {v_empty}"); + assert_eq!(v_both, v_none, "selecting both == no select"); + // select m1 == a source that only carries m1 + let only_m1 = calc(json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, + "projected": [{"kind": "fit", "fit": {"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, + "modules": [{"id": "m1", "type_id": 526, "state": "active"}]}}]})); + assert_eq!(v_m1, velocity(&only_m1), "select m1 == source with only m1"); + // unselected kinds contribute nothing: drone list present-but-empty + no module list -> no modules + let v_drones_only = velocity(&projected(json!({"drone_ids": []}))); + assert_eq!(v_drones_only, v_empty, "absent module_ids contributes no modules"); + // unmatched id -> one deduplicated warning, the matched id still projects + let miss = projected(json!({"module_ids": ["m1", "nope"]})); + assert_eq!(velocity(&miss), v_m1); + let w = miss["warnings"].as_array().unwrap(); + assert_eq!(w.iter().filter(|x| **x == "projected fit select: no module item with id 'nope'").count(), 1); + // select on kind != fit is ignored (warning, no error) + let other = calc(json!({"ship": {"type_id": 587}, "projected": [ + {"kind": "module", "module": {"type_id": 526, "state": "active"}, "select": {"module_ids": ["x"]}}]})); + assert!(other["error"].is_null()); + assert!(other["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap_or("").contains("select"))); +} + +#[test] +fn rpc_calc_and_full_precision() { + let r = exfa_core::rpc(&json!({"id": 7, "method": "calc", "params": {"ship": {"type_id": 587}, "modules": [{"type_id": 439}]}}).to_string()); + assert_eq!(r["id"], 7); + assert!(r["result"]["navigation"]["max_velocity"].is_number()); + // options.full_precision takes the raw path: unrounded floats + let v = calc(json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}, "options": {"full_precision": true}}))["capacitor"]["peak_recharge_gj_s"].as_f64().unwrap(); + let rounded = calc(json!({"ship": {"type_id": 587}, "character": {"skills": {"default_level": 5}}}))["capacitor"]["peak_recharge_gj_s"].as_f64().unwrap(); + assert_eq!(rounded, (v * 1e6).round() / 1e6, "raw path keeps >6 decimals: {v} vs {rounded}"); + assert!(v != rounded, "full_precision bypasses the 6-decimal rounding"); +}