From 02ad8afd29fedda2daf52eb6f3f9954d0c564887 Mon Sep 17 00:00:00 2001 From: liuyuancheng Date: Sun, 26 Feb 2023 16:43:45 +0800 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 4/6] 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 5/6] 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 6/6] 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"); } } });