Skip to content

Commit 2988a4d

Browse files
Merge pull request #73 from hubertshelley/2.0.0
2.0.0
2 parents ae42448 + a5655d5 commit 2988a4d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

79 files changed

+1124
-875
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@ homepage = "https://github.com/hubertshelley/silent"
1010
license = "Apache-2.0"
1111
readme = "./readme.md"
1212
repository = "https://github.com/hubertshelley/silent"
13-
version = "1.5.0"
13+
version = "2.0.0"
Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use serde::{Deserialize, Serialize};
2+
3+
use silent::middlewares::ExceptionHandler;
24
use silent::prelude::*;
35

46
#[derive(Deserialize, Serialize, Debug)]
@@ -10,13 +12,8 @@ struct Exception {
1012
fn main() {
1113
logger::fmt().with_max_level(Level::INFO).init();
1214
let route = Route::new("")
15+
.root_hook(ExceptionHandler::new(|res, _| async move { res }))
1316
.get(|mut req| async move { req.params_parse::<Exception>() })
14-
.route()
15-
.set_exception_handler(|e, _| async move {
16-
Exception {
17-
code: e.status().as_u16(),
18-
msg: e.to_string(),
19-
}
20-
});
17+
.route();
2118
Server::new().run(route);
2219
}

examples/form/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@ edition = "2021"
77

88
[dependencies]
99
silent = { path = "../../silent" }
10-
serde = { version = "1.0.213", features = ["derive"] }
10+
serde = { version = "1.0.210", features = ["derive"] }

examples/grpc/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ path = "src/client.rs"
1515
[dependencies]
1616
tonic = { version = "0.12.3" }
1717
prost = "0.13"
18-
tokio = { version = "1.41", features = ["macros", "rt-multi-thread"] }
18+
tokio = { version = "1.40", features = ["macros", "rt-multi-thread"] }
1919
silent = { path = "../../silent", features = ["grpc"] }
2020
async-trait = "0.1.83"
2121

examples/grpc/build.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
fn main() {
22
tonic_build::configure()
3-
.compile(&["proto/helloworld.proto"], &["/proto"])
3+
.compile_protos(&["proto/hello_world.proto"], &["/proto"])
44
.unwrap();
55
}

examples/grpc_h2c/proto/helloworld.proto renamed to examples/grpc/proto/hello_world.proto

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
syntax = "proto3";
1616

1717
option java_multiple_files = true;
18-
option java_package = "io.grpc.examples.helloworld";
18+
option java_package = "io.grpc.examples.hello_world";
1919
option java_outer_classname = "HelloWorldProto";
2020

21-
package helloworld;
21+
package hello_world;
2222

2323
// The greeting service definition.
2424
service Greeter {

examples/grpc/src/client.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use hello_world::greeter_client::GreeterClient;
22
use hello_world::HelloRequest;
33

44
pub mod hello_world {
5-
tonic::include_proto!("helloworld");
5+
tonic::include_proto!("hello_world");
66
}
77
#[allow(dead_code)]
88
#[tokio::main]

examples/grpc/src/main.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ use tonic::{Request, Response, Status};
33

44
use hello_world::greeter_server::{Greeter, GreeterServer};
55
use hello_world::{HelloReply, HelloRequest};
6-
use silent::prelude::{logger, HandlerAppend, Level, Route, RouteService, Server};
6+
use silent::prelude::{info, logger, HandlerAppend, Level, Route, Server};
7+
use silent::GrpcRegister;
78

89
mod client;
910

1011
pub mod hello_world {
11-
tonic::include_proto!("helloworld"); // The string specified here must match the proto package name
12+
tonic::include_proto!("hello_world"); // The string specified here must match the proto package name
1213
}
1314

1415
#[derive(Debug, Default)]
@@ -21,7 +22,7 @@ impl Greeter for MyGreeter {
2122
request: Request<HelloRequest>, // Accept request of type HelloRequest
2223
) -> Result<Response<HelloReply>, Status> {
2324
// Return an instance of type HelloReply
24-
println!("Got a request: {:?}", request);
25+
info!("Got a request: {:?}", request);
2526

2627
let reply = HelloReply {
2728
message: format!("Hello {}!", request.into_inner().name), // We must use .into_inner() as the fields of gRPC requests and responses are private
@@ -40,12 +41,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
4041
// // Wrap all services in the middleware stack
4142
// .add_service(greeter_server)
4243
// .into_router();
43-
let route = Route::new("").get(|_req| async { Ok("hello world") });
44-
let root = route.route().with_grpc(greeter_server.into());
45-
println!("route: \n{:?}", root);
44+
let route = Route::new("")
45+
.get(|_req| async { Ok("hello world") })
46+
.append(greeter_server.service());
47+
info!("route: \n{:?}", route);
4648
Server::new()
4749
.bind("0.0.0.0:50051".parse().unwrap())
48-
.serve(root)
50+
.serve(route)
4951
.await;
5052
Ok(())
5153
}

examples/grpc_h2c/build.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ fn main() {
44
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
55

66
tonic_build::configure()
7-
.file_descriptor_set_path(out_dir.join("helloworld_descriptor.bin"))
8-
.compile(&["proto/helloworld.proto"], &["/proto"])
7+
.file_descriptor_set_path(out_dir.join("hello_world_descriptor.bin"))
8+
.compile_protos(&["proto/hello_world.proto"], &["/proto"])
99
.unwrap();
1010
}

examples/grpc/proto/helloworld.proto renamed to examples/grpc_h2c/proto/hello_world.proto

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@
1515
syntax = "proto3";
1616

1717
option java_multiple_files = true;
18-
option java_package = "io.grpc.examples.helloworld";
18+
option java_package = "io.grpc.examples.hello_world";
1919
option java_outer_classname = "HelloWorldProto";
2020

21-
package helloworld;
21+
package hello_world;
2222

2323
// The greeting service definition.
2424
service Greeter {
@@ -34,4 +34,4 @@ message HelloRequest {
3434
// The response message containing the greetings
3535
message HelloReply {
3636
string message = 1;
37-
}
37+
}

examples/grpc_h2c/src/client.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use hyper_util::client::legacy::Client;
55
use hyper_util::rt::TokioExecutor;
66

77
pub mod hello_world {
8-
tonic::include_proto!("helloworld");
8+
tonic::include_proto!("hello_world");
99
}
1010

1111
#[tokio::main]

examples/grpc_h2c/src/main.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ use tonic::{Request, Response, Status};
33

44
use hello_world::greeter_server::{Greeter, GreeterServer};
55
use hello_world::{HelloReply, HelloRequest};
6-
use silent::prelude::{logger, HandlerAppend, Level, Route, RouteService};
6+
use silent::prelude::{info, logger, HandlerAppend, Level, Route};
7+
use silent::GrpcRegister;
78

89
pub mod hello_world {
9-
tonic::include_proto!("helloworld");
10+
tonic::include_proto!("hello_world");
1011
}
1112

1213
#[derive(Default)]
@@ -18,7 +19,7 @@ impl Greeter for MyGreeter {
1819
&self,
1920
request: Request<HelloRequest>,
2021
) -> Result<Response<HelloReply>, Status> {
21-
println!("Got a request from {:?}", request.remote_addr());
22+
info!("Got a request from {:?}", request.remote_addr());
2223

2324
let reply = hello_world::HelloReply {
2425
message: format!("Hello {}!", request.into_inner().name),
@@ -32,11 +33,11 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
3233
let greeter = MyGreeter::default();
3334
logger::fmt().with_max_level(Level::INFO).init();
3435

35-
let route = Route::new("").get(|_req| async { Ok("hello world") });
36-
let root = route.route().with_grpc(GreeterServer::new(greeter).into());
36+
let mut route = Route::new("").get(|_req| async { Ok("hello world") });
37+
GreeterServer::new(greeter).register(&mut route);
3738
silent::prelude::Server::new()
3839
.bind("0.0.0.0:50051".parse().unwrap())
39-
.serve(root)
40+
.serve(route)
4041
.await;
4142
Ok(())
4243
}

examples/grpc_streaming/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ path = "src/client.rs"
1515
[dependencies]
1616
tonic = { version = "0.12.3" }
1717
prost = "0.13"
18-
tokio = { version = "1.41", features = ["macros", "rt-multi-thread"] }
18+
tokio = { version = "1.40", features = ["macros", "rt-multi-thread"] }
1919
silent = { path = "../../silent", features = ["grpc"] }
2020
async-trait = "0.1.83"
2121
tokio-stream = "0.1.16"

examples/grpc_streaming/build.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
fn main() {
22
tonic_build::configure()
3-
.compile(&["proto/echo.proto"], &["/proto"])
3+
.compile_protos(&["proto/echo.proto"], &["/proto"])
44
.unwrap();
55
}

examples/grpc_streaming/src/client.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
7070

7171
println!("Streaming echo:");
7272
streaming_echo(&mut client, 5).await;
73-
tokio::time::sleep(Duration::from_secs(1)).await; //do not mess server println functions
73+
tokio::time::sleep(Duration::from_secs(1)).await; //do not mess server info functions
7474

7575
// Echo stream that sends 17 requests then graceful end that connection
7676
println!("\r\nBidirectional stream echo:");

examples/grpc_streaming/src/main.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ use tokio_stream::{wrappers::ReceiverStream, Stream, StreamExt};
55
use tonic::{Request, Response, Status, Streaming};
66

77
use pb::{EchoRequest, EchoResponse};
8-
use silent::prelude::{logger, HandlerAppend, Level, Route, RouteService, Server};
8+
use silent::prelude::{info, logger, HandlerAppend, Level, Route, RouteService, Server};
9+
use silent::GrpcRegister;
910

1011
mod client;
1112

@@ -54,8 +55,8 @@ impl pb::echo_server::Echo for EchoServer {
5455
&self,
5556
req: Request<EchoRequest>,
5657
) -> EchoResult<Self::ServerStreamingEchoStream> {
57-
println!("EchoServer::server_streaming_echo");
58-
println!("\tclient connected from: {:?}", req.remote_addr());
58+
info!("EchoServer::server_streaming_echo");
59+
info!("\tclient connected from: {:?}", req.remote_addr());
5960

6061
// creating infinite stream with requested message
6162
let repeat = std::iter::repeat(EchoResponse {
@@ -78,7 +79,7 @@ impl pb::echo_server::Echo for EchoServer {
7879
}
7980
}
8081
}
81-
println!("\tclient disconnected");
82+
info!("\tclient disconnected");
8283
});
8384

8485
let output_stream = ReceiverStream::new(rx);
@@ -100,7 +101,7 @@ impl pb::echo_server::Echo for EchoServer {
100101
&self,
101102
req: Request<Streaming<EchoRequest>>,
102103
) -> EchoResult<Self::BidirectionalStreamingEchoStream> {
103-
println!("EchoServer::bidirectional_streaming_echo");
104+
info!("EchoServer::bidirectional_streaming_echo");
104105

105106
let mut in_stream = req.into_inner();
106107
let (tx, rx) = mpsc::channel(128);
@@ -121,7 +122,7 @@ impl pb::echo_server::Echo for EchoServer {
121122
if io_err.kind() == ErrorKind::BrokenPipe {
122123
// here you can handle special case when client
123124
// disconnected in unexpected way
124-
eprintln!("\tclient disconnected: broken pipe");
125+
info!("\tclient disconnected: broken pipe");
125126
break;
126127
}
127128
}
@@ -133,7 +134,7 @@ impl pb::echo_server::Echo for EchoServer {
133134
}
134135
}
135136
}
136-
println!("\tstream ended");
137+
info!("\tstream ended");
137138
});
138139

139140
// echo just write the same data that was received
@@ -150,9 +151,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
150151
logger::fmt().with_max_level(Level::INFO).init();
151152
let server = EchoServer {};
152153
let route = Route::new("").get(|_req| async { Ok("hello world") });
153-
let root = route
154-
.route()
155-
.with_grpc(pb::echo_server::EchoServer::new(server).into());
154+
let mut root = route.route();
155+
root.push(pb::echo_server::EchoServer::new(server).service());
156156
Server::new()
157157
.bind("0.0.0.0:50051".parse().unwrap())
158158
.serve(root)

examples/middleware/src/main.rs

Lines changed: 2 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,7 @@ struct MiddleWare {
1919

2020
#[async_trait]
2121
impl MiddleWareHandler for MiddleWare {
22-
async fn pre_request(
23-
&self,
24-
_req: &mut Request,
25-
_res: &mut Response,
26-
) -> Result<MiddlewareResult> {
22+
async fn handle(&self, req: Request, next: &Next) -> Result<Response> {
2723
self.count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2824
let count = self.count.load(std::sync::atomic::Ordering::SeqCst);
2925
info!("pre_request count: {}", count);
@@ -34,21 +30,6 @@ impl MiddleWareHandler for MiddleWare {
3430
msg: "bad request:pre_request".to_string(),
3531
});
3632
}
37-
Ok(MiddlewareResult::Continue)
38-
}
39-
async fn after_response(&self, res: &mut Response) -> Result<MiddlewareResult> {
40-
let count = self.count.load(std::sync::atomic::Ordering::SeqCst);
41-
info!("after_response count: {}", count);
42-
if count % 3 == 0 {
43-
error!("set after_response error");
44-
return Err(SilentError::BusinessError {
45-
code: StatusCode::BAD_REQUEST,
46-
msg: "bad request:after_response".to_string(),
47-
});
48-
}
49-
if let ResBody::Once(body) = res.body() {
50-
println!("body: {:?}", body);
51-
}
52-
Ok(MiddlewareResult::Continue)
33+
next.call(req).await
5334
}
5435
}

examples/path_params/src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ fn main() {
1313
.append(Route::new("<key:**>/**").get(hello_world))
1414
.append(Route::new("<key>").get(hello_world))
1515
.append(Route::new("<key:other>/other").get(hello_world));
16-
println!("{:?}", route);
16+
info!("{:?}", route);
1717
Server::new().run(route);
1818
}
1919

examples/plugin_test/Cargo.toml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[package]
2+
name = "examples_plugin_test"
3+
edition.workspace = true
4+
authors.workspace = true
5+
homepage.workspace = true
6+
license.workspace = true
7+
readme.workspace = true
8+
repository.workspace = true
9+
version.workspace = true
10+
11+
[dependencies]
12+
silent = { path = "../../silent" }
13+
crossbeam-epoch = "0.9.18"
14+
dlopen2 = { version = "0.7.0", features = ["derive"] }

examples/plugin_test/README.MD

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
## where is lib from?
2+
3+
Compiled from example project plugins
4+
5+
this example lib is compiled by MacOS, if your system is different, you need to compile it by yourself and edit
6+
lib_path.
529 KB
Binary file not shown.

examples/plugin_test/src/main.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
use crossbeam_epoch::Pointable;
2+
use dlopen2::wrapper::{Container, WrapperApi};
3+
use silent::prelude::{logger, Level, Route, Server};
4+
use std::error::Error;
5+
6+
#[derive(WrapperApi)]
7+
struct PluginApi {
8+
// plugin_metadata: unsafe extern "C" fn() -> PluginMetadata,
9+
#[allow(improper_ctypes_definitions)]
10+
get_route: unsafe extern "C" fn() -> Route,
11+
}
12+
13+
fn main() -> Result<(), Box<dyn Error>> {
14+
logger::fmt().with_max_level(Level::INFO).init();
15+
let lib_path = "./libexamples_plugins.dylib";
16+
let container: Container<PluginApi> =
17+
unsafe { Container::load(lib_path) }.expect("无法加载插件");
18+
let route = unsafe { container.get_route() };
19+
Server::new().run(route);
20+
Ok(())
21+
}

examples/plugins/.cargo/config.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[build]
2+
target-dir = "target"

examples/plugins/Cargo.toml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
[package]
2+
name = "examples-plugins"
3+
edition.workspace = true
4+
authors.workspace = true
5+
homepage.workspace = true
6+
license.workspace = true
7+
readme.workspace = true
8+
repository.workspace = true
9+
version.workspace = true
10+
11+
[lib]
12+
crate-type = ['cdylib']
13+
14+
[dependencies]
15+
silent = { path = "../../silent" }

0 commit comments

Comments
 (0)