blitz_control_protocol/lifecycle.rs
1//! The embedder's answer to a request about the process, not the document.
2//!
3//! [`crate::in_process::DocumentControl`] refuses `Relaunch` and `Quit`, and
4//! that refusal is correct: a document cannot restart the program it is being
5//! displayed by. Somebody above the document has to answer, and which of them
6//! it is depends on the application rather than on the transport. AgencyZero
7//! drains its persistence layer and hands over to a restart supervisor; a plain
8//! host re-executes itself; a headless one has nothing to relaunch and says so.
9//!
10//! This is where that answer is registered. It lives beside the vocabulary
11//! rather than inside a host, because more than one host serves the same
12//! request: the Tauri runtime does it for a window today, and an embedder that
13//! drives a browser in process will do it for that browser next. It used to
14//! live in `izumo`, which meant an application registered a
15//! handler for an inspection service through a window runtime, and named the
16//! protocol's types through that runtime's re-export of this crate. Depending
17//! on a renderer to answer "restart yourself" is the edge this removes.
18//!
19//! Nothing here needs a feature. The handler is one `Arc` and a lock, and the
20//! types it names are the vocabulary, so a consumer that registers one pays
21//! serde and nothing else: no engine, no socket, no window.
22//!
23//! # One per process
24//!
25//! Deliberately global, and deliberately last-writer-wins. A process has one
26//! lifecycle, so a second registration is a second opinion about the same
27//! question rather than a second subject to ask it about. Registering from a
28//! test therefore disturbs any other test in the same binary that reads it;
29//! [`clear_lifecycle_handler`] exists so such a test can put the process back.
30
31use std::sync::{Arc, OnceLock, RwLock};
32
33use crate::{AgentControlRequest, DebugResponse};
34
35/// What an embedder installs to answer a lifecycle request.
36pub type LifecycleHandler = dyn Fn(AgentControlRequest) -> DebugResponse + Send + Sync + 'static;
37
38static LIFECYCLE_HANDLER: OnceLock<RwLock<Option<Arc<LifecycleHandler>>>> = OnceLock::new();
39
40fn slot() -> &'static RwLock<Option<Arc<LifecycleHandler>>> {
41 LIFECYCLE_HANDLER.get_or_init(|| RwLock::new(None))
42}
43
44/// Install the embedder's answer to `Relaunch` and `Quit`.
45///
46/// The handler runs on whichever thread the host serves control requests from,
47/// which for a windowed host is the UI thread. It must not block: a host that
48/// takes its time here stops answering every other request, including the
49/// `Inspect` a client is waiting on.
50pub fn set_lifecycle_handler(
51 handler: impl Fn(AgentControlRequest) -> DebugResponse + Send + Sync + 'static,
52) {
53 *slot().write().unwrap() = Some(Arc::new(handler));
54}
55
56/// The installed handler, if an embedder installed one.
57///
58/// A host calls this rather than holding the handler, because the embedder may
59/// install it after the host has started listening: AgencyZero registers during
60/// Tauri's `setup`, which runs after the runtime is built.
61pub fn lifecycle_handler() -> Option<Arc<LifecycleHandler>> {
62 slot().read().unwrap().clone()
63}
64
65/// Forget the installed handler, leaving the host's own behaviour.
66pub fn clear_lifecycle_handler() {
67 *slot().write().unwrap() = None;
68}
69
70#[cfg(test)]
71mod tests {
72 use super::*;
73 use crate::DebugError;
74
75 /// One process, one lifecycle: these share the static and must not run at
76 /// the same time as each other.
77 static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
78
79 #[test]
80 fn an_embedder_answers_relaunch_in_place_of_the_host() {
81 let _guard = SERIAL.lock().unwrap_or_else(|error| error.into_inner());
82 clear_lifecycle_handler();
83 assert!(lifecycle_handler().is_none());
84
85 set_lifecycle_handler(|request| match request {
86 AgentControlRequest::Relaunch => DebugResponse::Ack,
87 _ => DebugResponse::Error(DebugError {
88 code: "unsupportedEmbedderAction".into(),
89 message: "only relaunch is delegated".into(),
90 }),
91 });
92
93 let handler = lifecycle_handler().expect("a handler was installed");
94 assert_eq!(handler(AgentControlRequest::Relaunch), DebugResponse::Ack);
95 assert!(matches!(
96 handler(AgentControlRequest::Quit),
97 DebugResponse::Error(error) if error.code == "unsupportedEmbedderAction"
98 ));
99
100 clear_lifecycle_handler();
101 assert!(lifecycle_handler().is_none());
102 }
103
104 #[test]
105 fn the_last_registration_is_the_one_that_answers() {
106 let _guard = SERIAL.lock().unwrap_or_else(|error| error.into_inner());
107 clear_lifecycle_handler();
108
109 set_lifecycle_handler(|_| DebugResponse::Ack);
110 set_lifecycle_handler(|_| {
111 DebugResponse::Error(DebugError {
112 code: "second".into(),
113 message: "the later registration wins".into(),
114 })
115 });
116
117 let handler = lifecycle_handler().expect("a handler was installed");
118 assert!(matches!(
119 handler(AgentControlRequest::Relaunch),
120 DebugResponse::Error(error) if error.code == "second"
121 ));
122
123 clear_lifecycle_handler();
124 }
125}