use super::*;
impl Drop for InlineHookGuard {
fn drop(&mut self) {
let Self { key } = self;
let value: usize = key.load(sync::atomic::Ordering::Relaxed);
unregister_inline_hook(value);
}
}
impl<F> Drop for InlineDropGuard<F> {
#[inline(always)]
fn drop(&mut self) {
let Self { ptr } = self;
unsafe {
ptr::drop_in_place(*ptr);
}
}
}
unsafe impl Send for InlineHookCall<'_> {}
impl<'a> InlineHookCall<'a> {
#[inline(always)]
pub(crate) fn new(stream: &'a mut Stream, ctx: &'a mut Context, start: InlineStartFn) -> Self {
Self {
stream,
ctx,
start,
state: InlinePollState::Uninit,
storage: MaybeUninit::uninit(),
_pinned: PhantomPinned,
}
}
}
impl Drop for InlineHookCall<'_> {
#[inline(always)]
fn drop(&mut self) {
let Self { state, storage, .. } = self;
if matches!(state, InlinePollState::Uninit | InlinePollState::Done) {
return;
}
let previous: InlinePollState = mem::replace(state, InlinePollState::Done);
if let InlinePollState::Inline { drop_fn, .. } = previous {
let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
unsafe {
drop_fn(ptr);
}
}
}
}
impl Future for InlineHookCall<'_> {
type Output = Status;
#[inline(always)]
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
let Self {
stream,
ctx,
start,
state,
storage,
..
} = unsafe { self.get_unchecked_mut() };
match state {
InlinePollState::Uninit => {
let stream_addr: usize = (&mut **stream).into();
let ctx_addr: usize = (&mut **ctx).into();
let slot: *mut u8 = storage.as_mut_ptr().cast::<u8>();
let slot_len: usize = mem::size_of::<[usize; INLINE_FUTURE_WORDS]>();
match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) {
InlineStartOutcome::Ready(status) => Poll::Ready(status),
InlineStartOutcome::PendingInline { poll_fn, drop_fn } => {
*state = InlinePollState::Inline { poll_fn, drop_fn };
Poll::Pending
}
InlineStartOutcome::PendingBoxed(future) => {
*state = InlinePollState::Boxed(future);
Poll::Pending
}
}
}
InlinePollState::Inline { poll_fn, drop_fn } => {
let poll_entry: InlinePollFn = *poll_fn;
let drop_entry: unsafe fn(*mut u8) = *drop_fn;
let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
match unsafe { poll_entry(ptr, cx) } {
Poll::Ready(status) => {
*state = InlinePollState::Done;
unsafe {
drop_entry(ptr);
}
Poll::Ready(status)
}
Poll::Pending => Poll::Pending,
}
}
InlinePollState::Boxed(future) => match future.as_mut().poll(cx) {
Poll::Ready(status) => {
*state = InlinePollState::Done;
Poll::Ready(status)
}
Poll::Pending => Poll::Pending,
},
InlinePollState::Done => Poll::Ready(Status::default()),
}
}
}
unsafe impl Send for InlineHookChain<'_> {}
impl<'a> InlineHookChain<'a> {
#[inline(always)]
pub(crate) fn new(
stream: &'a mut Stream,
ctx: &'a mut Context,
hooks: &'a [CompiledHook],
) -> Self {
Self {
stream,
ctx,
hooks,
index: 0,
state: InlinePollState::Uninit,
storage: MaybeUninit::uninit(),
_pinned: PhantomPinned,
}
}
}
impl Drop for InlineHookChain<'_> {
#[inline(always)]
fn drop(&mut self) {
let Self { state, storage, .. } = self;
if matches!(state, InlinePollState::Uninit | InlinePollState::Done) {
return;
}
let previous: InlinePollState = mem::replace(state, InlinePollState::Done);
if let InlinePollState::Inline { drop_fn, .. } = previous {
let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
unsafe {
drop_fn(ptr);
}
}
}
}
impl Future for InlineHookChain<'_> {
type Output = Status;
#[inline(always)]
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
let Self {
stream,
ctx,
hooks,
index,
state,
storage,
..
} = unsafe { self.get_unchecked_mut() };
match state {
InlinePollState::Inline { poll_fn, drop_fn } => {
let poll_entry: InlinePollFn = *poll_fn;
let drop_entry: unsafe fn(*mut u8) = *drop_fn;
let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
match unsafe { poll_entry(ptr, cx) } {
Poll::Ready(status) => {
*state = InlinePollState::Uninit;
unsafe {
drop_entry(ptr);
}
if status.is_reject() {
return Poll::Ready(status);
}
}
Poll::Pending => return Poll::Pending,
}
}
InlinePollState::Boxed(future) => match future.as_mut().poll(cx) {
Poll::Ready(status) => {
*state = InlinePollState::Uninit;
if status.is_reject() {
return Poll::Ready(status);
}
}
Poll::Pending => return Poll::Pending,
},
InlinePollState::Uninit => {}
InlinePollState::Done => return Poll::Ready(Status::Continue),
}
let stream_addr: usize = (&mut **stream).into();
let ctx_addr: usize = (&mut **ctx).into();
let slot: *mut u8 = storage.as_mut_ptr().cast::<u8>();
let slot_len: usize = mem::size_of::<[usize; INLINE_FUTURE_WORDS]>();
let total: usize = hooks.len();
while *index < total {
let hook: &CompiledHook = &hooks[*index];
*index += 1;
match hook {
CompiledHook::Inline(start) => {
match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) {
InlineStartOutcome::Ready(status) => {
if status.is_reject() {
return Poll::Ready(status);
}
}
InlineStartOutcome::PendingInline { poll_fn, drop_fn } => {
*state = InlinePollState::Inline { poll_fn, drop_fn };
return Poll::Pending;
}
InlineStartOutcome::PendingBoxed(future) => {
*state = InlinePollState::Boxed(future);
return Poll::Pending;
}
}
}
CompiledHook::Dynamic(handler) => {
let mut future: FutureBox<Status> = handler(stream, ctx);
match future.as_mut().poll(cx) {
Poll::Ready(status) => {
if status.is_reject() {
return Poll::Ready(status);
}
}
Poll::Pending => {
*state = InlinePollState::Boxed(future);
return Poll::Pending;
}
}
}
}
}
Poll::Ready(Status::Continue)
}
}
impl CompiledHook {
#[inline(always)]
pub(crate) async fn call(&self, stream: &mut Stream, ctx: &mut Context) -> Status {
match self {
Self::Inline(start) => InlineHookCall::new(stream, ctx, *start).await,
Self::Dynamic(handler) => handler(stream, ctx).await,
}
}
}
impl CompiledPipeline {
pub(crate) fn from_server(server: &Server) -> Self {
let matcher: &RouteMatcher = server.get_route_matcher();
let static_count: usize = matcher.get_static_route().len();
let mut small_static_routes: SmallStaticRoutes = if static_count <= SMALL_STATIC_ROUTE_LIMIT
{
Vec::with_capacity(static_count)
} else {
Vec::new()
};
let mut static_routes: HashMapXxHash3_64<String, CompiledHook> = hash_map_xx_hash3_64();
let mut min_static_len: usize = usize::MAX;
let mut max_static_len: usize = 0;
for (path, handler) in matcher.get_static_route().iter() {
let len: usize = path.len();
if len < min_static_len {
min_static_len = len;
}
if len > max_static_len {
max_static_len = len;
}
let compiled: CompiledHook = lookup_inline_hook(handler);
if static_count <= SMALL_STATIC_ROUTE_LIMIT {
small_static_routes.push((path.clone(), compiled));
} else {
static_routes.insert(path.clone(), compiled);
}
}
let max_dyn_seg: usize = matcher
.get_dynamic_route()
.keys()
.copied()
.max()
.unwrap_or(0);
let has_dynamic: bool = !matcher.get_dynamic_route().is_empty();
let mut dynamic_routes: CompiledPatternBuckets = if has_dynamic {
vec![Vec::new(); max_dyn_seg + 1]
} else {
Vec::new()
};
for (&count, list) in matcher.get_dynamic_route().iter() {
let compiled: Vec<(RoutePattern, CompiledHook)> = list
.iter()
.map(|(pattern, handler): &(RoutePattern, ServerHookHandler)| {
(pattern.clone(), lookup_inline_hook(handler))
})
.collect();
dynamic_routes[count] = compiled;
}
let max_regex_seg: usize = matcher.get_regex_route().keys().copied().max().unwrap_or(0);
let has_regex: bool = !matcher.get_regex_route().is_empty();
let mut regex_routes: CompiledPatternBuckets = if has_regex {
vec![Vec::new(); max_regex_seg + 1]
} else {
Vec::new()
};
let mut regex_tail_routes: CompiledTailRegexRoutes = Vec::new();
for (&count, list) in matcher.get_regex_route().iter() {
let mut compiled: Vec<(RoutePattern, CompiledHook)> = Vec::with_capacity(list.len());
for (pattern, handler) in list.iter() {
let hook: CompiledHook = lookup_inline_hook(handler);
if pattern.has_tail_regex() {
regex_tail_routes.push((count, pattern.clone(), hook.clone()));
}
compiled.push((pattern.clone(), hook));
}
regex_routes[count] = compiled;
}
let request_middleware: Vec<CompiledHook> = server
.get_request_middleware()
.iter()
.map(lookup_inline_hook)
.collect();
let response_middleware: Vec<CompiledHook> = server
.get_response_middleware()
.iter()
.map(lookup_inline_hook)
.collect();
Self {
small_static_routes,
static_routes,
min_static_len,
max_static_len,
dynamic_routes,
has_dynamic,
regex_routes,
regex_tail_routes,
has_regex,
request_middleware,
response_middleware,
}
}
#[inline(always)]
pub(crate) fn resolve_route(
&self,
params: &mut HashMapXxHash3_64<String, String>,
path: &str,
) -> Option<&CompiledHook> {
let Self {
small_static_routes,
static_routes,
min_static_len,
max_static_len,
dynamic_routes,
has_dynamic,
regex_routes,
regex_tail_routes,
has_regex,
..
} = self;
let path_len: usize = path.len();
if path_len >= *min_static_len && path_len <= *max_static_len {
if !small_static_routes.is_empty() {
let path_bytes: &[u8] = path.as_bytes();
for (route_path, hook) in small_static_routes.iter() {
if route_path.as_bytes() == path_bytes {
return Some(hook);
}
}
} else if let Some(hook) = static_routes.get(path) {
return Some(hook);
}
}
if !*has_dynamic && !*has_regex {
return None;
}
let trimmed: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
let segment_count: usize = if trimmed.is_empty() {
0
} else {
let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0];
let mut count: usize = 1;
for &byte in trimmed.as_bytes() {
if byte == sep {
count += 1;
}
}
count
};
if *has_dynamic && let Some(routes) = dynamic_routes.get(segment_count) {
for (pattern, hook) in routes.iter() {
if pattern.try_match_path_into(path, params) {
return Some(hook);
}
}
}
if *has_regex {
if let Some(routes) = regex_routes.get(segment_count) {
for (pattern, hook) in routes.iter() {
if pattern.try_match_path_into(path, params) {
return Some(hook);
}
}
}
for (pattern_seg_count, pattern, hook) in regex_tail_routes.iter() {
if *pattern_seg_count != segment_count
&& *pattern_seg_count <= segment_count + 1
&& pattern.try_match_path_into(path, params)
{
return Some(hook);
}
}
}
None
}
#[inline(always)]
fn response_allows_keep_alive(ctx: &Context, req_keep_alive: bool) -> bool {
if !req_keep_alive {
return false;
}
let headers: &ResponseHeaders = ctx.get_response().get_headers();
if headers.is_empty() {
return true;
}
if let Some(values) = headers.get(CONNECTION) {
for header_value in values {
if header_value == KEEP_ALIVE {
continue;
}
for token in header_value.split(COMMA) {
if token.trim().eq_ignore_ascii_case(CLOSE) {
return false;
}
}
}
return true;
}
for (name, values) in headers {
if name.eq_ignore_ascii_case(CONNECTION) {
for header_value in values {
for token in header_value.split(COMMA) {
if token.trim().eq_ignore_ascii_case(CLOSE) {
return false;
}
}
}
}
}
true
}
#[inline(always)]
pub(crate) async fn run_request(
&self,
stream: &mut Stream,
ctx: &mut Context,
target: Option<String>,
) -> bool {
let Self {
request_middleware,
response_middleware,
..
} = self;
let keep_alive: bool = ctx.get_request().is_enable_keep_alive();
ctx.set_original_head(Some(ctx.get_request().get_method().is_head()));
if ctx.get_request().get_version().is_http1_1() {
ctx.get_mut_response().reset();
} else {
let version: HttpVersion = ctx.get_request().get_version().clone();
ctx.get_mut_response().reset().set_version(version);
}
ctx.clear_route_params();
ctx.reset_request_attributes();
match target {
Some(target) => {
ctx.set_request_target(target);
}
None => {
let parsed_target: Option<&str> = stream.get_request_target_slice().or_else(|| {
let line: &str = stream.get_line_buffer();
line.split_ascii_whitespace().nth(1)
});
if let Some(target) = parsed_target {
ctx.set_request_target(target);
} else {
let _: Option<String> = ctx.take_original_target();
}
}
}
stream.set_closed(false);
if !request_middleware.is_empty()
&& InlineHookChain::new(stream, ctx, request_middleware)
.await
.is_reject()
{
return stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive));
}
let matched_hook: Option<&CompiledHook> = {
let path: &str = ctx.request.get_path().as_str();
self.resolve_route(&mut ctx.route_params, path)
};
if let Some(hook) = matched_hook
&& hook.call(stream, ctx).await.is_reject()
{
return stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive));
}
if !response_middleware.is_empty()
&& InlineHookChain::new(stream, ctx, response_middleware)
.await
.is_reject()
{
return stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive));
}
stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive))
}
}