Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add "ip" feature #250

Merged
merged 3 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Select a native async runtime
npm create cloudflare ./path/to/project -- --template https://github.com/ohkami-rs/ohkami-templates/worker
```

Then your project directory has `wrangler.toml`, `package.json` and a Rust library crate. Local dev by `npm run dev` and deploy by `npm run deploy` !
then your project directory has `wrangler.toml`, `package.json` and a Rust library crate. Local dev by `npm run dev` and deploy by `npm run deploy` !

See README of the [template](https://github.com/ohkami-rs/ohkami-templates/tree/main/worker) for details.

Expand Down Expand Up @@ -140,6 +140,10 @@ async fn main() {
}
```

### `"ip"`:remote IP address

Get and hold remote peer's IP address

### `"nightly"`:enable nightly-only functionalities

- try response
Expand Down
3 changes: 3 additions & 0 deletions Taskfile.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,11 @@ tasks:
dir: ohkami
cmds:
- cargo check --lib --features rt_tokio,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,ip,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,sse,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,sse,ws,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,graceful,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_tokio,graceful,ip,{{.MAYBE_NIGHTLY}}

check_rt_async-std:
vars:
Expand All @@ -114,6 +116,7 @@ tasks:
dir: ohkami
cmds:
- cargo check --lib --features rt_async-std,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_async-std,ip,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_async-std,sse,{{.MAYBE_NIGHTLY}}
- cargo check --lib --features rt_async-std,sse,ws,{{.MAYBE_NIGHTLY}}

Expand Down
2 changes: 1 addition & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ members = [

[workspace.dependencies]
# set `default-features = false` to assure "DEBUG" feature be off even when DEBUGing `../ohkami`
ohkami = { path = "../ohkami", default-features = false, features = ["rt_tokio", "testing", "sse", "ws"] }
ohkami = { path = "../ohkami", default-features = false, features = ["rt_tokio", "testing", "sse", "ws", "ip"] }
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.7.3", features = ["runtime-tokio-native-tls", "postgres", "macros", "chrono", "uuid"] }
tracing = "0.1"
Expand Down
14 changes: 3 additions & 11 deletions examples/hello/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,9 @@ mod fangs {
#[derive(Clone)]
pub struct LogRequest;
impl FangAction for LogRequest {
fn fore<'a>(&'a self, req: &'a mut Request) -> impl std::future::Future<Output = Result<(), Response>> + Send {
let __method__ = req.method;
let __path__ = req.path.str();

tracing::info!("\n\
Got request:\n\
[ method ] {__method__}\n\
[ path ] {__path__}\n\
");

async {Ok(())}
async fn fore<'a>(&'a self, req: &'a mut Request) -> Result<(), Response> {
tracing::info!("\nGot request: {req:#?}");
Ok(())
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions ohkami/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ testing = []
sse = ["ohkami_lib/stream"]
ws = ["dep:sha1"]
graceful = ["rt_tokio", "tokio/signal", "tokio/macros"]
ip = []

##### DEBUG #####
DEBUG = [
Expand All @@ -60,6 +61,7 @@ DEBUG = [
# "testing",
# "sse",
# "ws",
# "ip",
# "rt_tokio",
# #"rt_async-std",
# #"rt_worker",
Expand Down
4 changes: 2 additions & 2 deletions ohkami/src/fang/builtin/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ impl<Payload: for<'de> Deserialize<'de>> JWT<Payload> {
let req_bytes = TestRequest::GET("/")
.header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDY4MTEwNzUsInVzZXJfaWQiOiI5ZmMwMDViMi1mODU4LTQzMzYtODkwYS1mMWEyYWVmNjBhMjQifQ.AKp-0zvKK4Hwa6qCgxskckD04Snf0gpSG7U1LOpcC_I")
.encode();
let mut req = Request::init();
let mut req = Request::init(#[cfg(feature="ip")] crate::utils::IP_0000);
let mut req = unsafe {Pin::new_unchecked(&mut req)};
req.as_mut().read(&mut &req_bytes[..]).await.ok();

Expand All @@ -427,7 +427,7 @@ impl<Payload: for<'de> Deserialize<'de>> JWT<Payload> {
// Modifed last `I` of the value above to `X`
.header("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDY4MTEwNzUsInVzZXJfaWQiOiI5ZmMwMDViMi1mODU4LTQzMzYtODkwYS1mMWEyYWVmNjBhMjQifQ.AKp-0zvKK4Hwa6qCgxskckD04Snf0gpSG7U1LOpcC_X")
.encode();
let mut req = Request::init();
let mut req = Request::init(#[cfg(feature="ip")] crate::utils::IP_0000);
let mut req = unsafe {Pin::new_unchecked(&mut req)};
req.as_mut().read(&mut &req_bytes[..]).await.ok();

Expand Down
22 changes: 15 additions & 7 deletions ohkami/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,25 @@
Can't activate multiple `rt_*` features at once!
"}

#[cfg(any(
all(feature="graceful", not(feature="rt_tokio")),
))] compile_error! {"
In current versoin, `graceful` feature is only supported on `rt_tokio`.
Please wait for future development for other runtimes...
"}

#[cfg(not(feature="DEBUG"))]
#[cfg(all(feature="rt_worker", not(target_arch="wasm32")))]
compile_error! {"
`rt_worker` must be activated on `wasm32` target!
(We recommend to touch `.cargo/config.toml`: `[build] target = \"wasm32-unknown-unknown\"`)
"}

#[cfg(all(feature="rt_worker", feature="ip"))]
compile_error! {"
Can't activate `ip` feature on `rt_worker`!
"}

#[cfg(any(
all(feature="graceful", not(feature="rt_tokio")),
))] compile_error! {"
In current versoin, `graceful` feature is only supported on `rt_tokio`.
Please wait for future development for other runtimes...
"}


#[allow(unused)]
mod __rt__ {
Expand Down Expand Up @@ -231,6 +236,9 @@ pub mod utils {

Timeout { proc, sleep: crate::__rt__::sleep(duration) }
}

#[cfg(feature="ip")]
pub(crate) const IP_0000: std::net::IpAddr = std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0));
}

#[cfg(feature="rt_worker")]
Expand Down
18 changes: 17 additions & 1 deletion ohkami/src/ohkami/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,8 +282,16 @@ impl Ohkami {
accept = listener.accept() => {
crate::DEBUG!("Accepted {accept:#?}");

#[cfg(not(feature="ip"))]
let Ok((connection, _)) = accept else {continue};
let session = Session::new(router.clone(), connection);
#[cfg(feature="ip")]
let Ok((connection, addr)) = accept else {continue};

let session = Session::new(
router.clone(),
connection,
#[cfg(feature="ip")] addr.ip()
);

let close_rx = close_rx.clone();
__rt__::task::spawn(async {
Expand All @@ -305,12 +313,16 @@ impl Ohkami {
}
#[cfg(all(feature="rt_tokio", not(feature="graceful")))] {
loop {
#[cfg(not(feature="ip"))]
let Ok((connection, _)) = listener.accept().await else {continue};
#[cfg(feature="ip")]
let Ok((connection, addr)) = listener.accept().await else {continue};

__rt__::task::spawn({
Session::new(
router.clone(),
connection,
#[cfg(feature="ip")] addr.ip()
).manage()
});
}
Expand All @@ -321,10 +333,14 @@ impl Ohkami {
while let Some(connection) = listener.incoming().next().await {
let Ok(connection) = connection else {continue};

#[cfg(feature="ip")]
let Ok(addr) = connection.peer_addr() else {continue};

__rt__::task::spawn({
Session::new(
router.clone(),
connection,
#[cfg(feature="ip")] addr.ip()
).manage()
});
}
Expand Down
12 changes: 10 additions & 2 deletions ohkami/src/request/_test_parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use super::{Request, Method, BUF_SIZE, Path, QueryParams, Store};

macro_rules! assert_parse {
($case:expr, $expected:expr) => {
let mut actual = Request::init();
let mut actual = Request::init(#[cfg(feature="ip")] crate::utils::IP_0000);
let mut actual = unsafe {Pin::new_unchecked(&mut actual)};
actual.as_mut().read(&mut $case.as_bytes()).await.ok();

Expand Down Expand Up @@ -79,6 +79,9 @@ fn parse_path() {
], None),
payload: None,
store: Store::init(),

#[cfg(feature="ip")]
addr: crate::utils::IP_0000
});


Expand Down Expand Up @@ -109,6 +112,9 @@ fn parse_path() {
br#"{"name":"kanarus","age":20}"#
))),
store: Store::init(),

#[cfg(feature="ip")]
addr: crate::utils::IP_0000
});

{
Expand Down Expand Up @@ -154,7 +160,9 @@ fn parse_path() {
),
payload: Some(CowSlice::Own(Vec::from("first_name=John&last_name=Doe&action=Submit").into())),
store: Store::init(),
// #[cfg(feature="websocket")] upgrade_id: None,

#[cfg(feature="ip")]
addr: crate::utils::IP_0000
});
}
}
54 changes: 34 additions & 20 deletions ohkami/src/request/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,13 +160,20 @@ pub struct Request {
pub headers: RequestHeaders,

pub payload: Option<CowSlice>,

store: Store,

#[cfg(feature="ip")]
pub addr: std::net::IpAddr
}

impl Request {
#[cfg(any(feature="rt_tokio",feature="rt_async-std",feature="rt_worker"))]
#[inline]
pub(crate) fn init() -> Self {
pub(crate) fn init(
#[cfg(feature="ip")]
addr: std::net::IpAddr
) -> Self {
Self {
#[cfg(any(feature="rt_tokio",feature="rt_async-std"))]
__buf__: Box::new([0; BUF_SIZE]),
Expand All @@ -184,6 +191,9 @@ impl Request {
headers: RequestHeaders::init(),
payload: None,
store: Store::init(),

#[cfg(feature="ip")]
addr
}
}
#[cfg(any(feature="rt_tokio",feature="rt_async-std"))]
Expand Down Expand Up @@ -431,22 +441,22 @@ impl Request {
const _: () = {
impl std::fmt::Debug for Request {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("Request");
let d = &mut d;

d
.field("method", &self.method)
.field("path", &self.path.str())
.field("queries", &self.query)
.field("headers", &self.headers);
if let Some(payload) = self.payload.as_ref().map(|cs| unsafe {cs.as_bytes()}) {
f.debug_struct("Request")
.field("method", &self.method)
.field("path", &self.path.str())
.field("queries", &self.query)
.field("headers", &self.headers)
.field("payload", &String::from_utf8_lossy(payload))
.finish()
} else {
f.debug_struct("Request")
.field("method", &self.method)
.field("path", &self.path.str())
.field("queries", &self.query)
.field("headers", &self.headers)
.finish()
d.field("payload", &String::from_utf8_lossy(payload));
}
#[cfg(feature="ip")] {
d.field("ip_address", &self.addr);
}

d.finish()
}
}
};
Expand All @@ -455,11 +465,15 @@ const _: () = {
#[cfg(test)] const _: () = {
impl PartialEq for Request {
fn eq(&self, other: &Self) -> bool {
self.method == other.method &&
unsafe {self.path.normalized_bytes() == other.path.normalized_bytes()} &&
self.query == other.query &&
self.headers == other.headers &&
self.payload == other.payload
#[cfg(feature="ip")] if self.addr != other.addr {
return false
}

self.method == other.method &&
unsafe {self.path.normalized_bytes() == other.path.normalized_bytes()} &&
self.query == other.query &&
self.headers == other.headers &&
self.payload == other.payload
}
}
};
15 changes: 12 additions & 3 deletions ohkami/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,24 @@ mod env {
pub(crate) struct Session {
router: Arc<RadixRouter>,
connection: TcpStream,

#[cfg(feature="ip")]
addr: std::net::IpAddr
}
impl Session {
pub(crate) fn new(
router: Arc<RadixRouter>,
connection: TcpStream,
router: Arc<RadixRouter>,
connection: TcpStream,

#[cfg(feature="ip")]
addr: std::net::IpAddr
) -> Self {
Self {
router,
connection,

#[cfg(feature="ip")]
addr
}
}

Expand All @@ -64,7 +73,7 @@ impl Session {
}

match timeout_in(Duration::from_secs(env::OHKAMI_KEEPALIVE_TIMEOUT()), async {
let mut req = Request::init();
let mut req = Request::init(#[cfg(feature="ip")] self.addr);
let mut req = unsafe {Pin::new_unchecked(&mut req)};
loop {
req.clear();
Expand Down
2 changes: 1 addition & 1 deletion ohkami/src/testing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl TestingOhkami {
let router = self.0.clone();

let res = async move {
let mut request = Request::init();
let mut request = Request::init(#[cfg(feature="ip")] crate::utils::IP_0000);
let mut request = unsafe {Pin::new_unchecked(&mut request)};

let res = match request.as_mut().read(&mut &req.encode()[..]).await {
Expand Down
Loading