Skip to content

Commit

Permalink
rename utils to util
Browse files Browse the repository at this point in the history
  • Loading branch information
kanarus committed Sep 26, 2024
1 parent 244efe2 commit a216ae8
Show file tree
Hide file tree
Showing 20 changed files with 156 additions and 157 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ Use some reverse proxy to do with HTTP/2,3.
```rust,no_run
use ohkami::prelude::*;
use ohkami::typed::DataStream;
use ohkami::utils::stream;
use ohkami::util::stream;
use {tokio::time::sleep, std::time::Duration};
async fn sse() -> DataStream<String> {
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/imf_fixdate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
extern crate test;

use ohkami_lib::time::UTCDateTime;
use ohkami::utils::unix_timestamp;
use ohkami::util::unix_timestamp;


#[bench] fn format_imf_fixdate(b: &mut test::Bencher) {
Expand Down
2 changes: 1 addition & 1 deletion benches_rt/glommio/src/bin/param.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use ohkami::prelude::*;
use ohkami::utils::num_cpus;
use ohkami::util::num_cpus;
use glommio::{LocalExecutorPoolBuilder, PoolPlacement, CpuSet};


Expand Down
2 changes: 1 addition & 1 deletion examples/openai/src/bin/reqwest_chat_completion.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::env;
use ohkami::utils::{StreamExt, stream};
use ohkami::util::{StreamExt, stream};
use openai::models::{ChatCompletions, ChatMessage, Role};


Expand Down
2 changes: 1 addition & 1 deletion examples/openai/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use models::{ChatMessage, ChatCompletions, Role};
use ohkami::prelude::*;
use ohkami::format::Text;
use ohkami::typed::DataStream;
use ohkami::utils::{StreamExt, stream};
use ohkami::util::{StreamExt, stream};


#[tokio::main]
Expand Down
2 changes: 1 addition & 1 deletion examples/realworld/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::sync::OnceLock;
use ohkami::utils::unix_timestamp;
use ohkami::util::unix_timestamp;
use ohkami::serde::{Serialize, Deserialize};
use ohkami::fang::{JWT, JWTToken};
use uuid::Uuid;
Expand Down
2 changes: 1 addition & 1 deletion examples/sse/src/bin/from_iter_async.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use ohkami::typed::DataStream;
use ohkami::utils::StreamExt;
use ohkami::util::StreamExt;


#[tokio::main]
Expand Down
2 changes: 1 addition & 1 deletion examples/sse/src/bin/queue_stream.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use ohkami::utils::{stream, StreamExt};
use ohkami::util::{stream, StreamExt};
use tokio::time::sleep;


Expand Down
8 changes: 4 additions & 4 deletions ohkami/src/fang/builtin/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ use crate::{Fang, FangProc, IntoResponse, Request, Response};
/// ) -> Result<JSON<AuthResponse>, Response> {
/// Ok(JSON(AuthResponse {
/// token: our_jwt().issue(OurJWTPayload {
/// iat: ohkami::utils::unix_timestamp(),
/// iat: ohkami::util::unix_timestamp(),
/// user_name: req.name.to_string()
/// })
/// }))
Expand Down Expand Up @@ -314,7 +314,7 @@ impl<Payload: for<'de> Deserialize<'de>> JWT<Payload> {
.ok_or_else(|| Response::BadRequest())?;
let payload: Payload = ::serde_json::from_slice(&base64::decode_url(payload_part))
.map_err(|_| Response::InternalServerError())?;
let now = crate::utils::unix_timestamp();
let now = crate::util::unix_timestamp();
if payload.get("nbf").is_some_and(|nbf| nbf.as_u64().unwrap_or(0) > now) {
return Err(Response::Unauthorized().with_text(UNAUTHORIZED_MESSAGE))
}
Expand Down Expand Up @@ -404,7 +404,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(crate::utils::IP_0000);
let mut req = Request::init(crate::util::IP_0000);
let mut req = unsafe {Pin::new_unchecked(&mut req)};
req.as_mut().read(&mut &req_bytes[..]).await.ok();

Expand All @@ -417,7 +417,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(crate::utils::IP_0000);
let mut req = Request::init(crate::util::IP_0000);
let mut req = unsafe {Pin::new_unchecked(&mut req)};
req.as_mut().read(&mut &req_bytes[..]).await.ok();

Expand Down
2 changes: 1 addition & 1 deletion ohkami/src/fang/builtin/timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const _: () = {
}
impl<Inner: FangProc> FangProc for TimeoutProc<Inner> {
async fn bite<'b>(&'b self, req: &'b mut Request) -> Response {
crate::utils::timeout_in(self.time, self.inner.bite(req)).await
crate::util::timeout_in(self.time, self.inner.bite(req)).await
.unwrap_or_else(|| Response::InternalServerError().with_text("timeout"))
}
}
Expand Down
131 changes: 2 additions & 129 deletions ohkami/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,141 +149,14 @@ pub mod ws;
#[cfg(feature="__rt__")]
pub mod testing;

pub mod utils {
#[doc(hidden)]
#[macro_export]
macro_rules! warning {
( $( $t:tt )* ) => {{
eprintln!( $( $t )* );

#[cfg(feature="rt_worker")]
worker::console_log!( $( $t )* );
}};
}

#[doc(hidden)]
#[macro_export]
macro_rules! push_unchecked {
($buf:ident <- $bytes:expr) => {
{
let (buf_len, bytes_len) = ($buf.len(), $bytes.len());
std::ptr::copy_nonoverlapping(
$bytes.as_ptr(),
$buf.as_mut_ptr().add(buf_len),
bytes_len
);
$buf.set_len(buf_len + bytes_len);
}
};
}

#[doc(hidden)]
#[macro_export]
macro_rules! DEBUG {
( $( $t:tt )* ) => {
#[cfg(feature="DEBUG")] {
println!( $( $t )* );
}
};
}

pub use crate::fang::FangAction;

#[cfg(feature="sse")]
pub use ohkami_lib::stream::{self, Stream, StreamExt};

#[cfg(not(feature="rt_worker"))]
/// ```
/// # let _ =
/// {
/// std::time::SystemTime::now()
/// .duration_since(std::time::UNIX_EPOCH)
/// .unwrap()
/// .as_secs()
/// }
/// # ;
/// ```
#[inline] pub fn unix_timestamp() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
}
#[cfg(feature="rt_worker")]
/// JavaScript `Date.now() / 1000` --as--> Rust `u64`
#[inline] pub fn unix_timestamp() -> u64 {
(worker::js_sys::Date::now() / 1000.) as _
}

pub struct ErrorMessage(pub String);
const _: () = {
impl std::fmt::Debug for ErrorMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::fmt::Display for ErrorMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for ErrorMessage {}
impl super::IntoResponse for ErrorMessage {
fn into_response(self) -> crate::Response {
crate::Response::InternalServerError().with_text(self.0)
}
}
};

#[cfg(feature="__rt_native__")]
pub fn timeout_in<T>(
duration: std::time::Duration,
proc: impl std::future::Future<Output = T>
) -> impl std::future::Future<Output = Option<T>> {
use std::task::Poll;
use std::pin::Pin;

struct Timeout<Sleep, Proc> { sleep: Sleep, proc: Proc }

impl<Sleep, Proc, T> std::future::Future for Timeout<Sleep, Proc>
where
Sleep: std::future::Future<Output = ()>,
Proc: std::future::Future<Output = T>,
{
type Output = Option<T>;

#[inline]
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
let Timeout { sleep, proc } = unsafe {self.get_unchecked_mut()};
match unsafe {Pin::new_unchecked(proc)}.poll(cx) {
Poll::Ready(t) => Poll::Ready(Some(t)),
Poll::Pending => unsafe {Pin::new_unchecked(sleep)}.poll(cx).map(|_| None)
}
}
}

#[cfg(feature="rt_glommio")]
/* for fang::builtin::timeout::Timeout::Proc::bite to return Send Future */
/* SAFETY: proc and sleep are executed on the same thread in rt_glommio */
/* ( glommio::timer::sleep itself returns not-Send Future because it's not needed due to the architecture ) */
unsafe impl<Sleep, Proc> Send for Timeout<Sleep, Proc> {}

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

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

#[cfg(feature="rt_glommio")]
pub use num_cpus;
}
pub mod util;

#[cfg(feature="rt_worker")]
pub use ::ohkami_macros::{worker, bindings};

pub mod prelude {
pub use crate::{Request, Response, IntoResponse, Method, Status};
pub use crate::utils::FangAction;
pub use crate::util::FangAction;
pub use crate::serde::{Serialize, Deserialize};
pub use crate::format::{JSON, Query};
pub use crate::fang::Memory;
Expand Down
2 changes: 1 addition & 1 deletion ohkami/src/ohkami/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ impl Ohkami {
/// *example_glommio.rs*
/// ```ignore
/// use ohkami::prelude::*;
/// use ohkami::utils::num_cpus;
/// use ohkami::util::num_cpus;
/// use glommio::{LocalExecutorPoolBuilder, PoolPlacement, CpuSet};
///
/// async fn hello() -> &'static str {
Expand Down
8 changes: 4 additions & 4 deletions ohkami/src/request/_test_parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn parse_path() {

macro_rules! assert_parse {
($case:expr, $expected:expr) => {
let mut actual = Request::init(crate::utils::IP_0000);
let mut actual = Request::init(crate::util::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 @@ -80,7 +80,7 @@ fn parse_path() {
], None),
payload: None,
store: Store::init(),
ip: crate::utils::IP_0000
ip: crate::util::IP_0000
});


Expand Down Expand Up @@ -111,7 +111,7 @@ fn parse_path() {
br#"{"name":"kanarus","age":20}"#
))),
store: Store::init(),
ip: crate::utils::IP_0000
ip: crate::util::IP_0000
});

{
Expand Down Expand Up @@ -157,7 +157,7 @@ fn parse_path() {
),
payload: Some(CowSlice::Own(Vec::from("first_name=John&last_name=Doe&action=Submit").into())),
store: Store::init(),
ip: crate::utils::IP_0000
ip: crate::util::IP_0000
});
}
}
2 changes: 1 addition & 1 deletion ohkami/src/request/from_request.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::borrow::Cow;
use crate::{utils::ErrorMessage, IntoResponse, Request, Response};
use crate::{util::ErrorMessage, IntoResponse, Request, Response};


/// "Retirieved from a `Request`".
Expand Down
4 changes: 2 additions & 2 deletions ohkami/src/response/_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ macro_rules! assert_bytes_eq {
#[crate::__rt__::test]
async fn test_response_into_bytes() {
let __now__ = ::ohkami_lib::imf_fixdate(
std::time::Duration::from_secs(crate::utils::unix_timestamp())
std::time::Duration::from_secs(crate::util::unix_timestamp())
);

let res = Response::NoContent();
Expand Down Expand Up @@ -107,7 +107,7 @@ async fn test_response_into_bytes() {
#[crate::__rt__::test]
async fn test_stream_response() {
let __now__ = ::ohkami_lib::imf_fixdate(
std::time::Duration::from_secs(crate::utils::unix_timestamp())
std::time::Duration::from_secs(crate::util::unix_timestamp())
);

fn repeat_by<T, F: Fn(usize) -> T + Unpin>(
Expand Down
4 changes: 2 additions & 2 deletions ohkami/src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use ohkami_lib::{CowSlice, Slice};
#[cfg(feature="__rt_native__")]
use crate::__rt__::AsyncWriter;
#[cfg(feature="sse")]
use crate::utils::StreamExt;
use crate::util::StreamExt;


/// # HTTP Response
Expand Down Expand Up @@ -124,7 +124,7 @@ impl Response {
#[inline(always)]
pub(crate) fn complete(&mut self) {
self.headers.set().Date(::ohkami_lib::imf_fixdate(
std::time::Duration::from_secs(crate::utils::unix_timestamp())
std::time::Duration::from_secs(crate::util::unix_timestamp())
));

match &self.content {
Expand Down
2 changes: 1 addition & 1 deletion ohkami/src/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{any::Any, pin::Pin, sync::Arc, time::Duration};
use std::panic::{AssertUnwindSafe, catch_unwind};
use crate::__rt__::TcpStream;
use crate::response::Upgrade;
use crate::utils::timeout_in;
use crate::util::timeout_in;
use crate::ohkami::router::RadixRouter;
use crate::{Request, Response};

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(#[cfg(feature="__rt_native__")] crate::utils::IP_0000);
let mut request = Request::init(#[cfg(feature="__rt_native__")] crate::util::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

0 comments on commit a216ae8

Please sign in to comment.