tokio_ipc 0.1.0

Multi-protocol RPC framework built on top of tokio
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Fixed version of rpc_macros.rs with proper paste! usage

#[macro_export]
macro_rules! protocol {
   (
       $(#[version($version:expr)])?
       pub mod $protocol_name:ident {
           $(
               $(#[$command_attr:meta])*
               $command:ident $(<$($command_lifetime:lifetime),*>)?
               $( ( $tuple_ty:ty ) )? $( {
                   $(
                       $(#[$command_field_attr:meta])*
                       $command_field:ident : $command_field_ty:ty
                   ),* $(,)?
               } )?
               $(->
                   $(#[$reply_attr:meta])*
                   {
                       $(
                           $(#[$reply_field_attr:meta])*
                           $reply_field:ident : $reply_field_ty:ty
                       ),* $(,)?
                   }
               )?
               $(return $plain_reply:ty)?
           );* $(;)?
       }
   ) => {
        $crate::paste! {           pub mod $protocol_name {
               use super::*;
               
               /*──── Protocol metadata and ID ──────────────────────────*/
               /// Auto-generated stable protocol ID
               pub const PROTOCOL_ID: u64 = {
                   // Combine crate name + protocol name for global uniqueness
                   const PROTOCOL_NAME: &str = concat!(
                       env!("CARGO_PKG_NAME"),
                       "::",
                       stringify!($protocol_name)
                   );
                    const VERSION: u32 = $crate::protocol!(@version $($version)?);
                    $crate::protocol_id(PROTOCOL_NAME, VERSION)               };
               
               /// Protocol metadata for debugging
               pub const PROTOCOL_NAME: &str = stringify!($protocol_name);
               pub const PROTOCOL_CRATE: &str = env!("CARGO_PKG_NAME");
               pub const PROTOCOL_VERSION: u32 = $crate::protocol!(@version $($version)?);
               
               /// Marker type for protocol metadata
               pub struct ProtocolMarker;
               
                impl $crate::ProtocolMetadata for ProtocolMarker {                   const PROTOCOL_ID: u64 = PROTOCOL_ID;
                   const PROTOCOL_NAME: &'static str = PROTOCOL_NAME;
                   const PROTOCOL_CRATE: &'static str = PROTOCOL_CRATE;
                   const PROTOCOL_VERSION: u32 = PROTOCOL_VERSION;
               }

               /*──── command / reply structs ───────────────────────────*/
               $(
                   pub mod $command {
                       use super::*;

                       $crate::protocol!(@request_struct
                           $(#[$command_attr])*
                           Request $(<$($command_lifetime),*>)?
                           $( ( $tuple_ty ) )?
                           $( {
                               $(
                                   $(#[$command_field_attr])*
                                   $command_field : $command_field_ty
                               ),*
                           } )?
                       );

                       // Handle structured reply separately
                       $crate::protocol!(@maybe_response_struct
                           $command
                           $(-> $(#[$reply_attr])* {
                               $(
                                   $(#[$reply_field_attr])*
                                   $reply_field : $reply_field_ty
                               ),*
                           })?
                           $(return $plain_reply)?
                       );
                   }
               )*

                /*──── request wrapper enum ──────────────────────────────*/
                #[derive( $crate::Serialize, $crate::Deserialize)]               #[allow(non_camel_case_types)]
               pub enum Requests {
                   $(
                       $command($command::Request $(<$($command_lifetime),*>)?),
                   )*
               }

               /*──── Protocol Sender Trait ──────────────────────────────*/
               /// Trait for sending this protocol's messages
               /// Any sender that implements RpcProtocolSender can implement this
                pub trait Sender: $crate::RpcProtocolSender {                   /*──── convenience methods for each command ──────────────*/
                   $(
                       $crate::protocol!(@sender_trait_method 
                           in_paste
                           $command $(<$($command_lifetime),*>)?
                           $( ( $tuple_ty ) )?
                           $( {
                               $(
                                   $command_field : $command_field_ty
                               ),*
                           } )?
                           $(-> {
                               $(
                                   $reply_field : $reply_field_ty
                               ),*
                           })?
                           $(return $plain_reply)?
                       );
                   )*
               }

               /*──── user-implemented handler trait ────────────────────*/
               pub trait Receive: Clone + Send + Sync + 'static {
                   $(
                       $crate::protocol!(@handler_fn
                           $command $(<$($command_lifetime),*>)?
                           $( ( $tuple_ty ) )?
                           $( {
                               $(
                                   $command_field : $command_field_ty
                               ),*
                           } )?
                           $(-> {
                               $(
                                   $reply_field : $reply_field_ty
                               ),*
                           })?
                           $(return $plain_reply)?
                       );
                   )*

                   fn into_receiver(self) -> Receiver<Self>
                   where
                       Self: Sized,
                   {
                       Receiver::new(self)
                   }
               }

               /*──── protocol receiver ──────────────────────────────────*/
               #[derive(Clone)]
               pub struct Receiver<R: Receive> {
                   handler: R,
               }

               impl<R: Receive> std::fmt::Debug for Receiver<R> {
                   fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                       f.debug_struct(stringify!(Receiver)).finish()
                   }
               }

               impl<R: Receive + 'static> Receiver<R> {
                   pub fn new(handler: R) -> Self {
                       Self { handler }
                   }

                   pub fn handler(&self) -> &R {
                       &self.handler
                   }
               }
               
               /// Wrapper to make Receiver implement ProtocolHandler
               pub struct ReceiverWrapper<R: Receive> {
                   receiver: Receiver<R>,
               }
               
               impl<R: Receive> ReceiverWrapper<R> {
                   pub fn new(handler: R) -> Self {
                       Self {
                           receiver: Receiver::new(handler),
                       }
                   }
               }
               
                impl<R: Receive + 'static> $crate::ProtocolHandler for ReceiverWrapper<R> {                   fn handle_packet(
                       &self,
                       peer: &$crate::SocketPeer,
                       buf: Vec<u8>,
                   ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<Option<Vec<u8>>>> + Send + '_>> {
                        Box::pin(async move {
                            let request_wrapper: Requests = $crate::bincode::deserialize(&buf)?;                           let handler = self.receiver.handler.clone();

                           match request_wrapper {
                               $(
                                   Requests::$command(request) => {
                                       $crate::protocol!(@handler_body
                                           handler,
                                           request,
                                           $command
                                           $( ( $tuple_ty ) )?
                                           $( {
                                               $(
                                                   $command_field : $command_field_ty
                                               ),*
                                           } )?
                                           $(-> {
                                               $(
                                                   $reply_field : $reply_field_ty
                                               ),*
                                           })?
                                           $(return $plain_reply)?
                                       )
                                   }
                               )*
                           }
                       })
                   }
               }

                // For backward compatibility with single-protocol usage
                impl<R: Receive + 'static> $crate::ReceiveRpcProtocol for Receiver<R> {                   async fn handle_packet(
                       &self,
                       _protocol_id: u64,
                       peer: &$crate::SocketPeer,
                       buf: Vec<u8>,
                   ) -> anyhow::Result<Option<Vec<u8>>> {
                        let wrapper = ReceiverWrapper::new(self.handler.clone());
                        use $crate::ProtocolHandler;                       wrapper.handle_packet(peer, buf).await
                   }
               }
           }
       }
   };
   
   (@version $version:expr) => { $version };
   (@version) => { 1 };

   /* helper: request struct definitions */
    (@request_struct $(#[$attr:meta])* Request $(<$($lifetime:lifetime),*>)? ( $tuple_ty:ty )) => {
        $(#[$attr])*
        #[derive( $crate::Serialize, $crate::Deserialize)]       pub struct Request $(<$($lifetime),*>)? (pub $tuple_ty);
   };

    (@request_struct $(#[$attr:meta])* Request $(<$($lifetime:lifetime),*>)? { $($(#[$field_attr:meta])* $field:ident : $ft:ty),+ }) => {
        $(#[$attr])*
        #[derive( $crate::Serialize, $crate::Deserialize)]       pub struct Request $(<$($lifetime),*>)? {
           $($(#[$field_attr])* pub $field: $ft,)+
       }
   };

    (@request_struct $(#[$attr:meta])* Request $(<$($lifetime:lifetime),*>)?) => {
        $(#[$attr])*
        #[derive( $crate::Serialize, $crate::Deserialize)]       pub struct Request $(<$($lifetime),*>)? ;
   };

   /* helper: response struct definitions */
    (@maybe_response_struct $command:ident -> $(#[$attr:meta])* { $($(#[$field_attr:meta])* $field:ident : $ft:ty),* }) => {
        $(#[$attr])*
        #[derive( $crate::Serialize, $crate::Deserialize)]       pub struct Response {
           $($(#[$field_attr])* pub $field: $ft,)*
       }
   };

   (@maybe_response_struct $command:ident return $plain_reply:ty) => {};
   (@maybe_response_struct $command:ident) => {};

   /* helper: sender trait methods - INSIDE paste context */
   (@sender_trait_method in_paste $command:ident { $($command_field:ident : $command_field_ty:ty),* } -> { $($reply_field:ident : $reply_field_ty:ty),* }) => {
       fn $command(&self, $($command_field: $command_field_ty,)*) 
           -> impl std::future::Future<Output = anyhow::Result<$command::Response>> + Send 
       {
           async move {
               let request = Requests::$command($command::Request { $($command_field,)* });
               self.peer().send_message_with_response_to_protocol(PROTOCOL_ID, &request).await
           }
       }
   };
   
   (@sender_trait_method in_paste $command:ident { $($command_field:ident : $command_field_ty:ty),* } return $plain_reply:ty) => {
       fn $command(&self, $($command_field: $command_field_ty,)*) 
           -> impl std::future::Future<Output = anyhow::Result<$plain_reply>> + Send 
       {
           async move {
               let request = Requests::$command($command::Request { $($command_field,)* });
               self.peer().send_message_with_response_to_protocol(PROTOCOL_ID, &request).await
           }
       }
   };
   
   (@sender_trait_method in_paste $command:ident { $($command_field:ident : $command_field_ty:ty),* }) => {
       fn $command(&self, $($command_field: $command_field_ty,)*) 
           -> impl std::future::Future<Output = anyhow::Result<()>> + Send 
       {
           async move {
               let request = Requests::$command($command::Request { $($command_field,)* });
               self.peer().send_message_to_protocol(PROTOCOL_ID, &request).await
           }
       }
   };
   
   (@sender_trait_method in_paste $command:ident -> { $($reply_field:ident : $reply_field_ty:ty),* }) => {
       fn $command(&self) 
           -> impl std::future::Future<Output = anyhow::Result<$command::Response>> + Send 
       {
           async move {
               let request = Requests::$command($command::Request);
               self.peer().send_message_with_response_to_protocol(PROTOCOL_ID, &request).await
           }
       }
   };
   
   (@sender_trait_method in_paste $command:ident return $plain_reply:ty) => {
       fn $command(&self) 
           -> impl std::future::Future<Output = anyhow::Result<$plain_reply>> + Send 
       {
           async move {
               let request = Requests::$command($command::Request);
               self.peer().send_message_with_response_to_protocol(PROTOCOL_ID, &request).await
           }
       }
   };
   
   (@sender_trait_method in_paste $command:ident) => {
       fn $command(&self) 
           -> impl std::future::Future<Output = anyhow::Result<()>> + Send 
       {
           async move {
               let request = Requests::$command($command::Request);
               self.peer().send_message_to_protocol(PROTOCOL_ID, &request).await
           }
       }
   };

   /* helper: handler function definitions */
   (@handler_fn $command:ident { $($command_field:ident : $command_field_ty:ty),* } -> { $($reply_field:ident : $reply_field_ty:ty),* }) => {
       fn $command(
           &self,
           $($command_field: $command_field_ty,)*
       ) -> impl std::future::Future<Output = anyhow::Result<$command::Response>> + Send + Sync;
   };
   
   (@handler_fn $command:ident { $($command_field:ident : $command_field_ty:ty),* } return $plain_reply:ty) => {
       fn $command(
           &self,
           $($command_field: $command_field_ty,)*
       ) -> impl std::future::Future<Output = anyhow::Result<$plain_reply>> + Send + Sync;
   };
   
   (@handler_fn $command:ident { $($command_field:ident : $command_field_ty:ty),* }) => {
       fn $command(
           &self,
           $($command_field: $command_field_ty,)*
       ) -> impl std::future::Future<Output = anyhow::Result<()>> + Send + Sync;
   };
   
   (@handler_fn $command:ident -> { $($reply_field:ident : $reply_field_ty:ty),* }) => {
       fn $command(
           &self,
       ) -> impl std::future::Future<Output = anyhow::Result<$command::Response>> + Send + Sync;
   };
   
   (@handler_fn $command:ident return $plain_reply:ty) => {
       fn $command(
           &self,
       ) -> impl std::future::Future<Output = anyhow::Result<$plain_reply>> + Send + Sync;
   };
   
   (@handler_fn $command:ident) => {
       fn $command(
           &self,
       ) -> impl std::future::Future<Output = anyhow::Result<()>> + Send + Sync;
   };

   /* helper: handler body implementation */
   (@handler_body $handler:ident, $request:ident, $command:ident { $($command_field:ident : $command_field_ty:ty),* } -> { $($reply_field:ident : $reply_field_ty:ty),* }) => {
       {
            let response = $handler.$command($($request.$command_field,)*).await?;
            Ok(Some($crate::bincode::serialize(&response)?))
        }
    };
    
    (@handler_body $handler:ident, $request:ident, $command:ident { $($command_field:ident : $command_field_ty:ty),* } return $plain_reply:ty) => {
        {
            let response = $handler.$command($($request.$command_field,)*).await?;
            Ok(Some($crate::bincode::serialize(&response)?))
        }
    };
    
    (@handler_body $handler:ident, $request:ident, $command:ident { $($command_field:ident : $command_field_ty:ty),* }) => {
        {
            $handler.$command($($request.$command_field,)*).await?;
            Ok(None)
        }
    };
    
    (@handler_body $handler:ident, $request:ident, $command:ident -> { $($reply_field:ident : $reply_field_ty:ty),* }) => {
        {
            let response = $handler.$command().await?;
            Ok(Some($crate::bincode::serialize(&response)?))
        }
    };
    
    (@handler_body $handler:ident, $request:ident, $command:ident return $plain_reply:ty) => {
        {
            let response = $handler.$command().await?;
            Ok(Some($crate::bincode::serialize(&response)?))
        }   };
   
   (@handler_body $handler:ident, $request:ident, $command:ident) => {
       {
           $handler.$command().await?;
           Ok(None)
       }
   };
}


pub use protocol;