diff --git a/.github/workflows/github-actions.yml b/.github/workflows/github-actions.yml index f78275a4..0271d2d1 100644 --- a/.github/workflows/github-actions.yml +++ b/.github/workflows/github-actions.yml @@ -27,6 +27,8 @@ jobs: - uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} + - name: Install Protoc + uses: arduino/setup-protoc@v1 - run: cargo check fmt: diff --git a/.gitignore b/.gitignore index 7933fb75..6a358bd3 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,4 @@ Cargo.lock **/*.rs.bk .vscode/ .idea/ -echo helloworld \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 87253e71..140c0797 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "common", "config", "dubbo", - "examples", + "examples/echo", + "examples/greeter", "dubbo-build" ] diff --git a/config/Cargo.toml b/config/Cargo.toml index 6821a065..80d843ee 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -1,7 +1,11 @@ [package] -name = "config" +name = "dubbo-config" version = "0.1.0" edition = "2021" +license = "Apache-2.0" +description = "dubbo-config" +documentation = "https://github.com/apache/dubbo-rust" +repository = "https://github.com/apache/dubbo-rust.git" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/dubbo-build/Cargo.toml b/dubbo-build/Cargo.toml index a4fbbc69..1c04bf7c 100644 --- a/dubbo-build/Cargo.toml +++ b/dubbo-build/Cargo.toml @@ -2,6 +2,10 @@ name = "dubbo-build" version = "0.1.0" edition = "2021" +license = "Apache-2.0" +description = "dubbo-build" +documentation = "https://github.com/apache/dubbo-rust" +repository = "https://github.com/apache/dubbo-rust.git" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/dubbo/Cargo.toml b/dubbo/Cargo.toml index efc0fa5b..fb039e98 100644 --- a/dubbo/Cargo.toml +++ b/dubbo/Cargo.toml @@ -2,6 +2,10 @@ name = "dubbo" version = "0.1.0" edition = "2021" +license = "Apache-2.0" +description = "dubbo" +documentation = "https://github.com/apache/dubbo-rust" +repository = "https://github.com/apache/dubbo-rust.git" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -30,4 +34,4 @@ axum = "0.5.9" async-stream = "0.3" flate2 = "1.0" -config = {path = "../config"} +dubbo-config = {path = "../config", version = "0.1.0"} diff --git a/dubbo/src/framework.rs b/dubbo/src/framework.rs index 4a82b42f..a494bdd7 100644 --- a/dubbo/src/framework.rs +++ b/dubbo/src/framework.rs @@ -26,7 +26,7 @@ use crate::common::url::Url; use crate::protocol::triple::triple_invoker::TripleInvoker; use crate::protocol::triple::triple_protocol::TripleProtocol; use crate::protocol::{Exporter, Protocol}; -use config::{get_global_config, RootConfig}; +use dubbo_config::{get_global_config, RootConfig}; pub type BoxExporter = Box>; // Invoker是否可以基于hyper写一个通用的 diff --git a/dubbo/src/triple/server/triple.rs b/dubbo/src/triple/server/triple.rs index d1621456..d1d1a1d7 100644 --- a/dubbo/src/triple/server/triple.rs +++ b/dubbo/src/triple/server/triple.rs @@ -27,7 +27,7 @@ use crate::triple::server::service::{ ClientStreamingSvc, ServerStreamingSvc, StreamingSvc, UnarySvc, }; use crate::BoxBody; -use config::BusinessConfig; +use dubbo_config::BusinessConfig; pub const GRPC_ACCEPT_ENCODING: &str = "grpc-accept-encoding"; pub const GRPC_ENCODING: &str = "grpc-encoding"; diff --git a/examples/Cargo.toml b/examples/echo/Cargo.toml similarity index 75% rename from examples/Cargo.toml rename to examples/echo/Cargo.toml index cc0c9f8d..e892d55c 100644 --- a/examples/Cargo.toml +++ b/examples/echo/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "examples" +name = "example-echo" version = "0.1.0" edition = "2021" @@ -23,8 +23,8 @@ prost = "0.10.4" async-trait = "0.1.56" tokio-stream = "0.1" -dubbo = {path = "../dubbo"} -config = {path = "../config"} +dubbo = {path = "../../dubbo", version = "0.1.0"} +dubbo-config = {path = "../../config", version = "0.1.0"} [build-dependencies] -dubbo-build = {path = "../dubbo-build"} +dubbo-build = {path = "../../dubbo-build", version = "0.1.0"} diff --git a/examples/LICENSE b/examples/echo/LICENSE similarity index 100% rename from examples/LICENSE rename to examples/echo/LICENSE diff --git a/examples/README.md b/examples/echo/README.md similarity index 69% rename from examples/README.md rename to examples/echo/README.md index 64b63166..e2f73794 100644 --- a/examples/README.md +++ b/examples/echo/README.md @@ -3,14 +3,14 @@ ## build and run ```sh -$ cd github.com/apache/dubbo-rust/examples +$ cd github.com/apache/dubbo-rust/examples/echo/ $ cargo build $ # run sever -$ ../target/debug/echo-server +$ ../../target/debug/echo-server $ # run client -$ ../target/debug/echo-client +$ ../../target/debug/echo-client reply: EchoResponse { message: "msg1 from server" } reply: EchoResponse { message: "msg2 from server" } reply: EchoResponse { message: "msg3 from server" } diff --git a/examples/README_CN.md b/examples/echo/README_CN.md similarity index 70% rename from examples/README_CN.md rename to examples/echo/README_CN.md index ef3773fc..b52cc1c4 100644 --- a/examples/README_CN.md +++ b/examples/echo/README_CN.md @@ -3,14 +3,14 @@ ## 构建并运行 ```sh -$ cd github.com/apache/dubbo-rust/examples +$ cd github.com/apache/dubbo-rust/examples/echo/ $ cargo build $ # 运行服务端 -$ ../target/debug/echo-server +$ ../../target/debug/echo-server $ # 运行客户端 -$ ../target/debug/echo-client +$ ../../target/debug/echo-client reply: EchoResponse { message: "msg1 from server" } reply: EchoResponse { message: "msg2 from server" } reply: EchoResponse { message: "msg3 from server" } diff --git a/examples/build.rs b/examples/echo/build.rs similarity index 100% rename from examples/build.rs rename to examples/echo/build.rs diff --git a/examples/src/echo/client.rs b/examples/echo/src/echo/client.rs similarity index 96% rename from examples/src/echo/client.rs rename to examples/echo/src/echo/client.rs index 2df0f6bf..1d09a0a9 100644 --- a/examples/src/echo/client.rs +++ b/examples/echo/src/echo/client.rs @@ -16,8 +16,8 @@ */ use dubbo::codegen::*; -use examples::protos::hello_echo::echo_client::EchoClient; -use examples::protos::hello_echo::EchoRequest; +use example_echo::protos::hello_echo::echo_client::EchoClient; +use example_echo::protos::hello_echo::EchoRequest; use futures_util::StreamExt; #[tokio::main] diff --git a/examples/src/echo/server.rs b/examples/echo/src/echo/server.rs similarity index 98% rename from examples/src/echo/server.rs rename to examples/echo/src/echo/server.rs index 067785bf..7c5b8097 100644 --- a/examples/src/echo/server.rs +++ b/examples/echo/src/echo/server.rs @@ -24,10 +24,10 @@ use futures_util::StreamExt; use tokio::sync::mpsc; use tokio_stream::wrappers::ReceiverStream; -use config::RootConfig; use dubbo::codegen::*; use dubbo::Dubbo; -use examples::protos::hello_echo::{ +use dubbo_config::RootConfig; +use example_echo::protos::hello_echo::{ echo_server::{register_server, Echo}, EchoRequest, EchoResponse, }; diff --git a/examples/src/lib.rs b/examples/echo/src/lib.rs similarity index 100% rename from examples/src/lib.rs rename to examples/echo/src/lib.rs diff --git a/examples/src/protos/hello_echo.rs b/examples/echo/src/protos/hello_echo.rs similarity index 100% rename from examples/src/protos/hello_echo.rs rename to examples/echo/src/protos/hello_echo.rs diff --git a/examples/src/protos/mod.rs b/examples/echo/src/protos/mod.rs similarity index 100% rename from examples/src/protos/mod.rs rename to examples/echo/src/protos/mod.rs diff --git a/examples/greeter/Cargo.toml b/examples/greeter/Cargo.toml new file mode 100644 index 00000000..306735d4 --- /dev/null +++ b/examples/greeter/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "example-greeter" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[[bin]] +name = "greeter-server" +path = "src/greeter/server.rs" + +[[bin]] +name = "greeter-client" +path = "src/greeter/client.rs" + +[dependencies] +http = "0.2" +http-body = "0.4.4" +futures-util = {version = "0.3", default-features = false} +tokio = { version = "1.0", features = [ "rt-multi-thread", "time", "fs", "macros", "net", "signal"] } +prost-derive = {version = "0.10", optional = true} +prost = "0.10.4" +async-trait = "0.1.56" +tokio-stream = "0.1" + +dubbo = {path = "../../dubbo", version = "0.1.0"} +dubbo-config = {path = "../../config", version = "0.1.0"} + +[build-dependencies] +dubbo-build = {path = "../../dubbo-build", version = "0.1.0"} diff --git a/examples/greeter/LICENSE b/examples/greeter/LICENSE new file mode 100644 index 00000000..d80bbdaa --- /dev/null +++ b/examples/greeter/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright (c) 2016 ~ 2018 Alex Stocks. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/examples/greeter/README.md b/examples/greeter/README.md new file mode 100644 index 00000000..33cda8aa --- /dev/null +++ b/examples/greeter/README.md @@ -0,0 +1,30 @@ +# Apache Dubbo-rust example - greeter + +## build and run + +```sh +$ cd github.com/apache/dubbo-rust/examples/greeter/ +$ cargo build + +$ # run sever +$ ../../target/debug/greeter-server + +$ # run client +$ ../../target/debug/greeter-client +# unary call +Response: GreeterReply { message: "hello, dubbo-rust" } +# client stream +client streaming, Response: GreeterReply { message: "hello client streaming" } +# bi stream +parts: Metadata { inner: {"date": "Wed, 28 Sep 2022 08:36:50 GMT", "content-type": "application/grpc"} } +reply: GreeterReply { message: "server reply: \"msg1 from client\"" } +reply: GreeterReply { message: "server reply: \"msg2 from client\"" } +reply: GreeterReply { message: "server reply: \"msg3 from client\"" } +trailer: Some(Metadata { inner: {"grpc-message": "poll trailer successfully.", "grpc-accept-encoding": "gzip,identity", "grpc-status": "0", "content-type": "application/grpc"} }) +# server stream +parts: Metadata { inner: {"content-type": "application/grpc", "date": "Wed, 28 Sep 2022 08:36:50 GMT"} } +reply: GreeterReply { message: "msg1 from server" } +reply: GreeterReply { message: "msg2 from server" } +reply: GreeterReply { message: "msg3 from server" } +trailer: Some(Metadata { inner: {"content-type": "application/grpc", "grpc-status": "0", "grpc-accept-encoding": "gzip,identity", "grpc-message": "poll trailer successfully."} }) +``` diff --git a/examples/greeter/README_CN.md b/examples/greeter/README_CN.md new file mode 100644 index 00000000..e24fe061 --- /dev/null +++ b/examples/greeter/README_CN.md @@ -0,0 +1,30 @@ +# Apache Dubbo-rust 示例 - greeter + +## 构建并运行 + +```sh +$ cd github.com/apache/dubbo-rust/examples/greeter/ +$ cargo build + +$ # 运行服务端 +$ ../../target/debug/greeter-server + +$ # 运行客户端 +$ ../../target/debug/greeter-client +# unary call +Response: GreeterReply { message: "hello, dubbo-rust" } +# client stream +client streaming, Response: GreeterReply { message: "hello client streaming" } +# bi stream +parts: Metadata { inner: {"date": "Wed, 28 Sep 2022 08:36:50 GMT", "content-type": "application/grpc"} } +reply: GreeterReply { message: "server reply: \"msg1 from client\"" } +reply: GreeterReply { message: "server reply: \"msg2 from client\"" } +reply: GreeterReply { message: "server reply: \"msg3 from client\"" } +trailer: Some(Metadata { inner: {"grpc-message": "poll trailer successfully.", "grpc-accept-encoding": "gzip,identity", "grpc-status": "0", "content-type": "application/grpc"} }) +# server stream +parts: Metadata { inner: {"content-type": "application/grpc", "date": "Wed, 28 Sep 2022 08:36:50 GMT"} } +reply: GreeterReply { message: "msg1 from server" } +reply: GreeterReply { message: "msg2 from server" } +reply: GreeterReply { message: "msg3 from server" } +trailer: Some(Metadata { inner: {"content-type": "application/grpc", "grpc-status": "0", "grpc-accept-encoding": "gzip,identity", "grpc-message": "poll trailer successfully."} }) +``` diff --git a/examples/greeter/build.rs b/examples/greeter/build.rs new file mode 100644 index 00000000..f3f5aae7 --- /dev/null +++ b/examples/greeter/build.rs @@ -0,0 +1,22 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +fn main() { + dubbo_build::prost::configure() + .compile(&["proto/greeter.proto"], &["proto/"]) + .unwrap(); +} diff --git a/examples/greeter/dubbo.yaml b/examples/greeter/dubbo.yaml new file mode 100644 index 00000000..1e4ade8f --- /dev/null +++ b/examples/greeter/dubbo.yaml @@ -0,0 +1,18 @@ +name: dubbo +service: + org.apache.dubbo.sample.tri.Greeter: + version: 1.0.0 + group: test + protocol: triple + registry: '' + serializer: json + protocol_configs: + triple: + ip: 0.0.0.0 + port: '8888' + name: triple +protocols: + triple: + ip: 0.0.0.0 + port: '8888' + name: triple diff --git a/examples/greeter/proto/greeter.proto b/examples/greeter/proto/greeter.proto new file mode 100644 index 00000000..0d8be79e --- /dev/null +++ b/examples/greeter/proto/greeter.proto @@ -0,0 +1,46 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +syntax = "proto3"; + +option java_multiple_files = true; + +package org.apache.dubbo.sample.tri; + + +// The request message containing the user's name. +message GreeterRequest { + string name = 1; +} + +// The response message containing the greetings +message GreeterReply { + string message = 1; +} + +service Greeter{ + + // unary + rpc greet(GreeterRequest) returns (GreeterReply); + + // clientStream + rpc greetClientStream(stream GreeterRequest) returns (GreeterReply); + + // serverStream + rpc greetServerStream(GreeterRequest) returns (stream GreeterReply); + + // bi streaming + rpc greetStream(stream GreeterRequest) returns (stream GreeterReply); + +} diff --git a/examples/greeter/src/greeter/client.rs b/examples/greeter/src/greeter/client.rs new file mode 100644 index 00000000..ba6b5244 --- /dev/null +++ b/examples/greeter/src/greeter/client.rs @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +pub mod protos { + #![allow(non_camel_case_types)] + include!(concat!(env!("OUT_DIR"), "/org.apache.dubbo.sample.tri.rs")); +} + +use dubbo::codegen::*; +use futures_util::StreamExt; +use protos::{greeter_client::GreeterClient, GreeterRequest}; + +#[tokio::main] +async fn main() { + let mut cli = GreeterClient::new().with_uri("http://127.0.0.1:8888".to_string()); + + println!("# unary call"); + let resp = cli + .greet(Request::new(GreeterRequest { + name: "message from client".to_string(), + })) + .await; + let resp = match resp { + Ok(resp) => resp, + Err(err) => return println!("{:?}", err), + }; + let (_parts, body) = resp.into_parts(); + println!("Response: {:?}", body); + + println!("# client stream"); + let data = vec![ + GreeterRequest { + name: "msg1 from client streaming".to_string(), + }, + GreeterRequest { + name: "msg2 from client streaming".to_string(), + }, + GreeterRequest { + name: "msg3 from client streaming".to_string(), + }, + ]; + let req = futures_util::stream::iter(data); + let resp = cli.greet_client_stream(req).await; + let client_streaming_resp = match resp { + Ok(resp) => resp, + Err(err) => return println!("{:?}", err), + }; + let (_parts, resp_body) = client_streaming_resp.into_parts(); + println!("client streaming, Response: {:?}", resp_body); + + println!("# bi stream"); + let data = vec![ + GreeterRequest { + name: "msg1 from client".to_string(), + }, + GreeterRequest { + name: "msg2 from client".to_string(), + }, + GreeterRequest { + name: "msg3 from client".to_string(), + }, + ]; + let req = futures_util::stream::iter(data); + + let bidi_resp = cli.greet_stream(req).await.unwrap(); + + let (parts, mut body) = bidi_resp.into_parts(); + println!("parts: {:?}", parts); + while let Some(item) = body.next().await { + match item { + Ok(v) => { + println!("reply: {:?}", v); + } + Err(err) => { + println!("err: {:?}", err); + } + } + } + let trailer = body.trailer().await.unwrap(); + println!("trailer: {:?}", trailer); + + println!("# server stream"); + let resp = cli + .greet_server_stream(Request::new(GreeterRequest { + name: "server streaming req".to_string(), + })) + .await + .unwrap(); + + let (parts, mut body) = resp.into_parts(); + println!("parts: {:?}", parts); + while let Some(item) = body.next().await { + match item { + Ok(v) => { + println!("reply: {:?}", v); + } + Err(err) => { + println!("err: {:?}", err); + } + } + } + let trailer = body.trailer().await.unwrap(); + println!("trailer: {:?}", trailer); +} diff --git a/examples/greeter/src/greeter/server.rs b/examples/greeter/src/greeter/server.rs new file mode 100644 index 00000000..37de6620 --- /dev/null +++ b/examples/greeter/src/greeter/server.rs @@ -0,0 +1,196 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +pub mod protos { + #![allow(non_camel_case_types)] + include!(concat!(env!("OUT_DIR"), "/org.apache.dubbo.sample.tri.rs")); +} + +use futures_util::StreamExt; +use protos::{ + greeter_server::{register_server, Greeter}, + GreeterReply, GreeterRequest, +}; + +use std::{io::ErrorKind, pin::Pin}; + +use async_trait::async_trait; +use futures_util::Stream; +use tokio::sync::mpsc; +use tokio_stream::wrappers::ReceiverStream; + +use dubbo::{codegen::*, Dubbo}; +use dubbo_config::RootConfig; + +type ResponseStream = + Pin> + Send>>; + +#[tokio::main] +async fn main() { + register_server(GreeterServerImpl { + name: "greeter".to_string(), + }); + + // Dubbo::new().start().await; + Dubbo::new() + .with_config({ + let r = RootConfig::new(); + match r.load() { + Ok(config) => config, + Err(_err) => panic!("err: {:?}", _err), // response was droped + } + }) + .start() + .await; +} + +#[allow(dead_code)] +#[derive(Default, Clone)] +struct GreeterServerImpl { + name: String, +} + +// #[async_trait] +#[async_trait] +impl Greeter for GreeterServerImpl { + async fn greet( + &self, + request: Request, + ) -> Result, dubbo::status::Status> { + println!("GreeterServer::greet {:?}", request.metadata); + + Ok(Response::new(GreeterReply { + message: "hello, dubbo-rust".to_string(), + })) + } + + async fn greet_client_stream( + &self, + request: Request>, + ) -> Result, dubbo::status::Status> { + let mut s = request.into_inner(); + loop { + let result = s.next().await; + match result { + Some(Ok(val)) => println!("result: {:?}", val), + Some(Err(val)) => println!("err: {:?}", val), + None => break, + } + } + Ok(Response::new(GreeterReply { + message: "hello client streaming".to_string(), + })) + } + + type greetServerStreamStream = ResponseStream; + async fn greet_server_stream( + &self, + request: Request, + ) -> Result, dubbo::status::Status> { + println!("greet_server_stream: {:?}", request.into_inner()); + + let data = vec![ + Result::<_, dubbo::status::Status>::Ok(GreeterReply { + message: "msg1 from server".to_string(), + }), + Result::<_, dubbo::status::Status>::Ok(GreeterReply { + message: "msg2 from server".to_string(), + }), + Result::<_, dubbo::status::Status>::Ok(GreeterReply { + message: "msg3 from server".to_string(), + }), + ]; + let resp = futures_util::stream::iter(data); + + Ok(Response::new(Box::pin(resp))) + } + + type greetStreamStream = ResponseStream; + async fn greet_stream( + &self, + request: Request>, + ) -> Result, dubbo::status::Status> { + println!( + "GreeterServer::greet_stream, grpc header: {:?}", + request.metadata + ); + + let mut in_stream = request.into_inner(); + let (tx, rx) = mpsc::channel(128); + + // this spawn here is required if you want to handle connection error. + // If we just map `in_stream` and write it back as `out_stream` the `out_stream` + // will be drooped when connection error occurs and error will never be propagated + // to mapped version of `in_stream`. + tokio::spawn(async move { + while let Some(result) = in_stream.next().await { + match result { + Ok(v) => { + // if v.name.starts_with("msg2") { + // tx.send(Err(dubbo::status::Status::internal(format!("err: args is invalid, {:?}", v.name)) + // )).await.expect("working rx"); + // continue; + // } + tx.send(Ok(GreeterReply { + message: format!("server reply: {:?}", v.name), + })) + .await + .expect("working rx") + } + Err(err) => { + if let Some(io_err) = match_for_io_error(&err) { + if io_err.kind() == ErrorKind::BrokenPipe { + // here you can handle special case when client + // disconnected in unexpected way + eprintln!("\tclient disconnected: broken pipe"); + break; + } + } + + match tx.send(Err(err)).await { + Ok(_) => (), + Err(_err) => break, // response was droped + } + } + } + } + println!("\tstream ended"); + }); + + // echo just write the same data that was received + let out_stream = ReceiverStream::new(rx); + + Ok(Response::new( + Box::pin(out_stream) as Self::greetStreamStream + )) + } +} + +fn match_for_io_error(err_status: &dubbo::status::Status) -> Option<&std::io::Error> { + let mut err: &(dyn std::error::Error + 'static) = err_status; + + loop { + if let Some(io_err) = err.downcast_ref::() { + return Some(io_err); + } + + err = match err.source() { + Some(err) => err, + None => return None, + }; + } +}