zng_env/process.rs
1use std::{
2 mem,
3 sync::atomic::{AtomicU8, Ordering},
4};
5
6use parking_lot::Mutex;
7
8#[doc(hidden)]
9#[cfg(not(target_arch = "wasm32"))]
10pub use linkme as __linkme;
11
12/// Register a `FnOnce(&ProcessStartArgs)` closure to be called on [`init!`].
13///
14/// Components that spawn special process instances implemented on the same executable
15/// can use this macro to inject their own "main" without needing to ask the user to plug an init
16/// function on the executable main. The component can spawn an instance of the current executable
17/// with marker environment variables that identify the component's process.
18///
19/// [`init!`]: crate::init!
20///
21/// # Examples
22///
23/// The example below declares a "main" for a foo component and a function that spawns it.
24///
25/// ```
26/// zng_env::on_process_start!(|args| {
27/// if args.yield_count == 0 {
28/// return args.yield_once();
29/// }
30///
31/// if std::env::var("FOO_MARKER").is_ok() {
32/// println!("Spawned as foo!");
33/// zng_env::exit(0);
34/// }
35/// });
36///
37/// fn main() {
38/// zng_env::init!(); // foo_main OR
39/// // normal main
40/// }
41///
42/// pub fn spawn_foo() -> std::io::Result<()> {
43/// std::process::Command::new(std::env::current_exe()?).env("FOO_MARKER", "").spawn()?;
44/// Ok(())
45/// }
46/// ```
47///
48/// Note that the handler yields once, this gives a chance for all handlers to run first before the handler is called again
49/// and takes over the process. It is good practice to yield at least once to ensure handlers that are supposed to affect all
50/// processes actually init, as an example, the trace recorder may never start for the process if it does not yield.
51///
52/// Also note the use of custom [`exit`], it is important to call it to collaborate with [`on_process_exit`] handlers.
53///
54/// # App Context
55///
56/// This event happens on the executable process context, before any `APP` context starts, you can use
57/// `zng::APP::on_init` here to register a handler to be called in the app context, if and when it starts.
58///
59/// # Web Assembly
60///
61/// Crates that declare `on_process_start` must have the [`wasm_bindgen`] dependency to compile for the `wasm32` target.
62///
63/// In `Cargo.toml` add this dependency:
64///
65/// ```toml
66/// [target.'cfg(target_arch = "wasm32")'.dependencies]
67/// wasm-bindgen = "0.2"
68/// ```
69///
70/// Try to match the version used by `zng-env`.
71///
72/// # Linker Optimizer Issues
73///
74/// The macOS system linker can "optimize" away crates that are only referenced via this macro, that is, a crate dependency
75/// that is not otherwise directly addressed by code. To workaround this issue you can add a bogus reference to the crate code, something
76/// that is not trivial to optimize away. Unfortunately this code must be added on the dependent crate, or on an intermediary dependency,
77/// if your crate is at risk of being used this way please document this issue.
78///
79/// See [`zng#437`] for an example of how to fix this issue.
80///
81/// [`wasm_bindgen`]: https://crates.io/crates/wasm-bindgen
82/// [`zng#437`]: https://github.com/zng-ui/zng/pull/437
83#[macro_export]
84macro_rules! on_process_start {
85 ($closure:expr) => {
86 $crate::__on_process_start! {$closure}
87 };
88}
89
90#[cfg(not(target_arch = "wasm32"))]
91#[doc(hidden)]
92#[macro_export]
93macro_rules! __on_process_start {
94 ($closure:expr) => {
95 const _: () = {
96 #[$crate::__linkme::distributed_slice($crate::ZNG_ENV_ON_PROCESS_START)]
97 #[linkme(crate = $crate::__linkme)]
98 #[doc(hidden)]
99 static _ON_PROCESS_START: fn(&$crate::ProcessStartArgs) = _on_process_start;
100 #[doc(hidden)]
101 fn _on_process_start(args: &$crate::ProcessStartArgs) {
102 fn on_process_start(args: &$crate::ProcessStartArgs, handler: impl FnOnce(&$crate::ProcessStartArgs)) {
103 handler(args)
104 }
105 on_process_start(args, $closure)
106 }
107 };
108 };
109}
110
111#[cfg(target_arch = "wasm32")]
112#[doc(hidden)]
113#[macro_export]
114macro_rules! __on_process_start {
115 ($closure:expr) => {
116 $crate::wasm_process_start! {$crate,$closure}
117 };
118}
119
120#[doc(hidden)]
121#[cfg(target_arch = "wasm32")]
122pub use wasm_bindgen::prelude::wasm_bindgen;
123
124#[doc(hidden)]
125#[cfg(target_arch = "wasm32")]
126pub use zng_env_proc_macros::wasm_process_start;
127use zng_txt::Txt;
128
129#[cfg(target_arch = "wasm32")]
130std::thread_local! {
131 #[doc(hidden)]
132 pub static WASM_INIT: std::cell::RefCell<Vec<fn(&ProcessStartArgs)>> = const { std::cell::RefCell::new(vec![]) };
133}
134
135#[cfg(not(target_arch = "wasm32"))]
136#[doc(hidden)]
137#[linkme::distributed_slice]
138pub static ZNG_ENV_ON_PROCESS_START: [fn(&ProcessStartArgs)];
139
140#[cfg(not(target_arch = "wasm32"))]
141pub(crate) fn process_init() -> impl Drop {
142 process_init_impl(&ZNG_ENV_ON_PROCESS_START)
143}
144
145fn process_init_impl(handlers: &[fn(&ProcessStartArgs)]) -> MainExitHandler {
146 let process_state = std::mem::replace(
147 &mut *zng_unique_id::hot_static_ref!(PROCESS_LIFETIME_STATE).lock(),
148 ProcessLifetimeState::Inited,
149 );
150 assert_eq!(process_state, ProcessLifetimeState::BeforeInit, "init!() already called");
151
152 let mut yielded = vec![];
153 let mut next_handlers_count = handlers.len();
154 for h in handlers {
155 next_handlers_count -= 1;
156 let args = ProcessStartArgs {
157 next_handlers_count,
158 yield_count: 0,
159 yield_requested: AtomicU8::new(0),
160 };
161 h(&args);
162 if args.yield_requested.load(Ordering::Relaxed) == ProcessStartArgs::YIELD_ONCE {
163 yielded.push(h);
164 next_handlers_count += 1;
165 }
166 }
167
168 let mut yield_count = 0;
169 while !yielded.is_empty() {
170 yield_count += 1;
171 if yield_count > ProcessStartArgs::MAX_YIELD_COUNT {
172 eprintln!("start handlers requested `yield_start` more them 32 times");
173 break;
174 }
175
176 next_handlers_count = yielded.len();
177 for h in mem::take(&mut yielded) {
178 next_handlers_count -= 1;
179 let args = ProcessStartArgs {
180 next_handlers_count,
181 yield_count,
182 yield_requested: AtomicU8::new(0),
183 };
184 h(&args);
185 if let ProcessStartArgs::YIELD_ONCE = args.yield_requested.load(Ordering::Relaxed) {
186 yielded.push(h);
187 next_handlers_count += 1;
188 }
189 }
190 }
191
192 MainExitHandler
193}
194
195#[cfg(target_arch = "wasm32")]
196pub(crate) fn process_init() -> impl Drop {
197 std::panic::set_hook(Box::new(console_error_panic_hook::hook));
198
199 let window = web_sys::window().expect("cannot 'init!', no window object");
200 let module = js_sys::Reflect::get(&window, &"__zng_env_init_module".into())
201 .expect("cannot 'init!', missing module in 'window.__zng_env_init_module'");
202
203 if module == wasm_bindgen::JsValue::undefined() || module == wasm_bindgen::JsValue::null() {
204 panic!("cannot 'init!', missing module in 'window.__zng_env_init_module'");
205 }
206
207 let module: js_sys::Object = module.into();
208
209 for entry in js_sys::Object::entries(&module) {
210 let entry: js_sys::Array = entry.into();
211 let ident = entry.get(0).as_string().expect("expected ident at entry[0]");
212
213 if ident.starts_with("__zng_env_start_") {
214 let func: js_sys::Function = entry.get(1).into();
215 if let Err(e) = func.call0(&wasm_bindgen::JsValue::NULL) {
216 panic!("'init!' function error, {e:?}");
217 }
218 }
219 }
220
221 process_init_impl(&WASM_INIT.with_borrow_mut(std::mem::take))
222}
223
224/// Arguments for [`on_process_start`] handlers.
225///
226/// Empty in this release.
227pub struct ProcessStartArgs {
228 /// Number of start handlers yet to run.
229 pub next_handlers_count: usize,
230
231 /// Number of times this handler has yielded.
232 ///
233 /// If this exceeds 32 times the handler is ignored.
234 pub yield_count: u16,
235
236 yield_requested: AtomicU8,
237}
238impl ProcessStartArgs {
239 /// Yield requests after this are ignored.
240 pub const MAX_YIELD_COUNT: u16 = 32;
241
242 const YIELD_ONCE: u8 = 1;
243
244 /// Let other process start handlers run first.
245 ///
246 /// The handler must call this if it takes over the process and it cannot determinate if it should from the environment.
247 ///
248 /// ```
249 /// # macro_rules! on_process_start { ($($tt:tt)*) => { } }
250 /// fn run_foo_process() {}
251 /// on_process_start!(|args| {
252 /// if args.yield_count == 0 {
253 /// return args.yield_once();
254 /// }
255 ///
256 /// // yielded once, handlers that affect all processes (loggers, tracers) are inited now
257 /// if std::env::var("IS_FOO").is_ok() {
258 /// // take over as "foo" process
259 /// run_foo_process();
260 /// zng_env::exit(0);
261 /// }
262 /// });
263 /// ```
264 pub fn yield_once(&self) {
265 self.yield_requested.store(Self::YIELD_ONCE, Ordering::Relaxed);
266 }
267}
268
269struct MainExitHandler;
270impl Drop for MainExitHandler {
271 fn drop(&mut self) {
272 run_exit_handlers(if std::thread::panicking() { 101 } else { 0 })
273 }
274}
275
276type ExitHandler = Box<dyn FnOnce(&ProcessExitArgs) + Send + 'static>;
277
278zng_unique_id::hot_static! {
279 static ON_PROCESS_EXIT: Mutex<Vec<ExitHandler>> = Mutex::new(vec![]);
280}
281
282/// Terminates the current process with the specified exit code.
283///
284/// This function must be used instead of `std::process::exit` as it runs the [`on_process_exit`].
285pub fn exit(code: i32) -> ! {
286 run_exit_handlers(code);
287 std::process::exit(code)
288}
289
290fn run_exit_handlers(code: i32) {
291 *zng_unique_id::hot_static_ref!(PROCESS_LIFETIME_STATE).lock() = ProcessLifetimeState::Exiting;
292
293 let on_exit = mem::take(&mut *zng_unique_id::hot_static_ref!(ON_PROCESS_EXIT).lock());
294 let args = ProcessExitArgs { code };
295 for h in on_exit {
296 h(&args);
297 }
298}
299
300/// Arguments for [`on_process_exit`] handlers.
301#[non_exhaustive]
302pub struct ProcessExitArgs {
303 /// Exit code that will be used.
304 pub code: i32,
305}
306
307/// Register a `handler` to run once when the current process exits.
308///
309/// Note that the handler is only called if the process is terminated by [`exit`], or by the executable main
310/// function returning if [`init!`] is called on it.
311///
312/// [`init!`]: crate::init!
313pub fn on_process_exit(handler: impl FnOnce(&ProcessExitArgs) + Send + 'static) {
314 zng_unique_id::hot_static_ref!(ON_PROCESS_EXIT).lock().push(Box::new(handler))
315}
316
317/// Defines the state of the current process instance.
318///
319/// Use [`process_lifetime_state()`] to get.
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum ProcessLifetimeState {
322 /// Init not called yet.
323 BeforeInit,
324 /// Init called and the function where it is called has not returned yet.
325 Inited,
326 /// Init called and the function where it is called is returning.
327 Exiting,
328}
329
330zng_unique_id::hot_static! {
331 static PROCESS_LIFETIME_STATE: Mutex<ProcessLifetimeState> = Mutex::new(ProcessLifetimeState::BeforeInit);
332}
333zng_unique_id::hot_static! {
334 static PROCESS_NAME: Mutex<Txt> = Mutex::new(Txt::from_static(""));
335}
336
337/// Get the state of the current process instance.
338pub fn process_lifetime_state() -> ProcessLifetimeState {
339 *zng_unique_id::hot_static_ref!(PROCESS_LIFETIME_STATE).lock()
340}
341
342/// Gets a process runtime name.
343///
344/// The primary use of this name is to identify the process in logs, see [`set_process_name`] for details about the logged name.
345/// On set or init the name is logged as an info message "pid: {pid}, name: {name}".
346///
347/// # Common Names
348///
349/// All Zng provided process handlers name the process.
350///
351/// * `"app-process"` - Set by `APP` if no other name was set before the app starts building.
352/// * `"view-process"` - Set by the view-process implementer when running in multi process mode.
353/// * `"crash-handler-process"` - Set by the crash-handler when running with crash handling.
354/// * `"crash-dialog-process"` - Set by the crash-handler on the crash dialog process.
355/// * `"worker-process ({worker_name}, {pid})"` - Set by task worker processes if no name was set before the task runner server starts.
356pub fn process_name() -> Txt {
357 zng_unique_id::hot_static_ref!(PROCESS_NAME).lock().clone()
358}
359
360/// Changes the process runtime name.
361///
362/// This sets [`process_name`] and traces an info message "pid: {pid}, name: {name}". If the same PID is named multiple times
363/// the last name should be used when presenting the process in trace viewers.
364///
365/// The process name ideally should be set only by the [`on_process_start!`] "process takeover" handlers. You can use [`init_process_name`]
366/// to only set the name if it has not been set yet.
367pub fn set_process_name(name: impl Into<Txt>) {
368 set_process_name_impl(name.into(), true);
369}
370
371/// Set the process runtime name if it has not been named yet.
372///
373/// See [`set_process_name`] for more details.
374///
375/// Returns `true` if the name was set.
376pub fn init_process_name(name: impl Into<Txt>) -> bool {
377 set_process_name_impl(name.into(), false)
378}
379
380fn set_process_name_impl(new_name: Txt, replace: bool) -> bool {
381 let mut name = zng_unique_id::hot_static_ref!(PROCESS_NAME).lock();
382 if replace || name.is_empty() {
383 *name = new_name;
384 drop(name);
385 tracing::info!("pid: {}, name: {}", std::process::id(), process_name());
386 true
387 } else {
388 false
389 }
390}
391
392/// Panics with an standard message if `zng::env::init!()` was not called or was not called correctly.
393pub fn assert_inited() {
394 match process_lifetime_state() {
395 ProcessLifetimeState::BeforeInit => panic!("env not inited, please call `zng::env::init!()` in main"),
396 ProcessLifetimeState::Inited => {}
397 ProcessLifetimeState::Exiting => {
398 panic!("env not inited correctly, please call `zng::env::init!()` at the beginning of the actual main function")
399 }
400 }
401}