From 02ad8afd29fedda2daf52eb6f3f9954d0c564887 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sun, 26 Feb 2023 16:43:45 +0800 Subject: [PATCH 01/26] Add: add remoting/net member --- Cargo.toml | 18 ++- remoting/net/Cargo.toml | 17 ++ remoting/net/src/conn.rs | 298 +++++++++++++++++++++++++++++++++++ remoting/net/src/dial.rs | 138 ++++++++++++++++ remoting/net/src/incoming.rs | 94 +++++++++++ remoting/net/src/lib.rs | 79 ++++++++++ remoting/net/src/probe.rs | 63 ++++++++ remoting/net/src/tests.rs | 2 + 8 files changed, 708 insertions(+), 1 deletion(-) create mode 100644 remoting/net/Cargo.toml create mode 100644 remoting/net/src/conn.rs create mode 100644 remoting/net/src/dial.rs create mode 100644 remoting/net/src/incoming.rs create mode 100644 remoting/net/src/lib.rs create mode 100644 remoting/net/src/probe.rs create mode 100644 remoting/net/src/tests.rs diff --git a/Cargo.toml b/Cargo.toml index d4404f23..eef89fd5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,5 +10,21 @@ members = [ "dubbo", "examples/echo", "examples/greeter", - "dubbo-build" + "dubbo-build", + "remoting/net" ] + + +[workspace.dependencies] +pin-project = "1" +tokio = "1.0" +tower = "0.4" +tokio-stream = "0.1" +tokio-util = "0.7" +socket2 = "0.4" +async-trait = "0.1" +dashmap = "5" +lazy_static = "1" +futures = "0.3" +tracing = "0.1" +tracing-subscriber = "0.3.15" \ No newline at end of file diff --git a/remoting/net/Cargo.toml b/remoting/net/Cargo.toml new file mode 100644 index 00000000..655a0f9b --- /dev/null +++ b/remoting/net/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "remoting" +version = "0.1.0" +edition = "2021" + + +[dependencies] +pin-project.workspace = true +tokio = { workspace = true, features = ["net", "time", "sync", "io-util"] } +tokio-stream = { workspace = true, features = ["net"] } +tower.workspace = true +socket2.workspace = true +async-trait.workspace = true +dashmap.workspace = true +lazy_static.workspace = true +futures.workspace = true +tracing.workspace = true \ No newline at end of file diff --git a/remoting/net/src/conn.rs b/remoting/net/src/conn.rs new file mode 100644 index 00000000..ed9efb78 --- /dev/null +++ b/remoting/net/src/conn.rs @@ -0,0 +1,298 @@ +use std::{ + io, + pin::Pin, + task::{Context, Poll}, +}; + +use pin_project::pin_project; +#[cfg(target_family = "unix")] +use tokio::net::{unix, UnixStream}; +use tokio::{ + io::{AsyncRead, AsyncWrite, ReadBuf}, + net::{tcp, TcpStream}, +}; + +use super::Address; + +#[derive(Clone)] +pub struct ConnInfo { + pub peer_addr: Option
, +} + +pub trait DynStream: AsyncRead + AsyncWrite + Send + 'static {} + +impl DynStream for T where T: AsyncRead + AsyncWrite + Send + 'static {} + +#[pin_project(project = IoStreamProj)] +pub enum ConnStream { + Tcp(#[pin] TcpStream), + #[cfg(target_family = "unix")] + Unix(#[pin] UnixStream), +} + +#[pin_project(project = OwnedWriteHalfProj)] +pub enum OwnedWriteHalf { + Tcp(#[pin] tcp::OwnedWriteHalf), + #[cfg(target_family = "unix")] + Unix(#[pin] unix::OwnedWriteHalf), +} + +impl AsyncWrite for OwnedWriteHalf { + #[inline] + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + match self.project() { + OwnedWriteHalfProj::Tcp(half) => half.poll_write(cx, buf), + #[cfg(target_family = "unix")] + OwnedWriteHalfProj::Unix(half) => half.poll_write(cx, buf), + } + } + + #[inline] + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match self.project() { + OwnedWriteHalfProj::Tcp(half) => half.poll_flush(cx), + #[cfg(target_family = "unix")] + OwnedWriteHalfProj::Unix(half) => half.poll_flush(cx), + } + } + + #[inline] + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match self.project() { + OwnedWriteHalfProj::Tcp(half) => half.poll_shutdown(cx), + #[cfg(target_family = "unix")] + OwnedWriteHalfProj::Unix(half) => half.poll_shutdown(cx), + } + } + + #[inline] + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[io::IoSlice<'_>], + ) -> Poll> { + match self.project() { + OwnedWriteHalfProj::Tcp(half) => half.poll_write_vectored(cx, bufs), + #[cfg(target_family = "unix")] + OwnedWriteHalfProj::Unix(half) => half.poll_write_vectored(cx, bufs), + } + } + + #[inline] + fn is_write_vectored(&self) -> bool { + match self { + Self::Tcp(half) => half.is_write_vectored(), + #[cfg(target_family = "unix")] + Self::Unix(half) => half.is_write_vectored(), + } + } +} + +#[pin_project(project = OwnedReadHalfProj)] +pub enum OwnedReadHalf { + Tcp(#[pin] tcp::OwnedReadHalf), + #[cfg(target_family = "unix")] + Unix(#[pin] unix::OwnedReadHalf), +} + +impl AsyncRead for OwnedReadHalf { + #[inline] + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + match self.project() { + OwnedReadHalfProj::Tcp(half) => half.poll_read(cx, buf), + #[cfg(target_family = "unix")] + OwnedReadHalfProj::Unix(half) => half.poll_read(cx, buf), + } + } +} + +impl ConnStream { + #[allow(clippy::type_complexity)] + pub fn into_split(self) -> (OwnedReadHalf, OwnedWriteHalf) { + match self { + Self::Tcp(stream) => { + let (rh, wh) = stream.into_split(); + (OwnedReadHalf::Tcp(rh), OwnedWriteHalf::Tcp(wh)) + } + #[cfg(target_family = "unix")] + Self::Unix(stream) => { + let (rh, wh) = stream.into_split(); + (OwnedReadHalf::Unix(rh), OwnedWriteHalf::Unix(wh)) + } + } + } +} + +impl From for ConnStream { + #[inline] + fn from(s: TcpStream) -> Self { + let _ = s.set_nodelay(true); + Self::Tcp(s) + } +} + +#[cfg(target_family = "unix")] +impl From for ConnStream { + #[inline] + fn from(s: UnixStream) -> Self { + Self::Unix(s) + } +} + +impl AsyncRead for ConnStream { + #[inline] + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + match self.project() { + IoStreamProj::Tcp(s) => s.poll_read(cx, buf), + #[cfg(target_family = "unix")] + IoStreamProj::Unix(s) => s.poll_read(cx, buf), + } + } +} + +impl AsyncWrite for ConnStream { + #[inline] + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + match self.project() { + IoStreamProj::Tcp(s) => s.poll_write(cx, buf), + #[cfg(target_family = "unix")] + IoStreamProj::Unix(s) => s.poll_write(cx, buf), + } + } + + #[inline] + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match self.project() { + IoStreamProj::Tcp(s) => s.poll_flush(cx), + #[cfg(target_family = "unix")] + IoStreamProj::Unix(s) => s.poll_flush(cx), + } + } + + #[inline] + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match self.project() { + IoStreamProj::Tcp(s) => s.poll_shutdown(cx), + #[cfg(target_family = "unix")] + IoStreamProj::Unix(s) => s.poll_shutdown(cx), + } + } + + #[inline] + fn poll_write_vectored( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[io::IoSlice<'_>], + ) -> Poll> { + match self.project() { + IoStreamProj::Tcp(s) => s.poll_write_vectored(cx, bufs), + #[cfg(target_family = "unix")] + IoStreamProj::Unix(s) => s.poll_write_vectored(cx, bufs), + } + } + + #[inline] + fn is_write_vectored(&self) -> bool { + match self { + Self::Tcp(s) => s.is_write_vectored(), + #[cfg(target_family = "unix")] + Self::Unix(s) => s.is_write_vectored(), + } + } +} + +impl ConnStream { + #[inline] + pub fn peer_addr(&self) -> Option
{ + match self { + Self::Tcp(s) => s.peer_addr().map(Address::from).ok(), + #[cfg(target_family = "unix")] + Self::Unix(s) => s.peer_addr().ok().and_then(|s| Address::try_from(s).ok()), + } + } +} +pub struct Conn { + pub stream: ConnStream, + pub info: ConnInfo, +} + +impl Conn { + #[inline] + pub fn new(stream: ConnStream, info: ConnInfo) -> Self { + Conn { stream, info } + } +} + +impl From for Conn +where + T: Into, +{ + #[inline] + fn from(i: T) -> Self { + let i = i.into(); + let peer_addr = i.peer_addr(); + Conn::new(i, ConnInfo { peer_addr }) + } +} + +impl AsyncRead for Conn { + #[inline] + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.stream).poll_read(cx, buf) + } +} + +impl AsyncWrite for Conn { + #[inline] + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.stream).poll_write(cx, buf) + } + + #[inline] + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.stream).poll_flush(cx) + } + + #[inline] + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.stream).poll_shutdown(cx) + } + + #[inline] + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bufs: &[io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut self.stream).poll_write_vectored(cx, bufs) + } + + #[inline] + fn is_write_vectored(&self) -> bool { + self.stream.is_write_vectored() + } +} diff --git a/remoting/net/src/dial.rs b/remoting/net/src/dial.rs new file mode 100644 index 00000000..8e51279b --- /dev/null +++ b/remoting/net/src/dial.rs @@ -0,0 +1,138 @@ +use std::io; + +use socket2::{Domain, Protocol, Socket, Type}; +#[cfg(target_family = "unix")] +use tokio::net::UnixStream; +use tokio::{ + io::{AsyncRead, AsyncWrite}, + net::TcpSocket, + time::{timeout, Duration}, +}; + +use super::{ + conn::{Conn, OwnedReadHalf, OwnedWriteHalf}, + Address, +}; + +/// [`MakeTransport`] creates an [`AsyncRead`] and an [`AsyncWrite`] for the given [`Address`]. +#[async_trait::async_trait] +pub trait MakeTransport: Clone + Send + Sync + 'static { + type ReadHalf: AsyncRead + Send + Sync + Unpin + 'static; + type WriteHalf: AsyncWrite + Send + Sync + Unpin + 'static; + + async fn make_transport(&self, addr: Address) -> io::Result<(Self::ReadHalf, Self::WriteHalf)>; + fn set_connect_timeout(&mut self, timeout: Option); + fn set_read_timeout(&mut self, timeout: Option); + fn set_write_timeout(&mut self, timeout: Option); +} + +#[derive(Default, Debug, Clone, Copy)] +pub struct DefaultMakeTransport { + cfg: Config, +} + +#[derive(Default, Debug, Clone, Copy)] +pub struct Config { + pub connect_timeout: Option, + pub read_timeout: Option, + pub write_timeout: Option, +} + +impl Config { + pub fn new( + connect_timeout: Option, + read_timeout: Option, + write_timeout: Option, + ) -> Self { + Self { + connect_timeout, + read_timeout, + write_timeout, + } + } + + pub fn with_connect_timeout(mut self, timeout: Option) -> Self { + self.connect_timeout = timeout; + self + } + + pub fn with_read_timeout(mut self, timeout: Option) -> Self { + self.read_timeout = timeout; + self + } + + pub fn with_write_timeout(mut self, timeout: Option) -> Self { + self.write_timeout = timeout; + self + } +} + +impl DefaultMakeTransport { + pub fn new() -> Self { + Self::default() + } +} + +#[async_trait::async_trait] +impl MakeTransport for DefaultMakeTransport { + type ReadHalf = OwnedReadHalf; + + type WriteHalf = OwnedWriteHalf; + + async fn make_transport(&self, addr: Address) -> io::Result<(Self::ReadHalf, Self::WriteHalf)> { + let conn = self.make_connection(addr).await?; + let (read, write) = conn.stream.into_split(); + Ok((read, write)) + } + + fn set_connect_timeout(&mut self, timeout: Option) { + self.cfg = self.cfg.with_connect_timeout(timeout); + } + + fn set_read_timeout(&mut self, timeout: Option) { + self.cfg = self.cfg.with_read_timeout(timeout); + } + + fn set_write_timeout(&mut self, timeout: Option) { + self.cfg = self.cfg.with_write_timeout(timeout); + } +} + +impl DefaultMakeTransport { + pub async fn make_connection(&self, addr: Address) -> Result { + match addr { + Address::Ip(addr) => { + let stream = { + let domain = Domain::for_address(addr); + let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?; + socket.set_nonblocking(true)?; + socket.set_read_timeout(self.cfg.read_timeout)?; + socket.set_write_timeout(self.cfg.write_timeout)?; + + #[cfg(unix)] + let socket = unsafe { + use std::os::unix::io::{FromRawFd, IntoRawFd}; + TcpSocket::from_raw_fd(socket.into_raw_fd()) + }; + #[cfg(windows)] + let socket = unsafe { + use std::os::windows::io::{FromRawSocket, IntoRawSocket}; + TcpSocket::from_raw_socket(socket.into_raw_socket()) + }; + + let connect = socket.connect(addr); + + if let Some(conn_timeout) = self.cfg.connect_timeout { + timeout(conn_timeout, connect).await?? + } else { + connect.await? + } + }; + stream.set_nodelay(true)?; + Ok(Conn::from(stream)) + } + #[cfg(target_family = "unix")] + Address::Unix(addr) => UnixStream::connect(addr).await.map(Conn::from), + } + } +} diff --git a/remoting/net/src/incoming.rs b/remoting/net/src/incoming.rs new file mode 100644 index 00000000..82ea077d --- /dev/null +++ b/remoting/net/src/incoming.rs @@ -0,0 +1,94 @@ +use std::{ + fmt, io, + task::{Context, Poll}, +}; + +use futures::Stream; +use pin_project::pin_project; +use tokio::net::TcpListener; +#[cfg(target_family = "unix")] +use tokio::net::UnixListener; +#[cfg(target_family = "unix")] +use tokio_stream::wrappers::UnixListenerStream; +use tokio_stream::{wrappers::TcpListenerStream, StreamExt}; + +use super::{conn::Conn, Address}; + +#[pin_project(project = IncomingProj)] +#[derive(Debug)] +pub enum DefaultIncoming { + Tcp(#[pin] TcpListenerStream), + #[cfg(target_family = "unix")] + Unix(#[pin] UnixListenerStream), +} + +#[async_trait::async_trait] +impl MakeIncoming for DefaultIncoming { + type Incoming = DefaultIncoming; + + async fn make_incoming(self) -> io::Result { + Ok(self) + } +} + +#[cfg(target_family = "unix")] +impl From for DefaultIncoming { + fn from(l: UnixListener) -> Self { + DefaultIncoming::Unix(UnixListenerStream::new(l)) + } +} + +impl From for DefaultIncoming { + fn from(l: TcpListener) -> Self { + DefaultIncoming::Tcp(TcpListenerStream::new(l)) + } +} + +#[async_trait::async_trait] +pub trait Incoming: fmt::Debug + Send + 'static { + async fn accept(&mut self) -> io::Result>; +} + +#[async_trait::async_trait] +impl Incoming for DefaultIncoming { + async fn accept(&mut self) -> io::Result> { + if let Some(conn) = self.try_next().await? { + tracing::trace!("[Net] recv a connection from: {:?}", conn.info.peer_addr); + Ok(Some(conn)) + } else { + Ok(None) + } + } +} + +#[async_trait::async_trait] +pub trait MakeIncoming { + type Incoming: Incoming; + + async fn make_incoming(self) -> io::Result; +} + +#[async_trait::async_trait] +impl MakeIncoming for Address { + type Incoming = DefaultIncoming; + + async fn make_incoming(self) -> io::Result { + match self { + Address::Ip(addr) => TcpListener::bind(addr).await.map(DefaultIncoming::from), + #[cfg(target_family = "unix")] + Address::Unix(addr) => UnixListener::bind(addr).map(DefaultIncoming::from), + } + } +} + +impl Stream for DefaultIncoming { + type Item = io::Result; + + fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + match self.project() { + IncomingProj::Tcp(s) => s.poll_next(cx).map_ok(Conn::from), + #[cfg(target_family = "unix")] + IncomingProj::Unix(s) => s.poll_next(cx).map_ok(Conn::from), + } + } +} diff --git a/remoting/net/src/lib.rs b/remoting/net/src/lib.rs new file mode 100644 index 00000000..dfcc8b6f --- /dev/null +++ b/remoting/net/src/lib.rs @@ -0,0 +1,79 @@ +pub mod conn; +pub mod dial; +pub mod incoming; +mod probe; +mod tests; + +use std::{borrow::Cow, fmt, net::Ipv6Addr, path::Path}; + +pub use incoming::{DefaultIncoming, MakeIncoming}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Address { + Ip(std::net::SocketAddr), + #[cfg(target_family = "unix")] + Unix(Cow<'static, Path>), +} + +impl Address { + pub fn favor_dual_stack(self) -> Self { + match self { + Address::Ip(addr) => { + if addr.ip().is_unspecified() && should_favor_ipv6() { + Address::Ip((Ipv6Addr::UNSPECIFIED, addr.port()).into()) + } else { + self + } + } + #[cfg(target_family = "unix")] + _ => self, + } + } +} + +fn should_favor_ipv6() -> bool { + let probed = probe::probe(); + !probed.ipv4 || probed.ipv4_mapped_ipv6 +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Address::Ip(addr) => write!(f, "{addr}"), + #[cfg(target_family = "unix")] + Address::Unix(path) => write!(f, "{}", path.display()), + } + } +} + +impl From for Address { + fn from(addr: std::net::SocketAddr) -> Self { + Address::Ip(addr) + } +} + +#[cfg(target_family = "unix")] +impl From> for Address { + fn from(addr: Cow<'static, Path>) -> Self { + Address::Unix(addr) + } +} + +#[cfg(target_family = "unix")] +impl TryFrom for Address { + type Error = std::io::Error; + + fn try_from(value: tokio::net::unix::SocketAddr) -> Result { + Ok(Address::Unix(Cow::Owned( + value + .as_pathname() + .ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::Other, + "unix socket doesn't have an address", + ) + })? + .to_owned(), + ))) + } +} diff --git a/remoting/net/src/probe.rs b/remoting/net/src/probe.rs new file mode 100644 index 00000000..27367e14 --- /dev/null +++ b/remoting/net/src/probe.rs @@ -0,0 +1,63 @@ +use lazy_static::lazy_static; +use socket2::{Domain, Protocol, Socket, Type}; + +#[derive(Debug)] +pub struct IpStackCapability { + pub ipv4: bool, + pub ipv6: bool, + pub ipv4_mapped_ipv6: bool, +} + +impl IpStackCapability { + fn probe() -> Self { + IpStackCapability { + ipv4: Self::probe_ipv4(), + ipv6: Self::probe_ipv6(), + ipv4_mapped_ipv6: Self::probe_ipv4_mapped_ipv6(), + } + } + + fn probe_ipv4() -> bool { + let s = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP)); + s.is_ok() + } + + fn probe_ipv6() -> bool { + let s = Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP)); + let s = match s { + Ok(s) => s, + Err(_) => return false, + }; + // this error is ignored in go, follow their strategy + let _ = s.set_only_v6(true); + let addr: std::net::SocketAddr = ([0, 0, 0, 0, 0, 0, 0, 1], 0).into(); + s.bind(&addr.into()).is_ok() + } + + fn probe_ipv4_mapped_ipv6() -> bool { + let s = Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP)); + let s = match s { + Ok(s) => s, + Err(_) => return false, + }; + !s.only_v6().unwrap_or(true) + } +} + +pub fn probe() -> &'static IpStackCapability { + lazy_static! { + static ref CAPABILITY: IpStackCapability = IpStackCapability::probe(); + } + &CAPABILITY +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore] + fn tryout_probe() { + println!("{:?}", probe()); + } +} diff --git a/remoting/net/src/tests.rs b/remoting/net/src/tests.rs new file mode 100644 index 00000000..90a52c2d --- /dev/null +++ b/remoting/net/src/tests.rs @@ -0,0 +1,2 @@ +#[test] +fn test_client() {} From b3cb54a7c7f59aa3ce43ed48b0bcb5709dc158a9 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sun, 26 Feb 2023 17:16:07 +0800 Subject: [PATCH 02/26] Add: add remoting/net member --- Cargo.toml | 2 +- remoting/net/Cargo.toml | 4 ++-- remoting/net/src/conn.rs | 17 +++++++++++++++++ remoting/net/src/dial.rs | 16 ++++++++++++++++ remoting/net/src/incoming.rs | 16 ++++++++++++++++ remoting/net/src/lib.rs | 17 +++++++++++++++++ remoting/net/src/probe.rs | 16 ++++++++++++++++ remoting/net/src/tests.rs | 35 +++++++++++++++++++++++++++++++++-- 8 files changed, 118 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index eef89fd5..ff43a2b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,4 +27,4 @@ dashmap = "5" lazy_static = "1" futures = "0.3" tracing = "0.1" -tracing-subscriber = "0.3.15" \ No newline at end of file +tracing-subscriber = "0.3.15" diff --git a/remoting/net/Cargo.toml b/remoting/net/Cargo.toml index 655a0f9b..c39a362e 100644 --- a/remoting/net/Cargo.toml +++ b/remoting/net/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" [dependencies] pin-project.workspace = true -tokio = { workspace = true, features = ["net", "time", "sync", "io-util"] } +tokio = { workspace = true, features = ["net", "time", "sync", "io-util","test-util","macros"] } tokio-stream = { workspace = true, features = ["net"] } tower.workspace = true socket2.workspace = true @@ -14,4 +14,4 @@ async-trait.workspace = true dashmap.workspace = true lazy_static.workspace = true futures.workspace = true -tracing.workspace = true \ No newline at end of file +tracing.workspace = true diff --git a/remoting/net/src/conn.rs b/remoting/net/src/conn.rs index ed9efb78..7a3f14ac 100644 --- a/remoting/net/src/conn.rs +++ b/remoting/net/src/conn.rs @@ -1,3 +1,20 @@ +/* + * 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. + */ + use std::{ io, pin::Pin, diff --git a/remoting/net/src/dial.rs b/remoting/net/src/dial.rs index 8e51279b..704e7cd3 100644 --- a/remoting/net/src/dial.rs +++ b/remoting/net/src/dial.rs @@ -1,3 +1,19 @@ +/* + * 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. + */ use std::io; use socket2::{Domain, Protocol, Socket, Type}; diff --git a/remoting/net/src/incoming.rs b/remoting/net/src/incoming.rs index 82ea077d..7a730839 100644 --- a/remoting/net/src/incoming.rs +++ b/remoting/net/src/incoming.rs @@ -1,3 +1,19 @@ +/* + * 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. + */ use std::{ fmt, io, task::{Context, Poll}, diff --git a/remoting/net/src/lib.rs b/remoting/net/src/lib.rs index dfcc8b6f..b79f2321 100644 --- a/remoting/net/src/lib.rs +++ b/remoting/net/src/lib.rs @@ -1,3 +1,20 @@ +/* + * 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 conn; pub mod dial; pub mod incoming; diff --git a/remoting/net/src/probe.rs b/remoting/net/src/probe.rs index 27367e14..216afbe3 100644 --- a/remoting/net/src/probe.rs +++ b/remoting/net/src/probe.rs @@ -1,3 +1,19 @@ +/* + * 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. + */ use lazy_static::lazy_static; use socket2::{Domain, Protocol, Socket, Type}; diff --git a/remoting/net/src/tests.rs b/remoting/net/src/tests.rs index 90a52c2d..cc43444a 100644 --- a/remoting/net/src/tests.rs +++ b/remoting/net/src/tests.rs @@ -1,2 +1,33 @@ -#[test] -fn test_client() {} +/* + * 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. + */ + +use crate::dial::DefaultMakeTransport; +use crate::Address; +use tokio::io::AsyncWriteExt; + +// listen by command: `nc -l 8858 -v` +#[tokio::test(flavor = "current_thread")] +async fn test_tcp_bytes_send() { + let transport = DefaultMakeTransport::new(); + let mut conn = transport + .make_connection(Address::Ip("127.0.0.1:8858".parse().unwrap())) + .await + .unwrap(); + conn.write_all("\n\rhello dubbo-rust\n\r".to_string().as_bytes()) + .await + .unwrap(); +} From b49eb4146e74e1f72f4f0ece9815383fec6ac39f Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sun, 26 Feb 2023 23:24:25 +0800 Subject: [PATCH 03/26] Add: remoting/net/incoming --- remoting/net/src/conn.rs | 20 ++++++++++++++++++ remoting/net/src/incoming.rs | 29 ++++++++++++++++++++++++++ remoting/net/src/lib.rs | 2 +- remoting/net/src/{tests.rs => pool.rs} | 17 --------------- 4 files changed, 50 insertions(+), 18 deletions(-) rename remoting/net/src/{tests.rs => pool.rs} (61%) diff --git a/remoting/net/src/conn.rs b/remoting/net/src/conn.rs index 7a3f14ac..d015a8ec 100644 --- a/remoting/net/src/conn.rs +++ b/remoting/net/src/conn.rs @@ -313,3 +313,23 @@ impl AsyncWrite for Conn { self.stream.is_write_vectored() } } + +#[cfg(test)] +mod tests { + use crate::dial::DefaultMakeTransport; + use crate::Address; + use tokio::io::AsyncWriteExt; + + // listen by command: nc -l 8858 -v + #[tokio::test(flavor = "current_thread")] + async fn test_write_bytes() { + let transport = DefaultMakeTransport::new(); + let mut conn = transport + .make_connection(Address::Ip("127.0.0.1:8858".parse().unwrap())) + .await + .unwrap(); + conn.write_all("\n\rhello dubbo-rust\n\r".to_string().as_bytes()) + .await + .unwrap(); + } +} diff --git a/remoting/net/src/incoming.rs b/remoting/net/src/incoming.rs index 7a730839..cd8b5a5c 100644 --- a/remoting/net/src/incoming.rs +++ b/remoting/net/src/incoming.rs @@ -108,3 +108,32 @@ impl Stream for DefaultIncoming { } } } + +#[cfg(test)] +mod tests { + use tokio::net::TcpListener; + use tokio_stream::wrappers::TcpListenerStream; + use tracing::info; + + use crate::incoming::Incoming; + use crate::{DefaultIncoming, MakeIncoming}; + + #[tokio::test] + async fn test_read_bytes() { + let listener = TcpListener::bind("[::]:8081").await.unwrap(); + let incoming = DefaultIncoming::Tcp(TcpListenerStream::new(listener)) + .make_incoming() + .await + .unwrap(); + println!("[VOLO] server start at: {:?}", incoming); + let mut incoming = incoming; + loop { + let conn = incoming.accept().await.unwrap(); + if let Some(conn) = conn { + info!("[VOLO] recv a connection from: {:?}", conn.info.peer_addr); + } else { + info!("[VOLO] recv a connection from: None"); + } + } + } +} diff --git a/remoting/net/src/lib.rs b/remoting/net/src/lib.rs index b79f2321..38f95a26 100644 --- a/remoting/net/src/lib.rs +++ b/remoting/net/src/lib.rs @@ -18,8 +18,8 @@ pub mod conn; pub mod dial; pub mod incoming; +mod pool; mod probe; -mod tests; use std::{borrow::Cow, fmt, net::Ipv6Addr, path::Path}; diff --git a/remoting/net/src/tests.rs b/remoting/net/src/pool.rs similarity index 61% rename from remoting/net/src/tests.rs rename to remoting/net/src/pool.rs index cc43444a..2944f981 100644 --- a/remoting/net/src/tests.rs +++ b/remoting/net/src/pool.rs @@ -14,20 +14,3 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -use crate::dial::DefaultMakeTransport; -use crate::Address; -use tokio::io::AsyncWriteExt; - -// listen by command: `nc -l 8858 -v` -#[tokio::test(flavor = "current_thread")] -async fn test_tcp_bytes_send() { - let transport = DefaultMakeTransport::new(); - let mut conn = transport - .make_connection(Address::Ip("127.0.0.1:8858".parse().unwrap())) - .await - .unwrap(); - conn.write_all("\n\rhello dubbo-rust\n\r".to_string().as_bytes()) - .await - .unwrap(); -} From fbe02d6c66b81fe6091ffb5cd358cf186ce8db03 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Mon, 27 Feb 2023 10:28:36 +0800 Subject: [PATCH 04/26] Add: remoting/net/incoming --- config/src/protocol.rs | 4 ++-- remoting/net/src/conn.rs | 3 +-- remoting/net/src/incoming.rs | 36 ++++++++++++++++++++++-------------- 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/config/src/protocol.rs b/config/src/protocol.rs index cdc357ad..4a47ac98 100644 --- a/config/src/protocol.rs +++ b/config/src/protocol.rs @@ -73,10 +73,10 @@ impl ProtocolRetrieve for ProtocolConfig { fn get_protocol_or_default(&self, protocol_key: &str) -> Protocol { let result = self.get_protocol(protocol_key); if let Some(..) = result { - result.unwrap().clone() + result.unwrap() } else { let result = self.get_protocol(protocol_key); - if result.is_none() { + if let Some(..) = result { panic!("default triple protocol dose not defined.") } else { result.unwrap() diff --git a/remoting/net/src/conn.rs b/remoting/net/src/conn.rs index d015a8ec..c3155017 100644 --- a/remoting/net/src/conn.rs +++ b/remoting/net/src/conn.rs @@ -316,8 +316,7 @@ impl AsyncWrite for Conn { #[cfg(test)] mod tests { - use crate::dial::DefaultMakeTransport; - use crate::Address; + use crate::{dial::DefaultMakeTransport, Address}; use tokio::io::AsyncWriteExt; // listen by command: nc -l 8858 -v diff --git a/remoting/net/src/incoming.rs b/remoting/net/src/incoming.rs index cd8b5a5c..c04eeb8a 100644 --- a/remoting/net/src/incoming.rs +++ b/remoting/net/src/incoming.rs @@ -111,29 +111,37 @@ impl Stream for DefaultIncoming { #[cfg(test)] mod tests { - use tokio::net::TcpListener; + use tokio::{io::AsyncReadExt, net::TcpListener}; use tokio_stream::wrappers::TcpListenerStream; - use tracing::info; - use crate::incoming::Incoming; - use crate::{DefaultIncoming, MakeIncoming}; + use crate::{incoming::Incoming, DefaultIncoming, MakeIncoming}; #[tokio::test] async fn test_read_bytes() { - let listener = TcpListener::bind("[::]:8081").await.unwrap(); + let listener = TcpListener::bind("127.0.0.1:8858").await.unwrap(); let incoming = DefaultIncoming::Tcp(TcpListenerStream::new(listener)) .make_incoming() .await .unwrap(); - println!("[VOLO] server start at: {:?}", incoming); - let mut incoming = incoming; - loop { - let conn = incoming.accept().await.unwrap(); - if let Some(conn) = conn { - info!("[VOLO] recv a connection from: {:?}", conn.info.peer_addr); - } else { - info!("[VOLO] recv a connection from: None"); + println!("[Dubbo-Rust] server start at: {:?}", incoming); + let join_handle = tokio::spawn(async move { + let mut incoming = incoming; + match incoming.accept().await.unwrap() { + Some(mut conn) => { + println!("[VOLO] recv a connection from: {:?}", conn.info.peer_addr); + let mut buf = vec![0; 1024]; + let n = conn.read(&mut buf).await.unwrap(); + println!( + "[VOLO] recv a connection from: {:?}", + String::from_utf8(buf[..n].to_vec()).unwrap() + ); + } + None => { + println!("[VOLO] recv a connection from: None"); + } } - } + }); + tokio::time::sleep(std::time::Duration::from_secs(10)).await; + drop(join_handle); } } From d48ae45842cd80fa41ddab8f46aed58a1b2a0a87 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Mon, 27 Feb 2023 10:36:33 +0800 Subject: [PATCH 05/26] Add: License --- remoting/net/LICENSE | 202 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 remoting/net/LICENSE diff --git a/remoting/net/LICENSE b/remoting/net/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/remoting/net/LICENSE @@ -0,0 +1,202 @@ + + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. From 8c4cbb42ecd58a5ba58f54705c886234eb256955 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Mon, 27 Feb 2023 13:06:16 +0800 Subject: [PATCH 06/26] Add: License --- remoting/net/src/incoming.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/remoting/net/src/incoming.rs b/remoting/net/src/incoming.rs index c04eeb8a..82672605 100644 --- a/remoting/net/src/incoming.rs +++ b/remoting/net/src/incoming.rs @@ -128,16 +128,19 @@ mod tests { let mut incoming = incoming; match incoming.accept().await.unwrap() { Some(mut conn) => { - println!("[VOLO] recv a connection from: {:?}", conn.info.peer_addr); + println!( + "[Dubbo-Rust] recv a connection from: {:?}", + conn.info.peer_addr + ); let mut buf = vec![0; 1024]; let n = conn.read(&mut buf).await.unwrap(); println!( - "[VOLO] recv a connection from: {:?}", + "[Dubbo-Rust] recv a connection from: {:?}", String::from_utf8(buf[..n].to_vec()).unwrap() ); } None => { - println!("[VOLO] recv a connection from: None"); + println!("[Dubbo-Rust] recv a connection from: None"); } } }); From 9ddb8d918b117af32ebdd156841d4e7f12eaa0ac Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 13:23:55 +0800 Subject: [PATCH 07/26] Rft: using subpackage to manage registry implementations for avoiding primary directory abuse. --- Cargo.toml | 3 +- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++++++++------ remoting/net/Cargo.toml | 10 +- .../net/benches/transport_benchmark/main.rs | 16 ++ remoting/net/src/incoming.rs | 10 +- 5 files changed, 147 insertions(+), 71 deletions(-) create mode 100644 remoting/net/benches/transport_benchmark/main.rs diff --git a/Cargo.toml b/Cargo.toml index ae339cd7..9ace07f6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,12 +24,11 @@ async-trait = "0.1" dashmap = "5" lazy_static = "1" futures = "0.3" -tracing = "0.1" -tracing-subscriber = "0.3.15" serde = "1" serde_json = "1" urlencoding = "2.1.2" logger = {path="./common/logger"} anyhow = "1.0.66" dubbo = { path = "./dubbo/" } +bb8 = "0.8.0" diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index ccb385cd..8758f85a 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -40,12 +40,16 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); + let path = http::uri::PathAndQuery::from_static( + "/grpc.examples.echo.Echo/UnaryEcho", + ); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -53,51 +57,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner - .server_streaming(request, codec, path, invocation) - .await + self.inner.server_streaming(request, codec, path, invocation).await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner - .client_streaming(request, codec, path, invocation) - .await + self.inner.client_streaming(request, codec, path, invocation).await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner - .bidi_streaming(request, codec, path, invocation) - .await + self.inner.bidi_streaming(request, codec, path, invocation).await } } } @@ -114,7 +118,9 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream> + type ServerStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -128,14 +134,19 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream> + type BidirectionalStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result, dubbo::status::Status>; + ) -> Result< + Response, + dubbo::status::Status, + >; } /// Echo is the echo service. #[derive(Debug)] @@ -165,7 +176,10 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + fn poll_ready( + &mut self, + _cx: &mut Context<'_>, + ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -178,18 +192,26 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -200,22 +222,32 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc for ServerStreamingEchoServer { + impl ServerStreamingSvc + for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.server_streaming_echo(request).await }; + let fut = async move { + inner.server_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -228,23 +260,31 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc for ClientStreamingEchoServer { + impl ClientStreamingSvc + for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.client_streaming_echo(request).await }; + let fut = async move { + inner.client_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -257,41 +297,56 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc for BidirectionalStreamingEchoServer { + impl StreamingSvc + for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = - async move { inner.bidirectional_streaming_echo(request).await }; + let fut = async move { + inner.bidirectional_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server - .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) + .bidi_streaming( + BidirectionalStreamingEchoServer { + inner, + }, + req, + ) .await; Ok(res) }; Box::pin(fut) } - _ => Box::pin(async move { - Ok(http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap()) - }), + _ => { + Box::pin(async move { + Ok( + http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap(), + ) + }) + } } } } diff --git a/remoting/net/Cargo.toml b/remoting/net/Cargo.toml index c39a362e..c62082e0 100644 --- a/remoting/net/Cargo.toml +++ b/remoting/net/Cargo.toml @@ -1,12 +1,15 @@ [package] -name = "remoting" +name = "net" version = "0.1.0" edition = "2021" +[[bench]] +name = "transport_benchmark" +harness=false [dependencies] pin-project.workspace = true -tokio = { workspace = true, features = ["net", "time", "sync", "io-util","test-util","macros"] } +tokio = { workspace = true, features = ["net", "time", "sync", "io-util", "test-util", "macros"] } tokio-stream = { workspace = true, features = ["net"] } tower.workspace = true socket2.workspace = true @@ -14,4 +17,5 @@ async-trait.workspace = true dashmap.workspace = true lazy_static.workspace = true futures.workspace = true -tracing.workspace = true +logger.workspace = true +bb8.workspace = true diff --git a/remoting/net/benches/transport_benchmark/main.rs b/remoting/net/benches/transport_benchmark/main.rs new file mode 100644 index 00000000..2944f981 --- /dev/null +++ b/remoting/net/benches/transport_benchmark/main.rs @@ -0,0 +1,16 @@ +/* + * 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. + */ diff --git a/remoting/net/src/incoming.rs b/remoting/net/src/incoming.rs index 82672605..bca797e9 100644 --- a/remoting/net/src/incoming.rs +++ b/remoting/net/src/incoming.rs @@ -20,6 +20,7 @@ use std::{ }; use futures::Stream; +use logger::tracing; use pin_project::pin_project; use tokio::net::TcpListener; #[cfg(target_family = "unix")] @@ -111,6 +112,7 @@ impl Stream for DefaultIncoming { #[cfg(test)] mod tests { + use logger::tracing::debug; use tokio::{io::AsyncReadExt, net::TcpListener}; use tokio_stream::wrappers::TcpListenerStream; @@ -123,24 +125,24 @@ mod tests { .make_incoming() .await .unwrap(); - println!("[Dubbo-Rust] server start at: {:?}", incoming); + debug!("[Dubbo-Rust] server start at: {:?}", incoming); let join_handle = tokio::spawn(async move { let mut incoming = incoming; match incoming.accept().await.unwrap() { Some(mut conn) => { - println!( + debug!( "[Dubbo-Rust] recv a connection from: {:?}", conn.info.peer_addr ); let mut buf = vec![0; 1024]; let n = conn.read(&mut buf).await.unwrap(); - println!( + debug!( "[Dubbo-Rust] recv a connection from: {:?}", String::from_utf8(buf[..n].to_vec()).unwrap() ); } None => { - println!("[Dubbo-Rust] recv a connection from: None"); + debug!("[Dubbo-Rust] recv a connection from: None"); } } }); From 3e594faf7637f9eb180bb0ea60513ed35b6e6461 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 14:21:07 +0800 Subject: [PATCH 08/26] Ftr: add common/utils subpackage --- Cargo.toml | 8 +++++++- common/utils/Cargo.toml | 10 ++++++++++ common/utils/src/lib.rs | 17 +++++++++++++++++ common/utils/src/yaml_util.rs | 16 ++++++++++++++++ config/Cargo.toml | 10 +++++----- 5 files changed, 55 insertions(+), 6 deletions(-) create mode 100644 common/utils/Cargo.toml create mode 100644 common/utils/src/lib.rs create mode 100644 common/utils/src/yaml_util.rs diff --git a/Cargo.toml b/Cargo.toml index 9ace07f6..06341845 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,7 @@ [workspace] members = [ + "common/logger", + "common/utils", "xds", "registry/zookeeper", "registry/nacos", @@ -28,7 +30,11 @@ serde = "1" serde_json = "1" urlencoding = "2.1.2" logger = {path="./common/logger"} +utils = {path="./common/utils"} anyhow = "1.0.66" dubbo = { path = "./dubbo/" } -bb8 = "0.8.0" +bb8 = "0.8.0" # A connecton pool based on tokio +serde_yaml = "0.9.4" # yaml file parser +once_cell = "1.16.0" + diff --git a/common/utils/Cargo.toml b/common/utils/Cargo.toml new file mode 100644 index 00000000..62be6f32 --- /dev/null +++ b/common/utils/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "utils" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde_yaml.workspace = true +serde = { workspace = true, features = ["derive"] } \ No newline at end of file diff --git a/common/utils/src/lib.rs b/common/utils/src/lib.rs new file mode 100644 index 00000000..f2ffa96a --- /dev/null +++ b/common/utils/src/lib.rs @@ -0,0 +1,17 @@ +/* + * 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 yaml_util; diff --git a/common/utils/src/yaml_util.rs b/common/utils/src/yaml_util.rs new file mode 100644 index 00000000..2944f981 --- /dev/null +++ b/common/utils/src/yaml_util.rs @@ -0,0 +1,16 @@ +/* + * 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. + */ diff --git a/config/Cargo.toml b/config/Cargo.toml index 1eaa89cb..39797970 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -10,8 +10,8 @@ repository = "https://github.com/apache/dubbo-rust.git" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -serde = {version="1.0.138", features = ["derive"]} -serde_yaml = "0.9.4" -tracing = "0.1" -lazy_static = "1.3.0" -once_cell = "1.16.0" +serde = { workspace = true, features = ["derive"] } +serde_yaml.workspace = true +lazy_static.workspace = true +once_cell.workspace = true +utils.workspace = true From b45d1bafba00a38236dd1934501647c04cf4c990 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 20:38:46 +0800 Subject: [PATCH 09/26] Ftr: add common/utils subpackage --- .github/workflows/github-actions.yml | 2 +- Cargo.toml | 1 + application.yaml | 19 ++++++++ common/logger/Cargo.toml | 2 +- common/utils/Cargo.toml | 5 ++- common/utils/src/lib.rs | 1 + common/utils/src/path_util.rs | 41 +++++++++++++++++ common/utils/src/yaml_util.rs | 39 ++++++++++++++++ common/utils/tests/application.yaml | 2 + config/Cargo.toml | 1 + config/src/config.rs | 44 +++++++------------ config/src/lib.rs | 13 +----- dubbo.yaml | 26 ----------- dubbo/Cargo.toml | 22 +++++----- dubbogo.yaml | 7 --- .../greeter/{dubbo.yaml => application.yaml} | 2 + scripts/ci-check.sh | 23 ---------- 17 files changed, 140 insertions(+), 110 deletions(-) create mode 100644 application.yaml create mode 100644 common/utils/src/path_util.rs create mode 100644 common/utils/tests/application.yaml delete mode 100644 dubbo.yaml delete mode 100644 dubbogo.yaml rename examples/greeter/{dubbo.yaml => application.yaml} (93%) delete mode 100755 scripts/ci-check.sh diff --git a/.github/workflows/github-actions.yml b/.github/workflows/github-actions.yml index e8881e01..b02b3bc9 100644 --- a/.github/workflows/github-actions.yml +++ b/.github/workflows/github-actions.yml @@ -94,5 +94,5 @@ jobs: ../../target/debug/greeter-client env: ZOOKEEPER_SERVERS: 127.0.0.1:2181 - DUBBO_CONFIG_PATH: ./dubbo.yaml + DUBBO_CONFIG_PATH: ./application.yaml working-directory: examples/greeter diff --git a/Cargo.toml b/Cargo.toml index 06341845..c879e4d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,5 +36,6 @@ dubbo = { path = "./dubbo/" } bb8 = "0.8.0" # A connecton pool based on tokio serde_yaml = "0.9.4" # yaml file parser once_cell = "1.16.0" +itertools = "0.10.1" diff --git a/application.yaml b/application.yaml new file mode 100644 index 00000000..7cd01252 --- /dev/null +++ b/application.yaml @@ -0,0 +1,19 @@ +logging: + level: INFO +dubbo: + protocols: + triple: + ip: 0.0.0.0 + port: '8888' + name: tri + registries: + demoZK: + protocol: zookeeper + address: 0.0.0.0:2181 + provider: + services: + GreeterProvider: + version: 1.0.0 + group: test + protocol: triple + interface: org.apache.dubbo.sample.tri.Greeter \ No newline at end of file diff --git a/common/logger/Cargo.toml b/common/logger/Cargo.toml index 14157bb1..578ddfef 100644 --- a/common/logger/Cargo.toml +++ b/common/logger/Cargo.toml @@ -7,4 +7,4 @@ edition = "2021" [dependencies] tracing = "0.1" -tracing-subscriber = "0.3" \ No newline at end of file +tracing-subscriber = "0.3" diff --git a/common/utils/Cargo.toml b/common/utils/Cargo.toml index 62be6f32..d2d004e3 100644 --- a/common/utils/Cargo.toml +++ b/common/utils/Cargo.toml @@ -7,4 +7,7 @@ edition = "2021" [dependencies] serde_yaml.workspace = true -serde = { workspace = true, features = ["derive"] } \ No newline at end of file +serde = { workspace = true, features = ["derive"] } +logger.workspace=true +project-root = "0.2.2" +anyhow.workspace=true \ No newline at end of file diff --git a/common/utils/src/lib.rs b/common/utils/src/lib.rs index f2ffa96a..47dbe626 100644 --- a/common/utils/src/lib.rs +++ b/common/utils/src/lib.rs @@ -14,4 +14,5 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +pub mod path_util; pub mod yaml_util; diff --git a/common/utils/src/path_util.rs b/common/utils/src/path_util.rs new file mode 100644 index 00000000..2386d72c --- /dev/null +++ b/common/utils/src/path_util.rs @@ -0,0 +1,41 @@ +/* + * 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. + */ + +use std::env; +use std::path::PathBuf; + +pub fn app_root_dir() -> PathBuf { + match project_root::get_project_root() { + // Cargo.lock file as app root dir + Ok(p) => p, + Err(_) => env::current_dir().unwrap(), + } +} + +#[cfg(test)] +mod tests { + use logger::tracing::info; + + use super::*; + + #[test] + fn test_app_root_dir() { + logger::init(); + let dir = app_root_dir().join("application.yaml"); + info!("dir: {}", dir.display()); + } +} diff --git a/common/utils/src/yaml_util.rs b/common/utils/src/yaml_util.rs index 2944f981..80de6f74 100644 --- a/common/utils/src/yaml_util.rs +++ b/common/utils/src/yaml_util.rs @@ -14,3 +14,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use std::fs; +use std::path::PathBuf; + +use anyhow::Error; +use serde_yaml::from_slice; + +use logger::tracing; + +// parse yaml file to structs +pub fn yaml_file_parser(path: PathBuf) -> Result +where + T: serde::de::DeserializeOwned + std::fmt::Debug, +{ + if !path.is_file() { + return Err(anyhow::anyhow!("path is not a file: {:?}", path)); + } + let data = fs::read(path.as_path())?; + tracing::debug!("config data: {:?}", String::from_utf8(data.clone())); + Ok(from_slice(&data).unwrap()) +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use crate::path_util::app_root_dir; + use crate::yaml_util::yaml_file_parser; + + #[test] + fn test_yaml_file_parser() { + let path = app_root_dir() + .join("common") + .join("utils") + .join("tests") + .join("application.yaml"); + let config = yaml_file_parser::>>(path).unwrap(); + println!("{:?}", config); + } +} diff --git a/common/utils/tests/application.yaml b/common/utils/tests/application.yaml new file mode 100644 index 00000000..ecfd4478 --- /dev/null +++ b/common/utils/tests/application.yaml @@ -0,0 +1,2 @@ +logging: + level: INFO diff --git a/config/Cargo.toml b/config/Cargo.toml index 39797970..b4e19d47 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -15,3 +15,4 @@ serde_yaml.workspace = true lazy_static.workspace = true once_cell.workspace = true utils.workspace = true +logger.workspace=true \ No newline at end of file diff --git a/config/src/config.rs b/config/src/config.rs index ed3a7140..eb44464f 100644 --- a/config/src/config.rs +++ b/config/src/config.rs @@ -15,16 +15,18 @@ * limitations under the License. */ -use std::{collections::HashMap, env, fs}; +use std::path::PathBuf; +use std::{collections::HashMap, env}; use crate::{protocol::Protocol, registry::RegistryConfig}; +use logger::tracing; use once_cell::sync::OnceCell; use serde::{Deserialize, Serialize}; -use tracing::trace; +use utils::yaml_util::yaml_file_parser; use super::{protocol::ProtocolConfig, provider::ProviderConfig, service::ServiceConfig}; -pub const DUBBO_CONFIG_PATH: &str = "./dubbo.yaml"; +pub const DUBBO_CONFIG_PATH: &str = "application.yaml"; pub static GLOBAL_ROOT_CONFIG: OnceCell = OnceCell::new(); pub const DUBBO_CONFIG_PREFIX: &str = "dubbo"; @@ -78,14 +80,16 @@ impl RootConfig { err, DUBBO_CONFIG_PATH ); - DUBBO_CONFIG_PATH.to_string() + utils::path_util::app_root_dir() + .join(DUBBO_CONFIG_PATH) + .to_str() + .unwrap() + .to_string() } }; - tracing::info!("current path: {:?}", env::current_dir()); - let data = fs::read(config_path)?; - trace!("config data: {:?}", String::from_utf8(data.clone())); - let conf: HashMap = serde_yaml::from_slice(&data).unwrap(); + let conf: HashMap = + yaml_file_parser(PathBuf::new().join(config_path)).unwrap(); let root_config: RootConfig = conf.get(DUBBO_CONFIG_PREFIX).unwrap().clone(); tracing::debug!("origin config: {:?}", conf); Ok(root_config) @@ -181,27 +185,9 @@ mod tests { #[test] fn test_load() { - // case 1: read config yaml from default path - println!("current path: {:?}", env::current_dir()); + logger::init(); let r = RootConfig::new(); - r.load(); - } - - #[test] - fn test_load1() { - // case 2: read config yaml from path in env - println!("current path: {:?}", env::current_dir()); - let r = RootConfig::new(); - r.load(); - } - - #[test] - fn test_write_yaml() { - let mut r = RootConfig::new(); - r.test_config(); - let yaml = serde_yaml::to_string(&r).unwrap(); - println!("config data: {:?}", yaml); - - fs::write("./test_dubbo.yaml", yaml); + let r = r.load().unwrap(); + println!("{:#?}", r); } } diff --git a/config/src/lib.rs b/config/src/lib.rs index e56d933a..0748c667 100644 --- a/config/src/lib.rs +++ b/config/src/lib.rs @@ -15,19 +15,10 @@ * limitations under the License. */ +pub use config::*; + pub mod config; pub mod protocol; pub mod provider; pub mod registry; pub mod service; - -pub use config::*; - -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - let result = 2 + 2; - assert_eq!(result, 4); - } -} diff --git a/dubbo.yaml b/dubbo.yaml deleted file mode 100644 index e14b5301..00000000 --- a/dubbo.yaml +++ /dev/null @@ -1,26 +0,0 @@ -name: dubbo -service: - echo: - version: 1.0.0 - group: test - protocol: triple - registry: '' - serializer: json - protocol_configs: - triple: - ip: 0.0.0.0 - port: '8888' - name: triple - listener: tcp - # helloworld.Greeter: - # version: 1.0.0 - # group: test - # protocol: triple - # registry: '' - # serializer: json -protocols: - triple: - ip: 0.0.0.0 - port: '8888' - name: triple - listener: tcp diff --git a/dubbo/Cargo.toml b/dubbo/Cargo.toml index b552b25a..5700e811 100644 --- a/dubbo/Cargo.toml +++ b/dubbo/Cargo.toml @@ -10,23 +10,22 @@ repository = "https://github.com/apache/dubbo-rust.git" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -hyper = { version = "0.14.19", features = ["full"]} +hyper = { version = "0.14.19", features = ["full"] } http = "0.2" tower-service = "0.3.1" http-body = "0.4.4" -tower = { version = "0.4.12", features = ["timeout"]} +tower = { version = "0.4.12", features = ["timeout"] } futures-util = "0.3.23" -futures-core ="0.3.23" -tokio = { version = "1.0", features = [ "rt-multi-thread", "time", "fs", "macros", "net", "signal"] } +futures-core = "0.3.23" +tokio = { version = "1.0", features = ["rt-multi-thread", "time", "fs", "macros", "net", "signal"] } prost = "0.10.4" -lazy_static = "1.3.0" async-trait = "0.1.56" tower-layer = "0.3" bytes = "1.0" -pin-project = "1.0" +pin-project.workspace = true rand = "0.8.5" -serde_json = "1.0.82" -serde = {version="1.0.138", features = ["derive"]} +serde_json.workspace = true +serde = { workspace = true, features = ["derive"] } futures = "0.3" tracing = "0.1" tracing-subscriber = "0.3.15" @@ -34,10 +33,11 @@ axum = "0.5.9" async-stream = "0.3" flate2 = "1.0" aws-smithy-http = "0.54.1" -itertools = "0.10.1" -urlencoding = "2.1.2" +itertools.workspace = true +urlencoding.workspace = true +lazy_static.workspace = true -dubbo-config = {path = "../config", version = "0.3.0" } +dubbo-config = { path = "../config", version = "0.3.0" } #对象存储 state = { version = "0.5", features = ["tls"] } diff --git a/dubbogo.yaml b/dubbogo.yaml deleted file mode 100644 index 2e6fe5ba..00000000 --- a/dubbogo.yaml +++ /dev/null @@ -1,7 +0,0 @@ -dubbo: - consumer: - references: - GreeterClientImpl: - protocol: tri - url: "tri://localhost:8889" - interface: helloworld.Greeter \ No newline at end of file diff --git a/examples/greeter/dubbo.yaml b/examples/greeter/application.yaml similarity index 93% rename from examples/greeter/dubbo.yaml rename to examples/greeter/application.yaml index 96daf95c..6683c6d1 100644 --- a/examples/greeter/dubbo.yaml +++ b/examples/greeter/application.yaml @@ -1,3 +1,5 @@ +logging: + level: INFO dubbo: protocols: triple: diff --git a/scripts/ci-check.sh b/scripts/ci-check.sh deleted file mode 100755 index 5ffd46d8..00000000 --- a/scripts/ci-check.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -#/* -# * 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. -# */ - -cargo fmt --all -- --check -# use stable channel -cargo check -target/debug/greeter-server && target/debug/greeter-client && sleep 3s ; From 05095fa37252dfc7a5e98d76417df94065cc1c76 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 20:42:37 +0800 Subject: [PATCH 10/26] Ftr: add common/utils subpackage --- common/utils/src/path_util.rs | 3 +- common/utils/src/yaml_util.rs | 6 +- config/src/config.rs | 3 +- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++------------ 4 files changed, 66 insertions(+), 125 deletions(-) diff --git a/common/utils/src/path_util.rs b/common/utils/src/path_util.rs index 2386d72c..74fdf625 100644 --- a/common/utils/src/path_util.rs +++ b/common/utils/src/path_util.rs @@ -15,8 +15,7 @@ * limitations under the License. */ -use std::env; -use std::path::PathBuf; +use std::{env, path::PathBuf}; pub fn app_root_dir() -> PathBuf { match project_root::get_project_root() { diff --git a/common/utils/src/yaml_util.rs b/common/utils/src/yaml_util.rs index 80de6f74..4cc5b6a2 100644 --- a/common/utils/src/yaml_util.rs +++ b/common/utils/src/yaml_util.rs @@ -14,8 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -use std::fs; -use std::path::PathBuf; +use std::{fs, path::PathBuf}; use anyhow::Error; use serde_yaml::from_slice; @@ -39,8 +38,7 @@ where mod tests { use std::collections::HashMap; - use crate::path_util::app_root_dir; - use crate::yaml_util::yaml_file_parser; + use crate::{path_util::app_root_dir, yaml_util::yaml_file_parser}; #[test] fn test_yaml_file_parser() { diff --git a/config/src/config.rs b/config/src/config.rs index eb44464f..f63b490c 100644 --- a/config/src/config.rs +++ b/config/src/config.rs @@ -15,8 +15,7 @@ * limitations under the License. */ -use std::path::PathBuf; -use std::{collections::HashMap, env}; +use std::{collections::HashMap, env, path::PathBuf}; use crate::{protocol::Protocol, registry::RegistryConfig}; use logger::tracing; diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index 8758f85a..ccb385cd 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -40,16 +40,12 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static( - "/grpc.examples.echo.Echo/UnaryEcho", - ); + let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -57,51 +53,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner.server_streaming(request, codec, path, invocation).await + self.inner + .server_streaming(request, codec, path, invocation) + .await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner.client_streaming(request, codec, path, invocation).await + self.inner + .client_streaming(request, codec, path, invocation) + .await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner.bidi_streaming(request, codec, path, invocation).await + self.inner + .bidi_streaming(request, codec, path, invocation) + .await } } } @@ -118,9 +114,7 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type ServerStreamingEchoStream: futures_util::Stream> + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -134,19 +128,14 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type BidirectionalStreamingEchoStream: futures_util::Stream> + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result< - Response, - dubbo::status::Status, - >; + ) -> Result, dubbo::status::Status>; } /// Echo is the echo service. #[derive(Debug)] @@ -176,10 +165,7 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready( - &mut self, - _cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -192,26 +178,18 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -222,32 +200,22 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc - for ServerStreamingEchoServer { + impl ServerStreamingSvc for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = + BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.server_streaming_echo(request).await - }; + let fut = async move { inner.server_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -260,31 +228,23 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc - for ClientStreamingEchoServer { + impl ClientStreamingSvc for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.client_streaming_echo(request).await - }; + let fut = async move { inner.client_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -297,56 +257,41 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc - for BidirectionalStreamingEchoServer { + impl StreamingSvc for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = + BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.bidirectional_streaming_echo(request).await - }; + let fut = + async move { inner.bidirectional_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server - .bidi_streaming( - BidirectionalStreamingEchoServer { - inner, - }, - req, - ) + .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) .await; Ok(res) }; Box::pin(fut) } - _ => { - Box::pin(async move { - Ok( - http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap(), - ) - }) - } + _ => Box::pin(async move { + Ok(http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap()) + }), } } } From 11139c647f5ae90cef7e869b9991e1b22df6a869 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 21:56:01 +0800 Subject: [PATCH 11/26] Ftr: add common/utils subpackage --- application.yaml | 2 +- common/logger/Cargo.toml | 2 + common/logger/src/level.rs | 23 +++ common/logger/src/lib.rs | 16 +- common/logger/src/tracing_configurer.rs | 38 ++-- common/utils/Cargo.toml | 4 +- common/utils/src/path_util.rs | 4 +- common/utils/src/yaml_util.rs | 49 ++++- common/utils/tests/application.yaml | 2 + .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++++++++------ 10 files changed, 225 insertions(+), 94 deletions(-) create mode 100644 common/logger/src/level.rs diff --git a/application.yaml b/application.yaml index 7cd01252..0de344e9 100644 --- a/application.yaml +++ b/application.yaml @@ -1,5 +1,5 @@ logging: - level: INFO + level: debug dubbo: protocols: triple: diff --git a/common/logger/Cargo.toml b/common/logger/Cargo.toml index 578ddfef..e965706e 100644 --- a/common/logger/Cargo.toml +++ b/common/logger/Cargo.toml @@ -8,3 +8,5 @@ edition = "2021" [dependencies] tracing = "0.1" tracing-subscriber = "0.3" +once_cell.workspace = true +utils.workspace = true \ No newline at end of file diff --git a/common/logger/src/level.rs b/common/logger/src/level.rs new file mode 100644 index 00000000..f5c2da9f --- /dev/null +++ b/common/logger/src/level.rs @@ -0,0 +1,23 @@ +use crate::Level; + +pub(crate) struct LevelWrapper { + pub(crate) inner: Level, +} +impl LevelWrapper { + pub fn new(level: Level) -> Self { + LevelWrapper { inner: level } + } +} + +impl From for LevelWrapper { + fn from(s: String) -> Self { + match s.to_lowercase().as_str().trim() { + "error" => LevelWrapper::new(Level::ERROR), + "warn" => LevelWrapper::new(Level::WARN), + "info" => LevelWrapper::new(Level::INFO), + "debug" => LevelWrapper::new(Level::DEBUG), + "trace" => LevelWrapper::new(Level::TRACE), + _ => LevelWrapper::new(Level::INFO), + } + } +} diff --git a/common/logger/src/lib.rs b/common/logger/src/lib.rs index 27372747..6edce9f0 100644 --- a/common/logger/src/lib.rs +++ b/common/logger/src/lib.rs @@ -15,22 +15,32 @@ * limitations under the License. */ +use std::sync::atomic::{AtomicBool, Ordering}; + pub use tracing::{self, Level}; +// flag for the sake of avoiding multiple initialization +static TRACING_CONFIGURED: AtomicBool = AtomicBool::new(false); + +mod level; mod tracing_configurer; // put on main method pub fn init() { - tracing_configurer::default() + if !TRACING_CONFIGURED.load(Ordering::SeqCst) { + tracing_configurer::default() + } } #[cfg(test)] mod tests { - use tracing::debug; + use tracing::{debug, info, trace}; #[test] fn test_print_info_log() { super::init(); - debug!("hello rust"); + debug!("hello rust:debug"); + trace!("hello rust:trace"); + info!("hello rust:info"); } } diff --git a/common/logger/src/tracing_configurer.rs b/common/logger/src/tracing_configurer.rs index 40b1e844..4c30581b 100644 --- a/common/logger/src/tracing_configurer.rs +++ b/common/logger/src/tracing_configurer.rs @@ -17,27 +17,25 @@ // https://github.com/tokio-rs/tracing/issues/971 -use tracing::{debug, Level}; +use crate::level::LevelWrapper; +use std::path::PathBuf; +use tracing::debug; +use utils::path_util; +use utils::yaml_util; pub(crate) fn default() { - if let Some(true) = configured() { - parse_from_config() - } else { - tracing_subscriber::fmt() - .compact() - .with_line_number(true) - .with_max_level(Level::DEBUG) - // sets this to be the default, global collector for this application. - .try_init() - .expect("init err."); - } + let path_buf = PathBuf::new() + .join(path_util::app_root_dir()) + .join("application.yaml"); + let level: LevelWrapper = yaml_util::yaml_key_reader(path_buf, "logging.level") + .unwrap() + .into(); + tracing_subscriber::fmt() + .compact() + .with_line_number(true) + .with_max_level(level.inner) + // sets this to be the default, global collector for this application. + .try_init() + .expect("init err."); debug!("Tracing configured.") } - -pub(crate) fn parse_from_config() { - todo!() -} - -pub(crate) fn configured() -> Option { - None -} diff --git a/common/utils/Cargo.toml b/common/utils/Cargo.toml index d2d004e3..4665ab6d 100644 --- a/common/utils/Cargo.toml +++ b/common/utils/Cargo.toml @@ -8,6 +8,6 @@ edition = "2021" [dependencies] serde_yaml.workspace = true serde = { workspace = true, features = ["derive"] } -logger.workspace=true project-root = "0.2.2" -anyhow.workspace=true \ No newline at end of file +anyhow.workspace=true +once_cell.workspace = true \ No newline at end of file diff --git a/common/utils/src/path_util.rs b/common/utils/src/path_util.rs index 74fdf625..347f1088 100644 --- a/common/utils/src/path_util.rs +++ b/common/utils/src/path_util.rs @@ -27,14 +27,12 @@ pub fn app_root_dir() -> PathBuf { #[cfg(test)] mod tests { - use logger::tracing::info; use super::*; #[test] fn test_app_root_dir() { - logger::init(); let dir = app_root_dir().join("application.yaml"); - info!("dir: {}", dir.display()); + println!("dir: {}", dir.display()); } } diff --git a/common/utils/src/yaml_util.rs b/common/utils/src/yaml_util.rs index 4cc5b6a2..575530e3 100644 --- a/common/utils/src/yaml_util.rs +++ b/common/utils/src/yaml_util.rs @@ -14,12 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use std::collections::HashMap; +use std::sync::Mutex; use std::{fs, path::PathBuf}; use anyhow::Error; -use serde_yaml::from_slice; +use once_cell::sync::Lazy; +use serde_yaml::{from_slice, Value}; -use logger::tracing; +static YAML_VALUE_CACHE_MAP: Lazy>> = + Lazy::new(|| Mutex::new(HashMap::new())); // parse yaml file to structs pub fn yaml_file_parser(path: PathBuf) -> Result @@ -30,14 +34,40 @@ where return Err(anyhow::anyhow!("path is not a file: {:?}", path)); } let data = fs::read(path.as_path())?; - tracing::debug!("config data: {:?}", String::from_utf8(data.clone())); Ok(from_slice(&data).unwrap()) } +// read value by a key like: logging.level +pub fn yaml_key_reader(path: PathBuf, key: &str) -> Result, Error> { + if !path.is_file() { + return Err(anyhow::anyhow!("path is not a file: {:?}", path)); + } + let cache_map = YAML_VALUE_CACHE_MAP.lock().unwrap(); + let split_keys = key.split('.'); + let data = fs::read(path.as_path())?; + let mut value: Value; + match cache_map.contains_key(path.as_path()) { + true => { + value = cache_map.get(path.as_path()).unwrap().clone(); + } + false => { + value = from_slice(&data).unwrap(); + } + } + for key in split_keys { + value = value[key].clone(); + } + if value.is_null() { + return Ok(None); + } + Ok(Some(value.as_str().unwrap().to_string())) +} + #[cfg(test)] mod tests { use std::collections::HashMap; + use crate::yaml_util::yaml_key_reader; use crate::{path_util::app_root_dir, yaml_util::yaml_file_parser}; #[test] @@ -50,4 +80,17 @@ mod tests { let config = yaml_file_parser::>>(path).unwrap(); println!("{:?}", config); } + + #[test] + fn test_yaml_key_reader() { + let path = app_root_dir() + .join("common") + .join("utils") + .join("tests") + .join("application.yaml"); + let config = yaml_key_reader(path.clone(), "logging.level").unwrap(); + println!("{:?}", config); + let config = yaml_key_reader(path, "logging.file.path").unwrap(); + println!("{:?}", config); + } } diff --git a/common/utils/tests/application.yaml b/common/utils/tests/application.yaml index ecfd4478..a40e4fe3 100644 --- a/common/utils/tests/application.yaml +++ b/common/utils/tests/application.yaml @@ -1,2 +1,4 @@ logging: level: INFO + file: + path: /tmp/test.log diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index ccb385cd..8758f85a 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -40,12 +40,16 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); + let path = http::uri::PathAndQuery::from_static( + "/grpc.examples.echo.Echo/UnaryEcho", + ); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -53,51 +57,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner - .server_streaming(request, codec, path, invocation) - .await + self.inner.server_streaming(request, codec, path, invocation).await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner - .client_streaming(request, codec, path, invocation) - .await + self.inner.client_streaming(request, codec, path, invocation).await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner - .bidi_streaming(request, codec, path, invocation) - .await + self.inner.bidi_streaming(request, codec, path, invocation).await } } } @@ -114,7 +118,9 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream> + type ServerStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -128,14 +134,19 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream> + type BidirectionalStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result, dubbo::status::Status>; + ) -> Result< + Response, + dubbo::status::Status, + >; } /// Echo is the echo service. #[derive(Debug)] @@ -165,7 +176,10 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + fn poll_ready( + &mut self, + _cx: &mut Context<'_>, + ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -178,18 +192,26 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -200,22 +222,32 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc for ServerStreamingEchoServer { + impl ServerStreamingSvc + for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.server_streaming_echo(request).await }; + let fut = async move { + inner.server_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -228,23 +260,31 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc for ClientStreamingEchoServer { + impl ClientStreamingSvc + for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.client_streaming_echo(request).await }; + let fut = async move { + inner.client_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -257,41 +297,56 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc for BidirectionalStreamingEchoServer { + impl StreamingSvc + for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = - async move { inner.bidirectional_streaming_echo(request).await }; + let fut = async move { + inner.bidirectional_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server - .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) + .bidi_streaming( + BidirectionalStreamingEchoServer { + inner, + }, + req, + ) .await; Ok(res) }; Box::pin(fut) } - _ => Box::pin(async move { - Ok(http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap()) - }), + _ => { + Box::pin(async move { + Ok( + http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap(), + ) + }) + } } } } From d3a048afe8f8b4a2f1e09b41763b31917ec3bf1e Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 22:03:34 +0800 Subject: [PATCH 12/26] Ftr: add common/utils subpackage --- common/logger/src/level.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/common/logger/src/level.rs b/common/logger/src/level.rs index f5c2da9f..5a081ff0 100644 --- a/common/logger/src/level.rs +++ b/common/logger/src/level.rs @@ -1,3 +1,19 @@ +/* + * 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. + */ use crate::Level; pub(crate) struct LevelWrapper { From e777e6bea1b2a7e11e36a022f45aede7e697275e Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 22:08:10 +0800 Subject: [PATCH 13/26] Ftr: add common/utils subpackage --- common/utils/LICENSE | 202 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 common/utils/LICENSE diff --git a/common/utils/LICENSE b/common/utils/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/common/utils/LICENSE @@ -0,0 +1,202 @@ + + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. From 319868c5adbb9e5833d30cae03bdcb2ed28b8749 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 22:13:49 +0800 Subject: [PATCH 14/26] Ftr: add common/utils subpackage --- common/logger/src/tracing_configurer.rs | 3 +- common/utils/src/yaml_util.rs | 10 +- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++------------ 3 files changed, 68 insertions(+), 124 deletions(-) diff --git a/common/logger/src/tracing_configurer.rs b/common/logger/src/tracing_configurer.rs index 4c30581b..1e2081f8 100644 --- a/common/logger/src/tracing_configurer.rs +++ b/common/logger/src/tracing_configurer.rs @@ -20,8 +20,7 @@ use crate::level::LevelWrapper; use std::path::PathBuf; use tracing::debug; -use utils::path_util; -use utils::yaml_util; +use utils::{path_util, yaml_util}; pub(crate) fn default() { let path_buf = PathBuf::new() diff --git a/common/utils/src/yaml_util.rs b/common/utils/src/yaml_util.rs index 575530e3..f8e0adfe 100644 --- a/common/utils/src/yaml_util.rs +++ b/common/utils/src/yaml_util.rs @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -use std::collections::HashMap; -use std::sync::Mutex; -use std::{fs, path::PathBuf}; +use std::{collections::HashMap, fs, path::PathBuf, sync::Mutex}; use anyhow::Error; use once_cell::sync::Lazy; @@ -67,8 +65,10 @@ pub fn yaml_key_reader(path: PathBuf, key: &str) -> Result, Error mod tests { use std::collections::HashMap; - use crate::yaml_util::yaml_key_reader; - use crate::{path_util::app_root_dir, yaml_util::yaml_file_parser}; + use crate::{ + path_util::app_root_dir, + yaml_util::{yaml_file_parser, yaml_key_reader}, + }; #[test] fn test_yaml_file_parser() { diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index 8758f85a..ccb385cd 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -40,16 +40,12 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static( - "/grpc.examples.echo.Echo/UnaryEcho", - ); + let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -57,51 +53,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner.server_streaming(request, codec, path, invocation).await + self.inner + .server_streaming(request, codec, path, invocation) + .await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner.client_streaming(request, codec, path, invocation).await + self.inner + .client_streaming(request, codec, path, invocation) + .await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner.bidi_streaming(request, codec, path, invocation).await + self.inner + .bidi_streaming(request, codec, path, invocation) + .await } } } @@ -118,9 +114,7 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type ServerStreamingEchoStream: futures_util::Stream> + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -134,19 +128,14 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type BidirectionalStreamingEchoStream: futures_util::Stream> + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result< - Response, - dubbo::status::Status, - >; + ) -> Result, dubbo::status::Status>; } /// Echo is the echo service. #[derive(Debug)] @@ -176,10 +165,7 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready( - &mut self, - _cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -192,26 +178,18 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -222,32 +200,22 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc - for ServerStreamingEchoServer { + impl ServerStreamingSvc for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = + BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.server_streaming_echo(request).await - }; + let fut = async move { inner.server_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -260,31 +228,23 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc - for ClientStreamingEchoServer { + impl ClientStreamingSvc for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.client_streaming_echo(request).await - }; + let fut = async move { inner.client_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -297,56 +257,41 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc - for BidirectionalStreamingEchoServer { + impl StreamingSvc for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = + BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.bidirectional_streaming_echo(request).await - }; + let fut = + async move { inner.bidirectional_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server - .bidi_streaming( - BidirectionalStreamingEchoServer { - inner, - }, - req, - ) + .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) .await; Ok(res) }; Box::pin(fut) } - _ => { - Box::pin(async move { - Ok( - http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap(), - ) - }) - } + _ => Box::pin(async move { + Ok(http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap()) + }), } } } From e696071fb98e4d16ebc4791e950d92380aac6922 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Wed, 1 Mar 2023 22:17:08 +0800 Subject: [PATCH 15/26] Ftr: add common/utils subpackage --- common/logger/src/level.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/common/logger/src/level.rs b/common/logger/src/level.rs index 5a081ff0..097f1058 100644 --- a/common/logger/src/level.rs +++ b/common/logger/src/level.rs @@ -25,9 +25,9 @@ impl LevelWrapper { } } -impl From for LevelWrapper { - fn from(s: String) -> Self { - match s.to_lowercase().as_str().trim() { +impl From> for LevelWrapper { + fn from(s: Option) -> Self { + match s.unwrap().to_lowercase().as_str().trim() { "error" => LevelWrapper::new(Level::ERROR), "warn" => LevelWrapper::new(Level::WARN), "info" => LevelWrapper::new(Level::INFO), From 51077ff81d88b653d05dbcaa80b2b48d7c2c7080 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 20:20:29 +0800 Subject: [PATCH 16/26] Ftr: host util --- common/utils/src/host_util.rs | 69 +++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 common/utils/src/host_util.rs diff --git a/common/utils/src/host_util.rs b/common/utils/src/host_util.rs new file mode 100644 index 00000000..6396e71c --- /dev/null +++ b/common/utils/src/host_util.rs @@ -0,0 +1,69 @@ +/* + * 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. + */ +use std::net::IpAddr; + +use port_selector::is_free; + +pub use port_selector::Port; + +// get local ip for linux/macos/windows +pub(crate) fn local_ip() -> IpAddr { + local_ip_address::local_ip().unwrap() +} + +pub(crate) fn is_free_port(port: Port) -> bool { + is_free(port) +} + +// scan from the give port +pub(crate) fn scan_free_port(port: Port) -> Port { + for selected_port in port..65535 { + if is_free_port(selected_port) { + return selected_port; + } else { + continue; + } + } + port +} + +#[cfg(test)] +mod tests { + use local_ip_address::list_afinet_netifas; + + use super::*; + + #[test] + fn test_local_ip() { + let ip = local_ip(); + println!("ip: {}", ip); + } + + #[test] + fn test_local_addresses() { + let network_interfaces = list_afinet_netifas().unwrap(); + for (name, ip) in network_interfaces.iter() { + println!("{}:\t{:?}", name, ip); + } + } + + #[test] + fn test_scan_free_port() { + let free_port = scan_free_port(7890); + println!("{}", free_port); + } +} From 721f89b820a1b6d552548a79101e8b7ec4dc5652 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 20:21:29 +0800 Subject: [PATCH 17/26] Ftr: host util --- common/utils/Cargo.toml | 4 +++- common/utils/src/lib.rs | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/common/utils/Cargo.toml b/common/utils/Cargo.toml index 4665ab6d..0b8c84f1 100644 --- a/common/utils/Cargo.toml +++ b/common/utils/Cargo.toml @@ -10,4 +10,6 @@ serde_yaml.workspace = true serde = { workspace = true, features = ["derive"] } project-root = "0.2.2" anyhow.workspace=true -once_cell.workspace = true \ No newline at end of file +once_cell.workspace = true +local-ip-address = "0.5.1" +port-selector = "0.1.6" \ No newline at end of file diff --git a/common/utils/src/lib.rs b/common/utils/src/lib.rs index 47dbe626..7a0a45b8 100644 --- a/common/utils/src/lib.rs +++ b/common/utils/src/lib.rs @@ -14,5 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +pub mod host_util; pub mod path_util; pub mod yaml_util; From c305ed7d9bf08f60d2ebe3659cdf7d3a48e747c7 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 21:08:14 +0800 Subject: [PATCH 18/26] Ftr: add common base --- Cargo.toml | 6 +- common/base/Cargo.toml | 11 + {protocol/protocol => common/base}/LICENSE | 0 .../consts.rs => common/base/src/constants.rs | 3 +- common/base/src/lib.rs | 23 ++ {dubbo/src/common => common/base/src}/url.rs | 10 +- common/utils/src/host_util.rs | 3 + config/src/protocol.rs | 2 +- dubbo/Cargo.toml | 1 + dubbo/src/cluster/directory.rs | 2 +- dubbo/src/cluster/loadbalance/impls/random.rs | 2 +- .../cluster/loadbalance/impls/roundrobin.rs | 2 +- dubbo/src/cluster/loadbalance/types.rs | 3 +- dubbo/src/cluster/support/cluster_invoker.rs | 2 +- dubbo/src/framework.rs | 6 +- dubbo/src/lib.rs | 1 - dubbo/src/protocol/mod.rs | 2 +- dubbo/src/protocol/triple/triple_invoker.rs | 3 +- dubbo/src/protocol/triple/triple_protocol.rs | 6 +- dubbo/src/protocol/triple/triple_server.rs | 3 +- dubbo/src/registry/memory_registry.rs | 8 +- dubbo/src/registry/mod.rs | 2 +- dubbo/src/registry/protocol.rs | 4 +- dubbo/src/registry/types.rs | 2 +- dubbo/src/triple/server/builder.rs | 3 +- dubbo/src/triple/transport/connection.rs | 2 +- .../echo/src/generated/grpc.examples.echo.rs | 183 ++++++++++------ examples/greeter/Cargo.toml | 1 + examples/greeter/src/greeter/client.rs | 3 +- protocol/README.md | 4 +- protocol/{protocol => base}/Cargo.toml | 0 protocol/base/LICENSE | 202 ++++++++++++++++++ .../mod.rs => protocol/base/src/layer.rs | 3 - protocol/{protocol => base}/src/lib.rs | 15 +- protocol/base/src/service.rs | 16 ++ registry/nacos/Cargo.toml | 1 + registry/nacos/src/lib.rs | 6 +- registry/nacos/src/utils/mod.rs | 2 +- registry/zookeeper/Cargo.toml | 1 + registry/zookeeper/src/lib.rs | 7 +- remoting/xds/Cargo.toml | 2 +- 41 files changed, 430 insertions(+), 128 deletions(-) create mode 100644 common/base/Cargo.toml rename {protocol/protocol => common/base}/LICENSE (100%) rename dubbo/src/common/consts.rs => common/base/src/constants.rs (97%) create mode 100644 common/base/src/lib.rs rename {dubbo/src/common => common/base/src}/url.rs (96%) rename protocol/{protocol => base}/Cargo.toml (100%) create mode 100644 protocol/base/LICENSE rename dubbo/src/common/mod.rs => protocol/base/src/layer.rs (96%) rename protocol/{protocol => base}/src/lib.rs (78%) create mode 100644 protocol/base/src/service.rs diff --git a/Cargo.toml b/Cargo.toml index ad660649..1d173a38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ members = [ "common/logger", "common/utils", "common/extention", + "common/base", "registry/zookeeper", "registry/nacos", "metadata", @@ -18,7 +19,7 @@ members = [ "remoting/exchange", "remoting/xds", "protocol/dubbo2", - "protocol/protocol", + "protocol/base", "protocol/triple" ] @@ -39,8 +40,9 @@ serde_json = "1" urlencoding = "2.1.2" logger = {path="./common/logger"} utils = {path="./common/utils"} +base = {path="./common/base"} remoting-net = {path="./remoting/net"} -protocol = {path="./protocol/protocol"} +protocol = {path= "protocol/base" } protocol-dubbo2 = {path="./protocol/dubbo2"} protocol-triple = {path="./protocol/triple"} registry-zookeeper = {path="./registry/zookeeper"} diff --git a/common/base/Cargo.toml b/common/base/Cargo.toml new file mode 100644 index 00000000..7397c195 --- /dev/null +++ b/common/base/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "base" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +urlencoding.workspace = true +http = "0.2" +logger.workspace = true \ No newline at end of file diff --git a/protocol/protocol/LICENSE b/common/base/LICENSE similarity index 100% rename from protocol/protocol/LICENSE rename to common/base/LICENSE diff --git a/dubbo/src/common/consts.rs b/common/base/src/constants.rs similarity index 97% rename from dubbo/src/common/consts.rs rename to common/base/src/constants.rs index 17993c80..09c17170 100644 --- a/dubbo/src/common/consts.rs +++ b/common/base/src/constants.rs @@ -14,9 +14,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - pub const REGISTRY_PROTOCOL: &str = "registry_protocol"; -pub const PROTOCOL: &str = "protocol"; +pub const PROTOCOL: &str = "base"; pub const REGISTRY: &str = "registry"; // URL key diff --git a/common/base/src/lib.rs b/common/base/src/lib.rs new file mode 100644 index 00000000..5d89c23c --- /dev/null +++ b/common/base/src/lib.rs @@ -0,0 +1,23 @@ +/* + * 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. + */ +#![cfg_attr( + debug_assertions, + allow(dead_code, unused_imports, unused_variables, unused_mut) +)] +pub mod constants; +pub mod url; +pub use url::Url; diff --git a/dubbo/src/common/url.rs b/common/base/src/url.rs similarity index 96% rename from dubbo/src/common/url.rs rename to common/base/src/url.rs index 2a36d72b..7b73f197 100644 --- a/dubbo/src/common/url.rs +++ b/common/base/src/url.rs @@ -20,13 +20,13 @@ use std::{ fmt::{Display, Formatter}, }; -use crate::common::consts::{GROUP_KEY, INTERFACE_KEY, VERSION_KEY}; +use crate::constants::{GROUP_KEY, INTERFACE_KEY, VERSION_KEY}; use http::Uri; #[derive(Debug, Clone, Default, PartialEq)] pub struct Url { pub raw_url_string: String, - // value of scheme is different to protocol name, eg. triple -> tri:// + // value of scheme is different to base name, eg. triple -> tri:// pub scheme: String, pub location: String, pub ip: String, @@ -48,7 +48,7 @@ impl Url { let uri = url .parse::() .map_err(|err| { - tracing::error!("fail to parse url({}), err: {:?}", url, err); + logger::tracing::error!("fail to parse url({}), err: {:?}", url, err); }) .unwrap(); let query = uri.path_and_query().unwrap().query(); @@ -179,8 +179,8 @@ impl From<&str> for Url { #[cfg(test)] mod tests { - use super::*; - use crate::common::consts::{ANYHOST_KEY, VERSION_KEY}; + use crate::constants::{ANYHOST_KEY, VERSION_KEY}; + use crate::url::Url; #[test] fn test_from_url() { diff --git a/common/utils/src/host_util.rs b/common/utils/src/host_util.rs index 6396e71c..0b029ef8 100644 --- a/common/utils/src/host_util.rs +++ b/common/utils/src/host_util.rs @@ -21,15 +21,18 @@ use port_selector::is_free; pub use port_selector::Port; // get local ip for linux/macos/windows +#[allow(dead_code)] pub(crate) fn local_ip() -> IpAddr { local_ip_address::local_ip().unwrap() } +#[allow(dead_code)] pub(crate) fn is_free_port(port: Port) -> bool { is_free(port) } // scan from the give port +#[allow(dead_code)] pub(crate) fn scan_free_port(port: Port) -> Port { for selected_port in port..65535 { if is_free_port(selected_port) { diff --git a/config/src/protocol.rs b/config/src/protocol.rs index 4a47ac98..86ff0531 100644 --- a/config/src/protocol.rs +++ b/config/src/protocol.rs @@ -77,7 +77,7 @@ impl ProtocolRetrieve for ProtocolConfig { } else { let result = self.get_protocol(protocol_key); if let Some(..) = result { - panic!("default triple protocol dose not defined.") + panic!("default triple base dose not defined.") } else { result.unwrap() } diff --git a/dubbo/Cargo.toml b/dubbo/Cargo.toml index 5700e811..3b66523b 100644 --- a/dubbo/Cargo.toml +++ b/dubbo/Cargo.toml @@ -36,6 +36,7 @@ aws-smithy-http = "0.54.1" itertools.workspace = true urlencoding.workspace = true lazy_static.workspace = true +base.workspace=true dubbo-config = { path = "../config", version = "0.3.0" } diff --git a/dubbo/src/cluster/directory.rs b/dubbo/src/cluster/directory.rs index 2879de4d..d92bb20c 100644 --- a/dubbo/src/cluster/directory.rs +++ b/dubbo/src/cluster/directory.rs @@ -23,10 +23,10 @@ use std::{ }; use crate::{ - common::url::Url, invocation::{Invocation, RpcInvocation}, registry::{memory_registry::MemoryNotifyListener, BoxRegistry, RegistryWrapper}, }; +use base::Url; /// Directory. /// diff --git a/dubbo/src/cluster/loadbalance/impls/random.rs b/dubbo/src/cluster/loadbalance/impls/random.rs index a5ca7dff..ddfcd396 100644 --- a/dubbo/src/cluster/loadbalance/impls/random.rs +++ b/dubbo/src/cluster/loadbalance/impls/random.rs @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use base::Url; use std::{ fmt::{Debug, Formatter}, sync::Arc, @@ -22,7 +23,6 @@ use std::{ use crate::{ cluster::loadbalance::types::{LoadBalance, Metadata}, codegen::RpcInvocation, - common::url::Url, }; pub struct RandomLoadBalance { diff --git a/dubbo/src/cluster/loadbalance/impls/roundrobin.rs b/dubbo/src/cluster/loadbalance/impls/roundrobin.rs index cd951bbe..0c59ed4e 100644 --- a/dubbo/src/cluster/loadbalance/impls/roundrobin.rs +++ b/dubbo/src/cluster/loadbalance/impls/roundrobin.rs @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use base::Url; use std::{ collections::HashMap, fmt::{Debug, Formatter}, @@ -26,7 +27,6 @@ use std::{ use crate::{ cluster::loadbalance::types::{LoadBalance, Metadata}, codegen::RpcInvocation, - common::url::Url, }; pub struct RoundRobinLoadBalance { diff --git a/dubbo/src/cluster/loadbalance/types.rs b/dubbo/src/cluster/loadbalance/types.rs index ac31176d..fd48ed96 100644 --- a/dubbo/src/cluster/loadbalance/types.rs +++ b/dubbo/src/cluster/loadbalance/types.rs @@ -15,9 +15,10 @@ * limitations under the License. */ +use base::Url; use std::{fmt::Debug, sync::Arc}; -use crate::{codegen::RpcInvocation, common::url::Url}; +use crate::codegen::RpcInvocation; pub type BoxLoadBalance = Box; diff --git a/dubbo/src/cluster/support/cluster_invoker.rs b/dubbo/src/cluster/support/cluster_invoker.rs index e00b8498..67c98397 100644 --- a/dubbo/src/cluster/support/cluster_invoker.rs +++ b/dubbo/src/cluster/support/cluster_invoker.rs @@ -18,6 +18,7 @@ use aws_smithy_http::body::SdkBody; use std::{str::FromStr, sync::Arc}; +use base::Url; use http::{uri::PathAndQuery, Request}; use crate::{ @@ -26,7 +27,6 @@ use crate::{ support::DEFAULT_LOADBALANCE, }, codegen::{Directory, RegistryDirectory, TripleClient}, - common::url::Url, invocation::RpcInvocation, }; diff --git a/dubbo/src/framework.rs b/dubbo/src/framework.rs index 71e11d2e..546e2d0f 100644 --- a/dubbo/src/framework.rs +++ b/dubbo/src/framework.rs @@ -22,11 +22,11 @@ use std::{ sync::{Arc, Mutex}, }; +use base::Url; use futures::{future, Future}; use tracing::{debug, info}; use crate::{ - common::url::Url, protocol::{BoxExporter, Protocol}, registry::{ protocol::RegistryProtocol, @@ -94,7 +94,7 @@ impl Dubbo { info!("protocol_url: {:?}", protocol_url); Url::from_url(&protocol_url) } else { - return Err(format!("protocol {:?} not exists", service_config.protocol).into()); + return Err(format!("base {:?} not exists", service_config.protocol).into()); }; info!("url: {:?}", url); if url.is_none() { @@ -126,7 +126,7 @@ impl Dubbo { let mut async_vec: Vec + Send>>> = Vec::new(); for (name, items) in self.protocols.iter() { for url in items.iter() { - info!("protocol: {:?}, service url: {:?}", name, url); + info!("base: {:?}, service url: {:?}", name, url); let exporter = mem_reg.clone().export(url.to_owned()); async_vec.push(exporter); //TODO multiple registry diff --git a/dubbo/src/lib.rs b/dubbo/src/lib.rs index 2174365b..63c09d3a 100644 --- a/dubbo/src/lib.rs +++ b/dubbo/src/lib.rs @@ -17,7 +17,6 @@ pub mod cluster; pub mod codegen; -pub mod common; pub mod context; pub mod filter; mod framework; diff --git a/dubbo/src/protocol/mod.rs b/dubbo/src/protocol/mod.rs index 2c8ad8f8..886308de 100644 --- a/dubbo/src/protocol/mod.rs +++ b/dubbo/src/protocol/mod.rs @@ -25,7 +25,7 @@ use async_trait::async_trait; use aws_smithy_http::body::SdkBody; use tower_service::Service; -use crate::common::url::Url; +use base::Url; pub mod server_desc; pub mod triple; diff --git a/dubbo/src/protocol/triple/triple_invoker.rs b/dubbo/src/protocol/triple/triple_invoker.rs index 2bcc2d33..d7d54ee1 100644 --- a/dubbo/src/protocol/triple/triple_invoker.rs +++ b/dubbo/src/protocol/triple/triple_invoker.rs @@ -16,10 +16,11 @@ */ use aws_smithy_http::body::SdkBody; +use base::Url; use std::fmt::{Debug, Formatter}; use tower_service::Service; -use crate::{common::url::Url, protocol::Invoker, triple::client::builder::ClientBoxService}; +use crate::{protocol::Invoker, triple::client::builder::ClientBoxService}; pub struct TripleInvoker { url: Url, diff --git a/dubbo/src/protocol/triple/triple_protocol.rs b/dubbo/src/protocol/triple/triple_protocol.rs index c6ade9b7..fd1d3691 100644 --- a/dubbo/src/protocol/triple/triple_protocol.rs +++ b/dubbo/src/protocol/triple/triple_protocol.rs @@ -18,14 +18,12 @@ use std::{boxed::Box, collections::HashMap}; use async_trait::async_trait; +use base::Url; use super::{ triple_exporter::TripleExporter, triple_invoker::TripleInvoker, triple_server::TripleServer, }; -use crate::{ - common::url::Url, - protocol::{BoxExporter, Protocol}, -}; +use crate::protocol::{BoxExporter, Protocol}; #[derive(Clone)] pub struct TripleProtocol { diff --git a/dubbo/src/protocol/triple/triple_server.rs b/dubbo/src/protocol/triple/triple_server.rs index d297a881..1db27fa0 100644 --- a/dubbo/src/protocol/triple/triple_server.rs +++ b/dubbo/src/protocol/triple/triple_server.rs @@ -15,7 +15,8 @@ * limitations under the License. */ -use crate::{common::url::Url, triple::server::builder::ServerBuilder}; +use crate::triple::server::builder::ServerBuilder; +use base::Url; #[derive(Default, Clone)] pub struct TripleServer { diff --git a/dubbo/src/registry/memory_registry.rs b/dubbo/src/registry/memory_registry.rs index b41a0e0a..7f900f63 100644 --- a/dubbo/src/registry/memory_registry.rs +++ b/dubbo/src/registry/memory_registry.rs @@ -23,7 +23,7 @@ use std::{ }; use tracing::debug; -use crate::common::url::Url; +use base::Url; use super::{NotifyListener, Registry, RegistryNotifyListener}; @@ -69,7 +69,7 @@ impl Registry for MemoryRegistry { Ok(()) } - fn unregister(&mut self, url: crate::common::url::Url) -> Result<(), crate::StdError> { + fn unregister(&mut self, url: base::Url) -> Result<(), crate::StdError> { let registry_group = match url.get_param(REGISTRY_GROUP_KEY) { Some(key) => key, None => "dubbo".to_string(), @@ -88,7 +88,7 @@ impl Registry for MemoryRegistry { fn subscribe( &self, - url: crate::common::url::Url, + url: base::Url, listener: RegistryNotifyListener, ) -> Result<(), crate::StdError> { todo!() @@ -96,7 +96,7 @@ impl Registry for MemoryRegistry { fn unsubscribe( &self, - url: crate::common::url::Url, + url: base::Url, listener: RegistryNotifyListener, ) -> Result<(), crate::StdError> { todo!() diff --git a/dubbo/src/registry/mod.rs b/dubbo/src/registry/mod.rs index 44835882..c5e26743 100644 --- a/dubbo/src/registry/mod.rs +++ b/dubbo/src/registry/mod.rs @@ -26,7 +26,7 @@ use std::{ sync::Arc, }; -use crate::common::url::Url; +use base::Url; pub type RegistryNotifyListener = Arc; pub trait Registry { diff --git a/dubbo/src/registry/protocol.rs b/dubbo/src/registry/protocol.rs index 04b8ac91..d28e43de 100644 --- a/dubbo/src/registry/protocol.rs +++ b/dubbo/src/registry/protocol.rs @@ -15,6 +15,7 @@ * limitations under the License. */ +use base::Url; use std::{ collections::HashMap, fmt::{Debug, Formatter}, @@ -23,7 +24,6 @@ use std::{ use super::{memory_registry::MemoryRegistry, BoxRegistry}; use crate::{ - common::url::Url, protocol::{ triple::{triple_exporter::TripleExporter, triple_protocol::TripleProtocol}, BoxExporter, BoxInvoker, Protocol, @@ -116,7 +116,7 @@ impl Protocol for RegistryProtocol { return pro.export(url).await; } _ => { - tracing::error!("protocol {:?} not implemented", url.scheme); + tracing::error!("base {:?} not implemented", url.scheme); Box::new(TripleExporter::new()) } } diff --git a/dubbo/src/registry/types.rs b/dubbo/src/registry/types.rs index 8b978645..a55e72c2 100644 --- a/dubbo/src/registry/types.rs +++ b/dubbo/src/registry/types.rs @@ -20,11 +20,11 @@ use std::{ sync::{Arc, Mutex}, }; +use base::Url; use itertools::Itertools; use tracing::info; use crate::{ - common::url::Url, registry::{BoxRegistry, Registry}, StdError, }; diff --git a/dubbo/src/triple/server/builder.rs b/dubbo/src/triple/server/builder.rs index af3cc6d4..e82ff058 100644 --- a/dubbo/src/triple/server/builder.rs +++ b/dubbo/src/triple/server/builder.rs @@ -20,11 +20,12 @@ use std::{ str::FromStr, }; +use base::Url; use http::{Request, Response, Uri}; use hyper::body::Body; use tower_service::Service; -use crate::{common::url::Url, triple::transport::DubboServer, BoxBody}; +use crate::{triple::transport::DubboServer, BoxBody}; #[derive(Clone, Default, Debug)] pub struct ServerBuilder { diff --git a/dubbo/src/triple/transport/connection.rs b/dubbo/src/triple/transport/connection.rs index c99b3998..360149bb 100644 --- a/dubbo/src/triple/transport/connection.rs +++ b/dubbo/src/triple/transport/connection.rs @@ -85,7 +85,7 @@ where let mut connector = Connect::new(get_connector(self.connector), builder); let uri = self.host.clone(); let fut = async move { - debug!("send rpc call to {}", uri); + debug!("send base call to {}", uri); let mut con = connector.call(uri).await.unwrap(); con.call(req) diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index 16fb1638..8758f85a 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -1,12 +1,12 @@ -// @generated by apache/dubbo-rust. - /// EchoRequest is the request for echo. +#[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct EchoRequest { #[prost(string, tag = "1")] pub message: ::prost::alloc::string::String, } /// EchoResponse is the response for echo. +#[allow(clippy::derive_partial_eq_without_eq)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct EchoResponse { #[prost(string, tag = "1")] @@ -40,12 +40,16 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); + let path = http::uri::PathAndQuery::from_static( + "/grpc.examples.echo.Echo/UnaryEcho", + ); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -53,51 +57,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner - .server_streaming(request, codec, path, invocation) - .await + self.inner.server_streaming(request, codec, path, invocation).await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner - .client_streaming(request, codec, path, invocation) - .await + self.inner.client_streaming(request, codec, path, invocation).await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner - .bidi_streaming(request, codec, path, invocation) - .await + self.inner.bidi_streaming(request, codec, path, invocation).await } } } @@ -114,7 +118,9 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream> + type ServerStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -128,14 +134,19 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream> + type BidirectionalStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result, dubbo::status::Status>; + ) -> Result< + Response, + dubbo::status::Status, + >; } /// Echo is the echo service. #[derive(Debug)] @@ -165,7 +176,10 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + fn poll_ready( + &mut self, + _cx: &mut Context<'_>, + ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -178,18 +192,26 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -200,22 +222,32 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc for ServerStreamingEchoServer { + impl ServerStreamingSvc + for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.server_streaming_echo(request).await }; + let fut = async move { + inner.server_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -228,23 +260,31 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc for ClientStreamingEchoServer { + impl ClientStreamingSvc + for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.client_streaming_echo(request).await }; + let fut = async move { + inner.client_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -257,41 +297,56 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc for BidirectionalStreamingEchoServer { + impl StreamingSvc + for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = - async move { inner.bidirectional_streaming_echo(request).await }; + let fut = async move { + inner.bidirectional_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server - .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) + .bidi_streaming( + BidirectionalStreamingEchoServer { + inner, + }, + req, + ) .await; Ok(res) }; Box::pin(fut) } - _ => Box::pin(async move { - Ok(http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap()) - }), + _ => { + Box::pin(async move { + Ok( + http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap(), + ) + }) + } } } } diff --git a/examples/greeter/Cargo.toml b/examples/greeter/Cargo.toml index 91cbefe6..a8c6cacf 100644 --- a/examples/greeter/Cargo.toml +++ b/examples/greeter/Cargo.toml @@ -33,6 +33,7 @@ dubbo = { path = "../../dubbo", version = "0.3.0" } dubbo-config = { path = "../../config", version = "0.3.0" } registry-zookeeper.workspace = true registry-nacos.workspace = true +base.workspace = true [build-dependencies] dubbo-build = { path = "../../dubbo-build", version = "0.3.0" } diff --git a/examples/greeter/src/greeter/client.rs b/examples/greeter/src/greeter/client.rs index 4b5437a7..4591fd9c 100644 --- a/examples/greeter/src/greeter/client.rs +++ b/examples/greeter/src/greeter/client.rs @@ -22,8 +22,9 @@ pub mod protos { use std::env; -use dubbo::{codegen::*, common::url::Url}; +use dubbo::codegen::*; +use base::Url; use futures_util::StreamExt; use protos::{greeter_client::GreeterClient, GreeterRequest}; use registry_nacos::NacosRegistry; diff --git a/protocol/README.md b/protocol/README.md index c6b9a8c7..c0fd296e 100644 --- a/protocol/README.md +++ b/protocol/README.md @@ -1,4 +1,6 @@ +```markdown /protocol /protocol # define protocol abstract layer /dubbo2 # for dubbo2 protocol, hessian2 codec as default - /triple # for triple protocol \ No newline at end of file + /triple # for triple protocol +``` \ No newline at end of file diff --git a/protocol/protocol/Cargo.toml b/protocol/base/Cargo.toml similarity index 100% rename from protocol/protocol/Cargo.toml rename to protocol/base/Cargo.toml diff --git a/protocol/base/LICENSE b/protocol/base/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/protocol/base/LICENSE @@ -0,0 +1,202 @@ + + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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/dubbo/src/common/mod.rs b/protocol/base/src/layer.rs similarity index 96% rename from dubbo/src/common/mod.rs rename to protocol/base/src/layer.rs index 23284214..2944f981 100644 --- a/dubbo/src/common/mod.rs +++ b/protocol/base/src/layer.rs @@ -14,6 +14,3 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -pub mod consts; -pub mod url; diff --git a/protocol/protocol/src/lib.rs b/protocol/base/src/lib.rs similarity index 78% rename from protocol/protocol/src/lib.rs rename to protocol/base/src/lib.rs index d64452d5..2aae1ffa 100644 --- a/protocol/protocol/src/lib.rs +++ b/protocol/base/src/lib.rs @@ -14,17 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -pub fn add(left: usize, right: usize) -> usize { - left + right -} -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} +pub(crate) mod layer; +pub(crate) mod service; diff --git a/protocol/base/src/service.rs b/protocol/base/src/service.rs new file mode 100644 index 00000000..2944f981 --- /dev/null +++ b/protocol/base/src/service.rs @@ -0,0 +1,16 @@ +/* + * 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. + */ diff --git a/registry/nacos/Cargo.toml b/registry/nacos/Cargo.toml index 1a3a6867..d30827b6 100644 --- a/registry/nacos/Cargo.toml +++ b/registry/nacos/Cargo.toml @@ -15,6 +15,7 @@ serde_json.workspace = true serde = { workspace = true, features = ["derive"] } anyhow.workspace = true logger.workspace = true +base.workspace = true [dev-dependencies] tracing-subscriber = "0.3.16" tracing = "0.1" diff --git a/registry/nacos/src/lib.rs b/registry/nacos/src/lib.rs index 38e710f0..cd6515be 100644 --- a/registry/nacos/src/lib.rs +++ b/registry/nacos/src/lib.rs @@ -16,16 +16,14 @@ */ mod utils; +use base::Url; use std::{ collections::{HashMap, HashSet}, sync::{Arc, Mutex}, }; use anyhow::anyhow; -use dubbo::{ - common::url::Url, - registry::{NotifyListener, Registry, RegistryNotifyListener, ServiceEvent}, -}; +use dubbo::registry::{NotifyListener, Registry, RegistryNotifyListener, ServiceEvent}; use logger::tracing::{error, info, warn}; use nacos_sdk::api::naming::{NamingService, NamingServiceBuilder, ServiceInstance}; diff --git a/registry/nacos/src/utils/mod.rs b/registry/nacos/src/utils/mod.rs index 2cca6a2e..f5067323 100644 --- a/registry/nacos/src/utils/mod.rs +++ b/registry/nacos/src/utils/mod.rs @@ -15,7 +15,7 @@ * limitations under the License. */ -use dubbo::common::url::Url; +use base::Url; use nacos_sdk::api::props::ClientProps; const APP_NAME_KEY: &str = "AppName"; diff --git a/registry/zookeeper/Cargo.toml b/registry/zookeeper/Cargo.toml index c4a4e592..c7fb82e9 100644 --- a/registry/zookeeper/Cargo.toml +++ b/registry/zookeeper/Cargo.toml @@ -15,3 +15,4 @@ serde_json.workspace = true serde = { workspace = true, features = ["derive"] } urlencoding.workspace = true logger.workspace = true +base.workspace = true diff --git a/registry/zookeeper/src/lib.rs b/registry/zookeeper/src/lib.rs index 9f7447b5..fe3d962a 100644 --- a/registry/zookeeper/src/lib.rs +++ b/registry/zookeeper/src/lib.rs @@ -24,6 +24,8 @@ use std::{ time::Duration, }; +use base::constants::{DUBBO_KEY, LOCALHOST_IP, PROVIDERS_KEY}; +use base::Url; use logger::tracing::{debug, error, info}; use serde::{Deserialize, Serialize}; #[allow(unused_imports)] @@ -32,10 +34,6 @@ use zookeeper::{Acl, CreateMode, WatchedEvent, WatchedEventType, Watcher, ZooKee use dubbo::{ cluster::support::cluster_invoker::ClusterInvoker, codegen::BoxRegistry, - common::{ - consts::{DUBBO_KEY, LOCALHOST_IP, PROVIDERS_KEY}, - url::Url, - }, registry::{ integration::ClusterRegistryIntegration, memory_registry::MemoryRegistry, NotifyListener, Registry, RegistryNotifyListener, ServiceEvent, @@ -384,6 +382,7 @@ mod tests { use zookeeper::{Acl, CreateMode, WatchedEvent, Watcher}; use crate::zookeeper_registry::ZookeeperRegistry; + use crate::ZookeeperRegistry; struct TestZkWatcher { pub watcher: Arc>, diff --git a/remoting/xds/Cargo.toml b/remoting/xds/Cargo.toml index 8bf8a3b8..eb8c027e 100644 --- a/remoting/xds/Cargo.toml +++ b/remoting/xds/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "xds" +name = "remoting-xds" version = "0.3.0" edition = "2021" license = "Apache-2.0" From e29a2b7d75a31e8ab83659665c4020dc4a412f14 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 21:21:06 +0800 Subject: [PATCH 19/26] Ftr: add common base --- application.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/application.yaml b/application.yaml index 0de344e9..d357db14 100644 --- a/application.yaml +++ b/application.yaml @@ -16,4 +16,9 @@ dubbo: version: 1.0.0 group: test protocol: triple - interface: org.apache.dubbo.sample.tri.Greeter \ No newline at end of file + interface: org.apache.dubbo.sample.tri.Greeter + consumer: + references: + GreeterClientImpl: + url: tri://localhost:20000 + protocol: tri \ No newline at end of file From e6c63b0b5e2e71f59338fdd81e28cae4c8593fb3 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 23:39:29 +0800 Subject: [PATCH 20/26] Ftr: protocol abstraction design --- common/base/src/lib.rs | 3 + .../src/layer.rs => common/base/src/node.rs | 12 ++ common/base/src/url.rs | 4 + protocol/base/Cargo.toml | 2 + protocol/base/src/error.rs | 35 ++++++ .../base/src/{service.rs => invocation.rs} | 12 ++ protocol/base/src/invoker.rs | 78 ++++++++++++ protocol/base/src/lib.rs | 23 +--- protocol/base/src/output.rs | 111 ++++++++++++++++++ protocol/triple/Cargo.toml | 3 +- protocol/triple/src/lib.rs | 2 + protocol/triple/src/triple_invoker.rs | 50 ++++++++ 12 files changed, 315 insertions(+), 20 deletions(-) rename protocol/base/src/layer.rs => common/base/src/node.rs (80%) create mode 100644 protocol/base/src/error.rs rename protocol/base/src/{service.rs => invocation.rs} (72%) create mode 100644 protocol/base/src/invoker.rs create mode 100644 protocol/base/src/output.rs create mode 100644 protocol/triple/src/triple_invoker.rs diff --git a/common/base/src/lib.rs b/common/base/src/lib.rs index 5d89c23c..b97b342f 100644 --- a/common/base/src/lib.rs +++ b/common/base/src/lib.rs @@ -19,5 +19,8 @@ allow(dead_code, unused_imports, unused_variables, unused_mut) )] pub mod constants; +pub mod node; pub mod url; + +pub use node::Node; pub use url::Url; diff --git a/protocol/base/src/layer.rs b/common/base/src/node.rs similarity index 80% rename from protocol/base/src/layer.rs rename to common/base/src/node.rs index 2944f981..1e4114e9 100644 --- a/protocol/base/src/layer.rs +++ b/common/base/src/node.rs @@ -14,3 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +use std::sync::Arc; + +use crate::Url; + +pub trait Node { + fn get_url(&self) -> Arc; + fn is_available(&self) -> bool; + fn destroy(&self); + + fn is_destroyed(&self) -> bool; +} diff --git a/common/base/src/url.rs b/common/base/src/url.rs index 7b73f197..0ccf3210 100644 --- a/common/base/src/url.rs +++ b/common/base/src/url.rs @@ -157,6 +157,10 @@ impl Url { pub fn short_url(&self) -> String { format!("{}://{}:{}", self.scheme, self.ip, self.port) } + + pub fn protocol(&self) -> String { + self.scheme.clone() + } } impl Display for Url { diff --git a/protocol/base/Cargo.toml b/protocol/base/Cargo.toml index 77c82607..379c3425 100644 --- a/protocol/base/Cargo.toml +++ b/protocol/base/Cargo.toml @@ -6,3 +6,5 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +dashmap.workspace = true +base.workspace = true \ No newline at end of file diff --git a/protocol/base/src/error.rs b/protocol/base/src/error.rs new file mode 100644 index 00000000..21ffc75b --- /dev/null +++ b/protocol/base/src/error.rs @@ -0,0 +1,35 @@ +/* + * 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. + */ + +use std::error::Error; +use std::fmt::{Debug, Display, Formatter}; + +pub struct InvokerError(String); + +impl Debug for InvokerError { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(self.0.as_str()) + } +} + +impl Display for InvokerError { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(self.0.as_str()) + } +} + +impl Error for InvokerError {} diff --git a/protocol/base/src/service.rs b/protocol/base/src/invocation.rs similarity index 72% rename from protocol/base/src/service.rs rename to protocol/base/src/invocation.rs index 2944f981..0f3f9162 100644 --- a/protocol/base/src/service.rs +++ b/protocol/base/src/invocation.rs @@ -14,3 +14,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +use std::any::Any; +use std::sync::Arc; + +pub trait Invocation { + fn get_method_name(&self) -> String; + fn get_parameter_types(&self) -> Vec; + fn get_arguments(&self) -> Vec; + fn get_reply(&self) -> Arc; +} + +pub type BoxInvocation = Arc; diff --git a/protocol/base/src/invoker.rs b/protocol/base/src/invoker.rs new file mode 100644 index 00000000..ce8748c2 --- /dev/null +++ b/protocol/base/src/invoker.rs @@ -0,0 +1,78 @@ +/* + * 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. + */ +use crate::invocation::BoxInvocation; +use crate::output::{BoxOutput, RPCOutput}; +use base::{Node, Url}; +use std::fmt::{Display, Formatter}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +pub struct BaseInvoker { + url: Arc, + available: AtomicBool, + destroyed: AtomicBool, +} + +pub trait Invoker { + type Output; + fn invoke(&self, invocation: BoxInvocation) -> Self::Output; +} + +impl Invoker for BaseInvoker { + type Output = BoxOutput; + fn invoke(&self, _invocation: BoxInvocation) -> Self::Output { + Arc::new(RPCOutput::default()) + } +} + +impl Node for BaseInvoker { + fn get_url(&self) -> Arc { + self.url.clone() + } + + fn is_available(&self) -> bool { + self.available.load(Ordering::SeqCst) + } + + fn destroy(&self) { + self.destroyed.store(true, Ordering::SeqCst); + self.available.store(false, Ordering::SeqCst) + } + fn is_destroyed(&self) -> bool { + self.destroyed.load(Ordering::SeqCst) + } +} + +impl Display for BaseInvoker { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Invoker") + .field("protocol", &self.url.scheme) + .field("host", &self.url.ip) + .field("path", &self.url.location) + .finish() + } +} + +impl BaseInvoker { + pub fn new(url: Url) -> Self { + Self { + url: Arc::new(url), + available: AtomicBool::new(true), + destroyed: AtomicBool::new(false), + } + } +} diff --git a/protocol/base/src/lib.rs b/protocol/base/src/lib.rs index 2aae1ffa..d6adb754 100644 --- a/protocol/base/src/lib.rs +++ b/protocol/base/src/lib.rs @@ -1,19 +1,4 @@ -/* - * 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(crate) mod layer; -pub(crate) mod service; +pub mod error; +pub mod invocation; +pub mod invoker; +pub mod output; diff --git a/protocol/base/src/output.rs b/protocol/base/src/output.rs new file mode 100644 index 00000000..eb8e4b10 --- /dev/null +++ b/protocol/base/src/output.rs @@ -0,0 +1,111 @@ +/* + * 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. + */ +use std::any::Any; +use std::fmt::Debug; +use std::sync::Arc; + +use dashmap::DashMap; + +use crate::error::InvokerError; + +pub type AttachmentsMap = DashMap; + +pub struct RPCOutput { + error: Option>, + result: Option>, + attachments: AttachmentsMap, +} + +// role of Output is same to Result, because of preload std::result::Result +pub trait Output { + fn set_error(&mut self, error: Arc); + fn error(&self) -> Option>; + fn set(&mut self, result: R); + fn get(&self) -> Option>; + fn set_attachments(&mut self, attachments: AttachmentsMap); + fn add_attachment(&mut self, key: &str, value: &str); + fn get_attachment_or_default(&self, key: &str, default_value: &str) -> String; +} + +pub type BoxOutput = Arc + Send + Sync + 'static>; + +impl Default for RPCOutput +where + R: Any + Debug, +{ + fn default() -> Self { + RPCOutput { + error: None, + result: None, + attachments: AttachmentsMap::new(), + } + } +} + +impl Output for RPCOutput +where + R: Any + Debug, +{ + fn set_error(&mut self, error: Arc) { + self.error = Some(error); + } + + fn error(&self) -> Option> { + self.error.clone() + } + + fn set(&mut self, result: R) + where + R: Any + Debug, + { + self.result = Some(Arc::new(result)) + } + + fn get(&self) -> Option> { + self.result.clone() + } + + fn set_attachments(&mut self, attachments: AttachmentsMap) { + self.attachments = attachments; + } + + fn add_attachment(&mut self, key: &str, value: &str) { + self.attachments.insert(key.to_string(), value.to_string()); + } + + fn get_attachment_or_default(&self, key: &str, default_value: &str) -> String { + self.attachments + .contains_key(key) + .then(|| self.attachments.get(key).unwrap().clone()) + .unwrap_or(default_value.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_result() { + let mut result: RPCOutput = RPCOutput::default(); + result.set("r".to_string()); + assert_eq!(result.get().unwrap().as_str(), "r"); + result.add_attachment("hello", "world"); + let string = result.get_attachment_or_default("hello", "test"); + println!("{}", string); + } +} diff --git a/protocol/triple/Cargo.toml b/protocol/triple/Cargo.toml index 43aa6c5b..b342a3b1 100644 --- a/protocol/triple/Cargo.toml +++ b/protocol/triple/Cargo.toml @@ -7,4 +7,5 @@ edition = "2021" [dependencies] remoting-net.workspace = true -protocol.workspace = true \ No newline at end of file +protocol.workspace = true +base.workspace = true diff --git a/protocol/triple/src/lib.rs b/protocol/triple/src/lib.rs index 9d8d4b05..d7d432b5 100644 --- a/protocol/triple/src/lib.rs +++ b/protocol/triple/src/lib.rs @@ -15,6 +15,8 @@ * limitations under the License. */ +pub mod triple_invoker; + pub fn add(left: usize, right: usize) -> usize { left + right } diff --git a/protocol/triple/src/triple_invoker.rs b/protocol/triple/src/triple_invoker.rs new file mode 100644 index 00000000..82783847 --- /dev/null +++ b/protocol/triple/src/triple_invoker.rs @@ -0,0 +1,50 @@ +/* + * 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. + */ +use base::{Node, Url}; +use protocol::invocation::BoxInvocation; +use protocol::invoker::{BaseInvoker, Invoker}; +use std::sync::Arc; + +pub struct TripleInvoker { + base: BaseInvoker, +} + +impl Invoker for TripleInvoker { + type Output = (); + + fn invoke(&self, invocation: BoxInvocation) -> Self::Output { + todo!() + } +} + +impl Node for TripleInvoker { + fn get_url(&self) -> Arc { + self.base.get_url() + } + + fn is_available(&self) -> bool { + self.base.is_available() + } + + fn destroy(&self) { + todo!() + } + + fn is_destroyed(&self) -> bool { + self.base.is_destroyed() + } +} From f222293ce6b4ad9d70a9eb5d39b896ee7db9008b Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 23:40:25 +0800 Subject: [PATCH 21/26] Ftr: protocol abstraction design --- common/base/src/url.rs | 6 +- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++------------ protocol/base/src/error.rs | 6 +- protocol/base/src/invocation.rs | 3 +- protocol/base/src/invoker.rs | 16 +- protocol/base/src/output.rs | 4 +- protocol/triple/src/triple_invoker.rs | 6 +- registry/zookeeper/src/lib.rs | 9 +- 8 files changed, 92 insertions(+), 137 deletions(-) diff --git a/common/base/src/url.rs b/common/base/src/url.rs index 0ccf3210..81a72c2b 100644 --- a/common/base/src/url.rs +++ b/common/base/src/url.rs @@ -183,8 +183,10 @@ impl From<&str> for Url { #[cfg(test)] mod tests { - use crate::constants::{ANYHOST_KEY, VERSION_KEY}; - use crate::url::Url; + use crate::{ + constants::{ANYHOST_KEY, VERSION_KEY}, + url::Url, + }; #[test] fn test_from_url() { diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index 8758f85a..ccb385cd 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -40,16 +40,12 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static( - "/grpc.examples.echo.Echo/UnaryEcho", - ); + let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -57,51 +53,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner.server_streaming(request, codec, path, invocation).await + self.inner + .server_streaming(request, codec, path, invocation) + .await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner.client_streaming(request, codec, path, invocation).await + self.inner + .client_streaming(request, codec, path, invocation) + .await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner.bidi_streaming(request, codec, path, invocation).await + self.inner + .bidi_streaming(request, codec, path, invocation) + .await } } } @@ -118,9 +114,7 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type ServerStreamingEchoStream: futures_util::Stream> + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -134,19 +128,14 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type BidirectionalStreamingEchoStream: futures_util::Stream> + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result< - Response, - dubbo::status::Status, - >; + ) -> Result, dubbo::status::Status>; } /// Echo is the echo service. #[derive(Debug)] @@ -176,10 +165,7 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready( - &mut self, - _cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -192,26 +178,18 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -222,32 +200,22 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc - for ServerStreamingEchoServer { + impl ServerStreamingSvc for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = + BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.server_streaming_echo(request).await - }; + let fut = async move { inner.server_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -260,31 +228,23 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc - for ClientStreamingEchoServer { + impl ClientStreamingSvc for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.client_streaming_echo(request).await - }; + let fut = async move { inner.client_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -297,56 +257,41 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc - for BidirectionalStreamingEchoServer { + impl StreamingSvc for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = + BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.bidirectional_streaming_echo(request).await - }; + let fut = + async move { inner.bidirectional_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server - .bidi_streaming( - BidirectionalStreamingEchoServer { - inner, - }, - req, - ) + .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) .await; Ok(res) }; Box::pin(fut) } - _ => { - Box::pin(async move { - Ok( - http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap(), - ) - }) - } + _ => Box::pin(async move { + Ok(http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap()) + }), } } } diff --git a/protocol/base/src/error.rs b/protocol/base/src/error.rs index 21ffc75b..0ad0c26c 100644 --- a/protocol/base/src/error.rs +++ b/protocol/base/src/error.rs @@ -15,8 +15,10 @@ * limitations under the License. */ -use std::error::Error; -use std::fmt::{Debug, Display, Formatter}; +use std::{ + error::Error, + fmt::{Debug, Display, Formatter}, +}; pub struct InvokerError(String); diff --git a/protocol/base/src/invocation.rs b/protocol/base/src/invocation.rs index 0f3f9162..d77cad47 100644 --- a/protocol/base/src/invocation.rs +++ b/protocol/base/src/invocation.rs @@ -15,8 +15,7 @@ * limitations under the License. */ -use std::any::Any; -use std::sync::Arc; +use std::{any::Any, sync::Arc}; pub trait Invocation { fn get_method_name(&self) -> String; diff --git a/protocol/base/src/invoker.rs b/protocol/base/src/invoker.rs index ce8748c2..62bc8bf7 100644 --- a/protocol/base/src/invoker.rs +++ b/protocol/base/src/invoker.rs @@ -14,12 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -use crate::invocation::BoxInvocation; -use crate::output::{BoxOutput, RPCOutput}; +use crate::{ + invocation::BoxInvocation, + output::{BoxOutput, RPCOutput}, +}; use base::{Node, Url}; -use std::fmt::{Display, Formatter}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +use std::{ + fmt::{Display, Formatter}, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, +}; pub struct BaseInvoker { url: Arc, diff --git a/protocol/base/src/output.rs b/protocol/base/src/output.rs index eb8e4b10..e0d25835 100644 --- a/protocol/base/src/output.rs +++ b/protocol/base/src/output.rs @@ -14,9 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -use std::any::Any; -use std::fmt::Debug; -use std::sync::Arc; +use std::{any::Any, fmt::Debug, sync::Arc}; use dashmap::DashMap; diff --git a/protocol/triple/src/triple_invoker.rs b/protocol/triple/src/triple_invoker.rs index 82783847..52c5608f 100644 --- a/protocol/triple/src/triple_invoker.rs +++ b/protocol/triple/src/triple_invoker.rs @@ -15,8 +15,10 @@ * limitations under the License. */ use base::{Node, Url}; -use protocol::invocation::BoxInvocation; -use protocol::invoker::{BaseInvoker, Invoker}; +use protocol::{ + invocation::BoxInvocation, + invoker::{BaseInvoker, Invoker}, +}; use std::sync::Arc; pub struct TripleInvoker { diff --git a/registry/zookeeper/src/lib.rs b/registry/zookeeper/src/lib.rs index fe3d962a..d95d291c 100644 --- a/registry/zookeeper/src/lib.rs +++ b/registry/zookeeper/src/lib.rs @@ -24,8 +24,10 @@ use std::{ time::Duration, }; -use base::constants::{DUBBO_KEY, LOCALHOST_IP, PROVIDERS_KEY}; -use base::Url; +use base::{ + constants::{DUBBO_KEY, LOCALHOST_IP, PROVIDERS_KEY}, + Url, +}; use logger::tracing::{debug, error, info}; use serde::{Deserialize, Serialize}; #[allow(unused_imports)] @@ -381,8 +383,7 @@ mod tests { use zookeeper::{Acl, CreateMode, WatchedEvent, Watcher}; - use crate::zookeeper_registry::ZookeeperRegistry; - use crate::ZookeeperRegistry; + use crate::{zookeeper_registry::ZookeeperRegistry, ZookeeperRegistry}; struct TestZkWatcher { pub watcher: Arc>, From 948dc742652de08d9ac7fdc8936babdf5e4412c5 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 23:42:10 +0800 Subject: [PATCH 22/26] Ftr: protocol abstraction design --- remoting/net/benches/transport_benchmark/main.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/remoting/net/benches/transport_benchmark/main.rs b/remoting/net/benches/transport_benchmark/main.rs index 2944f981..352e8569 100644 --- a/remoting/net/benches/transport_benchmark/main.rs +++ b/remoting/net/benches/transport_benchmark/main.rs @@ -14,3 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +fn main() { + todo!() +} From adc33be2de3d0ca64d5bbbbf5fe944babcaee249 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 23:43:35 +0800 Subject: [PATCH 23/26] Ftr: protocol abstraction design --- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++++++++------ protocol/triple/src/triple_invoker.rs | 2 +- registry/zookeeper/src/lib.rs | 2 +- 3 files changed, 119 insertions(+), 64 deletions(-) diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index ccb385cd..8758f85a 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -40,12 +40,16 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); + let path = http::uri::PathAndQuery::from_static( + "/grpc.examples.echo.Echo/UnaryEcho", + ); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -53,51 +57,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner - .server_streaming(request, codec, path, invocation) - .await + self.inner.server_streaming(request, codec, path, invocation).await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner - .client_streaming(request, codec, path, invocation) - .await + self.inner.client_streaming(request, codec, path, invocation).await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = - dubbo::codegen::ProstCodec::::default(); + let codec = dubbo::codegen::ProstCodec::< + super::EchoRequest, + super::EchoResponse, + >::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner - .bidi_streaming(request, codec, path, invocation) - .await + self.inner.bidi_streaming(request, codec, path, invocation).await } } } @@ -114,7 +118,9 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream> + type ServerStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -128,14 +134,19 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream> + type BidirectionalStreamingEchoStream: futures_util::Stream< + Item = Result, + > + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result, dubbo::status::Status>; + ) -> Result< + Response, + dubbo::status::Status, + >; } /// Echo is the echo service. #[derive(Debug)] @@ -165,7 +176,10 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + fn poll_ready( + &mut self, + _cx: &mut Context<'_>, + ) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -178,18 +192,26 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -200,22 +222,32 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc for ServerStreamingEchoServer { + impl ServerStreamingSvc + for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; - fn call(&mut self, request: Request) -> Self::Future { + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; + fn call( + &mut self, + request: Request, + ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.server_streaming_echo(request).await }; + let fut = async move { + inner.server_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -228,23 +260,31 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc for ClientStreamingEchoServer { + impl ClientStreamingSvc + for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { inner.client_streaming_echo(request).await }; + let fut = async move { + inner.client_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -257,41 +297,56 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc for BidirectionalStreamingEchoServer { + impl StreamingSvc + for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = - BoxFuture, dubbo::status::Status>; + type Future = BoxFuture< + Response, + dubbo::status::Status, + >; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = - async move { inner.bidirectional_streaming_echo(request).await }; + let fut = async move { + inner.bidirectional_streaming_echo(request).await + }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default()); + let mut server = TripleServer::new( + dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default(), + ); let res = server - .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) + .bidi_streaming( + BidirectionalStreamingEchoServer { + inner, + }, + req, + ) .await; Ok(res) }; Box::pin(fut) } - _ => Box::pin(async move { - Ok(http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap()) - }), + _ => { + Box::pin(async move { + Ok( + http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap(), + ) + }) + } } } } diff --git a/protocol/triple/src/triple_invoker.rs b/protocol/triple/src/triple_invoker.rs index 52c5608f..4a2e74f1 100644 --- a/protocol/triple/src/triple_invoker.rs +++ b/protocol/triple/src/triple_invoker.rs @@ -28,7 +28,7 @@ pub struct TripleInvoker { impl Invoker for TripleInvoker { type Output = (); - fn invoke(&self, invocation: BoxInvocation) -> Self::Output { + fn invoke(&self, _invocation: BoxInvocation) -> Self::Output { todo!() } } diff --git a/registry/zookeeper/src/lib.rs b/registry/zookeeper/src/lib.rs index d95d291c..4f11d3ae 100644 --- a/registry/zookeeper/src/lib.rs +++ b/registry/zookeeper/src/lib.rs @@ -383,7 +383,7 @@ mod tests { use zookeeper::{Acl, CreateMode, WatchedEvent, Watcher}; - use crate::{zookeeper_registry::ZookeeperRegistry, ZookeeperRegistry}; + use crate::ZookeeperRegistry; struct TestZkWatcher { pub watcher: Arc>, From 219076ace4c008d0942202cca5ee2da4ca91c6a4 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 23:48:41 +0800 Subject: [PATCH 24/26] Ftr: protocol abstraction design --- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++------------ 1 file changed, 62 insertions(+), 117 deletions(-) diff --git a/examples/echo/src/generated/grpc.examples.echo.rs b/examples/echo/src/generated/grpc.examples.echo.rs index 8758f85a..ccb385cd 100644 --- a/examples/echo/src/generated/grpc.examples.echo.rs +++ b/examples/echo/src/generated/grpc.examples.echo.rs @@ -40,16 +40,12 @@ pub mod echo_client { &mut self, request: Request, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("UnaryEcho")); - let path = http::uri::PathAndQuery::from_static( - "/grpc.examples.echo.Echo/UnaryEcho", - ); + let path = http::uri::PathAndQuery::from_static("/grpc.examples.echo.Echo/UnaryEcho"); self.inner.unary(request, codec, path, invocation).await } /// ServerStreamingEcho is server side streaming. @@ -57,51 +53,51 @@ pub mod echo_client { &mut self, request: Request, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ServerStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ServerStreamingEcho", ); - self.inner.server_streaming(request, codec, path, invocation).await + self.inner + .server_streaming(request, codec, path, invocation) + .await } /// ClientStreamingEcho is client side streaming. pub async fn client_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("ClientStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/ClientStreamingEcho", ); - self.inner.client_streaming(request, codec, path, invocation).await + self.inner + .client_streaming(request, codec, path, invocation) + .await } /// BidirectionalStreamingEcho is bidi streaming. pub async fn bidirectional_streaming_echo( &mut self, request: impl IntoStreamingRequest, ) -> Result>, dubbo::status::Status> { - let codec = dubbo::codegen::ProstCodec::< - super::EchoRequest, - super::EchoResponse, - >::default(); + let codec = + dubbo::codegen::ProstCodec::::default(); let invocation = RpcInvocation::default() .with_service_unique_name(String::from("grpc.examples.echo.Echo")) .with_method_name(String::from("BidirectionalStreamingEcho")); let path = http::uri::PathAndQuery::from_static( "/grpc.examples.echo.Echo/BidirectionalStreamingEcho", ); - self.inner.bidi_streaming(request, codec, path, invocation).await + self.inner + .bidi_streaming(request, codec, path, invocation) + .await } } } @@ -118,9 +114,7 @@ pub mod echo_server { request: Request, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the ServerStreamingEcho method. - type ServerStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type ServerStreamingEchoStream: futures_util::Stream> + Send + 'static; /// ServerStreamingEcho is server side streaming. @@ -134,19 +128,14 @@ pub mod echo_server { request: Request>, ) -> Result, dubbo::status::Status>; ///Server streaming response type for the BidirectionalStreamingEcho method. - type BidirectionalStreamingEchoStream: futures_util::Stream< - Item = Result, - > + type BidirectionalStreamingEchoStream: futures_util::Stream> + Send + 'static; /// BidirectionalStreamingEcho is bidi streaming. async fn bidirectional_streaming_echo( &self, request: Request>, - ) -> Result< - Response, - dubbo::status::Status, - >; + ) -> Result, dubbo::status::Status>; } /// Echo is the echo service. #[derive(Debug)] @@ -176,10 +165,7 @@ pub mod echo_server { type Response = http::Response; type Error = std::convert::Infallible; type Future = BoxFuture; - fn poll_ready( - &mut self, - _cx: &mut Context<'_>, - ) -> Poll> { + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn call(&mut self, req: http::Request) -> Self::Future { @@ -192,26 +178,18 @@ pub mod echo_server { } impl UnarySvc for UnaryEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); let fut = async move { inner.unary_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server.unary(UnaryEchoServer { inner }, req).await; Ok(res) }; @@ -222,32 +200,22 @@ pub mod echo_server { struct ServerStreamingEchoServer { inner: _Inner, } - impl ServerStreamingSvc - for ServerStreamingEchoServer { + impl ServerStreamingSvc for ServerStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::ServerStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; - fn call( - &mut self, - request: Request, - ) -> Self::Future { + type Future = + BoxFuture, dubbo::status::Status>; + fn call(&mut self, request: Request) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.server_streaming_echo(request).await - }; + let fut = async move { inner.server_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .server_streaming(ServerStreamingEchoServer { inner }, req) .await; @@ -260,31 +228,23 @@ pub mod echo_server { struct ClientStreamingEchoServer { inner: _Inner, } - impl ClientStreamingSvc - for ClientStreamingEchoServer { + impl ClientStreamingSvc for ClientStreamingEchoServer { type Response = super::EchoResponse; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.client_streaming_echo(request).await - }; + let fut = async move { inner.client_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server .client_streaming(ClientStreamingEchoServer { inner }, req) .await; @@ -297,56 +257,41 @@ pub mod echo_server { struct BidirectionalStreamingEchoServer { inner: _Inner, } - impl StreamingSvc - for BidirectionalStreamingEchoServer { + impl StreamingSvc for BidirectionalStreamingEchoServer { type Response = super::EchoResponse; type ResponseStream = T::BidirectionalStreamingEchoStream; - type Future = BoxFuture< - Response, - dubbo::status::Status, - >; + type Future = + BoxFuture, dubbo::status::Status>; fn call( &mut self, request: Request>, ) -> Self::Future { let inner = self.inner.0.clone(); - let fut = async move { - inner.bidirectional_streaming_echo(request).await - }; + let fut = + async move { inner.bidirectional_streaming_echo(request).await }; Box::pin(fut) } } let fut = async move { - let mut server = TripleServer::new( - dubbo::codegen::ProstCodec::< - super::EchoResponse, - super::EchoRequest, - >::default(), - ); + let mut server = TripleServer::new(dubbo::codegen::ProstCodec::< + super::EchoResponse, + super::EchoRequest, + >::default()); let res = server - .bidi_streaming( - BidirectionalStreamingEchoServer { - inner, - }, - req, - ) + .bidi_streaming(BidirectionalStreamingEchoServer { inner }, req) .await; Ok(res) }; Box::pin(fut) } - _ => { - Box::pin(async move { - Ok( - http::Response::builder() - .status(200) - .header("grpc-status", "12") - .header("content-type", "application/grpc") - .body(empty_body()) - .unwrap(), - ) - }) - } + _ => Box::pin(async move { + Ok(http::Response::builder() + .status(200) + .header("grpc-status", "12") + .header("content-type", "application/grpc") + .body(empty_body()) + .unwrap()) + }), } } } From 17e89b27d7f9a3460d77fb1a09ad50ef0f3ad850 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Fri, 3 Mar 2023 23:53:00 +0800 Subject: [PATCH 25/26] Ftr: protocol abstraction design --- protocol/base/src/lib.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/protocol/base/src/lib.rs b/protocol/base/src/lib.rs index d6adb754..6928742a 100644 --- a/protocol/base/src/lib.rs +++ b/protocol/base/src/lib.rs @@ -1,3 +1,20 @@ +/* + * 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 error; pub mod invocation; pub mod invoker; From 1d351d1776eb1e0a464c79f5b791d6c3f2cf1a24 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sat, 4 Mar 2023 00:25:00 +0800 Subject: [PATCH 26/26] Ftr: protocol abstraction design --- common/base/src/constants.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/base/src/constants.rs b/common/base/src/constants.rs index 09c17170..b1faf270 100644 --- a/common/base/src/constants.rs +++ b/common/base/src/constants.rs @@ -15,7 +15,7 @@ * limitations under the License. */ pub const REGISTRY_PROTOCOL: &str = "registry_protocol"; -pub const PROTOCOL: &str = "base"; +pub const PROTOCOL: &str = "protocol"; pub const REGISTRY: &str = "registry"; // URL key