ckb_script_ipc_common/
ipc.rs

1use crate::error::IpcError;
2use serde::{Deserialize, Serialize};
3
4/// The `Serve` trait defines the interface for handling requests and generating responses in an IPC context.
5/// Types implementing this trait can be used to process incoming requests and produce appropriate responses.
6///
7/// # Associated Types
8///
9/// * `Req` - The type of the request messages. It must implement `Serialize` and `Deserialize`.
10/// * `Resp` - The type of the response messages. It must implement `Serialize` and `Deserialize`.
11///
12/// # Required Methods
13///
14/// * `serve` - This method is responsible for processing a single request and generating a response.
15/// * `method` - This method extracts a method name from the request, if applicable. It returns an `Option` containing a static string slice representing the method name.
16///
17/// # Example
18///
19/// ```rust,ignore
20/// use ckb_script_ipc_common::ipc::Serve;
21/// use serde::{Serialize, Deserialize};
22///
23/// #[derive(Serialize, Deserialize)]
24/// struct MyRequest {
25///     // request fields
26/// }
27///
28/// #[derive(Serialize, Deserialize)]
29/// struct MyResponse {
30///     // response fields
31/// }
32///
33/// struct MyService;
34///
35/// impl Serve for MyService {
36///     type Req = MyRequest;
37///     type Resp = MyResponse;
38///
39///     fn serve(&mut self, req: Self::Req) -> Result<Self::Resp, IpcError> {
40///         // process the request and generate a response
41///         Ok(MyResponse { /* fields */ })
42///     }
43///
44///     fn method(&self, _request: &Self::Req) -> Option<&'static str> {
45///         Some("my_method")
46///     }
47/// }
48/// ```
49pub trait Serve {
50    /// Type of request.
51    type Req: Serialize + for<'de> Deserialize<'de>;
52
53    /// Type of response.
54    type Resp: Serialize + for<'de> Deserialize<'de>;
55
56    /// Responds to a single request.
57    fn serve(&mut self, req: Self::Req) -> Result<Self::Resp, IpcError>;
58
59    /// Extracts a method name from the request.
60    fn method(&self, _request: &Self::Req) -> Option<&'static str> {
61        None
62    }
63}