zng_view_api/
view_process.rs

1use std::{env, mem, time::Duration};
2
3#[cfg(not(target_arch = "wasm32"))]
4use std::time::Instant;
5
6#[cfg(target_arch = "wasm32")]
7use web_time::Instant;
8
9use parking_lot::Mutex;
10use zng_txt::Txt;
11
12use crate::{VIEW_MODE, VIEW_SERVER, VIEW_VERSION};
13
14/// Configuration for starting a view-process.
15#[derive(Clone, Debug)]
16pub struct ViewConfig {
17    /// The [`VERSION`] of the API crate in the app-process.
18    ///
19    /// [`VERSION`]: crate::VERSION
20    pub version: Txt,
21
22    /// Name of the initial channel used in [`connect_view_process`] to setup the connections to the
23    /// client app-process.
24    ///
25    /// [`connect_view_process`]: crate::ipc::connect_view_process
26    pub server_name: Txt,
27
28    /// If the server should consider all window requests, headless window requests.
29    pub headless: bool,
30}
31impl ViewConfig {
32    /// Reads config from environment variables set by the [`Controller`] in a view-process instance.
33    ///
34    /// View API implementers should call this to get the config when it suspects that is running as a view-process.
35    /// Returns `Some(_)` if the process was initialized as a view-process.
36    ///
37    /// [`Controller`]: crate::Controller
38    pub fn from_env() -> Option<Self> {
39        if let (Ok(version), Ok(server_name)) = (env::var(VIEW_VERSION), env::var(VIEW_SERVER)) {
40            let headless = env::var(VIEW_MODE).map(|m| m == "headless").unwrap_or(false);
41            Some(ViewConfig {
42                version: Txt::from_str(&version),
43                server_name: Txt::from_str(&server_name),
44                headless,
45            })
46        } else {
47            None
48        }
49    }
50
51    /// Returns `true` if the current process is awaiting for the config to start the
52    /// view process in the same process.
53    pub(crate) fn is_awaiting_same_process() -> bool {
54        matches!(*same_process().lock(), SameProcess::Awaiting)
55    }
56
57    /// Sets and unblocks the same-process config if there is a request.
58    ///
59    /// # Panics
60    ///
61    /// If there is no pending `wait_same_process`.
62    pub(crate) fn set_same_process(cfg: ViewConfig) {
63        if Self::is_awaiting_same_process() {
64            *same_process().lock() = SameProcess::Ready(cfg);
65        } else {
66            unreachable!("use `waiting_same_process` to check, then call `set_same_process` only once")
67        }
68    }
69
70    /// Wait for config from same-process.
71    ///
72    /// View API implementers should call this to sign that view-process config should be send to the same process
73    /// and then start the "app-process" code path in a different thread. This function returns when the app code path sends
74    /// the "view-process" configuration.
75    pub fn wait_same_process() -> Self {
76        let _s = tracing::trace_span!("ViewConfig::wait_same_process").entered();
77
78        if !matches!(*same_process().lock(), SameProcess::Not) {
79            panic!("`wait_same_process` can only be called once");
80        }
81
82        *same_process().lock() = SameProcess::Awaiting;
83
84        let time = Instant::now();
85        let timeout = Duration::from_secs(5);
86        let sleep = Duration::from_millis(10);
87
88        while Self::is_awaiting_same_process() {
89            std::thread::sleep(sleep);
90            if time.elapsed() >= timeout {
91                panic!("timeout, `wait_same_process` waited for `{timeout:?}`");
92            }
93        }
94
95        match mem::replace(&mut *same_process().lock(), SameProcess::Done) {
96            SameProcess::Ready(cfg) => cfg,
97            _ => unreachable!(),
98        }
99    }
100
101    /// Assert that the [`VERSION`] is the same in the app-process and view-process.
102    ///
103    /// This method must be called in the view-process implementation, it fails if the versions don't match, panics if
104    /// `is_same_process` or writes to *stderr* and exits with code .
105    ///
106    /// [`VERSION`]: crate::VERSION
107    pub fn assert_version(&self, is_same_process: bool) {
108        if self.version != crate::VERSION {
109            let msg = format!(
110                "view API version is not equal, app-process: {}, view-process: {}",
111                self.version,
112                crate::VERSION
113            );
114            if is_same_process {
115                panic!("{}", msg)
116            } else {
117                eprintln!("{msg}");
118                zng_env::exit(i32::from_le_bytes(*b"vapi"));
119            }
120        }
121    }
122
123    /// Returns `true` if a view-process exited because of [`assert_version`].
124    ///
125    /// [`assert_version`]: Self::assert_version
126    pub fn is_version_err(exit_code: Option<i32>, stderr: Option<&str>) -> bool {
127        exit_code.map(|e| e == i32::from_le_bytes(*b"vapi")).unwrap_or(false)
128            || stderr.map(|s| s.contains("view API version is not equal")).unwrap_or(false)
129    }
130}
131
132enum SameProcess {
133    Not,
134    Awaiting,
135    Ready(ViewConfig),
136    Done,
137}
138
139// because some view libs are dynamically loaded this variable needs to be patchable.
140//
141// This follows the same idea as the "hot-reload" patches, just manually implemented.
142static mut SAME_PROCESS: &Mutex<SameProcess> = &SAME_PROCESS_COLD;
143static SAME_PROCESS_COLD: Mutex<SameProcess> = Mutex::new(SameProcess::Not);
144
145fn same_process() -> &'static Mutex<SameProcess> {
146    // SAFETY: this is safe because SAME_PROCESS is only mutated on dynamic lib init, before any other code.
147    unsafe { *std::ptr::addr_of!(SAME_PROCESS) }
148}
149
150/// Dynamic view-process "same process" implementations must patch the static variables used by
151/// the view-api. This patch also propagates the tracing and log contexts.
152pub struct StaticPatch {
153    same_process: *const Mutex<SameProcess>,
154    tracing: tracing_shared::SharedLogger,
155}
156impl StaticPatch {
157    /// Called in the main executable.
158    pub fn capture() -> Self {
159        Self {
160            same_process: same_process(),
161            tracing: tracing_shared::SharedLogger::new(),
162        }
163    }
164
165    /// Called in the dynamic library.
166    ///
167    /// # Safety
168    ///
169    /// Only safe if it is the first view-process code to run in the dynamic library.
170    pub unsafe fn install(&self) {
171        // SAFETY: safety handled by the caller
172        unsafe {
173            *std::ptr::addr_of_mut!(SAME_PROCESS) = &*self.same_process;
174        }
175        self.tracing.install();
176    }
177}