1use super::args::{known_keys, opt_usize, str_list};
6use super::catalog::{
7 BrowseReq, CadStepReq, CatalogAddReq, CatalogEditReq, CatalogFillReq, SearchReq,
8};
9use super::layout::{LayoutExportReq, LayoutReq};
10use super::optim::{SwapReq, TolReq};
11use super::trace::{PluginReq, TraceReq};
12use super::{LoadSpec, RpcErr, Session};
13use lensbench_design::dls_spec::{OptimizeParams, ZoomParams};
14use lensbench_project::edit_spec::{EditOp, Ref};
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value};
17use std::path::{Path, PathBuf};
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum LoadHistory {
23 #[default]
25 Clear,
26 Push,
28 Keep,
30}
31
32#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
34pub struct LoadReq {
35 pub file: PathBuf,
36 pub glass_dirs: Vec<PathBuf>,
37 pub lens_catalogs: Vec<PathBuf>,
38 pub cfg: Option<usize>,
40 pub state: Option<String>,
42 pub beam_path: Option<String>,
44 pub history: LoadHistory,
45 pub strict_macros: bool,
46}
47
48#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum GetReq {
52 One(String),
53 Many(Vec<String>),
54}
55
56#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
58pub struct AnalyzeReq {
59 pub cmd: String,
60 pub args: Map<String, Value>,
61}
62
63impl AnalyzeReq {
64 pub fn new(cmd: impl Into<String>, args: Map<String, Value>) -> AnalyzeReq {
66 AnalyzeReq {
67 cmd: cmd.into(),
68 args,
69 }
70 }
71
72 pub(crate) fn parse(p: &Value) -> Result<AnalyzeReq, RpcErr> {
74 let m = p
75 .as_object()
76 .ok_or_else(|| RpcErr::params("params must be an object"))?;
77 let cmd = m
78 .get("cmd")
79 .and_then(Value::as_str)
80 .ok_or_else(|| RpcErr::params("cmd (the analysis name) is needed"))?;
81 let mut args = m.clone();
82 args.remove("cmd");
83 Ok(AnalyzeReq::new(cmd, args))
84 }
85}
86
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct ThermalReq {
91 pub temps: Vec<f64>,
92 #[serde(default, skip_serializing_if = "Vec::is_empty")]
93 pub pressures: Vec<f64>,
94}
95
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98#[serde(tag = "method", content = "params", rename_all = "snake_case")]
99pub enum Request {
100 Load(Box<LoadReq>),
101 Reload {
103 history: LoadHistory,
104 },
105 System,
107 Undo {
109 steps: usize,
110 },
111 Redo {
112 steps: usize,
113 },
114 History,
115 Get(GetReq),
116 Set {
118 values: Vec<(String, f64)>,
119 },
120 Write {
122 path: PathBuf,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
124 thermal: Option<ThermalReq>,
125 },
126 Edit {
128 ops: Vec<EditOp>,
129 },
130 Surfaces,
132 SurfaceData {
134 surface: Ref,
135 },
136 SystemData,
138 ConfigTable,
140 Configs,
142 WriteBack {
144 ops: Vec<EditOp>,
145 },
146 Save {
148 path: PathBuf,
149 },
150 SaveRange {
152 path: PathBuf,
153 from: usize,
154 to: usize,
155 },
156 Analyze(Box<AnalyzeReq>),
158 Layout(Box<LayoutReq>),
160 LayoutExport(Box<LayoutExportReq>),
162 Preview {
165 load: Box<LoadReq>,
166 layout: Box<LayoutReq>,
167 },
168 Trace(Box<TraceReq>),
170 Plugin(Box<PluginReq>),
172 Optimize(Box<OptimizeParams>),
174 Swap(Box<SwapReq>),
176 Tolerance(Box<TolReq>),
178 Zoom(Box<ZoomParams>),
180 Ping,
182 Describe,
184 Shutdown,
186 Surface {
188 surface: Ref,
189 },
190 ConfigDiff,
192 SaveProject {
194 path: PathBuf,
195 },
196 Plugins,
198 AnalysisArgs {
200 cmd: String,
201 },
202 Glasses(BrowseReq),
204 Lenses(BrowseReq),
206 CatalogSearch(Box<SearchReq>),
208 CatalogAdd(Box<CatalogAddReq>),
210 CatalogItems {
212 catalog: String,
213 },
214 CatalogEdit(Box<CatalogEditReq>),
216 CatalogFill(Box<CatalogFillReq>),
218 CadStep(Box<CadStepReq>),
220 Json {
222 method: String,
223 params: Value,
224 },
225}
226
227impl Request {
228 pub fn json(method: impl Into<String>, params: Value) -> Request {
230 Request::Json {
231 method: method.into(),
232 params,
233 }
234 }
235
236 pub fn method(&self) -> &str {
238 match self {
239 Request::Load(_) => "load",
240 Request::Reload { .. } => "reload",
241 Request::System => "system",
242 Request::Undo { .. } => "undo",
243 Request::Redo { .. } => "redo",
244 Request::History => "history",
245 Request::Get(_) => "get",
246 Request::Set { .. } => "set",
247 Request::Write { .. } => "write",
248 Request::Edit { .. } => "edit",
249 Request::Surfaces => "surface",
250 Request::SurfaceData { .. } => "surface_data",
251 Request::SystemData => "system_data",
252 Request::ConfigTable => "config_table",
253 Request::Configs => "configs",
254 Request::WriteBack { .. } => "write_back",
255 Request::Save { .. } => "save",
256 Request::SaveRange { .. } => "save_range",
257 Request::Analyze(_) => "analyze",
258 Request::Layout(_) => "layout",
259 Request::LayoutExport(_) => "layout_export",
260 Request::Preview { .. } => "preview",
261 Request::Trace(_) => "trace",
262 Request::Plugin(_) => "plugin",
263 Request::Optimize(_) => "optimize",
264 Request::Swap(_) => "swap",
265 Request::Tolerance(_) => "tolerance",
266 Request::Zoom(_) => "zoom",
267 Request::Ping => "ping",
268 Request::Describe => "describe",
269 Request::Shutdown => "shutdown",
270 Request::Surface { .. } => "surface",
271 Request::ConfigDiff => "config_diff",
272 Request::SaveProject { .. } => "save_project",
273 Request::Plugins => "plugins",
274 Request::AnalysisArgs { .. } => "analysis_args",
275 Request::Glasses(_) => "glasses",
276 Request::Lenses(_) => "lenses",
277 Request::CatalogSearch(_) => "catalog_search",
278 Request::CatalogAdd(_) => "catalog_add",
279 Request::CatalogItems { .. } => "catalog_items",
280 Request::CatalogEdit(_) => "catalog_edit",
281 Request::CatalogFill(_) => "catalog_fill",
282 Request::CadStep(_) => "cad_step",
283 Request::Json { method, .. } => method,
284 }
285 }
286
287 pub fn from_json(method: &str, p: &Value) -> Result<Request, super::CallError> {
290 super::catch_panic(|| Request::parse(method, p)).map_err(super::CallError::from)
291 }
292
293 pub(crate) fn parse(method: &str, p: &Value) -> Result<Request, RpcErr> {
295 Ok(match method {
296 "load" => Request::Load(Box::new(LoadReq::parse(p)?)),
297 "reload" => Request::Reload {
298 history: load_history(p)?,
299 },
300 "system" => Request::System,
301 "undo" => Request::Undo { steps: steps(p)? },
302 "redo" => Request::Redo { steps: steps(p)? },
303 "history" => Request::History,
304 "get" => Request::Get(match p.get("param").and_then(Value::as_str) {
305 Some(one) => GetReq::One(one.to_string()),
306 None => {
307 let list = p["params"]
308 .as_array()
309 .ok_or_else(|| RpcErr::params("get needs param or params (a list)"))?;
310 let names = list
311 .iter()
312 .map(|x| {
313 x.as_str()
314 .map(str::to_string)
315 .ok_or_else(|| RpcErr::params("params must be a list of strings"))
316 })
317 .collect::<Result<_, _>>()?;
318 GetReq::Many(names)
319 }
320 }),
321 "set" => Request::Set {
322 values: set_values(p)?,
323 },
324 "write" => Request::Write {
325 path: path_of(p, "write needs path")?,
326 thermal: match &p["thermal"] {
327 Value::Null => None,
328 v => Some(
329 serde_json::from_value(v.clone())
330 .map_err(|e| RpcErr::params(format!("thermal: {e}")))?,
331 ),
332 },
333 },
334 "edit" => Request::Edit {
335 ops: lensbench_project::edit_ops::parse(&p["ops"]).map_err(RpcErr::params)?,
336 },
337 "surface" if p.get("surface").is_none_or(Value::is_null) => Request::Surfaces,
338 "surface" => Request::Surface {
339 surface: surface_ref(p, "surface")?,
340 },
341 "surface_data" => Request::SurfaceData {
342 surface: surface_ref(p, "surface_data")?,
343 },
344 "system_data" => Request::SystemData,
345 "config_table" => Request::ConfigTable,
346 "configs" => Request::Configs,
347 "write_back" => Request::WriteBack {
348 ops: lensbench_project::edit_ops::parse(&p["ops"])?,
349 },
350 "save" => Request::Save {
351 path: path_of(p, "save needs path")?,
352 },
353 "save_range" => {
354 let path = path_of(p, "save_range needs path")?;
355 let num = |k: &str| {
356 p[k].as_u64().map(|x| x as usize).ok_or_else(|| {
357 RpcErr::params(format!("save_range needs {k} (a surface number)"))
358 })
359 };
360 Request::SaveRange {
361 path,
362 from: num("from")?,
363 to: num("to")?,
364 }
365 }
366 "analyze" => Request::Analyze(Box::new(AnalyzeReq::parse(p)?)),
367 "layout" => Request::Layout(Box::new(LayoutReq::parse(p)?)),
368 "layout_export" => Request::LayoutExport(Box::new(LayoutExportReq::parse(p)?)),
369 "trace" => Request::Trace(Box::new(TraceReq::parse(p)?)),
370 "plugin" => Request::Plugin(Box::new(PluginReq::parse(p)?)),
371 "optimize" => Request::Optimize(Box::new(
372 lensbench_design::dls_spec::read(p)
373 .map_err(|e| RpcErr::params(format!("optimize: {e}")))?,
374 )),
375 "swap" => Request::Swap(Box::new(SwapReq::parse(p)?)),
376 "tolerance" => Request::Tolerance(Box::new(TolReq::parse(p)?)),
377 "zoom" => Request::Zoom(Box::new(
378 lensbench_design::dls_spec::read(p)
379 .map_err(|e| RpcErr::params(format!("zoom: {e}")))?,
380 )),
381 "ping" => Request::Ping,
382 "describe" => Request::Describe,
383 "shutdown" => Request::Shutdown,
384 "config_diff" => Request::ConfigDiff,
385 "save_project" => Request::SaveProject {
386 path: path_of(p, "save_project needs path")?,
387 },
388 "plugins" => Request::Plugins,
389 "analysis_args" => Request::AnalysisArgs {
390 cmd: p["cmd"]
391 .as_str()
392 .ok_or_else(|| RpcErr::params("analysis_args needs cmd"))?
393 .to_string(),
394 },
395 "glasses" | "lenses" => {
396 let r = BrowseReq::parse(method, p)?;
397 if method == "glasses" {
398 Request::Glasses(r)
399 } else {
400 Request::Lenses(r)
401 }
402 }
403 "catalog_search" => Request::CatalogSearch(Box::new(SearchReq::parse(p)?)),
404 "catalog_add" => Request::CatalogAdd(Box::new(CatalogAddReq::parse(p)?)),
405 "catalog_items" => Request::CatalogItems {
406 catalog: super::catalog::catalog_of("catalog_items", p)?,
407 },
408 "catalog_edit" => Request::CatalogEdit(Box::new(CatalogEditReq::parse(p)?)),
409 "catalog_fill" => Request::CatalogFill(Box::new(CatalogFillReq::parse(p)?)),
410 "cad_step" => Request::CadStep(Box::new(CadStepReq::parse(p)?)),
411 m => Request::json(m, p.clone()),
412 })
413 }
414}
415
416impl LoadReq {
417 pub(crate) fn parse(p: &Value) -> Result<LoadReq, RpcErr> {
419 let history = load_history(p)?;
420 let file = p["file"]
421 .as_str()
422 .ok_or_else(|| RpcErr::params("load needs file"))?;
423 let keys = [
424 "file",
425 "glass_dirs",
426 "lens_catalogs",
427 "cfg",
428 "state",
429 "beam_path",
430 "history",
431 "strict_macros",
432 ];
433 known_keys(p, &keys)?;
434 let beam_path = match &p["beam_path"] {
435 Value::Null => None,
436 v => Some(
437 v.as_str()
438 .ok_or_else(|| {
439 RpcErr::params("beam_path must be a string (the BS path, e.g. \"TR\")")
440 })?
441 .to_string(),
442 ),
443 };
444 Ok(LoadReq {
445 file: PathBuf::from(file),
446 glass_dirs: str_list(&p["glass_dirs"], "glass_dirs")?,
447 lens_catalogs: str_list(&p["lens_catalogs"], "lens_catalogs")?,
448 cfg: opt_usize(p, "cfg")?,
449 state: p["state"].as_str().map(str::to_string),
450 beam_path,
451 history,
452 strict_macros: match &p["strict_macros"] {
453 Value::Null => false,
454 v => v
455 .as_bool()
456 .ok_or_else(|| RpcErr::params("strict_macros must be true or false"))?,
457 },
458 })
459 }
460
461 pub(crate) fn spec(&self, sess: &Session) -> Result<LoadSpec, RpcErr> {
463 let read_all = |v: &[PathBuf]| -> Result<Vec<PathBuf>, RpcErr> {
464 v.iter().map(|x| sess.files.check_path(x, false)).collect()
465 };
466 Ok(LoadSpec {
467 file: sess.files.check_path(Path::new(&self.file), false)?,
468 glass_dir: read_all(&self.glass_dirs)?,
469 lens_catalog: read_all(&self.lens_catalogs)?,
470 cfg: self.cfg.unwrap_or(1),
471 state: self.state.clone(),
472 path: self.beam_path.clone(),
473 names: lensbench_project::open::ArgNames::SERVE,
474 strict_macros: self.strict_macros,
475 })
476 }
477}
478
479fn load_history(p: &Value) -> Result<LoadHistory, RpcErr> {
480 Ok(match p.get("history").and_then(Value::as_str) {
481 None | Some("clear") => LoadHistory::Clear,
482 Some("push") => LoadHistory::Push,
483 Some("keep") => LoadHistory::Keep,
484 Some(x) => {
485 return Err(RpcErr::params(format!(
486 "history must be clear, push or keep ({x})"
487 )))
488 }
489 })
490}
491
492fn steps(p: &Value) -> Result<usize, RpcErr> {
493 Ok(opt_usize(p, "steps")?.unwrap_or(1).max(1))
494}
495
496fn set_values(p: &Value) -> Result<Vec<(String, f64)>, RpcErr> {
497 let bad = || RpcErr::params("set needs values (\"3.t\": 10.0, or [[\"3.t\", 10.0]])");
498 match p.get("values") {
499 Some(Value::Object(m)) => m
500 .iter()
501 .map(|(k, v)| Ok((k.clone(), v.as_f64().ok_or_else(bad)?)))
502 .collect(),
503 Some(Value::Array(a)) => a
504 .iter()
505 .map(|x| {
506 let k = x.get(0).and_then(Value::as_str).ok_or_else(bad)?;
507 let v = x.get(1).and_then(Value::as_f64).ok_or_else(bad)?;
508 Ok((k.to_string(), v))
509 })
510 .collect(),
511 _ => Err(bad()),
512 }
513}
514
515fn surface_ref(p: &Value, method: &str) -> Result<Ref, RpcErr> {
517 Ok(match p.get("surface") {
518 Some(Value::String(t)) => Ref::Name(t.clone()),
519 Some(v) => Ref::Index(
520 v.as_u64()
521 .map(|x| x as usize)
522 .ok_or_else(|| RpcErr::params("surface must be a surface number or name"))?,
523 ),
524 None => {
526 debug_assert_eq!(method, "surface_data");
527 return Err(RpcErr::params("surface_data needs surface"));
528 }
529 })
530}
531
532fn path_of(p: &Value, missing: &str) -> Result<PathBuf, RpcErr> {
533 p["path"]
534 .as_str()
535 .map(PathBuf::from)
536 .ok_or_else(|| RpcErr::params(missing))
537}
538
539#[cfg(test)]
540mod tests {
541 use super::*;
542 use serde_json::json;
543
544 #[test]
546 fn parsed_requests_survive_serde() {
547 let cases = [
548 ("glasses", json!({ "glass_dirs": "g" })),
549 (
550 "lenses",
551 json!({ "glass_dirs": ["g"], "lens_catalogs": ["c"] }),
552 ),
553 (
554 "catalog_search",
555 json!({ "kinds": ["splitter"], "specs": ["efl>=10"], "fits": 25.4 }),
556 ),
557 (
558 "catalog_add",
559 json!({ "catalog": "u.json", "name": " A ", "block": "L1", "replace": true }),
560 ),
561 ("catalog_items", json!({ "catalog": "u.json" })),
562 (
563 "catalog_edit",
564 json!({ "catalog": "u.json", "name": "A", "rename": " B ", "delete": false }),
565 ),
566 (
567 "catalog_fill",
568 json!({ "catalog": "c.json", "out": "o.json", "item": "X", "thickness": 3.0,
569 "diameter": [10, 20], "spec": { "thickness": 3.0 } }),
570 ),
571 ("cad_step", json!({ "catalog": "c.json", "item": "X" })),
572 ("surface", json!({ "surface": 3 })),
573 ("analysis_args", json!({ "cmd": "spot" })),
574 ("save_project", json!({ "path": "p.json" })),
575 (
576 "layout",
577 json!({ "plane": "3d", "fields": "all", "waves": [1, 2], "fan": "ring",
578 "color": "CFG", "cfgs": [1, 3], "offset": [0, 1, 2] }),
579 ),
580 (
581 "layout_export",
582 json!({ "file": "a.svg", "width": 800, "tube": 0.1 }),
583 ),
584 (
585 "trace",
586 json!({ "px": [0.0, 0.5], "py": [0.0, 0.0], "field": 2, "global": true }),
587 ),
588 (
589 "plugin",
590 json!({ "name": "p", "config": { "a": 1, "b": "x", "c": [1, 2], "d": true },
591 "inputs": { "m": [[1, 2], [3, 4]] } }),
592 ),
593 ("analyze", json!({ "cmd": "spot", "field": 1 })),
594 (
595 "optimize",
596 json!({ "vars": ["8.t", "7.t=0.5:3"], "merit": "spot", "configs": [1, "B"] }),
597 ),
598 ("zoom", json!({ "vars": ["G2.shift"], "efl": [50, null] })),
599 ("swap", json!({ "slots": [{ "block": "A" }], "top": 3 })),
600 ("tolerance", json!({ "configs": [1], "trials": 10 })),
601 (
602 "load",
603 json!({ "file": "a.zmx", "glass_dirs": ["g"], "cfg": 2, "strict_macros": true }),
604 ),
605 ("reload", json!({})),
606 ("undo", json!({ "steps": 2 })),
607 ("get", json!({ "param": "3.t" })),
608 ("get", json!({ "params": ["3.t", "4.c"] })),
609 ("set", json!({ "values": { "3.t": 10.0 } })),
610 ("write", json!({ "path": "a.zmx" })),
611 (
612 "write",
613 json!({ "path": "a.zmx", "thermal": { "temps": [-20, 60], "pressures": [1, 0.5] } }),
614 ),
615 (
616 "edit",
617 json!({ "ops": [{ "op": "set_stop", "surface": 1 }] }),
618 ),
619 (
620 "write_back",
621 json!({ "ops": [{ "op": "set_stop", "surface": 1 }] }),
622 ),
623 ("save", json!({ "path": "a.json" })),
624 (
625 "save_range",
626 json!({ "path": "a.json", "from": 1, "to": 3 }),
627 ),
628 ("surface_data", json!({ "surface": 2 })),
629 ];
630 for (m, p) in cases {
631 let r = Request::parse(m, &p).unwrap_or_else(|e| panic!("{m}: {}", e.msg));
632 assert_eq!(r.method(), m);
633 assert!(!matches!(r, Request::Json { .. }), "{m}");
634 let back: Request = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
635 assert_eq!(back, r, "{m}");
636 }
637 match Request::parse(
638 "catalog_add",
639 &json!({ "catalog": "u.json", "name": " A ", "block": "L1" }),
640 ) {
641 Ok(Request::CatalogAdd(r)) => {
642 assert_eq!(
643 (r.name.as_str(), r.blocks.as_slice()),
644 ("A", &["L1".to_string()][..])
645 )
646 }
647 r => panic!("{:?}", r.map_err(|e| e.msg)),
648 }
649 match Request::parse("layout", &json!({ "color": "CFG", "cfgs": [1, 3] })) {
650 Ok(Request::Layout(r)) => {
651 assert_eq!(
652 (r.color.as_deref(), r.cfgs.as_deref()),
653 (Some("cfg"), Some("1,3"))
654 )
655 }
656 r => panic!("{:?}", r.map_err(|e| e.msg)),
657 }
658 match Request::parse(
659 "plugin",
660 &json!({ "name": "p", "inputs": { "m": [[1, 2], [3, 4]] } }),
661 ) {
662 Ok(Request::Plugin(r)) => {
663 assert_eq!(
664 (r.inputs[0].shape.as_slice(), r.inputs[0].data.len()),
665 (&[2, 2][..], 4)
666 )
667 }
668 r => panic!("{:?}", r.map_err(|e| e.msg)),
669 }
670 let e = Request::parse("layout", &json!({ "fields": [0.5] })).unwrap_err();
672 assert_eq!(e.msg, "fields must be numbers from 1 or \"all\"");
673 let e = Request::parse("layout_export", &json!({})).unwrap_err();
674 assert_eq!(e.msg, "layout_export needs file");
675 let e = Request::parse("analyze", &json!({})).unwrap_err();
676 assert_eq!(e.msg, "cmd (the analysis name) is needed");
677 let e = Request::parse("catalog_search", &json!({ "kinds": ["nope"] })).unwrap_err();
678 assert_eq!(e.msg, "kinds: unknown kind nope");
679 let e = Request::parse("catalog_items", &json!({})).unwrap_err();
680 assert_eq!(e.msg, "catalog_items needs catalog (the user catalog file)");
681 let e = Request::parse("glasses", &json!({ "lens_catalogs": [] })).unwrap_err();
682 assert!(e.msg.starts_with("unknown key lens_catalogs"), "{}", e.msg);
683 }
684}