Skip to content

Commit

Permalink
feat: 🎉 support volo/motore
Browse files Browse the repository at this point in the history
  • Loading branch information
Forsworns committed Nov 29, 2022
1 parent 26e3717 commit 0b1d100
Show file tree
Hide file tree
Showing 15 changed files with 464 additions and 5 deletions.
7 changes: 2 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,5 @@ members = [
exclude = [
"examples/ebpf/probes",
"examples/ebpf/userspace",
"middleware/tower",
"middleware/tower/example",
"middleware/tonic",
"middleware/tonic/example",
]
"middleware/",
]
1 change: 1 addition & 0 deletions middleware/motore/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target
15 changes: 15 additions & 0 deletions middleware/motore/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
edition = "2021"
license = "MIT"
name = "sentinel-motore"
publish = false
version = "0.1.0"

[features]
default = []
volo = ["dep:volo"]

[dependencies]
motore = "0.2.1"
sentinel-core = {version="0.1.2", features=["async"]}
volo = {version = "0.2", optional = true}
7 changes: 7 additions & 0 deletions middleware/motore/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Sentinel in Motore

Implement Sentinel as a service in [Motore](https://github.com/cloudwego/motore).

In the `example` directory, we provide an example for [Volo](https://github.com/cloudwego/volo).

**Attention: Since TAIT feature is not stablized, you have to use the nightly rustc to compile this example.**
1 change: 1 addition & 0 deletions middleware/motore/example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target
30 changes: 30 additions & 0 deletions middleware/motore/example/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
[package]
edition = "2021"
license = "MIT"
name = "sentinel_motore_example"
publish = false
version = "0.1.0"

# hello
[[bin]]
name = "volo-server"
path = "src/server.rs"
[[bin]]
name = "volo-client"
path = "src/client.rs"

[dependencies]
sentinel-core = "0.1.2"
sentinel-motore = {path = "../", features=["volo"]}
volo = "0.2"
volo-gen = { path = "./volo-gen" }
volo-grpc = "0.2"

anyhow = "1"
async-trait = "0.1"
lazy_static = "1"
tokio = { version = "1.0", features = ["full"] }

pilota = "0.2"


15 changes: 15 additions & 0 deletions middleware/motore/example/proto/hello.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
syntax = "proto3";

package hello;

service HelloService {
rpc Hello (HelloRequest) returns (HelloResponse);
}

message HelloRequest {
string name = 1;
}

message HelloResponse {
string message = 1;
}
72 changes: 72 additions & 0 deletions middleware/motore/example/src/client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use sentinel_core::flow;
use sentinel_motore::{BoxError, SentinelLayer, ServiceRole};
use std::net::SocketAddr;
use std::sync::Arc;
use volo_gen::proto_gen::hello::{
HelloRequest, HelloServiceClientBuilder, HelloServiceRequestSend, HelloServiceResponseRecv,
};
use volo_grpc::{
context::ClientContext,
status::{Code, Status},
Request, Response,
};

const RESOURCE_NAME: &'static str = "motore_example";

fn custom_extractor(_cx: &ClientContext, _req: &Request<HelloServiceRequestSend>) -> String {
RESOURCE_NAME.into()
}

fn custom_fallback(
_cx: &ClientContext,
_req: &Request<HelloServiceRequestSend>,
err: &sentinel_core::Error,
) -> Result<Response<HelloServiceResponseRecv>, BoxError> {
Err(Status::new(
Code::Cancelled,
format!("Blocked by sentinel at client side: {:?}", err),
)
.into())
}

#[volo::main]
async fn main() {
// Init configurations for Sentinel Rust
sentinel_core::init_default().unwrap_or_else(|err| sentinel_core::logging::error!("{:?}", err));
let resource_name = String::from(RESOURCE_NAME);
// Load sentinel rules
flow::load_rules(vec![Arc::new(flow::Rule {
resource: resource_name.clone(),
threshold: 7.0,
calculate_strategy: flow::CalculateStrategy::Direct,
control_strategy: flow::ControlStrategy::Reject,
..Default::default()
})]);

let sentinel = SentinelLayer::new(ServiceRole::Client)
.with_extractor(custom_extractor)
.with_fallback(custom_fallback);
let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
let client = HelloServiceClientBuilder::new("hello")
.address(addr)
.layer_outer_front(sentinel)
.build();

let mut handlers = Vec::with_capacity(20);
for _ in 0..10 {
let mut c = client.clone();
handlers.push(tokio::spawn(async move {
let req = HelloRequest {
name: "Volo".to_string(),
};
let resp = c.hello(req).await;
match resp {
Ok(info) => println!("{:?}", info),
Err(e) => eprintln!("{:?}", e),
}
}))
}
for h in handlers {
h.await.unwrap();
}
}
73 changes: 73 additions & 0 deletions middleware/motore/example/src/server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use sentinel_core::flow;
use sentinel_motore::{BoxError, SentinelLayer, ServiceRole};
use std::net::SocketAddr;
use std::sync::Arc;
use volo_gen::proto_gen::hello::{
HelloRequest, HelloResponse, HelloService, HelloServiceRequestRecv, HelloServiceResponseSend,
HelloServiceServer,
};
use volo_grpc::{
context::ServerContext,
status::{Code, Status},
Request, Response,
};

const RESOURCE_NAME: &'static str = "motore_example";

fn custom_extractor(_cx: &ServerContext, _req: &Request<HelloServiceRequestRecv>) -> String {
RESOURCE_NAME.into()
}

fn custom_fallback(
_cx: &ServerContext,
_req: &Request<HelloServiceRequestRecv>,
err: &sentinel_core::Error,
) -> Result<Response<HelloServiceResponseSend>, BoxError> {
Err(Status::new(
Code::ResourceExhausted,
format!("Blocked by sentinel at server side: {:?}", err),
)
.into())
}

pub struct S;

#[volo::async_trait]
impl HelloService for S {
async fn hello(
&self,
req: ::volo_grpc::Request<HelloRequest>,
) -> Result<::volo_grpc::Response<HelloResponse>, ::volo_grpc::Status> {
let resp = HelloResponse {
message: format!("Hello, {}!", req.get_ref().name),
};
Ok(::volo_grpc::Response::new(resp))
}
}

#[volo::main]
async fn main() {
// Init configurations for Sentinel Rust
sentinel_core::init_default().unwrap_or_else(|err| sentinel_core::logging::error!("{:?}", err));
let resource_name = String::from(RESOURCE_NAME);
// Load sentinel rules
flow::load_rules(vec![Arc::new(flow::Rule {
resource: resource_name.clone(),
threshold: 3.0,
calculate_strategy: flow::CalculateStrategy::Direct,
control_strategy: flow::ControlStrategy::Reject,
..Default::default()
})]);

let sentinel = SentinelLayer::new(ServiceRole::Server)
.with_extractor(custom_extractor)
.with_fallback(custom_fallback);
let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
let addr = volo::net::Address::from(addr);

HelloServiceServer::new(S)
.layer_front(sentinel)
.run(addr)
.await
.unwrap();
}
1 change: 1 addition & 0 deletions middleware/motore/example/volo-gen/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target
20 changes: 20 additions & 0 deletions middleware/motore/example/volo-gen/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
edition = "2021"
license = "MIT"
name = "volo-gen"
version = "0.1.0"
publish = false

[dependencies]
anyhow = "1"
async-trait = "0.1"
futures = "0.3"
prost = "0.11"
tokio = { version = "1", features = ["full"] }

pilota = "0.2"
volo = "0.2"
volo-grpc = "0.2"

[build-dependencies]
volo-build = "0.2"
3 changes: 3 additions & 0 deletions middleware/motore/example/volo-gen/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() {
volo_build::ConfigBuilder::default().write().unwrap();
}
7 changes: 7 additions & 0 deletions middleware/motore/example/volo-gen/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#![feature(type_alias_impl_trait)]

mod gen {
volo::include_service!("proto_gen.rs");
}

pub use gen::*;
9 changes: 9 additions & 0 deletions middleware/motore/example/volo-gen/volo.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
entries:
proto:
protocol: protobuf
filename: proto_gen.rs
idls:
- source: local
path: ../proto/hello.proto
includes:
- ../proto
Loading

0 comments on commit 0b1d100

Please sign in to comment.