ctb_workspace_ipc/services/
process.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//! Process service implementation.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub mod api;
30pub mod channel;
31
32pub use api::{
33    METHOD_SHUTDOWN_OWN_TREE, METHOD_SHUTDOWN_TREE, ProcessService,
34    ShutdownTreeRequest, ShutdownTreeResponse,
35};
36
37pub use channel::{
38    OneshotShutdownProcessService, ShutdownChannelProcessService,
39};
40
41use crate::error::Error;
42use crate::protocol::{Request, Response, RpcError};
43use crate::router::IpcRouter;
44
45use anyhow::Result;
46
47/// Service name for process-level operations.
48pub const SERVICE_NAME: &str = "process";
49
50fn decode_shutdown_request(
51    args: &[u8],
52) -> Result<ShutdownTreeRequest, RpcError> {
53    if args.is_empty() {
54        return Ok(ShutdownTreeRequest::default());
55    }
56    postcard_helpers::decode::<ShutdownTreeRequest>(args, "shutdown request")
57        .map_err(|e| RpcError {
58            code: "invalid_args".into(),
59            message: format!("invalid workspace.shutdown args: {e}"),
60        })
61}
62
63pub(crate) async fn dispatch_process(
64    router: &IpcRouter,
65    request: Request,
66) -> Result<Response, Error> {
67    if let Err(resp) = IpcRouter::check_service(
68        router.process_service.as_ref(),
69        "process",
70        request.id,
71    ) {
72        return Ok(resp);
73    }
74    let Some(svc) = router.process_service.as_ref() else {
75        return Ok(IpcRouter::error_response(
76            request.id,
77            "not_implemented",
78            "process service not configured",
79        ));
80    };
81    // Note: shutdown_tree is for whole app shutdown (privileged).
82    // shutdown_own_tree is for shutting down the calling process and its
83    // descendants only. Capability enforcement happens at the router level.
84    match request.method.method.as_str() {
85        METHOD_SHUTDOWN_TREE => {
86            let shutdown_req = match decode_shutdown_request(&request.args) {
87                Ok(req) => req,
88                Err(e) => {
89                    return Ok(IpcRouter::error_response(
90                        request.id, &e.code, &e.message,
91                    ));
92                }
93            };
94            router
95                .handle_service_call(
96                    svc.shutdown_tree(shutdown_req),
97                    request.id,
98                )
99                .await
100        }
101        METHOD_SHUTDOWN_OWN_TREE => {
102            let shutdown_req = match decode_shutdown_request(&request.args) {
103                Ok(req) => req,
104                Err(e) => {
105                    return Ok(IpcRouter::error_response(
106                        request.id, &e.code, &e.message,
107                    ));
108                }
109            };
110            router
111                .handle_service_call(
112                    svc.shutdown_own_tree(shutdown_req),
113                    request.id,
114                )
115                .await
116        }
117        _ => Ok(IpcRouter::error_response(
118            request.id,
119            "not_implemented",
120            "method not implemented",
121        )),
122    }
123}
124
125#[cfg(test)]
126#[allow(
127    clippy::panic,
128    clippy::expect_used,
129    clippy::unwrap_used,
130    clippy::unwrap_in_result,
131    clippy::panic_in_result_fn,
132    clippy::indexing_slicing,
133    clippy::arithmetic_side_effects,
134    reason = "Standard repository test boilerplate"
135)]
136mod tests {
137    use super::*;
138
139    use crate::auth::capability::{
140        CapabilitySet, MethodRule, MethodSelector, ServiceName,
141    };
142
143    use crate::protocol::{MethodId, Request};
144    use crate::router::{ConnectionContext, Router};
145
146    use crate::services::process::api::MockProcessService;
147    use crate::types::ConnectionId;
148
149    use anyhow::Result;
150    use std::collections::HashMap;
151    use std::sync::Arc;
152
153    #[crate::ctb_test("tokio")]
154    async fn routes_workspace_shutdown() -> Result<()> {
155        let router =
156            IpcRouter::new().with_process_service(Arc::new(MockProcessService));
157
158        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
159        allowed.insert(
160            ServiceName("process".to_string()),
161            vec![MethodRule {
162                method: MethodSelector::Exact("shutdown_tree".into()),
163                quotas: None,
164            }],
165        );
166
167        let ctx = ConnectionContext {
168            id: ConnectionId::default(),
169            capabilities: CapabilitySet {
170                allowed,
171                global_limits: None,
172            },
173            metadata: None,
174        };
175
176        let req = Request {
177            id: Default::default(),
178            method: MethodId {
179                service: "process".into(),
180                method: "shutdown_tree".into(),
181            },
182            args: vec![],
183        };
184
185        let resp = router.dispatch(&ctx, req).await?;
186        anyhow::ensure!(resp.ok, "expected ok response: {resp:?}");
187        anyhow::ensure!(resp.error.is_none(), "unexpected error: {resp:?}");
188        Ok(())
189    }
190}