From 02ad8afd29fedda2daf52eb6f3f9954d0c564887 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sun, 26 Feb 2023 16:43:45 +0800 Subject: [PATCH 01/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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/23] 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 ce849bed3a016c6c4b1614e6603b0fc6a0bc883c Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sat, 4 Mar 2023 16:48:45 +0800 Subject: [PATCH 16/23] Ftr: remoting/exchange abstraction design --- Cargo.toml | 7 +- common/base/src/url.rs | 4 + dubbo/Cargo.toml | 17 +- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++++++++------ protocol/base/Cargo.toml | 3 +- protocol/base/src/error.rs | 24 +-- protocol/base/src/lib.rs | 2 + remoting/{exchange => base}/Cargo.toml | 6 + remoting/{exchange => base}/LICENSE | 0 remoting/base/src/codec.rs | 125 ++++++++++++ remoting/base/src/error.rs | 32 ++++ remoting/base/src/exchange.rs | 47 +++++ remoting/base/src/exchange_client.rs | 77 ++++++++ remoting/base/src/exchange_server.rs | 48 +++++ remoting/{exchange => base}/src/lib.rs | 26 +-- 15 files changed, 492 insertions(+), 105 deletions(-) rename remoting/{exchange => base}/Cargo.toml (55%) rename remoting/{exchange => base}/LICENSE (100%) create mode 100644 remoting/base/src/codec.rs create mode 100644 remoting/base/src/error.rs create mode 100644 remoting/base/src/exchange.rs create mode 100644 remoting/base/src/exchange_client.rs create mode 100644 remoting/base/src/exchange_server.rs rename remoting/{exchange => base}/src/lib.rs (71%) diff --git a/Cargo.toml b/Cargo.toml index 1d173a38..a25c9ad5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,7 @@ members = [ "remoting/http", "remoting/h2", "remoting/zookeeper", - "remoting/exchange", + "remoting/base", "remoting/xds", "protocol/dubbo2", "protocol/base", @@ -28,6 +28,8 @@ members = [ pin-project = "1" tokio = "1.0" tower = "0.4" +tower-service = "0.3.1" +tower-layer = "0.3" tokio-stream = "0.1" tokio-util = "0.7" socket2 = "0.4" @@ -48,10 +50,13 @@ protocol-triple = {path="./protocol/triple"} registry-zookeeper = {path="./registry/zookeeper"} registry-nacos = {path="./registry/nacos"} anyhow = "1.0.66" +thiserror = "1.0.30" 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" +bytes = "1.0" + diff --git a/common/base/src/url.rs b/common/base/src/url.rs index 81a72c2b..48fbc1eb 100644 --- a/common/base/src/url.rs +++ b/common/base/src/url.rs @@ -161,6 +161,10 @@ impl Url { pub fn protocol(&self) -> String { self.scheme.clone() } + + pub fn get_ip_port(&self) -> String { + format!("{}:{}", self.ip, self.port) + } } impl Display for Url { diff --git a/dubbo/Cargo.toml b/dubbo/Cargo.toml index 3b66523b..a814bd0d 100644 --- a/dubbo/Cargo.toml +++ b/dubbo/Cargo.toml @@ -12,23 +12,21 @@ repository = "https://github.com/apache/dubbo-rust.git" [dependencies] hyper = { version = "0.14.19", features = ["full"] } http = "0.2" -tower-service = "0.3.1" +tower-service.workspace = true http-body = "0.4.4" -tower = { version = "0.4.12", features = ["timeout"] } +tower = { workspace = true, 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"] } +tokio = { workspace = true, features = ["rt-multi-thread", "time", "fs", "macros", "net", "signal"] } prost = "0.10.4" async-trait = "0.1.56" -tower-layer = "0.3" -bytes = "1.0" +tower-layer.workspace = true +bytes.workspace = true pin-project.workspace = true rand = "0.8.5" serde_json.workspace = true serde = { workspace = true, features = ["derive"] } -futures = "0.3" -tracing = "0.1" -tracing-subscriber = "0.3.15" +futures.workspace = true axum = "0.5.9" async-stream = "0.3" flate2 = "1.0" @@ -36,7 +34,8 @@ aws-smithy-http = "0.54.1" itertools.workspace = true urlencoding.workspace = true lazy_static.workspace = true -base.workspace=true +base.workspace = true +logger.workspace = true dubbo-config = { path = "../config", version = "0.3.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/protocol/base/Cargo.toml b/protocol/base/Cargo.toml index 379c3425..40bc289c 100644 --- a/protocol/base/Cargo.toml +++ b/protocol/base/Cargo.toml @@ -7,4 +7,5 @@ edition = "2021" [dependencies] dashmap.workspace = true -base.workspace = true \ No newline at end of file +base.workspace = true +thiserror.workspace = true \ No newline at end of file diff --git a/protocol/base/src/error.rs b/protocol/base/src/error.rs index 0ad0c26c..e6c424a5 100644 --- a/protocol/base/src/error.rs +++ b/protocol/base/src/error.rs @@ -14,24 +14,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use thiserror::Error; -use std::{ - error::Error, - 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()) - } +#[derive(Error, Debug)] +pub enum InvokerError { + #[error("unknown invoker error.")] + Unknown, } - -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/lib.rs b/protocol/base/src/lib.rs index 6928742a..751af40c 100644 --- a/protocol/base/src/lib.rs +++ b/protocol/base/src/lib.rs @@ -19,3 +19,5 @@ pub mod error; pub mod invocation; pub mod invoker; pub mod output; + +pub type ProtocolName = &'static str; diff --git a/remoting/exchange/Cargo.toml b/remoting/base/Cargo.toml similarity index 55% rename from remoting/exchange/Cargo.toml rename to remoting/base/Cargo.toml index ec14668a..2b06bf97 100644 --- a/remoting/exchange/Cargo.toml +++ b/remoting/base/Cargo.toml @@ -6,3 +6,9 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +bytes.workspace = true +base.workspace = true +thiserror.workspace = true +dashmap.workspacpe = true +protocol.workspace = true +anyhow.workspace = true \ No newline at end of file diff --git a/remoting/exchange/LICENSE b/remoting/base/LICENSE similarity index 100% rename from remoting/exchange/LICENSE rename to remoting/base/LICENSE diff --git a/remoting/base/src/codec.rs b/remoting/base/src/codec.rs new file mode 100644 index 00000000..6f1b54bd --- /dev/null +++ b/remoting/base/src/codec.rs @@ -0,0 +1,125 @@ +/* +* 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::sync::Arc; + +use anyhow::{anyhow, Error}; +use bytes; +use bytes::Bytes; +use dashmap::DashMap; + +use protocol::ProtocolName; + +use crate::error::CodecError; +use crate::Response; + +#[derive(Clone)] +pub struct BoxedCodec(Arc); + +impl BoxedCodec { + pub fn new(codec: Arc) -> Self { + BoxedCodec(codec) + } +} + +pub trait Codec: Sync + Send { + fn encode_request(&self) -> Result; + fn encode_response(&self) -> Result; + fn decode(&self, bytes: Bytes) -> Result; +} + +pub struct CodecRegistry { + registry: DashMap, +} + +#[derive(Default)] +pub struct CodecResult { + is_request: bool, // heartbeat flag + result: Option, +} + +impl Default for CodecRegistry { + fn default() -> Self { + CodecRegistry { + registry: DashMap::new(), + } + } +} +impl CodecRegistry { + pub fn get_codec(&self, protocol: ProtocolName) -> Option { + let registry_map = &self.registry; + if let true = registry_map.contains_key(protocol) { + let option = registry_map.get(protocol); + let codec = option.as_deref().unwrap(); + Some(codec.clone()) + } else { + None + } + } + pub fn set_codec( + &mut self, + protocol: ProtocolName, + codec: BoxedCodec, + ) -> anyhow::Result<(), CodecError> { + if let true = self.registry.contains_key(protocol) { + return Err(CodecError::RegistryExistsProtocol(protocol)); + } else { + self.registry.insert(protocol, codec); + } + Ok(()) + } + + pub fn is_registered(&self, protocol: ProtocolName) -> bool { + self.registry.contains_key(protocol) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use bytes::Bytes; + + use crate::codec::{BoxedCodec, CodecRegistry, CodecResult}; + use crate::error::CodecError; + use crate::Codec; + + #[derive(Default)] + struct TestCodec; + impl Codec for TestCodec { + fn encode_request(&self) -> Result { + Ok(Bytes::new()) + } + + fn encode_response(&self) -> Result { + Ok(Bytes::new()) + } + + fn decode(&self, bytes: Bytes) -> Result { + Ok(CodecResult::default()) + } + } + + #[test] + fn test_registry() { + let mut codec_registry = CodecRegistry::default(); + codec_registry + .set_codec("test", BoxedCodec(Arc::new(TestCodec::default()))) + .unwrap(); + assert!(codec_registry.is_registered("test")); + } +} diff --git a/remoting/base/src/error.rs b/remoting/base/src/error.rs new file mode 100644 index 00000000..f0098cb6 --- /dev/null +++ b/remoting/base/src/error.rs @@ -0,0 +1,32 @@ +/* +* 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 protocol::ProtocolName; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum CodecError { + #[error("unknown codec error.")] + Unknown, + #[error("protocol {0} is registered.")] + RegistryExistsProtocol(ProtocolName), +} + +#[derive(Error, Debug)] +pub enum ClientError { + #[error("unknown client error")] + Unknown, +} diff --git a/remoting/base/src/exchange.rs b/remoting/base/src/exchange.rs new file mode 100644 index 00000000..266f1111 --- /dev/null +++ b/remoting/base/src/exchange.rs @@ -0,0 +1,47 @@ +/* + * 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::error::CodecError; +use std::any::Any; +use std::sync::Arc; + +pub type BoxedExchangeBody = Arc; + +pub struct Request { + id: u64, + version: String, // protocol version + serial_id: u8, // serial ID (ignore) + body: Option, + two_way: bool, + event: bool, +} + +pub struct Response { + id: u64, + version: String, // protocol version + serial_id: u8, // serial ID (ignore) + status: u8, + body: Option, // mean result + event: bool, + error: Option, +} + +impl Response { + fn is_heart_beat(&self) -> bool { + self.event && self.body.is_none() + } +} diff --git a/remoting/base/src/exchange_client.rs b/remoting/base/src/exchange_client.rs new file mode 100644 index 00000000..d932f498 --- /dev/null +++ b/remoting/base/src/exchange_client.rs @@ -0,0 +1,77 @@ +/* + * 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::Url; +use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; +use std::sync::Arc; +use std::time; +use std::time::Duration; + +use crate::error::ClientError; +use crate::exchange::{Request, Response}; + +pub struct BoxedClient(Arc); + +pub trait Client: Sync + Send { + fn connect(&self, url: Url) -> Result<(), ClientError>; + fn request(&self, request: Request, timeout: Duration) -> Result; + fn close(&mut self) -> Result<(), ClientError>; + fn is_available(&self) -> bool; +} + +pub struct ExchangeClient { + connection_timeout: Duration, // timeout when connecting to server + address: String, // listening ip:port + client: Option, // dealing with the transports + init: AtomicBool, // whether the client is initialized + active: AtomicI32, // the number of active service bind to this client +} + +impl ExchangeClient { + pub fn new(url: Url, client: BoxedClient, connection_timeout: Duration) -> Self { + ExchangeClient { + connection_timeout, + address: url.get_ip_port(), + client: None, + init: AtomicBool::new(false), + active: AtomicI32::new(0), + } + } +} + +impl Client for ExchangeClient { + fn connect(&self, url: Url) -> Result<(), ClientError> { + if self.init.load(Ordering::SeqCst) { + return Ok(()); + } + Ok(()) + } + + fn request(&self, request: Request, timeout: Duration) -> Result { + todo!() + } + + fn close(&mut self) -> Result<(), ClientError> { + self.init.store(false, Ordering::SeqCst); + Ok(()) + } + + fn is_available(&self) -> bool { + let client = self.client.as_ref().unwrap(); + client.0.is_available() + } +} diff --git a/remoting/base/src/exchange_server.rs b/remoting/base/src/exchange_server.rs new file mode 100644 index 00000000..26b1ecc5 --- /dev/null +++ b/remoting/base/src/exchange_server.rs @@ -0,0 +1,48 @@ +/* +* 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 anyhow::{Error, Result}; +use base::Url; +use std::sync::Arc; + +pub struct BoxedServer(Arc); + +pub trait Server: Sync + Send { + fn start(&self) -> Result<(), Error>; + fn stop(&self) -> Result<(), Error>; +} + +pub struct ExchangeServer { + server: BoxedServer, + url: Url, +} + +impl ExchangeServer { + pub fn new(url: Url, server: BoxedServer) -> Self { + ExchangeServer { server, url } + } +} + +impl Server for ExchangeServer { + fn start(&self) -> Result<(), Error> { + self.server.0.start() + } + + fn stop(&self) -> Result<(), Error> { + self.server.0.stop() + } +} diff --git a/remoting/exchange/src/lib.rs b/remoting/base/src/lib.rs similarity index 71% rename from remoting/exchange/src/lib.rs rename to remoting/base/src/lib.rs index d64452d5..5d26d7b0 100644 --- a/remoting/exchange/src/lib.rs +++ b/remoting/base/src/lib.rs @@ -14,17 +14,17 @@ * 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_attr( + debug_assertions, + allow(dead_code, unused_imports, unused_variables, unused_mut) +)] +pub use codec::Codec; +pub mod codec; +pub mod error; +pub mod exchange; +pub mod exchange_client; +pub mod exchange_server; -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} +pub use exchange::BoxedExchangeBody; +pub use exchange::Request; +pub use exchange::Response; From 519b3b1ef6564efe203367b0e3abb76fcf06ab0e Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sat, 4 Mar 2023 16:56:28 +0800 Subject: [PATCH 17/23] Ftr: remoting/exchange abstraction design --- remoting/base/src/builder_client.rs | 18 ++++++++++++++++++ remoting/base/src/builder_server.rs | 18 ++++++++++++++++++ remoting/base/src/lib.rs | 2 ++ 3 files changed, 38 insertions(+) create mode 100644 remoting/base/src/builder_client.rs create mode 100644 remoting/base/src/builder_server.rs diff --git a/remoting/base/src/builder_client.rs b/remoting/base/src/builder_client.rs new file mode 100644 index 00000000..4dded803 --- /dev/null +++ b/remoting/base/src/builder_client.rs @@ -0,0 +1,18 @@ +/* + * 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. + */ +// for tower ServiceBuilder; the input starts from Bytes +// exchange is a part of LayerStack diff --git a/remoting/base/src/builder_server.rs b/remoting/base/src/builder_server.rs new file mode 100644 index 00000000..4dded803 --- /dev/null +++ b/remoting/base/src/builder_server.rs @@ -0,0 +1,18 @@ +/* + * 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. + */ +// for tower ServiceBuilder; the input starts from Bytes +// exchange is a part of LayerStack diff --git a/remoting/base/src/lib.rs b/remoting/base/src/lib.rs index 5d26d7b0..436e0e17 100644 --- a/remoting/base/src/lib.rs +++ b/remoting/base/src/lib.rs @@ -19,6 +19,8 @@ allow(dead_code, unused_imports, unused_variables, unused_mut) )] pub use codec::Codec; +pub mod builder_client; +pub mod builder_server; pub mod codec; pub mod error; pub mod exchange; From 0c269565a8c4fa8ed3c13985b3bd2c7aabb3c054 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sat, 4 Mar 2023 17:10:09 +0800 Subject: [PATCH 18/23] Ftr: remoting/exchange abstraction design --- dubbo/src/cluster/directory.rs | 1 + dubbo/src/context.rs | 1 + dubbo/src/filter/context.rs | 1 + dubbo/src/filter/timeout.rs | 1 + dubbo/src/framework.rs | 19 +++++++++---------- dubbo/src/registry/memory_registry.rs | 2 +- dubbo/src/registry/protocol.rs | 1 + dubbo/src/registry/types.rs | 2 +- dubbo/src/triple/decode.rs | 1 + dubbo/src/triple/server/builder.rs | 1 + dubbo/src/triple/transport/connection.rs | 2 +- .../transport/connector/http_connector.rs | 1 + .../transport/connector/unix_connector.rs | 1 + dubbo/src/triple/transport/listener/mod.rs | 1 + .../triple/transport/listener/tcp_listener.rs | 1 + .../transport/listener/unix_listener.rs | 1 + dubbo/src/triple/transport/service.rs | 1 + remoting/base/Cargo.toml | 2 +- remoting/base/src/codec.rs | 14 +++++++------- remoting/base/src/exchange.rs | 3 +-- remoting/base/src/exchange_client.rs | 18 ++++++++++++------ remoting/base/src/lib.rs | 4 +--- 22 files changed, 47 insertions(+), 32 deletions(-) diff --git a/dubbo/src/cluster/directory.rs b/dubbo/src/cluster/directory.rs index d92bb20c..8c2536c0 100644 --- a/dubbo/src/cluster/directory.rs +++ b/dubbo/src/cluster/directory.rs @@ -27,6 +27,7 @@ use crate::{ registry::{memory_registry::MemoryNotifyListener, BoxRegistry, RegistryWrapper}, }; use base::Url; +use logger::tracing; /// Directory. /// diff --git a/dubbo/src/context.rs b/dubbo/src/context.rs index 6def1bf4..e94eb26a 100644 --- a/dubbo/src/context.rs +++ b/dubbo/src/context.rs @@ -21,6 +21,7 @@ use std::{ thread, }; +use logger::tracing; use serde_json::Value; use state::Container; diff --git a/dubbo/src/filter/context.rs b/dubbo/src/filter/context.rs index 3f73fd00..b17168bf 100644 --- a/dubbo/src/filter/context.rs +++ b/dubbo/src/filter/context.rs @@ -17,6 +17,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; +use logger::tracing; use serde_json::Value; use crate::{ diff --git a/dubbo/src/filter/timeout.rs b/dubbo/src/filter/timeout.rs index 353585d7..ea14183f 100644 --- a/dubbo/src/filter/timeout.rs +++ b/dubbo/src/filter/timeout.rs @@ -14,6 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +use logger::tracing; use std::time::{SystemTime, UNIX_EPOCH}; use crate::{ diff --git a/dubbo/src/framework.rs b/dubbo/src/framework.rs index 546e2d0f..f91ee434 100644 --- a/dubbo/src/framework.rs +++ b/dubbo/src/framework.rs @@ -22,10 +22,6 @@ use std::{ sync::{Arc, Mutex}, }; -use base::Url; -use futures::{future, Future}; -use tracing::{debug, info}; - use crate::{ protocol::{BoxExporter, Protocol}, registry::{ @@ -34,7 +30,10 @@ use crate::{ BoxRegistry, Registry, }, }; +use base::Url; use dubbo_config::{get_global_config, protocol::ProtocolRetrieve, RootConfig}; +use futures::{future, Future}; +use logger::tracing; // Invoker是否可以基于hyper写一个通用的 @@ -78,10 +77,10 @@ impl Dubbo { } let root_config = self.config.as_ref().unwrap(); - debug!("global conf: {:?}", root_config); + tracing::debug!("global conf: {:?}", root_config); // env::set_var("ZOOKEEPER_SERVERS",root_config); for (_, service_config) in root_config.provider.services.iter() { - info!("init service name: {}", service_config.interface); + tracing::info!("init service name: {}", service_config.interface); let url = if root_config .protocols .contains_key(service_config.protocol.as_str()) @@ -91,12 +90,12 @@ impl Dubbo { .get_protocol_or_default(service_config.protocol.as_str()); let protocol_url = format!("{}/{}", protocol.to_url(), service_config.interface.clone(),); - info!("protocol_url: {:?}", protocol_url); + tracing::info!("protocol_url: {:?}", protocol_url); Url::from_url(&protocol_url) } else { return Err(format!("base {:?} not exists", service_config.protocol).into()); }; - info!("url: {:?}", url); + tracing::info!("url: {:?}", url); if url.is_none() { continue; } @@ -116,7 +115,7 @@ impl Dubbo { pub async fn start(&mut self) { self.init().unwrap(); - info!("starting..."); + tracing::info!("starting..."); // TODO: server registry let mem_reg = Box::new( RegistryProtocol::new() @@ -126,7 +125,7 @@ impl Dubbo { let mut async_vec: Vec + Send>>> = Vec::new(); for (name, items) in self.protocols.iter() { for url in items.iter() { - info!("base: {:?}, service url: {:?}", name, url); + tracing::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/registry/memory_registry.rs b/dubbo/src/registry/memory_registry.rs index 7f900f63..38d08e26 100644 --- a/dubbo/src/registry/memory_registry.rs +++ b/dubbo/src/registry/memory_registry.rs @@ -17,11 +17,11 @@ #![allow(unused_variables, dead_code, missing_docs)] +use logger::tracing::debug; use std::{ collections::HashMap, sync::{Arc, RwLock}, }; -use tracing::debug; use base::Url; diff --git a/dubbo/src/registry/protocol.rs b/dubbo/src/registry/protocol.rs index d28e43de..4f86fd35 100644 --- a/dubbo/src/registry/protocol.rs +++ b/dubbo/src/registry/protocol.rs @@ -16,6 +16,7 @@ */ use base::Url; +use logger::tracing; use std::{ collections::HashMap, fmt::{Debug, Formatter}, diff --git a/dubbo/src/registry/types.rs b/dubbo/src/registry/types.rs index a55e72c2..16b9063d 100644 --- a/dubbo/src/registry/types.rs +++ b/dubbo/src/registry/types.rs @@ -22,7 +22,7 @@ use std::{ use base::Url; use itertools::Itertools; -use tracing::info; +use logger::tracing::info; use crate::{ registry::{BoxRegistry, Registry}, diff --git a/dubbo/src/triple/decode.rs b/dubbo/src/triple/decode.rs index 26c4cd64..efdbee6b 100644 --- a/dubbo/src/triple/decode.rs +++ b/dubbo/src/triple/decode.rs @@ -20,6 +20,7 @@ use std::{pin::Pin, task::Poll}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use futures_util::{future, ready, Stream}; use http_body::Body; +use logger::tracing; use super::compression::{decompress, CompressionEncoding}; use crate::{ diff --git a/dubbo/src/triple/server/builder.rs b/dubbo/src/triple/server/builder.rs index e82ff058..1623540a 100644 --- a/dubbo/src/triple/server/builder.rs +++ b/dubbo/src/triple/server/builder.rs @@ -23,6 +23,7 @@ use std::{ use base::Url; use http::{Request, Response, Uri}; use hyper::body::Body; +use logger::tracing; use tower_service::Service; use crate::{triple::transport::DubboServer, BoxBody}; diff --git a/dubbo/src/triple/transport/connection.rs b/dubbo/src/triple/transport/connection.rs index 360149bb..2188f2bd 100644 --- a/dubbo/src/triple/transport/connection.rs +++ b/dubbo/src/triple/transport/connection.rs @@ -18,8 +18,8 @@ use std::task::Poll; use hyper::client::{conn::Builder, service::Connect}; +use logger::tracing::debug; use tower_service::Service; -use tracing::debug; use crate::{boxed, triple::transport::connector::get_connector}; diff --git a/dubbo/src/triple/transport/connector/http_connector.rs b/dubbo/src/triple/transport/connector/http_connector.rs index f324466b..255d64e0 100644 --- a/dubbo/src/triple/transport/connector/http_connector.rs +++ b/dubbo/src/triple/transport/connector/http_connector.rs @@ -22,6 +22,7 @@ use std::{ use http::Uri; use hyper::client::connect::dns::Name; +use logger::tracing; use tokio::net::TcpStream; use tower_service::Service; diff --git a/dubbo/src/triple/transport/connector/unix_connector.rs b/dubbo/src/triple/transport/connector/unix_connector.rs index 491ba23a..70ceda99 100644 --- a/dubbo/src/triple/transport/connector/unix_connector.rs +++ b/dubbo/src/triple/transport/connector/unix_connector.rs @@ -22,6 +22,7 @@ use std::{ use http::Uri; use hyper::client::connect::dns::Name; +use logger::tracing; use tokio::net::UnixStream; use tower_service::Service; diff --git a/dubbo/src/triple/transport/listener/mod.rs b/dubbo/src/triple/transport/listener/mod.rs index 31356194..e3a70d76 100644 --- a/dubbo/src/triple/transport/listener/mod.rs +++ b/dubbo/src/triple/transport/listener/mod.rs @@ -22,6 +22,7 @@ pub mod unix_listener; use std::net::SocketAddr; use async_trait::async_trait; +use logger::tracing; use tokio::io::{AsyncRead, AsyncWrite}; use super::io::BoxIO; diff --git a/dubbo/src/triple/transport/listener/tcp_listener.rs b/dubbo/src/triple/transport/listener/tcp_listener.rs index a7c94879..2ebbf4f3 100644 --- a/dubbo/src/triple/transport/listener/tcp_listener.rs +++ b/dubbo/src/triple/transport/listener/tcp_listener.rs @@ -21,6 +21,7 @@ use super::Listener; use async_trait::async_trait; use futures_core::Stream; use hyper::server::accept::Accept; +use logger::tracing; use tokio::net::{TcpListener as tokioTcpListener, TcpStream}; pub struct TcpListener { diff --git a/dubbo/src/triple/transport/listener/unix_listener.rs b/dubbo/src/triple/transport/listener/unix_listener.rs index 5034de56..add071a8 100644 --- a/dubbo/src/triple/transport/listener/unix_listener.rs +++ b/dubbo/src/triple/transport/listener/unix_listener.rs @@ -21,6 +21,7 @@ use super::Listener; use async_trait::async_trait; use futures_core::Stream; use hyper::server::accept::Accept; +use logger::tracing; use tokio::net::{UnixListener as tokioUnixListener, UnixStream}; pub struct UnixListener { diff --git a/dubbo/src/triple/transport/service.rs b/dubbo/src/triple/transport/service.rs index 9698276d..b306085d 100644 --- a/dubbo/src/triple/transport/service.rs +++ b/dubbo/src/triple/transport/service.rs @@ -20,6 +20,7 @@ use std::net::SocketAddr; use futures_core::Future; use http::{Request, Response}; use hyper::body::Body; +use logger::tracing; use tokio::time::Duration; use tower_service::Service; diff --git a/remoting/base/Cargo.toml b/remoting/base/Cargo.toml index 2b06bf97..43bef927 100644 --- a/remoting/base/Cargo.toml +++ b/remoting/base/Cargo.toml @@ -9,6 +9,6 @@ edition = "2021" bytes.workspace = true base.workspace = true thiserror.workspace = true -dashmap.workspacpe = true +dashmap.workspace = true protocol.workspace = true anyhow.workspace = true \ No newline at end of file diff --git a/remoting/base/src/codec.rs b/remoting/base/src/codec.rs index 6f1b54bd..c7a029cc 100644 --- a/remoting/base/src/codec.rs +++ b/remoting/base/src/codec.rs @@ -18,14 +18,12 @@ use std::sync::Arc; use anyhow::{anyhow, Error}; -use bytes; -use bytes::Bytes; +use bytes::{self, Bytes}; use dashmap::DashMap; use protocol::ProtocolName; -use crate::error::CodecError; -use crate::Response; +use crate::{error::CodecError, Response}; #[derive(Clone)] pub struct BoxedCodec(Arc); @@ -94,9 +92,11 @@ mod tests { use bytes::Bytes; - use crate::codec::{BoxedCodec, CodecRegistry, CodecResult}; - use crate::error::CodecError; - use crate::Codec; + use crate::{ + codec::{BoxedCodec, CodecRegistry, CodecResult}, + error::CodecError, + Codec, + }; #[derive(Default)] struct TestCodec; diff --git a/remoting/base/src/exchange.rs b/remoting/base/src/exchange.rs index 266f1111..a816e988 100644 --- a/remoting/base/src/exchange.rs +++ b/remoting/base/src/exchange.rs @@ -16,8 +16,7 @@ */ use crate::error::CodecError; -use std::any::Any; -use std::sync::Arc; +use std::{any::Any, sync::Arc}; pub type BoxedExchangeBody = Arc; diff --git a/remoting/base/src/exchange_client.rs b/remoting/base/src/exchange_client.rs index d932f498..4fceca7d 100644 --- a/remoting/base/src/exchange_client.rs +++ b/remoting/base/src/exchange_client.rs @@ -16,13 +16,19 @@ */ use base::Url; -use std::sync::atomic::{AtomicBool, AtomicI32, Ordering}; -use std::sync::Arc; -use std::time; -use std::time::Duration; +use std::{ + sync::{ + atomic::{AtomicBool, AtomicI32, Ordering}, + Arc, + }, + time, + time::Duration, +}; -use crate::error::ClientError; -use crate::exchange::{Request, Response}; +use crate::{ + error::ClientError, + exchange::{Request, Response}, +}; pub struct BoxedClient(Arc); diff --git a/remoting/base/src/lib.rs b/remoting/base/src/lib.rs index 436e0e17..8dc23f17 100644 --- a/remoting/base/src/lib.rs +++ b/remoting/base/src/lib.rs @@ -27,6 +27,4 @@ pub mod exchange; pub mod exchange_client; pub mod exchange_server; -pub use exchange::BoxedExchangeBody; -pub use exchange::Request; -pub use exchange::Response; +pub use exchange::{BoxedExchangeBody, Request, Response}; From 8723f2eea232fbca614b731bbbdd9a2715cb5ca3 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sat, 4 Mar 2023 17:10:22 +0800 Subject: [PATCH 19/23] Ftr: remoting/exchange 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 044c987b95625ca22bd32172f4a6373010153a66 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Mon, 6 Mar 2023 09:09:42 +0800 Subject: [PATCH 20/23] Ftr: remoting/exchange abstraction design --- Cargo.toml | 3 +- .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++++++++------ protocol/base/Cargo.toml | 2 +- protocol/dubbo2/Cargo.toml | 4 +- protocol/triple/Cargo.toml | 2 +- protocol/triple/src/triple_invoker.rs | 7 +- remoting/base/Cargo.toml | 4 +- remoting/base/src/codec.rs | 3 +- remoting/base/src/error.rs | 2 +- 9 files changed, 130 insertions(+), 76 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a25c9ad5..c436a0d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,8 @@ logger = {path="./common/logger"} utils = {path="./common/utils"} base = {path="./common/base"} remoting-net = {path="./remoting/net"} -protocol = {path= "protocol/base" } +remoting-base = {path="./remoting/base"} +protocol-base = {path= "protocol/base" } protocol-dubbo2 = {path="./protocol/dubbo2"} protocol-triple = {path="./protocol/triple"} registry-zookeeper = {path="./registry/zookeeper"} 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/base/Cargo.toml b/protocol/base/Cargo.toml index 40bc289c..e3e8d86c 100644 --- a/protocol/base/Cargo.toml +++ b/protocol/base/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "protocol" +name = "protocol-base" version = "0.1.0" edition = "2021" diff --git a/protocol/dubbo2/Cargo.toml b/protocol/dubbo2/Cargo.toml index 09e950ca..1f39f12e 100644 --- a/protocol/dubbo2/Cargo.toml +++ b/protocol/dubbo2/Cargo.toml @@ -6,5 +6,5 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -remoting-net.workspace = true -protocol.workspace = true \ No newline at end of file +remoting-base.workspace = true +protocol-base.workspace = true diff --git a/protocol/triple/Cargo.toml b/protocol/triple/Cargo.toml index b342a3b1..7b4dd9f9 100644 --- a/protocol/triple/Cargo.toml +++ b/protocol/triple/Cargo.toml @@ -7,5 +7,5 @@ edition = "2021" [dependencies] remoting-net.workspace = true -protocol.workspace = true +protocol-base.workspace = true base.workspace = true diff --git a/protocol/triple/src/triple_invoker.rs b/protocol/triple/src/triple_invoker.rs index 4a2e74f1..6093e7d6 100644 --- a/protocol/triple/src/triple_invoker.rs +++ b/protocol/triple/src/triple_invoker.rs @@ -15,10 +15,9 @@ * limitations under the License. */ use base::{Node, Url}; -use protocol::{ - invocation::BoxInvocation, - invoker::{BaseInvoker, Invoker}, -}; + +use protocol_base::invocation::BoxInvocation; +use protocol_base::invoker::{BaseInvoker, Invoker}; use std::sync::Arc; pub struct TripleInvoker { diff --git a/remoting/base/Cargo.toml b/remoting/base/Cargo.toml index 43bef927..f5f2efcd 100644 --- a/remoting/base/Cargo.toml +++ b/remoting/base/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "remoting-exchange" +name = "remoting-base" version = "0.1.0" edition = "2021" @@ -10,5 +10,5 @@ bytes.workspace = true base.workspace = true thiserror.workspace = true dashmap.workspace = true -protocol.workspace = true +protocol-base.workspace = true anyhow.workspace = true \ No newline at end of file diff --git a/remoting/base/src/codec.rs b/remoting/base/src/codec.rs index c7a029cc..d53383d4 100644 --- a/remoting/base/src/codec.rs +++ b/remoting/base/src/codec.rs @@ -20,8 +20,7 @@ use std::sync::Arc; use anyhow::{anyhow, Error}; use bytes::{self, Bytes}; use dashmap::DashMap; - -use protocol::ProtocolName; +use protocol_base::ProtocolName; use crate::{error::CodecError, Response}; diff --git a/remoting/base/src/error.rs b/remoting/base/src/error.rs index f0098cb6..4351b755 100644 --- a/remoting/base/src/error.rs +++ b/remoting/base/src/error.rs @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -use protocol::ProtocolName; +use protocol_base::ProtocolName; use thiserror::Error; #[derive(Error, Debug)] From 52490d0e0db6627e590c9f57a91f34541758e9b6 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Mon, 6 Mar 2023 09:14:22 +0800 Subject: [PATCH 21/23] Ftr: remoting/exchange abstraction design --- Cargo.toml | 1 - .../echo/src/generated/grpc.examples.echo.rs | 179 ++++++---------- protocol/triple/src/triple_invoker.rs | 6 +- remoting/h2/Cargo.toml | 8 - remoting/h2/LICENSE | 202 ------------------ remoting/h2/src/lib.rs | 30 --- 6 files changed, 66 insertions(+), 360 deletions(-) delete mode 100644 remoting/h2/Cargo.toml delete mode 100644 remoting/h2/LICENSE delete mode 100644 remoting/h2/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index c436a0d0..735eda40 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,6 @@ members = [ "dubbo-build", "remoting/net", "remoting/http", - "remoting/h2", "remoting/zookeeper", "remoting/base", "remoting/xds", 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/triple/src/triple_invoker.rs b/protocol/triple/src/triple_invoker.rs index 6093e7d6..6756dce4 100644 --- a/protocol/triple/src/triple_invoker.rs +++ b/protocol/triple/src/triple_invoker.rs @@ -16,8 +16,10 @@ */ use base::{Node, Url}; -use protocol_base::invocation::BoxInvocation; -use protocol_base::invoker::{BaseInvoker, Invoker}; +use protocol_base::{ + invocation::BoxInvocation, + invoker::{BaseInvoker, Invoker}, +}; use std::sync::Arc; pub struct TripleInvoker { diff --git a/remoting/h2/Cargo.toml b/remoting/h2/Cargo.toml deleted file mode 100644 index 12a28045..00000000 --- a/remoting/h2/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[package] -name = "remoting-h2" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] diff --git a/remoting/h2/LICENSE b/remoting/h2/LICENSE deleted file mode 100644 index d6456956..00000000 --- a/remoting/h2/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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/remoting/h2/src/lib.rs b/remoting/h2/src/lib.rs deleted file mode 100644 index d64452d5..00000000 --- a/remoting/h2/src/lib.rs +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 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); - } -} From 9c84d3b9e0fa9482f9ad7d2b659b5e7f983583c7 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Mon, 6 Mar 2023 09:27:27 +0800 Subject: [PATCH 22/23] Ftr: remoting/exchange abstraction design --- remoting/base/src/{builder_client.rs => builder/client.rs} | 0 remoting/base/src/builder/mod.rs | 2 ++ remoting/base/src/{builder_server.rs => builder/server.rs} | 0 remoting/base/src/{exchange_client.rs => exchange/client.rs} | 0 remoting/base/src/{exchange.rs => exchange/mod.rs} | 2 ++ remoting/base/src/{exchange_server.rs => exchange/server.rs} | 0 remoting/base/src/lib.rs | 5 +---- 7 files changed, 5 insertions(+), 4 deletions(-) rename remoting/base/src/{builder_client.rs => builder/client.rs} (100%) create mode 100644 remoting/base/src/builder/mod.rs rename remoting/base/src/{builder_server.rs => builder/server.rs} (100%) rename remoting/base/src/{exchange_client.rs => exchange/client.rs} (100%) rename remoting/base/src/{exchange.rs => exchange/mod.rs} (97%) rename remoting/base/src/{exchange_server.rs => exchange/server.rs} (100%) diff --git a/remoting/base/src/builder_client.rs b/remoting/base/src/builder/client.rs similarity index 100% rename from remoting/base/src/builder_client.rs rename to remoting/base/src/builder/client.rs diff --git a/remoting/base/src/builder/mod.rs b/remoting/base/src/builder/mod.rs new file mode 100644 index 00000000..c07f47e0 --- /dev/null +++ b/remoting/base/src/builder/mod.rs @@ -0,0 +1,2 @@ +pub mod client; +pub mod server; diff --git a/remoting/base/src/builder_server.rs b/remoting/base/src/builder/server.rs similarity index 100% rename from remoting/base/src/builder_server.rs rename to remoting/base/src/builder/server.rs diff --git a/remoting/base/src/exchange_client.rs b/remoting/base/src/exchange/client.rs similarity index 100% rename from remoting/base/src/exchange_client.rs rename to remoting/base/src/exchange/client.rs diff --git a/remoting/base/src/exchange.rs b/remoting/base/src/exchange/mod.rs similarity index 97% rename from remoting/base/src/exchange.rs rename to remoting/base/src/exchange/mod.rs index a816e988..968b6cd1 100644 --- a/remoting/base/src/exchange.rs +++ b/remoting/base/src/exchange/mod.rs @@ -17,6 +17,8 @@ use crate::error::CodecError; use std::{any::Any, sync::Arc}; +pub mod client; +pub mod server; pub type BoxedExchangeBody = Arc; diff --git a/remoting/base/src/exchange_server.rs b/remoting/base/src/exchange/server.rs similarity index 100% rename from remoting/base/src/exchange_server.rs rename to remoting/base/src/exchange/server.rs diff --git a/remoting/base/src/lib.rs b/remoting/base/src/lib.rs index 8dc23f17..0417afc6 100644 --- a/remoting/base/src/lib.rs +++ b/remoting/base/src/lib.rs @@ -19,12 +19,9 @@ allow(dead_code, unused_imports, unused_variables, unused_mut) )] pub use codec::Codec; -pub mod builder_client; -pub mod builder_server; +pub mod builder; pub mod codec; pub mod error; pub mod exchange; -pub mod exchange_client; -pub mod exchange_server; pub use exchange::{BoxedExchangeBody, Request, Response}; From 96f19070112fabeda729efeb90450fee50cb432c Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Mon, 6 Mar 2023 09:36:16 +0800 Subject: [PATCH 23/23] Ftr: remoting/exchange abstraction design --- remoting/base/src/builder/mod.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/remoting/base/src/builder/mod.rs b/remoting/base/src/builder/mod.rs index c07f47e0..069b5308 100644 --- a/remoting/base/src/builder/mod.rs +++ b/remoting/base/src/builder/mod.rs @@ -1,2 +1,18 @@ +/* + * 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 client; pub mod server;