ctb_workspace_ipc/services/macros.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//! Macro helpers for service dispatch/client glue.
21//!
22//! These macros exist to remove repetitive boilerplate across IPC services
23//! while keeping behavior (wire format, error codes, logging labels) the same.
24
25/// Generate a postcard service dispatcher.
26///
27/// This expands to:
28/// - service availability checks via `router.check_service`,
29/// - request decoding via `router.decode_request`,
30/// - calling the service method and piping through `router.handle_service_call`.
31///
32/// The macro is intentionally small and explicit: you still list each method,
33/// but you don’t repeat the same decode/handle scaffolding for every service.
34#[macro_export]
35macro_rules! ipc_dispatch_postcard_service {
36 (
37 router: $router:expr,
38 request: $request:expr,
39 service_field: $service_field:ident,
40 service_name: $service_name:expr,
41 methods: {
42 $(
43 $method_id:pat => $decode_label:literal => $req_ty:ty => $svc_method:ident
44 ),+ $(,)?
45 }
46 ) => {{
47 if let Err(resp) = $crate::router::IpcRouter::check_service(
48 $router.$service_field.as_ref(),
49 $service_name,
50 $request.id,
51 ) {
52 return Ok(resp);
53 }
54
55 let svc = $router.$service_field.as_ref().ok_or_else(|| {
56 anyhow::anyhow!("{service_name} service missing", service_name = $service_name)
57 })?;
58
59 match $request.method.method.as_str() {
60 $(
61 $method_id => {
62 let req: $req_ty = match $crate::router::IpcRouter::decode_request(
63 &$request.args,
64 $decode_label,
65 $request.id,
66 ) {
67 Ok(req) => req,
68 Err(resp) => return Ok(resp),
69 };
70
71 $router
72 .handle_service_call(svc.$svc_method(req), $request.id)
73 .await
74 }
75 )+
76 _ => Ok($crate::router::IpcRouter::error_response(
77 $request.id,
78 "not_implemented",
79 "method not implemented",
80 )),
81 }
82 }};
83}
84
85/// Generate a simple postcard-based IPC client method.
86///
87/// This is intended for the common case where a client method:
88/// - constructs a request DTO,
89/// - calls `ChildProcess::call_postcard`,
90/// - maps the decoded response to the return value.
91///
92/// More complex IPC paths (data plane, FD transfer, streaming) should remain
93/// hand-written.
94#[macro_export]
95macro_rules! ipc_client_postcard_method {
96 (
97 $(#[$meta:meta])*
98 $vis:vis async fn $name:ident(
99 &self $(, $arg:ident : $arg_ty:ty )* $(,)?
100 ) -> $ret:ty {
101 service: $service_name:expr,
102 method: $method_name:expr,
103 request: $req_expr:expr,
104 response: $resp_ty:ty,
105 map: |$resp:ident| $map_expr:expr $(,)?
106 }
107 ) => {
108 $(#[$meta])*
109 $vis async fn $name(
110 &self $(, $arg : $arg_ty )*
111 ) -> $ret {
112 let req = $req_expr;
113 let __ipc_resp: $resp_ty = self
114 .proc
115 .call_postcard($service_name, $method_name, &req)
116 .await?;
117 Ok({
118 let $resp = __ipc_resp;
119 $map_expr
120 })
121 }
122 };
123}
124
125/// Generate a postcard-based IPC client method for *proxied* child calls.
126///
127/// This is the common case where a child process asks the workspace to spawn
128/// another child, then communicates with it via the parent `proxy_call` API.
129#[macro_export]
130macro_rules! ipc_peer_proxied_postcard_method {
131 (
132 $(#[$meta:meta])*
133 $vis:vis async fn $name:ident(
134 &self $(, $arg:ident : $arg_ty:ty )* $(,)?
135 ) -> $ret:ty {
136 service: $service_name:expr,
137 method: $method_name:expr,
138 request: $req_expr:expr,
139 response: $resp_ty:ty,
140 map: |$resp:ident| $map_expr:expr $(,)?
141 }
142 ) => {
143 $(#[$meta])*
144 $vis async fn $name(
145 &self $(, $arg : $arg_ty )*
146 ) -> $ret {
147 let req = $req_expr;
148 let __ipc_resp: $resp_ty = self
149 .proxy
150 .call_postcard($service_name, $method_name, &req)
151 .await?;
152 Ok({
153 let $resp = __ipc_resp;
154 $map_expr
155 })
156 }
157 };
158}
159
160/// Generate an `async_trait` impl that forwards each method to a local
161/// async method on `self`.
162///
163/// This is intended for service clients that have already defined the IPC
164/// methods (often via `ipc_client_postcard_method!` or
165/// `ipc_peer_proxied_postcard_method!`) and just need to implement the
166/// corresponding `ctb_utilities::ipc::service_traits::*ClientTrait`.
167///
168/// Example:
169/// ```
170/// # use ctb_utilities::anyhow::{self, Result};
171/// # use ctb_workspace_ipc::ipc_impl_forward_async_trait;
172/// # #[async_trait::async_trait]
173/// # trait RuntimeClientTrait {
174/// # async fn start(&self, document: Vec<u8>) -> Result<()>;
175/// # }
176/// # struct RuntimeClient;
177/// # impl RuntimeClient {
178/// # async fn start_ipc(&self, document: Vec<u8>) -> Result<()> {
179/// # anyhow::ensure!(document == b"document", "Incorrect forwarded document");
180/// # Ok(())
181/// # }
182/// # }
183/// ipc_impl_forward_async_trait!(
184/// impl RuntimeClientTrait for RuntimeClient {
185/// async fn start(&self, document: Vec<u8>) -> Result<()> => start_ipc;
186/// }
187/// );
188/// # #[tokio::main]
189/// # async fn main() -> Result<()> {
190/// # RuntimeClientTrait::start(&RuntimeClient, b"document".to_vec()).await
191/// # }
192/// ```
193#[macro_export]
194macro_rules! ipc_impl_forward_async_trait {
195 (
196 impl $trait:ident for $ty:ty {
197 $(
198 async fn $name:ident(
199 &self $(, $arg:ident : $arg_ty:ty )* $(,)?
200 ) -> $ret:ty => $target:ident;
201 )+
202 }
203 ) => {
204 #[async_trait::async_trait]
205 impl $trait for $ty {
206 $(
207 async fn $name(
208 &self $(, $arg : $arg_ty )*
209 ) -> $ret {
210 self.$target($($arg),*).await
211 }
212 )+
213 }
214 };
215}
216
217/// Generate an `async_trait` impl where each method calls an IPC client
218/// extension trait generated by `#[ipc_method]`.
219///
220/// This supports the common ergonomic pattern where the public client trait
221/// takes borrowed inputs (like `&str`), while the IPC layer uses owned types.
222/// Currently, `&str` arguments are converted to `String` via `.to_string()`.
223///
224/// Example:
225/// ```
226/// # use ctb_utilities::anyhow::Result;
227/// # use ctb_workspace_ipc::ipc_impl_ipc_ext_async_trait;
228/// # #[async_trait::async_trait]
229/// # trait NetworkClientTrait {
230/// # async fn fetch(&self, url: &str) -> Result<Vec<u8>>;
231/// # }
232/// # #[async_trait::async_trait]
233/// # trait FetchIpcClientExt {
234/// # async fn fetch(&self, url: String) -> Result<Vec<u8>>;
235/// # }
236/// # struct NetworkClient;
237/// # #[async_trait::async_trait]
238/// # impl FetchIpcClientExt for NetworkClient {
239/// # async fn fetch(&self, url: String) -> Result<Vec<u8>> {
240/// # Ok(url.into_bytes())
241/// # }
242/// # }
243/// ipc_impl_ipc_ext_async_trait!(
244/// impl NetworkClientTrait for NetworkClient {
245/// async fn fetch(&self, url: &str) -> Result<Vec<u8>>
246/// => FetchIpcClientExt(url.to_string());
247/// }
248/// );
249/// # #[tokio::main]
250/// # async fn main() -> Result<()> {
251/// # assert_eq!(NetworkClientTrait::fetch(&NetworkClient, "url").await?, b"url");
252/// # Ok(())
253/// # }
254/// ```
255#[macro_export]
256macro_rules! ipc_impl_ipc_ext_async_trait {
257 (
258 impl $trait:ident for $ty:ty {
259 $(
260 async fn $name:ident(
261 &self $(, $arg:ident : $arg_ty:ty )* $(,)?
262 ) -> $ret:ty => $ext_trait:ident ( $( $call_arg:expr ),* $(,)? );
263 )+
264 }
265 ) => {
266 #[async_trait::async_trait]
267 impl $trait for $ty {
268 $(
269 async fn $name(
270 &self $(, $arg : $arg_ty )*
271 ) -> $ret {
272 <Self as $ext_trait>::$name(
273 self
274 $(, $call_arg )*
275 )
276 .await
277 }
278 )+
279 }
280 };
281}