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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
#![cfg_attr(feature = "docs", feature(doc_cfg))]
// non-builtin inner attribute is not stable
// #![cfg_attr(
//     any(
//         feature = "async_std_runtime",
//         feature = "tokio_runtime",
//         feature = "http_tide",
//         feature = "http_warp",
//         feature = "http_actix_web"
//     ),
//     any_runtime
// )]

//! # A toy RPC crate based on `async-std` that mimics the `golang`'s `net/rpc` package
//!
//! This crate aims at providing an easy-to-use RPC that is similar to `golang`'s
//! `net/rpc`.
//!
//! The usage is similar to that of `golang`'s `net/rpc` with functions sharing similar
//! names and functionalities. Certain function names are changed to be more rusty.
//! Because `rust` doesn't have reflection, attribute macros are used to make certain
//! method "exported".
//!
//! ## Content
//!
//! - [Crate Feature Flags](#crate-feature-flags)
//!   - [Default Features](#default-features)
//! - [Documentation](#documentation)
//! - [Examples](#examples)
//!   - [RPC over socket](#rpc-over-socket)
//!   - [RPC over HTTP with `tide`](#rpc-over-http-with-tide)
//!   - [RPC over HTTP with `actix-web`](#rpc-over-http-with-actix-web)
//! - [Change Log](#change-log)
//! - [Future Plan](#future-plan)
//!
//!
//! ## Crate Feature Flags
//!
//! This crate offers the following features flag
//!
//! - `std`: enables `serde/std`
//! - `serde_bincode`: the default codec will use `bincode`
//! for serialization/deserialization
//! - `serde_json`: the default codec will use `serde_json`
//! for `json` serialization/deserialization
//! - `serde_cbor`: the default codec will use `serde_cbor`
//! for serialization/deserialization
//! - `serde_rmp`: the default codec will use `rmp-serde`
//! for serialization/deserialization
//! - `logging`: enables logging
//! - `tide`: enables `tide` integration on the server side
//! - `actix-web`: enables `actix-web` integration on the server side
//! - `surf`: enables HTTP client on the client side
//!
//! ### Default Features
//!
//! ```toml
//! [features]
//! default = [
//!     "std",
//!     "serde_bincode",
//!     "tide",
//!     "surf",
//! ]
//! ```
//!
//! ## Documentation
//!
//! The following documentation is adapted based on `golang`'s documentation.
//!
//! This crate provides access to the methods marked with `#[export_impl]`
//! and `#[export_method]` of an object across a network connection. A server
//! registers an object, making it visible as a service with a name provided by the user.
//! After the registration, the "exported" methods will be accessible remotely.
//! A server may register multiple objects as multiple services, and multiple
//! objects of the same type or different types could be registered on the same
//! `Server` object.
//!
//! To export a method, use `#[export_method]` attribute in an impl block marked with
//! `#[export_impl]` attribute. This crate currently `only` support using `#[export_impl]` attribute
//! on `one` impl block per type.
//!
//! ```rust
//! struct ExampleService { }
//!
//! #[export_impl]
//! impl ExampleService {
//!     #[export_method]
//!     async fn exported_method(&self, args: ()) -> Result<String, String> {
//!         Ok("This is an exported method".to_string())
//!     }
//!
//!     async fn not_exported_method(&self, args: ()) -> Result<String, String> {
//!         Ok("This method is NOT exported".to_string())
//!     }
//! }
//! ```
//!
//! The methods to export must meet the following criteria on the server side
//!
//! - the method resides in an impl block marked with `#[export_impl]`
//! - the method is marked with `#[export_method]` attribute
//! - the method takes one argument other than `&self` and returns a `Result<T, E>`
//!   
//!   - the argument must implement trait `serde::Deserialize`
//!   - the `Ok` type `T` of the result must implement trait `serde::Serialize`
//!   - the `Err` type `E` of the result must implement trait `ToString`
//!   
//! - the method is essentially in the form
//!
//! ```rust
//! struct ServiceState { }
//!
//! #[export_impl]
//! impl ServiceState {
//!     #[export_method]
//!     async fn method_name(&self, args: Req) -> Result<Res, Msg>
//!     where
//!         Req: serde::Deserialize,
//!         Res: serde::Serialize,
//!         Msg: ToString,
//!     {
//!         unimplemented!()
//!     }
//! }
//! ```
//!
//! `Req` and `Res` are marshaled/unmarshaled (serialized/deserialized) by `serde`.
//! Realistically the `Req` and `Res` type must also be marshaled/unmarshaled on
//! the client side, and thus `Req` and `Res` must both implement *both*
//! `serde::Serialize` and `serde::Deserialize`.
//!
//! The method's argument reprements the argument provided by the client caller,
//! and the `Ok` type of result represents success parameters to be returned to
//! the client caller. The `Err` type of result is passed back to the client as
//! a `String`.
//!
//! The server may handle requests on a single connection by calling `serve_conn`,
//! and it may handle multiple connections by creating a `async_std::net::TcpListener`
//! and call `accept`. Integration with HTTP currently only supports `tide` by calling
//! `into_endpoint`.
//!
//! A client wishing to use the service establishes a `async_std::net::TcpStream` connection
//! and then creates `Client` over the connection. The convenience function `dial` performs
//! this step for raw TCP socket connection, and `dial_http` performs this for an HTTP
//! connection. A `Client` with HTTP connection or socket connection has three methods, `call`, `async_call`,
//! and `spawn_task`, to specify the service and method to call and the argument.
//!
//! Please note that `call_http`, `async_call_http` and `spawn_task_http` are becoming deprecated
//! as the same API now can be called for both a socket client and an HTTP client.
//!
//! - `call` method is synchronous and waits for the remote call
//! to complete and then returns the result.
//! - `async_call` is the `async` versions of `call` and `call_http`,
//! respectively. Because they are `async` functions, they must be called with `.await` to
//! be executed.
//! - `spawn_task` method spawns an `async` task and returns a `JoinHandle`.
//! The result can be obtained using the `JoinHandle`.
//!
//! Unless an explicity codec is set up (with `serve_codec` method, HTTP is *NOT* supported yet),
//! the default codec specified by one of the following features tags (`bincode`, `serde_json`)
//! will be used to transport data.
//!
//! ## HTTP integrations
//!
//! `toy-rpc` supports integration with `actix-web`, `tide`, and `warp`. The integration is
//! implemented using WebSocket as the transport protocol.
//!
//! `tide`
//!
//! ```rust
//! // assume rpc_server already exist
//! r
//! ```
//!
//! ## Examples
//!
//! A few simple examples are shown below. More examples can be found in the `examples`
//! directory in the repo.
//!
//! ### RPC over socket
//!
//! The default feature flags will work with the example below.
//!
//! server.rs
//!
//! ```rust
//! use async_std::net::TcpListener;
//! use async_std::sync::{Arc, Mutex};
//! use async_std::task;
//! use serde::{Serialize, Deserialize};
//!
//! use toy_rpc::macros::{export_impl, service};
//! use toy_rpc::Server;
//!
//! pub struct ExampleService {
//!     counter: Mutex<i32>
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleRequest {
//!     pub a: u32,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleResponse {
//!     a: u32,
//! }
//!
//! #[async_trait::async_trait]
//! trait Rpc {
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String>;
//! }
//!
//! #[async_trait::async_trait]
//! #[export_impl]
//! impl Rpc for ExampleService {
//!     #[export_method]
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String> {
//!         let mut counter = self.counter.lock().await;
//!         *counter += 1;
//!
//!         let res = ExampleResponse{ a: req.a };
//!         Ok(res)
//!     }
//! }
//!
//! #[async_std::main]
//! async fn main() {
//!     let addr = "127.0.0.1:8888";
//!     let example_service = Arc::new(
//!         ExampleService {
//!             counter: Mutex::new(0),
//!         }
//!     );
//!
//!     let server = Server::builder()
//!         .register("example", service!(example_service, ExampleService))
//!         .build();
//!
//!     let listener = TcpListener::bind(addr).await.unwrap();
//!     println!("Starting listener at {}", &addr);
//!
//!     let handle = task::spawn(async move {
//!         server.accept(listener).await.unwrap();
//!     });
//!     handle.await;
//! }
//!
//! ```
//!
//! client.rs
//!
//! ```rust
//! use serde::{Serialize, Deserialize};
//! use toy_rpc::Client;
//! use toy_rpc::error::Error;
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleRequest {
//!     a: u32
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleResponse {
//!     a: u32
//! }
//!
//! #[async_std::main]
//! async fn main() {
//!     let addr = "127.0.0.1:8888";
//!     let client = Client::dial(addr).await.unwrap();
//!
//!     let args = ExampleRequest{a: 1};
//!     let reply: Result<ExampleResponse, Error> = client.call("example.echo", &args);
//!     println!("{:?}", reply);
//! }
//! ```
//!
//! ### RPC over HTTP with `tide`
//!
//! The default feature flags will work with the example below.
//!
//! server.rs
//!
//! ```rust
//! use async_std::sync::{Arc, Mutex};
//! use serde::{Serialize, Deserialize};
//!
//! use toy_rpc::macros::{export_impl, service};
//! use toy_rpc::Server;
//!
//!
//! pub struct ExampleService {
//!     counter: Mutex<i32>
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleRequest {
//!     pub a: u32,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleResponse {
//!     a: u32,
//! }
//!
//! #[async_trait::async_trait]
//! trait Rpc {
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String>;
//! }
//!
//! #[async_trait::async_trait]
//! #[export_impl]
//! impl Rpc for ExampleService {
//!     #[export_method]
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String> {
//!         let mut counter = self.counter.lock().await;
//!         *counter += 1;
//!
//!         let res = ExampleResponse{ a: req.a };
//!         Ok(res)
//!     }
//! }
//!
//! #[async_std::main]
//! async fn main() -> tide::Result<()> {
//!     let addr = "127.0.0.1:8888";
//!     let example_service = Arc::new(
//!         ExampleService {
//!             counter: Mutex::new(0),
//!         }
//!     );
//!
//!     let server = Server::builder()
//!         .register("example", service!(example_service, ExampleService))
//!         .build();
//!
//!     let mut app = tide::new();
//!     app.at("/rpc/").nest(server.into_endpoint());
//!     "handle_http" is a conenience function that calls "into_endpoint"
//!     // with the "tide" feature turned on and "actix-web" feature disabled
//!     //app.at("/rpc/").nest(server.handle_http());
//!
//!     app.listen(addr).await?;
//!     Ok(())
//! }
//!
//! ```
//!
//! client.rs
//!
//! ```rust
//! use serde::{Serialize, Deserialize};
//! use toy_rpc::Client;
//! use toy_rpc::error::Error;
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleRequest {
//!     a: u32
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleResponse {
//!     a: u32
//! }
//!
//! #[async_std::main]
//! async fn main() {
//!     // note that the endpoint path must be specified
//!     let path = "ws://127.0.0.1:8888/rpc/";
//!     let client = Client::dial_http(path).await.unwrap();
//!
//!     let args = ExampleRequest{a: 1};
//!     let reply: Result<ExampleResponse, Error> = client.call("example.echo", &args);
//!     println!("{:?}", reply);
//! }
//! ```
//!
//! ### RPC over HTTP with `actix-web`
//!
//! ```toml
//! toy-rpc = { version = "0.5.0", default-features = false, features = ["std", "serde_bincode", "actix-web", "surf"] }
//! ```
//!
//! server.rs
//!
//! ```rust
//! use async_std::sync::{Arc, Mutex};
//! use serde::{Serialize, Deserialize};
//! use actix_web::{App, HttpServer, web};
//!
//! use toy_rpc::macros::{export_impl, service};
//! use toy_rpc::Server;
//!
//!
//! pub struct ExampleService {
//!     counter: Mutex<i32>
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleRequest {
//!     pub a: u32,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleResponse {
//!     a: u32,
//! }
//!
//! #[async_trait::async_trait]
//! trait Rpc {
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String>;
//! }
//!
//! #[async_trait::async_trait]
//! #[export_impl]
//! impl Rpc for ExampleService {
//!     #[export_method]
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String> {
//!         let mut counter = self.counter.lock().await;
//!         *counter += 1;
//!
//!         let res = ExampleResponse{ a: req.a };
//!         Ok(res)
//!     }
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//!     let addr = "127.0.0.1:8888";
//!     let example_service = Arc::new(
//!         ExampleService {
//!             counter: Mutex::new(0),
//!         }
//!     );
//!
//!     let server = Server::builder()
//!         .register("example", service!(example_service, ExampleService))
//!         .build();
//!
//!     HttpServer::new(
//!         move || {
//!             App::new()
//!                 .service(
//!                     web::scope("/rpc/")
//!                         .app_data(app_data.clone())
//!                         .configure(Server::scope_config)
//!                         // The line above may be replaced with line below if "actix-web"
//!                         // is enabled and "tide" is disabled
//!                         //.configure(Server::handle_http()) // use the convenience "handle_http"
//!                 )
//!         }
//!     )
//!     .bind(addr)?
//!     .run()
//!     .await
//! }
//!
//! ```
//!
//! client.rs
//!
//! ```rust
//! use serde::{Serialize, Deserialize};
//! use toy_rpc::Client;
//! use toy_rpc::error::Error;
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleRequest {
//!     a: u32
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleResponse {
//!     a: u32
//! }
//!
//! #[async_std::main]
//! async fn main() {
//!     // note that the endpoint path must be specified
//!     let path = "ws://127.0.0.1:8888/rpc/";
//!     let client = Client::dial_http(path).await.unwrap();
//!
//!     let args = ExampleRequest{a: 1};
//!     let reply: Result<ExampleResponse, Error> = client.call("example.echo", &args);
//!     println!("{:?}", reply);
//! }
//!
//! ```
//!
//! ### RPC over HTTP with `warp`
//!
//! ```toml
//! toy-rpc = { version = "0.5.0", default-features = false, features = ["std", "serde_bincode", "warp"] }
//! ```
//!
//! server.rs
//!
//! ```rust
//! use warp::Filter;
//! use async_std::sync::{Arc, Mutex};
//! use serde::{Serialize, Deserialize};
//! use actix_web::{App, HttpServer, web};
//!
//! use toy_rpc::macros::{export_impl, service};
//! use toy_rpc::Server;
//!
//!
//! pub struct ExampleService {
//!     counter: Mutex<i32>
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleRequest {
//!     pub a: u32,
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! pub struct ExampleResponse {
//!     a: u32,
//! }
//!
//! #[async_trait::async_trait]
//! trait Rpc {
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String>;
//! }
//!
//! #[async_trait::async_trait]
//! #[export_impl]
//! impl Rpc for ExampleService {
//!     #[export_method]
//!     async fn echo(&self, req: ExampleRequest) -> Result<ExampleResponse, String> {
//!         let mut counter = self.counter.lock().await;
//!         *counter += 1;
//!
//!         let res = ExampleResponse{ a: req.a };
//!         Ok(res)
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() -> std::io::Result<()> {
//!     let example_service = Arc::new(
//!         ExampleService {
//!             counter: Mutex::new(0),
//!         }
//!     );
//!
//!     let server = Server::builder()
//!         .register("example", service!(example_service, ExampleService))
//!         .build();
//!
//!     let state = warp::any().map(move || server.clone());
//!     let rpc_route = warp::path(Server::handler_path())
//!         .and(state)
//!         .and(warp::ws())
//!         .map(Server::warp_websocket_handler);
//!     let routes = warp::path("rpc")
//!         .and(rpc_route);
//!
//!     warp::serve(routes).run([127.0.0.1], 8888).await;
//! }
//!
//! ```
//!
//! client.rs
//!
//! ```rust
//! use serde::{Serialize, Deserialize};
//! use toy_rpc::Client;
//! use toy_rpc::error::Error;
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleRequest {
//!     a: u32
//! }
//!
//! #[derive(Debug, Serialize, Deserialize)]
//! struct ExampleResponse {
//!     a: u32
//! }
//!
//! #[async_std::main]
//! async fn main() {
//!     // note that the endpoint path must be specified
//!     let path = "ws://127.0.0.1:8888/rpc/";
//!     let client = Client::dial_http(path).await.unwrap();
//!
//!     let args = ExampleRequest{a: 1};
//!     let reply: Result<ExampleResponse, Error> = client.call("example.echo", &args);
//!     println!("{:?}", reply);
//! }
//!
//! ```
//! ## Change Log
//!
//! ### 0.4.5
//!
//! - Added `Sink` implementation for the custom binary transport protocol `Frame`
//!
//! ### 0.4.4
//!
//! - Modified traits `CodecRead`, `CodecWrite`, `ServerCodec`, `ClientCodec` to no longer
//! return number of bytes written
//! - The number of bytes written for header and body will be logged separately
//!
//! ### 0.4.3
//!
//! - Removed previously unused NoneError
//! - Unified `call`, `async_call` and `spawn_task` for socket client
//! and HTTP client. The `call_http`, `async_call_http`, and `spawn_task_http`
//! methods are kept for compatibility.
//!
//! ### 0.4.2
//!
//! - Temporary fix of `spawn_task()` and `spawn_task_http()` with `Arc<Mutex<_>>` until
//! lifetime with async task is figured out. As a result, `Client` no longer needs to be declared `mut`.
//!
//! ### 0.4.1
//!
//! - Updated documentation
//!
//! ### 0.4.0
//!
//! - Added `actix-web` feature flag to support integration with `actix-web`
//!
//! ### 0.3.1
//!
//! - Added `serde_rmp` features flag
//! - Updated and corrected examples in the documentation
//!
//! ### 0.3.0
//!
//! - Added `serde_cbor` feature flag
//! - Changed `bincode` feature flag to `serde_bincode`
//!
//!
//! ## Future Plan
//!
//! - `warp` integration
//! - switch http client implementation to use `isahc`
//! - websocket with `async_tungstenite`
//!   - tide-websocket
//!   - actix-web websocket
//!   - warp websocket
//! - support other I/O connection
//! - unify `call`, `async_call`, and `spawn_task` for raw connection and HTTP connection
//!

pub mod codec;
pub mod error;
pub mod message;
pub mod service;
pub mod transport;

cfg_if::cfg_if! {
    if #[cfg(any(
        feature = "async_std_runtime",
        feature = "tokio_runtime",
        feature = "http_tide",
        feature = "http_warp",
        feature = "http_actix_web",
        feature ="docs",
    ))] {
        pub mod client;
        pub mod server;

        pub use client::Client;
        pub use server::{Server, ServerBuilder};
    }
}

pub mod macros {
    pub use toy_rpc_macros::{export_impl, service};

    #[cfg(all(
        any(
            feature = "serde_bincode",
            feature = "serde_cbor",
            feature = "serde_rmp",
            feature = "serde_json"
        ),
        any(
            feature = "async_std_runtime",
            feature = "tokio_runtime",
            feature = "http_tide",
            feature = "http_warp",
            feature = "http_actix_web"
        )
    ))]
    pub(crate) use toy_rpc_macros::impl_inner_deserializer;
}

// re-export
pub use erased_serde;
pub use lazy_static;

#[async_trait::async_trait]
pub trait GracefulShutdown {
    async fn close(&mut self);
}