Skip to main content

lensbench_engine/
session.rs

1//! serve の場([`Session`]): 系を読み込んだまま、JSON の要求(method と params)で系の変更・解析を繰り返す。
2//!
3//! 書式は docs/serve.md。要求を運ぶ道(TCP・パイプ・共有メモリ、1 行 1 要求の JSON-RPC)は CLI の `serve` が持ち、
4//! 同じプロセスの GUI・Web 版は [`Session::call`] を直接呼ぶ。要点:
5//!
6//! - 系は場に 1 つ。要求は場ごとに 1 つずつ順に処理する
7//! - 解析(`analyze`)は解析の登録簿の解析で、CLI のサブコマンドと同じ設定・同じ結果。系はファイルを読まず、読み込んだ系を使う
8
9use lensbench_core::{LockExt, RwLockExt};
10use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Mutex};
13use web_time::Instant;
14
15use lensbench_core::coating::C64;
16use lensbench_core::history::History;
17use lensbench_core::system::Launch;
18use lensbench_core::System;
19use lensbench_export::d2::Plane;
20use lensbench_formats::zmx_write;
21use serde_json::{json, Map, Value};
22
23use crate::load::{read_file_notes, Faces, ReadFile, SysSpec as LoadSpec};
24use lensbench_project::open::Source;
25use lensbench_project::retarget::Retarget;
26use lensbench_project::{BlockSpans, FaceId};
27
28/// 要求で与えたパスの扱い
29pub enum Files {
30    /// そのまま読み書きする(localhost だけで待ち受け、--root なし)
31    Any,
32    /// このフォルダ(正規化済み)の下だけ
33    Root(PathBuf),
34    /// 読み書きしない(--allow-remote で --root なし)
35    Deny,
36}
37
38/// 評価関数の項(1 つか並び)の zplm のファイル・フォルダを [`Files::check_path`] で確かめる。ファイルを限っているとき
39/// (--root・--allow-remote)は、既定の場所(LENSBENCH_MACROS・今のフォルダ)を探さない
40impl Files {
41    /// 評価関数の項の zplm のファイル・フォルダを確かめる(CLI の optimize・tolerance の項のファイルにも)
42    pub fn check_terms(&self, t: &mut Value) -> lensbench_core::Result<()> {
43        Ok(self.check_term_paths(t).map_err(|e| e.msg)?)
44    }
45
46    pub(crate) fn check_term_paths(&self, t: &mut Value) -> Result<(), RpcErr> {
47        let limited = !matches!(self, Files::Any);
48        let items: Vec<&mut Value> = match t {
49            Value::Array(a) => a.iter_mut().collect(),
50            x => vec![x],
51        };
52        for x in items {
53            let Some(o) = x.as_object_mut() else { continue };
54            let ty = o.get("type").and_then(Value::as_str).unwrap_or_default();
55            if !ty.eq_ignore_ascii_case("zplm") {
56                continue;
57            }
58            if let Some(f) = o.get_mut("file") {
59                if let Some(p) = f.as_str() {
60                    *f = json!(self.check_path(Path::new(p), false)?.to_string_lossy());
61                }
62            }
63            if let Some(Value::Array(ds)) = o.get_mut("macro_dirs") {
64                for d in ds.iter_mut() {
65                    if let Some(p) = d.as_str() {
66                        *d = json!(self.check_path(Path::new(p), false)?.to_string_lossy());
67                    }
68                }
69            }
70            if limited {
71                o.insert("default_dirs".into(), json!(false));
72            }
73        }
74        Ok(())
75    }
76
77    /// 要求で与えたパスを確かめて、使うパスを返す(write は書き出し)
78    pub(crate) fn check_path(&self, p: &Path, write: bool) -> Result<PathBuf, RpcErr> {
79        match self {
80        Files::Any => Ok(p.to_path_buf()),
81        Files::Deny => Err(RpcErr::app(format!(
82            "{}: with --allow-remote, requests don't read or write files (limit the place with --root to allow it)",
83            p.display()
84        ))),
85        Files::Root(root) => {
86            let q = if p.is_absolute() {
87                p.to_path_buf()
88            } else {
89                root.join(p)
90            };
91            let bad = || RpcErr::app(format!("{} is outside --root", p.display()));
92            // 在るものは実体(シンボリックリンクの先)で、書き出す新しいファイルはフォルダの実体で確かめる
93            let real = match q.canonicalize() {
94                Ok(r) => r,
95                Err(_) if write => {
96                    let name = q.file_name().filter(|n| *n != "..").ok_or_else(bad)?;
97                    let dir = q.parent().ok_or_else(bad)?;
98                    let dir = dir.canonicalize().map_err(|e| {
99                        RpcErr::app(format!("{}: {e}", dir.display()))
100                    })?;
101                    dir.join(name)
102                }
103                Err(e) => return Err(RpcErr::app(format!("{}: {e}", p.display()))),
104            };
105            if real.starts_with(root) {
106                Ok(real)
107            } else {
108                Err(bad())
109            }
110        }
111    }
112    }
113}
114
115/// 読み込んだ後の変更(干渉の解析で、別の構成・状態の光束にも同じ変更を当てる)
116#[derive(Clone)]
117enum Change {
118    /// set: (名前, 変える前の値, 値)
119    Set(Vec<(String, f64, f64)>),
120    /// edit の ops
121    Edit(Vec<lensbench_project::edit_ops::EditOp>),
122}
123
124struct Served {
125    sys: Arc<System>,
126    spec: LoadSpec,
127    /// 読んだときのファイル(別の構成・状態・経路はファイルを読み直さずにここから)
128    src: Arc<Source>,
129    /// プロジェクトの id のあるブロック・群ごとの系の面の範囲(読んだときのもの。面を足す・消す edit の後は空)
130    blocks: Arc<Vec<BlockSpans>>,
131    /// プロジェクトの読んだときの系の面ごとの名前(変更の記録 log はこの系からの変更。別の状態・経路へ当て直す)
132    faces: Arc<Faces>,
133    /// 読んだときの注意(load・reload の返事の notes)
134    notes: Vec<String>,
135    log: Vec<Change>,
136    /// 元に戻す・やり直すための前の系と変更の記録。段の名前は変更の短い記述(GUI の一覧の名前)
137    hist: History<Snap, Value>,
138    /// 最後に記録した set の名前と時刻(同じ名前の set が続けば 1 段にまとめる。スライダーのドラッグなど)
139    last_set: Option<(Vec<String>, Instant)>,
140}
141
142/// 読み込んだ系([`Session::current_full`])
143pub(crate) struct Current {
144    /// 読み込んだ後の変更(set・edit)の入った系
145    sys: Arc<System>,
146    spec: LoadSpec,
147    /// 読んだときのファイル
148    src: Arc<Source>,
149    /// 読んだときの系の面ごとの名前
150    faces: Arc<Faces>,
151    /// 読み込んだ後の変更
152    log: Vec<Change>,
153}
154
155/// 読み込んだ .zmx の今の構成(多重構成の表があれば表の今の構成。set_config で替えたものも)
156fn active_cfg(cur: &System, spec: &LoadSpec) -> usize {
157    cur.configs.as_ref().map_or(spec.cfg, |t| t.active)
158}
159
160/// 元に戻す 1 段: 系と読み方、そのときの注意と変更の記録
161#[derive(Clone)]
162struct Snap {
163    sys: Arc<System>,
164    spec: LoadSpec,
165    src: Arc<Source>,
166    blocks: Arc<Vec<BlockSpans>>,
167    faces: Arc<Faces>,
168    notes: Vec<String>,
169    log: Vec<Change>,
170}
171/// 同じ名前の set をまとめる間隔 [s]
172const SET_MERGE_S: f64 = 1.0;
173
174/// serve の 1 つの場: 読み込んだ系・変更の記録・元に戻す段・走っている最適化などの進み具合と、要求で与えたパスの扱い。
175/// 系を変える要求は場ごとに 1 つずつ順に、読むだけの要求([`Access::Read`])は並行に処理する。
176/// 最適化などの長い要求([`Access::Long`])は始めたときの系で回し、その間も他の要求を止めない。TCP・パイプの serve は 1 つの場を全部の接続で共有し、GUI は [`global`] の場を、
177/// 試験は場を別々に作って使う
178pub struct Session {
179    pub(crate) files: Files,
180    served: Mutex<Option<Served>>,
181    /// 系を変える要求は書き、読むだけの要求は読みで取る
182    request: std::sync::RwLock<()>,
183    /// 長い要求(最適化・公差・差し替え探索・ズーム軌跡)を 1 つずつ
184    long: Mutex<()>,
185    /// 最適化の apply で当てる変更(長い要求の計算の後、プールの外で当てる。[`dispatch`])
186    pending_apply: Mutex<Option<PendingApply>>,
187    /// 処理している要求の中断の印(`cancel` で全部倒す)
188    running: Mutex<Vec<lensbench_core::par::CancelToken>>,
189    /// 走っている最適化・公差・差し替え探索の進み具合と中断の印([`optim::Job`])
190    opt_run: optim::JobSlot,
191    tol_run: optim::JobSlot,
192    swap_run: optim::JobSlot,
193}
194
195impl Default for Session {
196    fn default() -> Self {
197        Self::with_files(Files::Any)
198    }
199}
200
201/// プロセスで共通の場(GUI・[`call`] など場を渡さない関数が使う)
202pub fn global() -> &'static Session {
203    static G: std::sync::OnceLock<Session> = std::sync::OnceLock::new();
204    G.get_or_init(Session::default)
205}
206
207impl Session {
208    /// 空の場(要求で与えたパスはそのまま読み書きする)
209    pub fn new() -> Self {
210        Self::default()
211    }
212
213    /// 要求で与えたパスの扱いを決めた空の場
214    pub fn with_files(files: Files) -> Self {
215        Session {
216            files,
217            served: Mutex::new(None),
218            request: std::sync::RwLock::new(()),
219            long: Mutex::new(()),
220            pending_apply: Mutex::new(None),
221            running: Mutex::new(Vec::new()),
222            opt_run: Default::default(),
223            tol_run: Default::default(),
224            swap_run: Default::default(),
225        }
226    }
227
228    /// 系を読んで場に置く(起動の引数で与えた系。要求で与えたパスの扱いは当てない)
229    pub fn open(&self, spec: LoadSpec, threads: Option<usize>) -> lensbench_core::Result<()> {
230        let r = lensbench_core::with_threads(threads, || read_file_notes(&spec))?;
231        store(self, r, spec);
232        Ok(())
233    }
234
235    /// 要求で与えたパスの扱い
236    pub fn files(&self) -> &Files {
237        &self.files
238    }
239
240    /// 要求を 1 つ処理する(要求を運ぶ道から。配列は bin で受け渡す)。panic は誤りにする
241    pub fn handle(
242        &self,
243        method: &str,
244        params: &Value,
245        bins: Vec<Bin>,
246        threads: Option<usize>,
247    ) -> Result<(Value, Vec<Bin>), CallError> {
248        dispatch(self, method, params, bins, threads)
249            .and_then(|(a, b)| Ok((a.into_json()?, b)))
250            .map_err(CallError::from)
251    }
252
253    fn served(&self) -> std::sync::MutexGuard<'_, Option<Served>> {
254        self.served.lock_ok()
255    }
256
257    /// 読み込んだ系
258    pub(crate) fn current_system(&self) -> Result<Arc<System>, RpcErr> {
259        Ok(self.current()?.0)
260    }
261
262    /// 読み込んだ系・読み方・読んだファイル・変更の記録を 1 度に(鍵を持たない長い要求が、間の set で混ざらないように)
263    fn current_full(&self) -> Result<Current, RpcErr> {
264        self.served()
265            .as_ref()
266            .map(|x| Current {
267                sys: x.sys.clone(),
268                spec: x.spec.clone(),
269                src: x.src.clone(),
270                faces: x.faces.clone(),
271                log: x.log.clone(),
272            })
273            .ok_or_else(|| RpcErr::app("no system (load first)"))
274    }
275
276    fn current(&self) -> Result<(Arc<System>, LoadSpec), RpcErr> {
277        self.served()
278            .as_ref()
279            .map(|x| (x.sys.clone(), x.spec.clone()))
280            .ok_or_else(|| RpcErr::app("no system (load first)"))
281    }
282}
283
284/// 読み込んだ系を置く(変更の記録・元に戻す段は空にする)
285fn store(sess: &Session, r: ReadFile, spec: LoadSpec) {
286    *sess.served() = Some(Served {
287        sys: Arc::new(r.sys),
288        spec,
289        src: Arc::new(r.src),
290        blocks: Arc::new(r.blocks),
291        faces: Arc::new(r.faces),
292        notes: r.notes,
293        log: Vec::new(),
294        hist: History::default(),
295        last_set: None,
296    });
297}
298
299/// 読み込んだ系を置く。h が Push なら前の系を段に積み、Keep なら段はそのまま
300fn store_loaded(sess: &Session, r: ReadFile, spec: LoadSpec, h: LoadHistory, reload: bool) {
301    let mut g = sess.served();
302    let Some(mut x) = g.take().filter(|_| h != LoadHistory::Clear) else {
303        drop(g);
304        store(sess, r, spec);
305        return;
306    };
307    if h == LoadHistory::Push {
308        let name = spec
309            .file
310            .file_name()
311            .map(|f| f.to_string_lossy().into_owned())
312            .unwrap_or_default();
313        let what = if reload {
314            json!({ "reload": name })
315        } else {
316            json!({ "open": name })
317        };
318        push_undo(&mut x, what);
319    }
320    x.sys = Arc::new(r.sys);
321    x.spec = spec;
322    x.src = Arc::new(r.src);
323    x.blocks = Arc::new(r.blocks);
324    x.faces = Arc::new(r.faces);
325    x.notes = r.notes;
326    x.log = Vec::new();
327    x.last_set = None;
328    *g = Some(x);
329}
330
331mod answer;
332use answer::surfaces_view;
333pub use answer::Answer;
334mod request;
335mod run;
336pub use request::{AnalyzeReq, GetReq, LoadHistory, LoadReq, Request, ThermalReq};
337#[path = "session_hist.rs"]
338mod hist;
339
340mod args;
341mod catalog;
342mod layout;
343mod optim;
344mod proto;
345mod replay;
346mod save_project;
347mod trace;
348pub mod views;
349use args::{known_keys, opt_f64, opt_usize, str_list};
350pub use catalog::range_system;
351pub use catalog::{
352    BrowseReq, CadStepReq, CatalogAddReq, CatalogEditReq, CatalogFillReq, SearchReq,
353};
354use hist::{change_label, config_only, history_json, snap_was_load, summary, CONFIG_KEY};
355use layout::{configs, layout, layout_export, layout_with};
356pub use layout::{LayoutExportReq, LayoutReq};
357use optim::{apply_pending, optimize, swap, tolerance, zoom, PendingApply};
358pub use optim::{
359    optimize_cancel, optimize_progress, swap_cancel, swap_progress, tolerance_cancel,
360    tolerance_progress,
361};
362pub use optim::{SwapReq, TolReq};
363pub use proto::{Access, METHODS, PROTOCOL};
364use replay::replay;
365use trace::{plugin, trace};
366pub use trace::{PluginInput, PluginReq, PluginValue, TraceReq};
367
368/// 今の系の写し
369fn snap(x: &Served) -> Snap {
370    Snap {
371        sys: x.sys.clone(),
372        spec: x.spec.clone(),
373        src: x.src.clone(),
374        blocks: x.blocks.clone(),
375        faces: x.faces.clone(),
376        notes: x.notes.clone(),
377        log: x.log.clone(),
378    }
379}
380
381/// 今の系を元に戻す段に積む(深さを超えたら古い段を捨てる。やり直す段は捨てる)
382fn push_undo(x: &mut Served, what: Value) {
383    let s = snap(x);
384    x.hist.record(s, what);
385}
386
387/// 変更した系を置き、変更を記録する。前の系は元に戻す段に積む(やり直す段は空にする)
388fn store_changed(sess: &Session, sys: System, spec: LoadSpec, c: Change) {
389    let mut g = sess.served();
390    // 読み込む前の set・edit は current で断るので、ここには来ない(一度置いた系は外さない)
391    let Some(mut x) = g.take() else {
392        return;
393    };
394    let now = Instant::now();
395    // 構成の切り替えだけの edit が続くときは、間があいても 1 段にまとめる(名前は CONFIG_KEY)
396    let names = match &c {
397        Change::Set(v) => Some(v.iter().map(|r| r.0.clone()).collect::<Vec<_>>()),
398        Change::Edit(o) => config_only(o).then(|| vec![CONFIG_KEY.to_string()]),
399    };
400    let merge = matches!((&names, &x.last_set), (Some(n), Some((m, t))) if n == m
401        && (n[..] == [CONFIG_KEY] || now.duration_since(*t).as_secs_f64() < SET_MERGE_S));
402    let s = snap(&x);
403    x.hist.record_or_merge(s, change_label(Some(&c)), merge);
404    // 面を足す・消すと面の番号がずれるので、ブロックの面の範囲は捨てる
405    if sys.surfaces.len() != x.sys.surfaces.len() || moves_surfaces(&c) {
406        x.blocks = Arc::default();
407    }
408    x.last_set = names.map(|n| (n, now));
409    x.log.push(c);
410    x.sys = Arc::new(sys);
411    x.spec = spec;
412    *g = Some(x);
413}
414
415/// 面を足す・消す edit か(面の番号がずれる)
416fn moves_surfaces(c: &Change) -> bool {
417    use lensbench_project::edit_ops::EditOp as O;
418    matches!(c, Change::Edit(ops) if ops.iter().any(|o| matches!(o, O::InsertSurface { .. } | O::DeleteSurface { .. })))
419}
420
421/// 元に戻す(back)・やり直す。戻した後の系の面の数と、残りの段の数
422fn step_history(sess: &Session, back: bool) -> Result<Value, RpcErr> {
423    let mut g = sess.served();
424    let x = g
425        .as_mut()
426        .ok_or_else(|| RpcErr::app("no system (load first)"))?;
427    let cur = snap(x);
428    let Some(snap) = x.hist.step(cur, back) else {
429        return Err(RpcErr::app(if back {
430            "no change to undo"
431        } else {
432            "no change to redo"
433        }));
434    };
435    let file0 = std::mem::replace(&mut x.spec, snap.spec).file;
436    x.sys = snap.sys;
437    x.src = snap.src;
438    x.blocks = snap.blocks;
439    x.faces = snap.faces;
440    x.notes = snap.notes;
441    x.log = snap.log;
442    x.last_set = None;
443    let hash = lensbench_project::sysfile::system_hash(&x.sys).map_err(RpcErr::app)?;
444    let mut v = history_json(x);
445    v["surfaces"] = json!(x.sys.surfaces.len());
446    v["system_hash"] = json!(hash);
447    // 開く・読み直すを戻したら、戻した系の概要(ファイルが変わる)
448    if x.spec.file != file0 || snap_was_load(&v, back) {
449        v["loaded"] = summary(&x.sys, &x.spec, &x.notes, &x.blocks);
450    }
451    Ok(v)
452}
453
454/// 元に戻せる段・やり直せる段(`history_json`)
455fn history(sess: &Session) -> Value {
456    sess.served()
457        .as_ref()
458        .map_or_else(|| json!(views::HistoryView::default()), history_json)
459}
460
461/// 結果に段の数と一覧を足す
462fn add_history(sess: &Session, v: &mut Value) {
463    if let (Some(o), Value::Object(h)) = (v.as_object_mut(), history(sess)) {
464        o.extend(h);
465    }
466}
467
468/// steps 段まとめて戻す・やり直す(途中で尽きたらそこまで)
469fn step_history_n(sess: &Session, back: bool, n: usize) -> Result<Value, RpcErr> {
470    let mut v = step_history(sess, back)?;
471    let mut loaded = v.get("loaded").is_some();
472    for _ in 1..n {
473        match step_history(sess, back) {
474            Ok(w) => {
475                loaded |= w.get("loaded").is_some();
476                v = w;
477            }
478            Err(_) => break,
479        }
480    }
481    // 途中で開く・読み直すを越えたら、最後の系の概要
482    if loaded && v.get("loaded").is_none() {
483        if let Some(x) = sess.served().as_ref() {
484            v["loaded"] = summary(&x.sys, &x.spec, &x.notes, &x.blocks);
485        }
486    }
487    Ok(v)
488}
489
490/// JSON-RPC のエラー
491pub(crate) struct RpcErr {
492    code: i64,
493    pub(crate) msg: String,
494    /// core の誤りの種類([`lensbench_core::Error::kind`]。返す誤りの `data.kind`)
495    kind: Option<&'static str>,
496    /// core の誤りの符号([`lensbench_core::Error::code`]。返す誤りの `data.code`)
497    ecode: Option<&'static str>,
498}
499
500impl RpcErr {
501    fn app(m: impl Into<String>) -> Self {
502        RpcErr {
503            code: -32000,
504            msg: m.into(),
505            kind: None,
506            ecode: None,
507        }
508    }
509    /// core の誤りの種類と符号を付ける(文を作り直したとき)
510    pub(crate) fn with_core(self, e: &lensbench_core::Error) -> Self {
511        RpcErr {
512            kind: Some(e.kind()),
513            ecode: Some(e.code()),
514            ..self
515        }
516    }
517    pub(crate) fn params(m: impl Into<String>) -> Self {
518        RpcErr {
519            code: -32602,
520            msg: m.into(),
521            kind: None,
522            ecode: None,
523        }
524    }
525}
526
527/// 文字列の誤り(project などの `Err(String)`)は英語で書いてあるので、表示の言語に訳す
528impl From<String> for RpcErr {
529    fn from(m: String) -> Self {
530        RpcErr::app(lensbench_core::i18n::tr(&m))
531    }
532}
533
534impl From<lensbench_core::Error> for RpcErr {
535    fn from(e: lensbench_core::Error) -> Self {
536        RpcErr::app(e.to_string()).with_core(&e)
537    }
538}
539
540/// 展開の誤り(ブロックの名前を文の前に付ける)
541impl From<lensbench_project::ExpandError> for RpcErr {
542    fn from(e: lensbench_project::ExpandError) -> Self {
543        lensbench_core::Error::from(e).into()
544    }
545}
546
547impl From<RpcErr> for CallError {
548    fn from(e: RpcErr) -> Self {
549        CallError {
550            code: e.code,
551            message: e.msg,
552            kind: e.kind.map(str::to_string),
553            data_code: e.ecode.map(str::to_string),
554        }
555    }
556}
557
558/// 配列(バイナリで渡す)
559#[derive(Debug, Clone, PartialEq)]
560pub enum Data {
561    F64(Vec<f64>),
562    I32(Vec<i32>),
563    U8(Vec<u8>),
564    C64(Vec<C64>),
565    Bool(Vec<bool>),
566}
567
568/// 名前と形のついた配列(要求・応答の bin)
569#[derive(Debug, Clone, PartialEq)]
570pub struct Bin {
571    pub name: String,
572    pub shape: Vec<usize>,
573    pub data: Data,
574}
575
576impl Bin {
577    pub fn f64(name: &str, v: Vec<f64>) -> Bin {
578        Bin {
579            name: name.into(),
580            shape: vec![v.len()],
581            data: Data::F64(v),
582        }
583    }
584    pub fn i32(name: &str, v: Vec<i32>) -> Bin {
585        Bin {
586            name: name.into(),
587            shape: vec![v.len()],
588            data: Data::I32(v),
589        }
590    }
591    /// numpy の dtype の文字
592    pub fn dtype(&self) -> &'static str {
593        match self.data {
594            Data::F64(_) => "<f8",
595            Data::I32(_) => "<i4",
596            Data::U8(_) => "|u1",
597            Data::C64(_) => "<c16",
598            Data::Bool(_) => "|b1",
599        }
600    }
601    /// ヘッダの bin の 1 項目
602    pub fn header(&self) -> Value {
603        json!({ "name": self.name, "dtype": self.dtype(), "shape": self.shape })
604    }
605    /// 生のバイト列(リトルエンディアン)を足す
606    pub fn write_to(&self, out: &mut Vec<u8>) {
607        match &self.data {
608            Data::F64(v) => {
609                out.reserve(v.len() * 8);
610                for x in v {
611                    out.extend_from_slice(&x.to_le_bytes());
612                }
613            }
614            Data::I32(v) => {
615                out.reserve(v.len() * 4);
616                for x in v {
617                    out.extend_from_slice(&x.to_le_bytes());
618                }
619            }
620            Data::U8(v) => out.extend_from_slice(v),
621            Data::C64(v) => {
622                out.reserve(v.len() * 16);
623                for x in v {
624                    out.extend_from_slice(&x.re.to_le_bytes());
625                    out.extend_from_slice(&x.im.to_le_bytes());
626                }
627            }
628            Data::Bool(v) => out.extend(v.iter().map(|&b| b as u8)),
629        }
630    }
631}
632
633thread_local! {
634    /// このスレッドの最後の panic の文と場所([`note_panic`])
635    static LAST_PANIC: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
636}
637
638/// panic の hook から、panic の文と場所を残す([`Session::handle`] が「内部エラー(panic): …」に載せる)
639pub fn note_panic(text: &str) {
640    LAST_PANIC.with(|l| *l.borrow_mut() = Some(text.to_string()));
641}
642
643/// 要求を 1 つ処理する(鍵は [`Access`]。panic はエラーにする)
644fn dispatch(
645    sess: &Session,
646    method: &str,
647    params: &Value,
648    bins: Vec<Bin>,
649    threads: Option<usize>,
650) -> Result<(Answer, Vec<Bin>), RpcErr> {
651    // 進み具合・中断・停止は、処理している要求を待たずに答える(別の接続から)
652    if let Some(r) = status(sess, method, params) {
653        return r.map(|(v, b)| (Answer::Json(v), b));
654    }
655    // params を読む所の panic も誤りにする
656    let req = catch_panic(|| Request::parse(method, params))?;
657    dispatch_req(sess, req, bins, threads)
658}
659
660/// f の panic を誤り「internal error (panic)」にする(panic の hook が残した文と場所を添える)
661pub(crate) fn catch_panic<T>(f: impl FnOnce() -> Result<T, RpcErr>) -> Result<T, RpcErr> {
662    LAST_PANIC.with(|l| l.borrow_mut().take());
663    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|e| {
664        // panic の hook(GUI の crash.rs)が残した文と場所。無ければ panic の文だけ
665        let t = LAST_PANIC
666            .with(|l| l.borrow_mut().take())
667            .or_else(|| e.downcast_ref::<&str>().map(|s| s.to_string()))
668            .or_else(|| e.downcast_ref::<String>().cloned());
669        Err(RpcErr::app(match t {
670            Some(t) => format!("internal error (panic): {t}"),
671            None => "internal error (panic)".into(),
672        }))
673    })
674}
675
676/// 型の要求を 1 つ処理する(鍵は [`Access`]。panic はエラーにする)
677fn dispatch_req(
678    sess: &Session,
679    req: Request,
680    bins: Vec<Bin>,
681    threads: Option<usize>,
682) -> Result<(Answer, Vec<Bin>), RpcErr> {
683    let (_r, _w, _l);
684    let access = Access::of(req.method());
685    match access {
686        Access::Read => _r = sess.request.read_ok(),
687        Access::Write => _w = sess.request.write_ok(),
688        // 長い要求は鍵を持たずに回す(系は始めに写しを取る。結果を当てるのは計算の後、プールの外で)
689        Access::Long => _l = sess.long.lock_ok(),
690    }
691    // 中断の印: 呼び出し側(GUI の Worker)が置いた印があればそれを使う
692    let tok = lensbench_core::par::current().cancel.unwrap_or_default();
693    sess.running.lock_ok().push(tok.clone());
694    struct Done<'a>(&'a Session, lensbench_core::par::CancelToken);
695    impl Drop for Done<'_> {
696        fn drop(&mut self) {
697            let mut r = self.0.running.lock_ok();
698            if let Some(i) = r.iter().position(|t| t.same(&self.1)) {
699                r.swap_remove(i);
700            }
701        }
702    }
703    let _d = Done(sess, tok.clone());
704    let run = || {
705        catch_panic(|| lensbench_core::par::with_cancel(Some(&tok), || run::run(sess, req, bins)))
706    };
707    if access != Access::Long {
708        return lensbench_core::with_threads(threads, run);
709    }
710    // 長い要求は別のプールで(読む要求のプールの盗みに載せない)。場の鍵はプールのスレッドでは待たない
711    let r = lensbench_core::par::with_threads_apart(threads, run);
712    let p = sess.pending_apply.lock_ok().take();
713    match (r, p) {
714        (Ok((mut v, b)), Some(p)) => {
715            apply_pending(sess, p, &mut v);
716            Ok((v, b))
717        }
718        (r, _) => r,
719    }
720}
721
722/// 処理している要求を待たない method: `progress`(最適化・公差・差し替え探索の進み具合と、要求を処理しているか)、
723/// `cancel`(処理している要求に途中でやめるよう頼む。解析は「中断した」の誤りで返る)、
724/// `stop`(`what` の最適化・公差・差し替え探索を止め、そこまでの結果を返させる)
725fn status(sess: &Session, method: &str, p: &Value) -> Option<Result<Reply, RpcErr>> {
726    let r = match method {
727        "progress" => json!({
728            "running": !sess.running.lock_ok().is_empty(),
729            "optimize": sess.optimize_progress(),
730            "tolerance": sess.tolerance_progress(),
731            "swap": sess.swap_progress(),
732        }),
733        "cancel" => {
734            let r = sess.running.lock_ok();
735            r.iter().for_each(|t| t.cancel());
736            json!(!r.is_empty())
737        }
738        "stop" => match p["what"].as_str() {
739            Some("optimize") => {
740                sess.optimize_cancel();
741                json!(true)
742            }
743            Some("tolerance") => {
744                sess.tolerance_cancel();
745                json!(true)
746            }
747            Some("swap") => {
748                sess.swap_cancel();
749                json!(true)
750            }
751            _ => {
752                return Some(Err(RpcErr::params(
753                    "stop what must be optimize, tolerance or swap",
754                )))
755            }
756        },
757        _ => return None,
758    };
759    Some(Ok((r, Vec::new())))
760}
761
762/// [`call`] のエラー(JSON-RPC の error と同じ code・message)
763#[derive(Debug, Clone, PartialEq)]
764pub struct CallError {
765    pub code: i64,
766    pub message: String,
767    /// core の誤りの種類(`not_implemented`・`invalid`・`io`・`cancelled`。serve は `data.kind` に書く)
768    pub kind: Option<String>,
769    /// core の誤りの符号(`lensbench_core::error::code` の値か種類の名前。serve は `data.code` に書く)
770    pub data_code: Option<String>,
771}
772
773impl std::fmt::Display for CallError {
774    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
775        f.write_str(&self.message)
776    }
777}
778
779/// 結果の配列(`trace` の x・y・z・opl・err・vig など。名前と f64 の並び、整数も f64 にする)
780pub type Arrays = Vec<(String, Vec<f64>)>;
781
782impl Session {
783    /// serve と同じ method を同じプロセスの中から呼ぶ(GUI が使う)。params・result は TCP の要求と同じ JSON。
784    /// 系は場に 1 つで、TCP の要求と同じく 1 つずつ順に処理する。bin(配列)を使う `trace`・`echo` は
785    /// JSON の並びで渡す。結果の配列が要るときは [`call_arrays`]。`shutdown` はプロセスを止めない。
786    pub fn call(
787        &self,
788        method: &str,
789        params: &Value,
790        threads: Option<usize>,
791    ) -> Result<Value, CallError> {
792        self.call_arrays(method, params, threads).map(|(v, _)| v)
793    }
794
795    /// [`call`] と同じで、結果の配列(TCP では bin で返るもの)も受け取る
796    pub fn call_arrays(
797        &self,
798        method: &str,
799        params: &Value,
800        threads: Option<usize>,
801    ) -> Result<(Value, Arrays), CallError> {
802        let (a, arrays) = self.call_answer(method, params, threads)?;
803        Ok((
804            a.into_json()
805                .map_err(|e| CallError::from(RpcErr::from(e)))?,
806            arrays,
807        ))
808    }
809
810    /// [`call_arrays`] と同じで、結果の型が決まっている method(面の表・最適化・差し替え探索・公差・ズーム軌跡)は
811    /// JSON を通さずに型のまま返す([`Answer`]。GUI が使う)
812    pub fn call_answer(
813        &self,
814        method: &str,
815        params: &Value,
816        threads: Option<usize>,
817    ) -> Result<(Answer, Arrays), CallError> {
818        dispatch(self, method, params, Vec::new(), threads)
819            .map(arrays_of)
820            .map_err(CallError::from)
821    }
822
823    /// 型の要求を同じプロセスの中から渡す(JSON を通さない。GUI が使う)。答えは [`call_answer`] と同じ
824    pub fn request(
825        &self,
826        req: Request,
827        threads: Option<usize>,
828    ) -> Result<(Answer, Arrays), CallError> {
829        let r = match req {
830            // 型を付けていない method は JSON の口で(進み具合・中断・停止は待たずに答える)
831            Request::Json { method, params } => {
832                dispatch(self, &method, &params, Vec::new(), threads)
833            }
834            req => dispatch_req(self, req, Vec::new(), threads),
835        };
836        r.map(arrays_of).map_err(CallError::from)
837    }
838
839    /// 系を読んで(`load` と同じ params)、そのレイアウト図(`layout` と同じ結果)を返す。読み込んだ系は変えず、
840    /// 他の要求の順番も待たない。GUI が、解析を回している間も組合せの図だけ先に描き直すのに使う
841    pub fn preview_layout(&self, load: &Value, opts: &Value) -> Result<Value, CallError> {
842        let f = || -> Result<(LoadReq, LayoutReq), RpcErr> {
843            Ok((LoadReq::parse(load)?, LayoutReq::parse(opts)?))
844        };
845        let (l, o) = f().map_err(CallError::from)?;
846        self.preview(&l, &o)
847    }
848
849    /// [`Session::preview_layout`] の型の口
850    pub fn preview(&self, load: &LoadReq, opts: &LayoutReq) -> Result<Value, CallError> {
851        let f = || preview_of(self, load, opts);
852        std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
853            .unwrap_or_else(|_| Err(RpcErr::app("internal error (panic)")))
854            .map_err(CallError::from)
855    }
856
857    /// カタログの要求(`glasses`・`lenses`・`catalog_search`・`catalog_items`・`catalog_edit`・`catalog_fill`)を、
858    /// 読み込んだ系に関係なく、他の要求の順番も待たずに処理する。GUI が、解析を回している間もカタログを読み・
859    /// 下書きの worker からユーザーカタログを変えるのに使う(`catalog_add` は読み込んだ系が要るので [`Session::request`] で)
860    pub fn catalog(&self, req: &Request) -> Result<Value, CallError> {
861        let sess = self;
862        let f = || match req {
863            Request::Glasses(r) => catalog::glasses(sess, r),
864            Request::Lenses(r) => catalog::lenses(sess, r),
865            Request::CatalogSearch(r) => catalog::catalog_search(sess, r),
866            Request::CatalogItems { catalog } => catalog::catalog_items(sess, catalog),
867            Request::CatalogEdit(r) => catalog::catalog_edit(sess, r),
868            Request::CatalogFill(r) => catalog::catalog_fill(sess, r),
869            r => {
870                let m = r.method();
871                Err(RpcErr::params(format!(
872                    "{m} must be glasses, lenses, catalog_search, catalog_items, catalog_edit or catalog_fill"
873                )))
874            }
875        };
876        std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))
877            .unwrap_or_else(|_| Err(RpcErr::app("internal error (panic)")))
878            .map_err(CallError::from)
879    }
880
881    /// [`Session::catalog`] の JSON の口(method と serve の params)
882    pub fn browse(&self, method: &str, params: &Value) -> Result<Value, CallError> {
883        self.catalog(&Request::from_json(method, params)?)
884    }
885}
886
887/// [`Session::preview`](読み込んだ系は変えない)
888fn preview_of(sess: &Session, load: &LoadReq, opts: &LayoutReq) -> Result<Value, RpcErr> {
889    let spec = load.spec(sess)?;
890    let r = read_file_notes(&spec)?;
891    let mut v = layout_with(&r.sys, &spec, opts, None)?;
892    // 要素ごとの面の範囲(GUI の組合せの図・レンズデータの要素の行)
893    v["blocks"] = json!(r.blocks);
894    Ok(v)
895}
896
897/// 答えの bin を名前と f64 の並びに(整数・真偽も f64、複素数は 名前.re・名前.im の 2 つ)
898fn arrays_of((v, bins): (Answer, Vec<Bin>)) -> (Answer, Arrays) {
899    let a = bins
900        .into_iter()
901        .flat_map(|b| {
902            let d = match b.data {
903                Data::F64(x) => x,
904                Data::I32(x) => x.into_iter().map(f64::from).collect(),
905                Data::U8(x) => x.into_iter().map(f64::from).collect(),
906                Data::Bool(x) => x.into_iter().map(|b| b as u8 as f64).collect(),
907                // 複素数は 名前.re・名前.im の 2 つに分ける
908                Data::C64(x) => {
909                    let im = x.iter().map(|z| z.im).collect();
910                    return vec![
911                        (format!("{}.re", b.name), x.iter().map(|z| z.re).collect()),
912                        (format!("{}.im", b.name), im),
913                    ];
914                }
915            };
916            vec![(b.name, d)]
917        })
918        .collect();
919    (v, a)
920}
921
922/// [`global`] の場の [`Session::call`]
923pub fn call(method: &str, params: &Value, threads: Option<usize>) -> Result<Value, CallError> {
924    global().call(method, params, threads)
925}
926
927/// [`global`] の場の [`Session::call_arrays`]
928pub fn call_arrays(
929    method: &str,
930    params: &Value,
931    threads: Option<usize>,
932) -> Result<(Value, Arrays), CallError> {
933    global().call_arrays(method, params, threads)
934}
935
936/// [`global`] の場の [`Session::request`]
937pub fn request(req: Request, threads: Option<usize>) -> Result<(Answer, Arrays), CallError> {
938    global().request(req, threads)
939}
940
941/// [`global`] の場の [`Session::call_answer`]
942pub fn call_answer(
943    method: &str,
944    params: &Value,
945    threads: Option<usize>,
946) -> Result<(Answer, Arrays), CallError> {
947    global().call_answer(method, params, threads)
948}
949
950/// [`global`] の場の [`Session::preview_layout`]
951pub fn preview_layout(load: &Value, opts: &Value) -> Result<Value, CallError> {
952    global().preview_layout(load, opts)
953}
954
955/// [`global`] の場の [`Session::preview`]
956pub fn preview(load: &LoadReq, opts: &LayoutReq) -> Result<Value, CallError> {
957    global().preview(load, opts)
958}
959
960/// [`global`] の場の [`Session::catalog`]
961pub fn catalog(req: &Request) -> Result<Value, CallError> {
962    global().catalog(req)
963}
964
965/// [`global`] の場の [`Session::browse`]
966pub fn browse(method: &str, params: &Value) -> Result<Value, CallError> {
967    global().browse(method, params)
968}
969
970type Reply = (Value, Vec<Bin>);
971
972/// 型を付けていない method(`echo` と、知らない method の誤り)
973fn answer(method: &str, p: &Value, bins: Vec<Bin>) -> Result<(Answer, Vec<Bin>), RpcErr> {
974    handle(method, p, bins).map(|(v, b)| (Answer::Json(v), b))
975}
976
977fn handle(method: &str, p: &Value, bins: Vec<Bin>) -> Result<Reply, RpcErr> {
978    match method {
979        // 配列をそのまま返す(往復の時間を測る)
980        "echo" => Ok((json!({ "params": p }), bins)),
981        "" => Err(RpcErr {
982            code: -32600,
983            msg: "no method".into(),
984            kind: None,
985            ecode: None,
986        }),
987        m => Err(RpcErr {
988            code: -32601,
989            msg: format!("no method {m}"),
990            kind: None,
991            ecode: None,
992        }),
993    }
994}
995
996/// set の値: {"values": {"3.t": 10.0}} か {"values": [["3.t", 10.0], ...]}
997fn parse_changes(
998    s: &System,
999    values: &[(String, f64)],
1000) -> Result<Vec<(lensbench_core::param::Param, f64)>, RpcErr> {
1001    values.iter().map(|(k, v)| Ok((s.param(k)?, *v))).collect()
1002}
1003
1004/// 解析の登録簿の解析(と膜の境界)を、読み込んだ系で実行する。最適化・公差・レイアウトの書き出しは専用のメソッド
1005fn analyze(sess: &Session, r: &AnalyzeReq) -> Result<Answer, RpcErr> {
1006    sess.current()?;
1007    let (cmd, m) = (r.cmd.as_str(), &r.args);
1008    if cmd == "coatings" {
1009        return crate::analyze::coatings_loaded(sess, m).map(Answer::Json);
1010    }
1011    match crate::analyses().get(cmd).cloned() {
1012        Some(def) => crate::analyze::run(sess, def.as_ref(), m),
1013        None => Err(RpcErr::params(match cmd {
1014            "optimize" | "tolerance" | "swap" | "zoom" | "layout" => format!(
1015                "{cmd} is not an analyze analysis (use method {})",
1016                if cmd == "layout" {
1017                    "layout_export"
1018                } else {
1019                    cmd
1020                }
1021            ),
1022            _ => format!(
1023                "{cmd} is not an analyze analysis (list them with analysis_args or plugins)"
1024            ),
1025        })),
1026    }
1027}
1028
1029/// 登録簿の解析に渡す系の読み方(load で選んだもの。別に読んだ系にも読み込んだ後の変更を当てる)で f を呼ぶ
1030pub(crate) fn with_source<R>(
1031    sess: &Session,
1032    f: impl FnOnce(&dyn lensbench_analysis::Source) -> R,
1033) -> Result<R, RpcErr> {
1034    let Current {
1035        sys,
1036        spec,
1037        src,
1038        faces,
1039        log,
1040    } = sess.current_full()?;
1041    let r = |s: System, to: &[Option<FaceId>], l: &str, n: &mut Vec<String>| {
1042        replay(s, &log, (&faces, to), l, n)
1043    };
1044    Ok(f(&crate::source::FileSource::loaded(&spec, src, &sys, &r)))
1045}
1046
1047fn is_zmx(f: &Path) -> bool {
1048    f.extension().is_some_and(|x| x.eq_ignore_ascii_case("zmx"))
1049}
1050
1051/// .zmx の多重構成を、表(set_config_count・set_config_row・set_config の edit の操作)にする
1052fn config_diff(spec: &LoadSpec, src: &Source) -> Result<Value, RpcErr> {
1053    use lensbench_core::param::{Kind, Param};
1054    if !is_zmx(&spec.file) {
1055        return Err(RpcErr::params("config_diff is only for .zmx systems"));
1056    }
1057    // 読み込んだときのファイルの中身から(読み直さない)
1058    let n = src.configurations()?;
1059    if n < 2 {
1060        return Err(RpcErr::app("this .zmx has no multiple configurations"));
1061    }
1062    let mut systems = Vec::with_capacity(n);
1063    for k in 1..=n {
1064        let mut c = spec.clone();
1065        c.cfg = k;
1066        systems.push(
1067            crate::load::load_source(src, &c).map_err(|e| e.at(format!("configuration {k}")))?,
1068        );
1069    }
1070    let m = systems[0].surfaces.len();
1071    if systems.iter().any(|s| s.surfaces.len() != m) {
1072        return Err(RpcErr::app(
1073            "the configurations have different numbers of surfaces (no table)",
1074        ));
1075    }
1076    let mut kinds = vec![Kind::Curv, Kind::Conic, Kind::Thick];
1077    kinds.extend((0..8).map(Kind::Asph));
1078    kinds.extend([
1079        Kind::Dx,
1080        Kind::Dy,
1081        Kind::Tx,
1082        Kind::Ty,
1083        Kind::Tz,
1084        Kind::Dn,
1085        Kind::Disp,
1086    ]);
1087    let mut ops = vec![json!({ "op": "set_config_count", "n": n })];
1088    let mut notes = Vec::new();
1089    for j in 0..m {
1090        for &kind in &kinds {
1091            let p = Param::new(j, kind);
1092            let vals: Option<Vec<f64>> = systems.iter().map(|s| s.get_param(p).ok()).collect();
1093            let Some(vals) = vals else { continue };
1094            if vals.iter().any(|v| v.to_bits() != vals[0].to_bits()) {
1095                ops.push(json!({
1096                    "op": "set_config_row", "param": systems[0].param_name(p), "values": vals,
1097                }));
1098            }
1099        }
1100        let differs = |f: &dyn Fn(&System) -> String| {
1101            let a = f(&systems[0]);
1102            systems.iter().any(|s| f(s) != a)
1103        };
1104        type Get = fn(&lensbench_core::surface::Surface) -> String;
1105        if differs(&|s| s.surfaces[j].mat.name()) {
1106            let names: Vec<String> = systems.iter().map(|s| s.surfaces[j].mat.name()).collect();
1107            ops.push(json!({
1108                "op": "set_config_materials",
1109                "param": systems[0].param_name(Param::new(j, Kind::Material)),
1110                "names": names,
1111            }));
1112        }
1113        if differs(&|s| s.surfaces[j].coat.clone()) {
1114            let names: Vec<String> = systems.iter().map(|s| s.surfaces[j].coat.clone()).collect();
1115            ops.push(json!({
1116                "op": "set_config_coatings",
1117                "param": systems[0].param_name(Param::new(j, Kind::Coating)),
1118                "names": names,
1119            }));
1120        }
1121        let checks: [(&str, Get); 3] = [
1122            ("ignore", |d| d.ignore.to_string()),
1123            ("semi-diameter", |d| format!("{:?}", d.semi)),
1124            ("stop", |d| d.stop.to_string()),
1125        ];
1126        for (what, f) in checks {
1127            if differs(&|s| f(&s.surfaces[j])) {
1128                notes.push(format!(
1129                    "surface {j}: {what} differs by configuration (can't tabulate)"
1130                ));
1131            }
1132        }
1133    }
1134    let differs_sys = |f: &dyn Fn(&System) -> String| {
1135        let a = f(&systems[0]);
1136        systems.iter().any(|s| f(s) != a)
1137    };
1138    if differs_sys(&|s| format!("{:?}", s.wavelengths)) {
1139        notes.push("wavelengths differ by configuration (can't tabulate)".into());
1140    }
1141    if differs_sys(&|s| format!("{:?}", s.fields)) {
1142        notes.push("fields differ by configuration (can't tabulate)".into());
1143    }
1144    ops.push(json!({ "op": "set_config", "k": spec.cfg.clamp(1, n) }));
1145    Ok(json!({ "ops": ops, "notes": notes, "rows": ops.len() - 2 }))
1146}
1147
1148/// プロジェクトファイル(系ファイルは含めない)
1149fn is_project(f: &Path) -> bool {
1150    lensbench_project::open::FileKind::of(f) == lensbench_project::open::FileKind::Project
1151}