ctb_workspace_ipc/services/
runtime.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//! IPC client wrapper and code generation stub for the runtime service.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::services::IpcServiceClient;
30
31use ctb_utilities::ipc::service_traits::renderer::RenderSettings;
32
33include!("runtime.generated.rs");
34
35#[cfg(test)]
36#[allow(
37    clippy::panic,
38    clippy::expect_used,
39    clippy::unwrap_used,
40    clippy::unwrap_in_result,
41    clippy::panic_in_result_fn,
42    clippy::indexing_slicing,
43    clippy::arithmetic_side_effects,
44    reason = "Standard repository test boilerplate"
45)]
46mod tests {
47    use super::*;
48
49    use crate::auth::capability::{
50        CapabilitySet, MethodRule, MethodSelector, ServiceName,
51    };
52    use crate::data_plane::shared_memory::{
53        BlobAllocator as _, BlobBackend, SharedMemoryBlobs,
54    };
55    use crate::protocol::{MethodId, Request};
56    use crate::router::{ConnectionContext, IpcRouter, Router};
57    use anyhow::{Result, bail};
58    use std::collections::HashMap;
59
60    #[crate::ctb_test("tokio")]
61    async fn routes_runtime_start() -> Result<()> {
62        let router = IpcRouter::new();
63
64        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
65        allowed.insert(
66            ServiceName(SERVICE_NAME.to_string()),
67            vec![MethodRule {
68                method: MethodSelector::Exact(METHOD_START.into()),
69                quotas: None,
70            }],
71        );
72
73        let ctx = ConnectionContext {
74            id: crate::types::ConnectionId::default(),
75            capabilities: CapabilitySet {
76                allowed,
77                global_limits: None,
78            },
79            metadata: None,
80        };
81
82        let blobs = SharedMemoryBlobs::new(BlobBackend::TempFileFallback);
83        let bytes = b"test document";
84        let blob = blobs.create(u64::try_from(bytes.len())?).await?;
85        blob.write_all(bytes)
86            .map_err(|e| anyhow::anyhow!("blob write failed: {e}"))?;
87        let args = postcard_helpers::encode(
88            &(blob.token.clone(), blob.descriptor.clone()),
89            "runtime start args",
90        )?;
91        let req = Request {
92            id: u64::default(),
93            method: MethodId {
94                service: SERVICE_NAME.into(),
95                method: METHOD_START.into(),
96            },
97            args,
98        };
99
100        let resp = router.dispatch(&ctx, req).await?;
101        if !resp.ok {
102            bail!("expected ok response, got error: {:?}", resp.error);
103        }
104
105        let _ = blobs.cleanup(&blob.token).await;
106        Ok(())
107    }
108
109    #[crate::ctb_test("tokio")]
110    async fn routes_runtime_test_prepend() -> Result<()> {
111        let router = IpcRouter::new();
112
113        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
114        allowed.insert(
115            ServiceName(SERVICE_NAME.to_string()),
116            vec![MethodRule {
117                method: MethodSelector::Exact(METHOD_TEST_PREPEND.into()),
118                quotas: None,
119            }],
120        );
121
122        let ctx = ConnectionContext {
123            id: crate::types::ConnectionId::default(),
124            capabilities: CapabilitySet {
125                allowed,
126                global_limits: None,
127            },
128            metadata: None,
129        };
130
131        let args = postcard_helpers::encode(
132            &("world".to_string(), "hello ".to_string()),
133            "prepend args",
134        )?;
135        let req = Request {
136            id: u64::default(),
137            method: MethodId {
138                service: SERVICE_NAME.into(),
139                method: METHOD_TEST_PREPEND.into(),
140            },
141            args,
142        };
143
144        let resp = router.dispatch(&ctx, req).await?;
145        if !resp.ok {
146            bail!("expected ok response, got error: {:?}", resp.error);
147        }
148
149        let bytes = resp
150            .result
151            .ok_or_else(|| anyhow::anyhow!("ok response missing result"))?;
152        let decoded: String =
153            postcard_helpers::decode(&bytes, "prepend result")?;
154        anyhow::ensure!(
155            decoded == "hello world",
156            "unexpected value: {decoded}"
157        );
158        Ok(())
159    }
160
161    #[crate::ctb_test("tokio")]
162    async fn runtime_test_prepend_exit_is_not_implemented() -> Result<()> {
163        let router = IpcRouter::new();
164
165        // We explicitly authorize the unknown method so the router reaches the
166        // runtime dispatcher (this catches any "magic" method mapping).
167        let mut allowed: HashMap<ServiceName, Vec<MethodRule>> = HashMap::new();
168        allowed.insert(
169            ServiceName(SERVICE_NAME.to_string()),
170            vec![MethodRule {
171                method: MethodSelector::Exact("test_prepend_exit".into()),
172                quotas: None,
173            }],
174        );
175
176        let ctx = ConnectionContext {
177            id: crate::types::ConnectionId::default(),
178            capabilities: CapabilitySet {
179                allowed,
180                global_limits: None,
181            },
182            metadata: None,
183        };
184
185        // Args are irrelevant because dispatch should reject the method before
186        // decoding.
187        let req = Request {
188            id: u64::default(),
189            method: MethodId {
190                service: SERVICE_NAME.into(),
191                method: "test_prepend_exit".into(),
192            },
193            args: Vec::new(),
194        };
195
196        let resp = router.dispatch(&ctx, req).await?;
197        anyhow::ensure!(!resp.ok, "expected error response");
198        let err = resp.error.ok_or_else(|| anyhow::anyhow!("missing error"))?;
199        anyhow::ensure!(
200            err.code == "not_implemented",
201            "unexpected error code: {}",
202            err.code
203        );
204        Ok(())
205    }
206}