ctb_workspace/
workspace.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Main workspace process coordinating services, IPC, and child lifecycles.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29import_all_ipc_client_ext_traits!();
30
31use ctb_utilities::ipc::{ChildKind, format_child_kind};
32use ctb_workspace_ipc::auth::capability::CapabilitySet;
33use ctb_workspace_ipc::workspace_runner::cli::start_service;
34use ctb_workspace_ipc::workspace_runner::{Workspace, WorkspaceServices};
35
36use crate::panic_hooks::{
37    setup_subprocess_panic_hooks, setup_workspace_panic_hooks,
38};
39use crate::utilities::resource_lock::check_filesystem_lock_support;
40use crate::utilities::storage::get_storage_dir;
41use cli::Cli;
42use ctb_cli as cli;
43pub use serde_json::json as utilities_serde_json_json;
44use std::sync::OnceLock;
45
46use std::path::PathBuf;
47
48use anyhow::Result;
49use ctb_workspace_ipc::services::parent::ParentMessageEvent;
50use ctb_workspace_ipc::workspace_runner::workspace_runtime::{
51    ResolvedParentMessage, WorkspaceRuntime,
52};
53use ctb_workspace_ipc::workspace_runner::{
54    SpawnRequestDecision, SpawnRequester, WorkspaceExt, WorkspaceRunner,
55    WorkspaceRunnerConfig,
56};
57
58use crate::capabilities::{
59    create_io_capabilities, create_network_capabilities,
60    create_renderer_capabilities, create_runtime_capabilities,
61    create_storage_capabilities,
62};
63
64use ctb_utilities::testing::binary_path::resolve_binary_path_supporting_tests_or_example;
65
66pub use ctb_workspace_ipc;
67pub mod capabilities;
68pub mod crlite;
69pub mod environment;
70pub mod panic_hooks;
71pub mod process;
72pub mod update_status;
73
74pub async fn entry() -> anyhow::Result<()> {
75    ctb_wasm_substitutes::ensure_registered();
76    let raw_args: Vec<String> = std::env::args().collect();
77    invocation_settings::apply_command_line_args(&raw_args)?;
78
79    // Parse either a subprocess invocation or a user CLI command set.
80    let invocation = cli::parse_invocation(Some(raw_args))?;
81
82    match invocation {
83        cli::Invocation::Subprocess(sub) => {
84            crate::utilities::environment::set_process_role(
85                crate::utilities::environment::ProcessRole::ServiceSubprocess,
86            );
87            setup_logger_for_subprocess(&sub.kind)?;
88            setup_subprocess_panic_hooks();
89            ctb_storage_minimal::xkb::ensure_xkb_config_root()?;
90            ctb_storage_minimal::xkb::ensure_x11_locale_root()?;
91            ctb_storage::validate_resource_bundle()?;
92            start_service(&sub.kind, &sub.args).await?;
93            Ok(())
94        }
95        cli::Invocation::User(cli_args) => {
96            if cli_args.command.is_some() {
97                crate::utilities::environment::set_process_role(
98                    crate::utilities::environment::ProcessRole::LightweightCli,
99                );
100            } else {
101                crate::utilities::environment::set_process_role(
102                    crate::utilities::environment::ProcessRole::WorkspaceMain,
103                );
104            }
105            // Skip for subprocesses to avoid race.
106            check_filesystem_lock_support()?;
107
108            // Try lightweight tools (hex2dec, etc.).
109            if let Some(code) = cli::maybe_run_lightweight(&cli_args).await? {
110                // Allow tests to inspect code by returning an error code if
111                // desired, but typically just exit here:
112                std::process::exit(code);
113            }
114
115            // Proceed with full application boot.
116            ctb_storage_minimal::xkb::ensure_xkb_config_root()?;
117            ctb_storage_minimal::xkb::ensure_x11_locale_root()?;
118            setup_logger_for_user()?;
119            setup_workspace_panic_hooks();
120            ctb_storage::validate_resource_bundle()?;
121            boot(cli_args).await?;
122            Ok(())
123        }
124    }
125}
126
127fn setup_logger_for_user() -> anyhow::Result<()> {
128    crate::utilities::logging::setup_logger(
129        "workspace".to_string(),
130        "workspace".to_string(),
131    )
132}
133
134fn setup_logger_for_subprocess(kind: &ChildKind) -> anyhow::Result<()> {
135    let sub_index = format_child_kind(kind).to_string();
136    let service_name = format_child_kind(kind).to_string();
137    crate::utilities::logging::setup_logger(sub_index, service_name)
138}
139
140/// Main boot logic for normal application startup.
141async fn boot(args: Cli) -> Result<()> {
142    // The real workspace should run until it receives a shutdown request
143    // (e.g. Ctrl-C or an explicit child->parent shutdown request).
144    let runner = WorkspaceRunner::new(
145        CtbWorkspace::default().with_args(args),
146        WorkspaceRunnerConfig::default(),
147        resolve_exe_path()?.into(),
148        None,
149    );
150    let stats = runner.run().await?;
151
152    anyhow::ensure!(
153        stats.shutdown_received,
154        "Workspace timed out or exited without shutdown"
155    );
156    anyhow::ensure!(
157        !stats.forced_termination,
158        "Workspace required forced termination"
159    );
160
161    debug_fmt!(
162        "--- Shutdown summary: received {} data plane messages, shutdown={} ---",
163        stats.data_plane_messages_received,
164        stats.shutdown_received
165    );
166    Ok(())
167}
168
169#[derive(Debug)]
170struct CtbWorkspace {
171    services: WorkspaceServices,
172    args: Cli,
173}
174
175impl CtbWorkspace {
176    fn with_args(mut self, args: Cli) -> Self {
177        self.args = args;
178        self
179    }
180
181    fn args(&self) -> &Cli {
182        &self.args
183    }
184}
185
186impl Default for CtbWorkspace {
187    fn default() -> Self {
188        Self {
189            services: WorkspaceServices::default(),
190            args: Cli {
191                ctoolbox_ipc_port: None,
192                no_update: false,
193                use_bundled_tls_validator: false,
194                use_system_tls_validator: false,
195                insecure_skip_crlite_check: false,
196                retry_on_host_error:
197                    invocation_settings::DEFAULT_RETRY_ON_HOST_ERROR,
198                recover_graph: false,
199                version_json: false,
200                command: None,
201            },
202        }
203    }
204}
205
206#[async_trait::async_trait]
207impl Workspace for CtbWorkspace {
208    fn services_needed(&self) -> Vec<(ChildKind, CapabilitySet)> {
209        vec![
210            (ChildKind::Io, create_io_capabilities()),
211            (ChildKind::Network, create_network_capabilities()),
212            (ChildKind::Storage, create_storage_capabilities()),
213        ]
214    }
215
216    fn services(&self) -> &WorkspaceServices {
217        &self.services
218    }
219
220    fn set_services(&mut self, services: WorkspaceServices) {
221        self.services = services;
222    }
223
224    async fn boot(&mut self, rt: &WorkspaceRuntime) -> Result<()> {
225        info_fmt!(
226            "Starting Collective Toolbox on socket: {}",
227            rt.socket_path()
228        );
229
230        if self.args().no_update {
231            log!("Skipping update checks due to --no-update");
232        } else {
233            // Check for an already-downloaded pending update on disk before opening the UI.
234            match update_status::apply_pending_startup_update() {
235                update_status::StartupUpdateResult::UpgradeStarted => {
236                    // Upgrade process was initiated - we need to exit
237                    info!(
238                        "Upgrade started, exiting to allow canary process to take over"
239                    );
240                    std::process::exit(0);
241                }
242                update_status::StartupUpdateResult::NoPendingUpdate
243                | update_status::StartupUpdateResult::TimedOut => {}
244                update_status::StartupUpdateResult::Error(e) => {
245                    warn_fmt!("Startup pending update check failed: {e}");
246                }
247            }
248        }
249
250        // Best-effort Ctrl-C handling: request graceful shutdown of the
251        // workspace runner.
252        //
253        // Note: `ctrlc` handlers are synchronous, so we forward the request
254        // onto the Tokio runtime.
255        let rt_for_signal = rt.clone();
256        let handle = tokio::runtime::Handle::current();
257        if let Err(e) = ctrlc::set_handler(move || {
258            let rt = rt_for_signal.clone();
259            handle.spawn(async move {
260                if let Err(e) =
261                    rt.request_shutdown(Some("ctrl-c".to_string())).await
262                {
263                    warn_fmt!("Failed to request shutdown; will try to force after timeout: {e:#}");
264                }
265            });
266        }) {
267            warn_fmt!("Failed to set ctrlc handler: {e:#}");
268        }
269
270        Ok(())
271    }
272
273    #[expect(
274        clippy::items_after_statements,
275        reason = "uniform macro injection patterns"
276    )]
277    async fn run(&self, rt: &WorkspaceRuntime) -> Result<()> {
278        // Allow the ipc! macro to be used in this function, so that instead of
279        // writing `self.io()?` one can write `ipc!(io)`.
280        macro_rules! __ctb_ipc_ctx {
281            () => {
282                self
283            };
284        }
285        macro_rules! __ctb_ipc_get {
286            ($ctx:expr, $service:ident) => {
287                $ctx.$service()?
288            };
289        }
290
291        let _storage_dir = get_storage_dir()?;
292        // let _renderer = ipc!(renderer)?;
293
294        ipc!(io).start_local_webui().await?;
295
296        // Capture the full boot environment and run network update checks in
297        // the background after the local Web UI is already up.
298        drop(tokio::task::spawn_blocking(
299            ctb_io_environment::init_boot_env,
300        ));
301
302        if !self.args().no_update {
303            // Reason for fallback: unconfigured server URL setting uses default official server URL
304            let server_url = pc_settings::get_str_setting(
305                pc_settings::PcSettingStrKey::ServerUrl,
306            )
307            .unwrap_or_else(default_url);
308            drop(tokio::spawn(async move {
309                match update_status::check_startup_network_update().await {
310                    update_status::StartupUpdateResult::NoPendingUpdate
311                    | update_status::StartupUpdateResult::UpgradeStarted => {}
312                    update_status::StartupUpdateResult::TimedOut => {
313                        log!(
314                            "Startup update check timed out, continuing startup"
315                        );
316                    }
317                    update_status::StartupUpdateResult::Error(e) => {
318                        warn_fmt!("Startup update check failed: {e}");
319                    }
320                }
321                if let Err(e) = update_status::spawn_update_checker(server_url)
322                {
323                    warn_fmt!(
324                        "Failed to start background update checker: {e:#}"
325                    );
326                }
327            }));
328        }
329
330        /* Example calls. A bit outdated. Leave here for now.
331        print(strtovec(
332            renderer.test_echo_3x("Hello, world!".into())
333                .await?,
334        ));
335
336        sleep(1);
337
338        let doc = ipc!(storage)
339            .get_asset("intro.html").expect("Could not load intro.html");
340        // let doc = strtovec("0");
341        let doc_str = vectostr(&doc);
342        print(strtovec(format!("Document: {doc_str}").as_str()));
343        // let pid = ipc!(runtime).start(ctb_formats::convert_from(doc, strtovec("html")));
344        // ipc!(runtime).start(ctb_formats::convert_from(doc, strtovec("html")));
345        data_channel_test().await; */
346
347        // Keep the workspace alive until shutdown is requested.
348        rt.wait_for_shutdown().await;
349
350        Ok(())
351    }
352
353    async fn on_parent_message(
354        &self,
355        rt: &WorkspaceRuntime,
356        event: ParentMessageEvent,
357    ) -> Result<()> {
358        debug_fmt!(
359            "Workspace received message from {:?}",
360            event.ctx.process_kind
361        );
362        handle_parent_message(rt, &event).await?;
363        Ok(())
364    }
365
366    async fn evaluate_spawn_request(
367        &self,
368        rt: &WorkspaceRuntime,
369        requester: SpawnRequester,
370        request: ctb_workspace_ipc::services::parent::api::SpawnChildRequest,
371    ) -> Result<SpawnRequestDecision> {
372        // If the request is for a singleton service (like Storage, Network, Io, Formats),
373        // and it is already running, we accept the request.
374        let is_singleton = matches!(
375            request.kind,
376            ChildKind::Storage
377                | ChildKind::Network
378                | ChildKind::Io
379                | ChildKind::Formats
380        );
381
382        if is_singleton {
383            if let Some(pid) = rt.get_singleton_pid(request.kind).await {
384                return Ok(SpawnRequestDecision::Accept {
385                    parent: Some(pid),
386                    caps: CapabilitySet::default(),
387                    extra_args: vec![],
388                });
389            }
390        }
391
392        // Allow the "io" service to spawn/access the runtime process.
393        if requester.ctx.process_kind.as_deref() == Some("io")
394            && request.kind == ChildKind::Runtime
395        {
396            let caps = create_runtime_capabilities();
397            return Ok(SpawnRequestDecision::Accept {
398                parent: None,
399                caps,
400                extra_args: vec![],
401            });
402        }
403
404        // Allow runtime processes to spawn nested runtimes or renderers.
405        if requester.ctx.process_kind.as_deref() == Some("runtime") {
406            if request.kind != ChildKind::Runtime
407                && request.kind != ChildKind::Renderer
408            {
409                return Ok(SpawnRequestDecision::Reject {
410                    error: Some(
411                        "only runtime + renderer spawn requests are allowed from runtime"
412                            .into(),
413                    ),
414                });
415            }
416
417            let caps = match request.kind {
418                ChildKind::Runtime => create_runtime_capabilities(),
419                ChildKind::Renderer => create_renderer_capabilities(),
420                _ => unreachable!(),
421            };
422
423            return Ok(SpawnRequestDecision::Accept {
424                parent: requester.pid,
425                caps,
426                extra_args: vec![],
427            });
428        }
429
430        Ok(SpawnRequestDecision::Reject {
431            error: Some(format!(
432                "spawn request for {:?} from {:?} denied by policy",
433                request.kind, requester.ctx.process_kind
434            )),
435        })
436    }
437}
438
439async fn handle_parent_message(
440    rt: &WorkspaceRuntime,
441    event: &ParentMessageEvent,
442) -> Result<()> {
443    match rt.resolve_parent_message(event).await? {
444        ResolvedParentMessage::DataPlaneBytes { bytes, .. } => {
445            debug_fmt!(
446                "Workspace received data plane message: {}",
447                String::from_utf8_lossy(&bytes)
448            );
449        }
450        ResolvedParentMessage::DataPlaneReadFailed { error, .. } => {
451            debug_fmt!("Workspace failed to read data plane blob: {error:#}");
452        }
453        ResolvedParentMessage::ShutdownRequest { reason } => {
454            debug_fmt!(
455                "Workspace received shutdown request: {}",
456                // Reason for fallback: shutdown request without explicit reason message defaults to "no reason"
457                reason.unwrap_or_else(|| "no reason".into())
458            );
459        }
460        ResolvedParentMessage::Text(text) => {
461            debug_fmt!("Workspace received text message: {text}");
462        }
463        ResolvedParentMessage::Other { kind } => {
464            debug_fmt!("Workspace received message of kind: {kind:?}");
465        }
466    }
467    Ok(())
468}
469
470fn resolve_exe_path() -> Result<PathBuf> {
471    resolve_binary_path_supporting_tests_or_example(
472        "ctoolbox",
473        Some("CTB_WORKSPACE_EXE"),
474    )
475}
476
477pub struct TestHarness;
478
479static HARNESS: OnceLock<TestHarness> = OnceLock::new();
480
481// Not meant to be used directly - use #[crate::ctb_test] instead.
482pub fn boot_for_test() -> Option<&'static TestHarness> {
483    if HARNESS.get().is_some() {
484        return HARNESS.get();
485    }
486
487    // Note that this logger setup is only used for the workspace tests.
488    // Individual tests have their own loggers set up by the ctb_test macro.
489    if setup_logger_for_user().is_ok() {
490        setup_workspace_panic_hooks();
491        let _ = HARNESS.set(TestHarness);
492    }
493
494    HARNESS.get()
495}