diff --git a/Cargo.toml b/Cargo.toml index 4119ca2f..9218e9a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ categories = ["network-programming", "web-programming"] exclude.workspace = true [workspace.package] -version = "23.3.2" +version = "23.4.0" readme = "README.md" edition = "2024" authors = ["root@devhub.vip"] @@ -86,13 +86,13 @@ members = [ ] [workspace.dependencies] -hyperlane = { path = ".", version = "23.3.2" } -http-type = { path = "type", version = "23.3.2" } -hyperlane-core = { path = "core", version = "23.3.2" } -http-request = { path = "request", version = "23.3.2" } -http-compress = { path = "compress", version = "23.3.2" } -http-constant = { path = "constant", version = "23.3.2" } -hyperlane-macros = { path = "macros", version = "23.3.2" } +hyperlane = { path = ".", version = "23.4.0" } +http-type = { path = "type", version = "23.4.0" } +hyperlane-core = { path = "core", version = "23.4.0" } +http-request = { path = "request", version = "23.4.0" } +http-compress = { path = "compress", version = "23.4.0" } +http-constant = { path = "constant", version = "23.4.0" } +hyperlane-macros = { path = "macros", version = "23.4.0" } h3 = "0.0.8" h2 = "0.4.20" diff --git a/compress/src/brotli/fn.rs b/compress/src/brotli/fn.rs index 8fb4f13c..3a436d91 100644 --- a/compress/src/brotli/fn.rs +++ b/compress/src/brotli/fn.rs @@ -106,35 +106,46 @@ pub fn encode_into(data: &[u8], out: &mut Vec) -> bool { let mut available_in: usize = data.len(); let mut input_offset: usize = 0; let mut total_out: Option = Some(0); - let mut scratch: [u8; BROTLI_ENCODE_SCRATCH_LEN] = [0u8; BROTLI_ENCODE_SCRATCH_LEN]; - loop { - let mut available_out: usize = scratch.len(); - let mut output_offset: usize = 0; - let ok: bool = state.compress_stream( - BrotliEncoderOperation::BROTLI_OPERATION_FINISH, - &mut available_in, - data, - &mut input_offset, - &mut available_out, - &mut scratch, - &mut output_offset, - &mut total_out, - &mut |_: &mut PredictionModeContextMap>, - _: &mut [StaticCommand], - _: InputPair<'_>, - _: &mut BrotliTlAlloc| {}, - ); - if !ok { - out.truncate(start_len); - return false; - } - if output_offset > 0 { - out.extend_from_slice(&scratch[..output_offset]); - } - if state.is_finished() { - return true; + BROTLI_ENCODE_SCRATCH.with(|cell: &RefCell<[u8; BROTLI_ENCODE_SCRATCH_LEN]>| { + let mut fallback: [u8; BROTLI_ENCODE_SCRATCH_LEN]; + let mut borrowed: Option> = + cell.try_borrow_mut().ok(); + let scratch: &mut [u8] = match borrowed.as_deref_mut() { + Some(buf) => buf.as_mut_slice(), + None => { + fallback = [0u8; BROTLI_ENCODE_SCRATCH_LEN]; + fallback.as_mut_slice() + } + }; + loop { + let mut available_out: usize = scratch.len(); + let mut output_offset: usize = 0; + let ok: bool = state.compress_stream( + BrotliEncoderOperation::BROTLI_OPERATION_FINISH, + &mut available_in, + data, + &mut input_offset, + &mut available_out, + scratch, + &mut output_offset, + &mut total_out, + &mut |_: &mut PredictionModeContextMap>, + _: &mut [StaticCommand], + _: InputPair<'_>, + _: &mut BrotliTlAlloc| {}, + ); + if !ok { + out.truncate(start_len); + return false; + } + if output_offset > 0 { + out.extend_from_slice(&scratch[..output_offset]); + } + if state.is_finished() { + return true; + } } - } + }) } /// Compresses the given data using the Brotli compression algorithm. @@ -171,44 +182,59 @@ pub fn encode(data: &'_ [u8], buffer_size: usize) -> Cow<'_, [u8]> { let mut available_in: usize = data.len(); let mut input_offset: usize = 0; let mut total_out: Option = Some(0); - let mut scratch: [u8; BROTLI_ENCODE_SCRATCH_LEN] = [0u8; BROTLI_ENCODE_SCRATCH_LEN]; let mut out: Vec = Vec::new(); - loop { - let mut available_out: usize = scratch.len(); - let mut output_offset: usize = 0; - let ok: bool = state.compress_stream( - BrotliEncoderOperation::BROTLI_OPERATION_FINISH, - &mut available_in, - data, - &mut input_offset, - &mut available_out, - &mut scratch, - &mut output_offset, - &mut total_out, - &mut |_: &mut PredictionModeContextMap>, - _: &mut [StaticCommand], - _: InputPair<'_>, - _: &mut BrotliTlAlloc| {}, - ); - if !ok { - return Cow::Owned(Vec::new()); - } - if state.is_finished() && out.is_empty() { - return Cow::Owned(scratch[..output_offset].to_vec()); - } - if output_offset > 0 { - if out.is_empty() { - let initial_capacity: usize = data - .len() - .min(buffer_size.max(output_offset)) - .max(output_offset); - out.reserve(initial_capacity); + let ok: bool = BROTLI_ENCODE_SCRATCH.with(|cell: &RefCell<[u8; BROTLI_ENCODE_SCRATCH_LEN]>| { + let mut fallback: [u8; BROTLI_ENCODE_SCRATCH_LEN]; + let mut borrowed: Option> = + cell.try_borrow_mut().ok(); + let scratch: &mut [u8] = match borrowed.as_deref_mut() { + Some(buf) => buf.as_mut_slice(), + None => { + fallback = [0u8; BROTLI_ENCODE_SCRATCH_LEN]; + fallback.as_mut_slice() + } + }; + loop { + let mut available_out: usize = scratch.len(); + let mut output_offset: usize = 0; + let ok: bool = state.compress_stream( + BrotliEncoderOperation::BROTLI_OPERATION_FINISH, + &mut available_in, + data, + &mut input_offset, + &mut available_out, + scratch, + &mut output_offset, + &mut total_out, + &mut |_: &mut PredictionModeContextMap>, + _: &mut [StaticCommand], + _: InputPair<'_>, + _: &mut BrotliTlAlloc| {}, + ); + if !ok { + return false; + } + if state.is_finished() && out.is_empty() { + out = scratch[..output_offset].to_vec(); + return true; + } + if output_offset > 0 { + if out.is_empty() { + let initial_capacity: usize = data + .len() + .min(buffer_size.max(output_offset)) + .max(output_offset); + out.reserve(initial_capacity); + } + out.extend_from_slice(&scratch[..output_offset]); + } + if state.is_finished() { + return true; } - out.extend_from_slice(&scratch[..output_offset]); - } - if state.is_finished() { - break; } + }); + if !ok { + return Cow::Owned(Vec::new()); } Cow::Owned(out) } @@ -236,51 +262,65 @@ pub fn decode(data: &'_ [u8], buffer_size: usize) -> Cow<'_, [u8]> { let mut available_in: usize = data.len(); let mut input_offset: usize = 0; let mut total_out: usize = 0; - let mut scratch: [u8; BROTLI_DECODE_SCRATCH_LEN] = [0u8; BROTLI_DECODE_SCRATCH_LEN]; let mut out: Vec = Vec::new(); - loop { - let mut available_out: usize = scratch.len(); - let mut output_offset: usize = 0; - let result: BrotliResult = BrotliDecompressStream( - &mut available_in, - &mut input_offset, - data, - &mut available_out, - &mut output_offset, - &mut scratch, - &mut total_out, - &mut state, - ); - if out.len().saturating_add(output_offset) > MAX_DECOMPRESSED_BYTES { - return Cow::Owned(Vec::new()); - } - match result { - BrotliResult::ResultSuccess => { - if out.is_empty() { - return Cow::Owned(scratch[..output_offset].to_vec()); - } - if output_offset > 0 { - out.extend_from_slice(&scratch[..output_offset]); - } - return Cow::Owned(out); + let ok: bool = BROTLI_DECODE_SCRATCH.with(|cell: &RefCell<[u8; BROTLI_DECODE_SCRATCH_LEN]>| { + let mut fallback: [u8; BROTLI_DECODE_SCRATCH_LEN]; + let mut borrowed: Option> = + cell.try_borrow_mut().ok(); + let scratch: &mut [u8] = match borrowed.as_deref_mut() { + Some(buf) => buf.as_mut_slice(), + None => { + fallback = [0u8; BROTLI_DECODE_SCRATCH_LEN]; + fallback.as_mut_slice() + } + }; + loop { + let mut available_out: usize = scratch.len(); + let mut output_offset: usize = 0; + let result: BrotliResult = BrotliDecompressStream( + &mut available_in, + &mut input_offset, + data, + &mut available_out, + &mut output_offset, + scratch, + &mut total_out, + &mut state, + ); + if out.len().saturating_add(output_offset) > MAX_DECOMPRESSED_BYTES { + return false; } - BrotliResult::NeedsMoreOutput => { - if output_offset > 0 { + match result { + BrotliResult::ResultSuccess => { if out.is_empty() { - let initial_capacity: usize = data - .len() - .saturating_mul(4) - .max(output_offset.saturating_mul(2)) - .min(buffer_size.max(output_offset.saturating_mul(2))) - .min(MAX_DECOMPRESSED_BYTES); - out.reserve(initial_capacity); + out = scratch[..output_offset].to_vec(); + } else if output_offset > 0 { + out.extend_from_slice(&scratch[..output_offset]); } - out.extend_from_slice(&scratch[..output_offset]); + return true; + } + BrotliResult::NeedsMoreOutput => { + if output_offset > 0 { + if out.is_empty() { + let initial_capacity: usize = data + .len() + .saturating_mul(4) + .max(output_offset.saturating_mul(2)) + .min(buffer_size.max(output_offset.saturating_mul(2))) + .min(MAX_DECOMPRESSED_BYTES); + out.reserve(initial_capacity); + } + out.extend_from_slice(&scratch[..output_offset]); + } + } + BrotliResult::NeedsMoreInput | BrotliResult::ResultFailure => { + return false; } - } - BrotliResult::NeedsMoreInput | BrotliResult::ResultFailure => { - return Cow::Owned(Vec::new()); } } + }); + if !ok { + return Cow::Owned(Vec::new()); } + Cow::Owned(out) } diff --git a/compress/src/brotli/static.rs b/compress/src/brotli/static.rs index 17f60e32..354f9fb2 100644 --- a/compress/src/brotli/static.rs +++ b/compress/src/brotli/static.rs @@ -3,4 +3,8 @@ use super::*; thread_local! { /// Thread-local typed buffer pool reused across Brotli encode and decode operations. pub(crate) static BROTLI_BUFFER_POOL: RefCell = RefCell::new(BrotliBufferPool::default()); + /// Thread-local reusable scratch buffer for Brotli streaming encode output. + pub(crate) static BROTLI_ENCODE_SCRATCH: RefCell<[u8; BROTLI_ENCODE_SCRATCH_LEN]> = const { RefCell::new([0u8; BROTLI_ENCODE_SCRATCH_LEN]) }; + /// Thread-local reusable scratch buffer for Brotli streaming decode output. + pub(crate) static BROTLI_DECODE_SCRATCH: RefCell<[u8; BROTLI_DECODE_SCRATCH_LEN]> = const { RefCell::new([0u8; BROTLI_DECODE_SCRATCH_LEN]) }; } diff --git a/compress/src/compress/const.rs b/compress/src/compress/const.rs index 2e3bd666..34e45bfb 100644 --- a/compress/src/compress/const.rs +++ b/compress/src/compress/const.rs @@ -17,7 +17,7 @@ pub(crate) const CONTENT_ENCODING_DEFLATE: &str = "deflate"; pub(crate) const CONTENT_ENCODING_BROTLI: &str = "br"; /// The default brotli compression quality. -pub(crate) const BROTLI_DEFAULT_QUALITY: u32 = 5; +pub(crate) const BROTLI_DEFAULT_QUALITY: u32 = 4; /// The default brotli sliding window size, in bits. pub(crate) const BROTLI_DEFAULT_WINDOW_BITS: u32 = 22; diff --git a/compress/src/deflate/const.rs b/compress/src/deflate/const.rs index 690186a1..8a55d3e3 100644 --- a/compress/src/deflate/const.rs +++ b/compress/src/deflate/const.rs @@ -1,5 +1,8 @@ /// Minimum output buffer reserve increment during raw deflate compression and decompression. pub(crate) const DEFLATE_MIN_RESERVE: usize = 4096; +/// Default raw deflate compression level tuned for high-throughput HTTP responses. +pub(crate) const DEFLATE_DEFAULT_LEVEL: u32 = 4; + /// Maximum per-step output buffer growth increment while decompressing raw deflate streams. pub(crate) const DEFLATE_MAX_GROW_STEP: usize = 1024 * 1024; diff --git a/compress/src/deflate/fn.rs b/compress/src/deflate/fn.rs index df416fc3..cd09944f 100644 --- a/compress/src/deflate/fn.rs +++ b/compress/src/deflate/fn.rs @@ -55,7 +55,7 @@ pub(crate) fn compress_raw_into(data: &[u8], out: &mut Vec) -> bool { compress_raw_with_state(&mut compressor, data, out) } else { let mut compressor: flate2::Compress = - flate2::Compress::new(Compression::default(), false); + flate2::Compress::new(Compression::new(DEFLATE_DEFAULT_LEVEL), false); compress_raw_with_state(&mut compressor, data, out) } }) diff --git a/compress/src/deflate/static.rs b/compress/src/deflate/static.rs index de1f0fd5..9e4b8392 100644 --- a/compress/src/deflate/static.rs +++ b/compress/src/deflate/static.rs @@ -2,7 +2,7 @@ use super::*; thread_local! { /// Thread-local reusable raw DEFLATE compressor state. - pub(crate) static DEFLATE_COMPRESSOR: RefCell = RefCell::new(flate2::Compress::new(Compression::default(), false)); + pub(crate) static DEFLATE_COMPRESSOR: RefCell = RefCell::new(flate2::Compress::new(Compression::new(DEFLATE_DEFAULT_LEVEL), false)); /// Thread-local reusable raw DEFLATE decompressor state. pub(crate) static DEFLATE_DECOMPRESSOR: RefCell = RefCell::new(Decompress::new(false)); } diff --git a/compress/src/lib.rs b/compress/src/lib.rs index 5f6026e7..d5d2d050 100644 --- a/compress/src/lib.rs +++ b/compress/src/lib.rs @@ -23,7 +23,7 @@ pub(crate) use compress::{ use std::{ borrow::Cow, - cell::RefCell, + cell::{RefCell, RefMut}, collections::HashMap, fmt, mem::{MaybeUninit, size_of}, diff --git a/compress/src/xx_hash3_64/const.rs b/compress/src/xx_hash3_64/const.rs index dd42e7f1..6097ec8a 100644 --- a/compress/src/xx_hash3_64/const.rs +++ b/compress/src/xx_hash3_64/const.rs @@ -1,2 +1,32 @@ +/// XXH64 avalanche multiplier prime 2. +pub(crate) const XXH3_PRIME64_2: u64 = 0xC2B2_AE3D_27D4_EB4F; + +/// XXH64 avalanche multiplier prime 3. +pub(crate) const XXH3_PRIME64_3: u64 = 0x1656_67B1_9E37_79F9; + +/// XXH3 avalanche multiplier prime MX1. +pub(crate) const XXH3_PRIME_MX1: u64 = 0x1656_6791_9E37_79F9; + +/// XXH3 short-key multiplier prime MX2. +pub(crate) const XXH3_PRIME_MX2: u64 = 0x9FB2_1C65_1E98_DF25; + +/// Precomputed XXH3-64 hash of the empty slice with the default seed and secret. +pub(crate) const XXH3_EMPTY_HASH: u64 = 0x2D06_8005_38D3_94C2; + +/// Pre-XORed default-secret word for 1..=3 byte XXH3-64 inputs. +pub(crate) const XXH3_SECRET_1_3: u64 = 0x0000_0000_8727_5A9B; + +/// Pre-XORed default-secret word for 4..=8 byte XXH3-64 inputs. +pub(crate) const XXH3_SECRET_4_8: u64 = 0xC73A_B174_C5EC_D5A2; + +/// Maximum input length handled directly by the inline short-key XXH3-64 path. +pub(crate) const XXH3_SHORT_LIMIT: usize = 16; + +/// Pre-XORed default-secret high word for 9..=16 byte XXH3-64 inputs. +pub(crate) const XXH3_SECRET_9_16_HI: u64 = 0xAF56_BC3B_0996_523A; + +/// Pre-XORed default-secret low word for 9..=16 byte XXH3-64 inputs. +pub(crate) const XXH3_SECRET_9_16_LO: u64 = 0x6782_737B_EA42_39B9; + /// The maximum input length handled by the buffered short-key path. pub(crate) const HASH_PREFIX_CAPACITY: usize = 128; diff --git a/compress/src/xx_hash3_64/fn.rs b/compress/src/xx_hash3_64/fn.rs new file mode 100644 index 00000000..6eb4b316 --- /dev/null +++ b/compress/src/xx_hash3_64/fn.rs @@ -0,0 +1,107 @@ +use super::*; + +/// Finalizes a 64-bit hash with the XXH64 avalanche mixer. +/// +/// # Arguments +/// +/// - `u64` - Input hash state. +/// +/// # Returns +/// +/// - `u64` - Mixed 64-bit hash value. +#[inline(always)] +fn avalanche_xxh64(mut value: u64) -> u64 { + value ^= value >> 33; + value = value.wrapping_mul(XXH3_PRIME64_2); + value ^= value >> 29; + value = value.wrapping_mul(XXH3_PRIME64_3); + value ^= value >> 32; + value +} + +/// Finalizes a 64-bit hash with the XXH3 avalanche mixer. +/// +/// # Arguments +/// +/// - `u64` - Input hash state. +/// +/// # Returns +/// +/// - `u64` - Mixed 64-bit hash value. +#[inline(always)] +fn avalanche_xxh3(mut value: u64) -> u64 { + value ^= value >> 37; + value = value.wrapping_mul(XXH3_PRIME_MX1); + value ^= value >> 32; + value +} + +/// Computes the exact XXH3-64 hash for default-seed inputs of `0..=16` bytes inline. +/// +/// # Safety +/// +/// - `input_ptr` must be valid for reads of `len` bytes and `len <= XXH3_SHORT_LIMIT`. +/// +/// # Arguments +/// +/// - `*const u8` - Pointer to initialized input bytes. +/// - `usize` - Input length (`0..=16`). +/// +/// # Returns +/// +/// - `u64` - Bit-identical XXH3-64 hash for the default seed and secret. +#[inline(always)] +pub(crate) unsafe fn hash_short_prefix(input_ptr: *const u8, len: usize) -> u64 { + if len > 8 { + // SAFETY: `9 <= len <= 16` guarantees both 8-byte reads are in bounds. + let first: u64 = unsafe { u64::from_le(ptr::read_unaligned(input_ptr.cast::())) }; + let last: u64 = + unsafe { u64::from_le(ptr::read_unaligned(input_ptr.add(len - 8).cast::())) }; + let low: u64 = XXH3_SECRET_9_16_LO ^ first; + let high: u64 = XXH3_SECRET_9_16_HI ^ last; + let mul_result: u128 = (low as u128).wrapping_mul(high as u128); + let acc: u64 = (len as u64) + .wrapping_add(low.swap_bytes()) + .wrapping_add(high) + .wrapping_add((mul_result as u64) ^ ((mul_result >> 64) as u64)); + return avalanche_xxh3(acc); + } + if len >= 4 { + // SAFETY: `4 <= len <= 8` guarantees both 4-byte reads are in bounds. + let first: u32 = unsafe { u32::from_le(ptr::read_unaligned(input_ptr.cast::())) }; + let last: u32 = + unsafe { u32::from_le(ptr::read_unaligned(input_ptr.add(len - 4).cast::())) }; + let combined: u64 = (last as u64) | ((first as u64) << 32); + let mut value: u64 = XXH3_SECRET_4_8 ^ combined; + value ^= value.rotate_left(49) ^ value.rotate_left(24); + value = value.wrapping_mul(XXH3_PRIME_MX2); + value ^= (value >> 35).wrapping_add(len as u64); + value = value.wrapping_mul(XXH3_PRIME_MX2); + value ^= value >> 28; + return value; + } + if len > 0 { + // SAFETY: `1 <= len <= 3` guarantees indices `0`, `len >> 1`, and `len - 1` are in bounds. + let b0: u32 = unsafe { *input_ptr } as u32; + let b_mid: u32 = unsafe { *input_ptr.add(len >> 1) } as u32; + let b_last: u32 = unsafe { *input_ptr.add(len - 1) } as u32; + let combined: u32 = b_last | ((len as u32) << 8) | (b0 << 16) | (b_mid << 24); + return avalanche_xxh64(XXH3_SECRET_1_3 ^ (combined as u64)); + } + XXH3_EMPTY_HASH +} + +/// Computes the XXH3-64 hash for medium buffered inputs (`17..=128` bytes) out of line. +/// +/// # Arguments +/// +/// - `&[u8]` - Initialized prefix bytes. +/// +/// # Returns +/// +/// - `u64` - XXH3-64 hash for the default seed and secret. +#[cold] +#[inline(never)] +pub(crate) fn hash_medium_prefix(bytes: &[u8]) -> u64 { + xxhash3_64::Hasher::oneshot(bytes) +} diff --git a/compress/src/xx_hash3_64/impl.rs b/compress/src/xx_hash3_64/impl.rs index 81c6fa44..31c1d3cc 100644 --- a/compress/src/xx_hash3_64/impl.rs +++ b/compress/src/xx_hash3_64/impl.rs @@ -205,10 +205,16 @@ impl core::hash::Hasher for XxHash3_64 { match inner { Some(hasher) => hasher.finish(), None => { - // SAFETY: `0..*prefix_len` bytes in `prefix` were initialized by prior writes. - let initialized: &[u8] = - unsafe { slice::from_raw_parts(prefix.as_ptr().cast::(), *prefix_len) }; - xxhash3_64::Hasher::oneshot(initialized) + let len: usize = *prefix_len; + let base_ptr: *const u8 = prefix.as_ptr().cast::(); + if len <= XXH3_SHORT_LIMIT { + // SAFETY: `0..len` bytes in `prefix` were initialized by prior writes and `len <= XXH3_SHORT_LIMIT`. + unsafe { hash_short_prefix(base_ptr, len) } + } else { + // SAFETY: `0..len` bytes in `prefix` were initialized by prior writes. + let initialized: &[u8] = unsafe { slice::from_raw_parts(base_ptr, len) }; + hash_medium_prefix(initialized) + } } } } diff --git a/compress/src/xx_hash3_64/mod.rs b/compress/src/xx_hash3_64/mod.rs index b57fcddd..3fbb2016 100644 --- a/compress/src/xx_hash3_64/mod.rs +++ b/compress/src/xx_hash3_64/mod.rs @@ -1,9 +1,10 @@ mod r#const; +mod r#fn; mod r#impl; mod r#struct; pub use r#struct::*; -pub(super) use r#const::*; +pub(crate) use {r#const::*, r#fn::*}; use super::*; diff --git a/core/src/context/impl.rs b/core/src/context/impl.rs index 07fa7f5d..a30888bf 100644 --- a/core/src/context/impl.rs +++ b/core/src/context/impl.rs @@ -466,6 +466,9 @@ impl Context { V: AnySendSyncClone, K: AsRef, { + if self.get_attributes().is_empty() { + return None; + } let key: &str = key.as_ref(); let mut stack_buf: [MaybeUninit; 128] = [const { MaybeUninit::uninit() }; 128]; if let Some(formatted) = Self::try_format_plain_external_key(key, &mut stack_buf) { @@ -512,6 +515,9 @@ impl Context { None => None, }; } + if self.get_attributes().is_empty() { + return None; + } let mut stack_buf: [MaybeUninit; 128] = [const { MaybeUninit::uninit() }; 128]; if let Some(formatted) = Self::try_format_plain_external_key(key, &mut stack_buf) { return self diff --git a/core/src/hook/trait.rs b/core/src/hook/trait.rs index 49b9fab6..0c9cfff2 100644 --- a/core/src/hook/trait.rs +++ b/core/src/hook/trait.rs @@ -81,4 +81,23 @@ pub trait ServerHook: Send + Sync + 'static { /// /// - `impl Future` - `Status::Continue` if the pipeline should proceed, `Status::Reject` if the pipeline should be aborted. fn handle(self, stream: &mut Stream, ctx: &mut Context) -> impl Future + Send; + + /// Optional zero-future synchronous fast path evaluated before constructing `new`/`handle` futures. + /// + /// Returning `Some(status)` completes the hook immediately without state-machine construction + /// or inline slot writes; returning `None` falls back to `Self::new(stream, ctx).await.handle(stream, ctx).await`. + /// + /// # Arguments + /// + /// - `&mut Stream` - The active request stream. + /// - `&mut Context` - The active request context. + /// + /// # Returns + /// + /// - `Option` - Immediate lifecycle decision, or `None` to drive the async hook. + #[doc(hidden)] + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, _ctx: &mut Context) -> Option { + None + } } diff --git a/core/src/protocol/http2/const.rs b/core/src/protocol/http2/const.rs index c8cf3971..c5b09df2 100644 --- a/core/src/protocol/http2/const.rs +++ b/core/src/protocol/http2/const.rs @@ -1,5 +1,8 @@ /// Maximum HTTP/2 DATA frame payload stored inline without heap allocation. -pub(crate) const H2_INLINE_BODY_CAP: usize = 64; +pub(crate) const H2_INLINE_BODY_CAP: usize = 128; /// Maximum number of pooled HTTP/2 DATA body buffers retained per worker thread. pub(crate) const MAX_POOLED_H2_BODIES: usize = 64; + +/// Maximum retained capacity of a recycled HTTP/2 `HeaderMap` kept across pooled streams. +pub(crate) const H2_RECYCLED_HEADER_CAP: usize = 64; diff --git a/core/src/protocol/http2/fn.rs b/core/src/protocol/http2/fn.rs index 7318b3e4..309726df 100644 --- a/core/src/protocol/http2/fn.rs +++ b/core/src/protocol/http2/fn.rs @@ -209,9 +209,16 @@ pub(crate) async fn h2_request_task( return_pooled_context(ctx); return; } + let mut recycled_headers: HeaderMap = mem::take(&mut parts.headers); + recycled_headers.clear(); let is_head: bool = ctx.get_request().get_method().is_head(); - let mut stream_guard: H2StreamGuard = - H2StreamGuard::take(send_response, peers, request_config, is_head); + let mut stream_guard: H2StreamGuard = H2StreamGuard::take( + send_response, + peers, + request_config, + is_head, + recycled_headers, + ); if let Some(stream) = stream_guard.stream_mut() { server .run_protocol_lifecycle_in_place(&shared.pipeline, stream, &mut ctx, target) @@ -246,8 +253,13 @@ pub(crate) async fn h2_fail_request( ctx.get_mut_response().reset().set_version(version.clone()); ctx.clear_route_params(); ctx.reset_request_attributes(); - let mut stream_guard: H2StreamGuard = - H2StreamGuard::take(send_response, peers, request_config, false); + let mut stream_guard: H2StreamGuard = H2StreamGuard::take( + send_response, + peers, + request_config, + false, + HeaderMap::new(), + ); if let Some(stream) = stream_guard.stream_mut() { reply_to_request_error(server, stream, ctx, &error, Some(version)).await; let _: Result<(), io::Error> = stream.get_mut_stream().shutdown().await; diff --git a/core/src/protocol/http2/impl.rs b/core/src/protocol/http2/impl.rs index 42dda4c0..abc9505d 100644 --- a/core/src/protocol/http2/impl.rs +++ b/core/src/protocol/http2/impl.rs @@ -152,14 +152,14 @@ impl H2DirectState { /// # Arguments /// /// - `SendResponse` - The response half of the new HTTP/2 stream. - /// - `StreamPeers` - The local and remote addresses of the carrying TCP connection. /// - `bool` - Whether the incoming request method was `HEAD`. + /// - `HeaderMap` - Cleared `HeaderMap` recycled from the incoming request. #[inline(always)] pub(super) fn reinit( &mut self, send_response: SendResponse, - peers: StreamPeers, is_head: bool, + mut incoming_headers: HeaderMap, ) { self.set_send_response(Some(send_response)); self.set_send_stream(None); @@ -173,7 +173,12 @@ impl H2DirectState { self.set_body_len(0); self.set_finished(false); self.set_failed(false); - self.set_peers(peers); + self.set_direct_inflight(false); + let inc_cap: usize = incoming_headers.capacity(); + if inc_cap > 0 && inc_cap <= H2_RECYCLED_HEADER_CAP { + incoming_headers.clear(); + self.set_recycled_headers(incoming_headers); + } } /// Cleans up stream handles and trims oversized buffers before returning state to the pool. @@ -195,6 +200,13 @@ impl H2DirectState { self.get_mut_pending_body().clear(); } self.set_pending_body_offset(0); + self.set_direct_inflight(false); + let recycled: &mut HeaderMap = self.get_mut_recycled_headers(); + if recycled.capacity() > H2_RECYCLED_HEADER_CAP { + *recycled = HeaderMap::new(); + } else { + recycled.clear(); + } } /// Resets the underlying HTTP/2 stream after a framing error or truncation. @@ -384,28 +396,82 @@ impl H2DirectState { head_bytes: &[u8], body_bytes: &[u8], ) -> io::Result { - let parsed: ParsedProtocolHead = - match parse_protocol_response_head(head_bytes, self.get_is_head()) { - Ok(parsed) => parsed, - Err(error) => return Err(self.fail(&error.to_string())), - }; + let is_head: bool = self.get_is_head(); + let parsed: ParsedProtocolHead = match parse_protocol_response_head( + head_bytes, + is_head, + self.get_mut_recycled_headers(), + ) { + Ok(parsed) => parsed, + Err(error) => return Err(self.fail(&error.to_string())), + }; self.emit_parsed_head_and_inline_body(context, parsed, body_bytes) } } /// Inherent implementation of [`H2DirectTransport`]. impl H2DirectTransport { - /// Creates a direct HTTP/2 transport backed by a shared pooled state handle. + /// Creates a direct HTTP/2 transport owning its framing state inline. /// /// # Arguments /// - /// - `Arc>` - Shared framing state recycled across requests. + /// - `StreamPeers` - Local and remote addresses of the carrying TCP connection. + /// - `H2DirectState` - Direct framing state for this stream. /// /// # Returns /// /// - `Self` - The direct HTTP/2 transport. - pub(crate) fn from_shared(state: Arc>) -> Self { - Self { state } + #[inline(always)] + pub(crate) fn new(peers: StreamPeers, state: H2DirectState) -> Self { + Self { peers, state } + } + + /// Reinitializes this transport in place for a new HTTP/2 request stream. + /// + /// # Arguments + /// + /// - `SendResponse` - The response half of the new stream. + /// - `StreamPeers` - Local and remote addresses of the carrying TCP connection. + /// - `bool` - Whether the incoming request method was `HEAD`. + /// - `HeaderMap` - Cleared `HeaderMap` recycled from the incoming request. + #[inline(always)] + pub(super) fn reinit( + &mut self, + send_response: SendResponse, + peers: StreamPeers, + is_head: bool, + recycled_headers: HeaderMap, + ) { + let Self { + peers: slot_peers, + state, + } = self; + *slot_peers = peers; + state.reinit(send_response, is_head, recycled_headers); + } +} + +// SAFETY: `H2DirectTransport` is `Send`, and every `&self` method (`Debug`, `peer_addr`, +// `local_addr`, `supports_direct_response`) accesses only `self.peers` (`Copy + Send + Sync`); +// `self.state` is accessed exclusively through `&mut self`. +unsafe impl Sync for H2DirectTransport {} + +/// Implements [`fmt::Debug`] for [`H2DirectTransport`]. +impl fmt::Debug for H2DirectTransport { + /// Formats the direct HTTP/2 transport without touching mutable framing state. + /// + /// # Arguments + /// + /// - `&mut fmt::Formatter<'_>` - The formatter to write into. + /// + /// # Returns + /// + /// - `fmt::Result` - The formatting result. + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("H2DirectTransport") + .field("peers", &self.peers) + .finish() } } @@ -419,6 +485,7 @@ impl H2StreamGuard { /// - `StreamPeers` - The local and remote addresses of the carrying TCP connection. /// - `RequestConfig` - The active request limits for the stream. /// - `bool` - Whether the incoming request method was `HEAD`. + /// - `HeaderMap` - Cleared `HeaderMap` recycled from the incoming request. /// /// # Returns /// @@ -429,43 +496,89 @@ impl H2StreamGuard { peers: StreamPeers, request_config: RequestConfig, is_head: bool, + mut recycled_headers: HeaderMap, ) -> Self { - let pooled: Option<(Stream, Arc>)> = + let pooled: Option = H2_STREAM_POOL.with(|pool: &RefCell>| pool.borrow_mut().pop()); - let pair: (Stream, Arc>) = match pooled { - Some((mut stream, state)) if *stream.get_request_config() == request_config => { - if let Ok(mut guard) = state.lock() { - guard.reinit(send_response, peers, is_head); + let stream: Stream = match pooled { + Some(mut stream) if *stream.get_request_config() == request_config => { + if let Some(transport) = stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + transport.reinit(send_response, peers, is_head, recycled_headers); + stream.clear_cached_addrs(); + stream.set_closed(false); + return Self { + inner: Some(stream), + }; } - stream.clear_cached_addrs(); - stream.set_closed(false); - (stream, state) + let retained: HeaderMap = if recycled_headers.capacity() <= H2_RECYCLED_HEADER_CAP { + recycled_headers.clear(); + recycled_headers + } else { + HeaderMap::new() + }; + Stream::from_transport( + H2DirectTransport::new( + peers, + H2DirectState { + send_response: Some(send_response), + send_stream: None, + pending_head: Vec::new(), + pending_body: Vec::new(), + pending_body_offset: 0, + head_sent: false, + suppress_body: is_head, + is_head, + announced_len: None, + body_len: 0, + finished: false, + failed: false, + direct_inflight: false, + recycled_headers: retained, + }, + ), + request_config, + false, + ) } _ => { - let state: Arc> = Arc::new(Mutex::new(H2DirectState { - send_response: Some(send_response), - send_stream: None, - pending_head: Vec::new(), - pending_body: Vec::new(), - pending_body_offset: 0, - head_sent: false, - suppress_body: is_head, - is_head, - announced_len: None, - body_len: 0, - finished: false, - failed: false, - peers, - })); - let stream: Stream = Stream::from_transport( - H2DirectTransport::from_shared(Arc::clone(&state)), + let retained: HeaderMap = if recycled_headers.capacity() <= H2_RECYCLED_HEADER_CAP { + recycled_headers.clear(); + recycled_headers + } else { + HeaderMap::new() + }; + Stream::from_transport( + H2DirectTransport::new( + peers, + H2DirectState { + send_response: Some(send_response), + send_stream: None, + pending_head: Vec::new(), + pending_body: Vec::new(), + pending_body_offset: 0, + head_sent: false, + suppress_body: is_head, + is_head, + announced_len: None, + body_len: 0, + finished: false, + failed: false, + direct_inflight: false, + recycled_headers: retained, + }, + ), request_config, false, - ); - (stream, state) + ) } }; - Self { inner: Some(pair) } + Self { + inner: Some(stream), + } } /// Returns a mutable reference to the pooled `Stream`. @@ -476,39 +589,45 @@ impl H2StreamGuard { #[inline(always)] pub(crate) fn stream_mut(&mut self) -> Option<&mut Stream> { let Self { inner } = self; - inner - .as_mut() - .map(|pair: &mut (Stream, Arc>)| &mut pair.0) + inner.as_mut() } /// Finalizes the HTTP/2 stream if end-of-stream was not yet emitted, then recycles it. #[inline(always)] pub(crate) async fn finish(mut self) { let Self { inner } = &mut self; - let Some((mut stream, state)) = inner.take() else { + let Some(mut stream) = inner.take() else { return; }; - let already_finished: bool = match state.lock() { - Ok(mut guard) if guard.get_finished() && !guard.get_failed() => { - guard.release(); + let already_finished: bool = match stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + Some(transport) if transport.state.finished && !transport.state.failed => { + transport.state.release(); true } - Ok(_) => false, - Err(_) => return, + Some(_) => false, + None => return, }; if !already_finished { let _: Result<(), io::Error> = stream.get_mut_stream().shutdown().await; - if let Ok(mut guard) = state.lock() { - guard.release(); + if let Some(transport) = stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + transport.state.release(); } else { return; } } stream.set_closed(false); H2_STREAM_POOL.with(|pool: &RefCell>| { - let mut pool: RefMut<'_, Vec<(Stream, Arc>)>> = pool.borrow_mut(); + let mut pool: RefMut<'_, Vec> = pool.borrow_mut(); if pool.len() < MAX_POOLED_CONTEXTS { - pool.push((stream, state)); + pool.push(stream); } }); } @@ -519,19 +638,23 @@ impl Drop for H2StreamGuard { /// Resets any unfinished stream and recycles the boxed `Stream` wrapper. fn drop(&mut self) { let Self { inner } = self; - let Some((mut stream, state)) = inner.take() else { + let Some(mut stream) = inner.take() else { return; }; - if let Ok(mut guard) = state.lock() { - guard.release(); + if let Some(transport) = stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + transport.state.release(); } else { return; } stream.set_closed(false); H2_STREAM_POOL.with(|pool: &RefCell>| { - let mut pool: RefMut<'_, Vec<(Stream, Arc>)>> = pool.borrow_mut(); + let mut pool: RefMut<'_, Vec> = pool.borrow_mut(); if pool.len() < MAX_POOLED_CONTEXTS { - pool.push((stream, state)); + pool.push(stream); } }); } @@ -541,9 +664,8 @@ impl Drop for H2StreamGuard { impl Drop for H2DirectTransport { /// Resets the stream when dropped before end-of-stream was emitted. fn drop(&mut self) { - if let Ok(mut state) = self.get_state().lock() - && !state.finished - { + let Self { state, .. } = self; + if !state.finished { state.reset(); } } @@ -556,11 +678,10 @@ impl Transport for H2DirectTransport { /// # Returns /// /// - `Result` - The peer socket address. + #[inline(always)] fn peer_addr(&self) -> Result { - self.get_state() - .lock() - .map(|state: MutexGuard<'_, H2DirectState>| state.get_peers().remote) - .map_err(|_| io::Error::other(MISSING_SEND_CAPACITY)) + let Self { peers, .. } = self; + Ok(peers.remote) } /// Reports the local address of the carrying TCP connection. @@ -568,11 +689,102 @@ impl Transport for H2DirectTransport { /// # Returns /// /// - `Result` - The local socket address. + #[inline(always)] fn local_addr(&self) -> Result { - self.get_state() - .lock() - .map(|state: MutexGuard<'_, H2DirectState>| state.get_peers().local) - .map_err(|_| io::Error::other(MISSING_SEND_CAPACITY)) + let Self { peers, .. } = self; + Ok(peers.local) + } + + /// Exposes a mutable dynamic reference for pooled transport reuse. + /// + /// # Returns + /// + /// - `Option<&mut dyn Any>` - Mutable reference to `self`. + #[inline(always)] + fn as_any_mut(&mut self) -> Option<&mut dyn Any> { + Some(self) + } + + /// Reports support for direct structured [`Response`] emission without HTTP/1.1 serialization. + /// + /// # Returns + /// + /// - `bool` - Always `true` for [`H2DirectTransport`]. + #[inline(always)] + fn supports_direct_response(&self) -> bool { + true + } + + /// Directly frames a [`Response`] onto the HTTP/2 stream without HTTP/1.1 wire serialization. + /// + /// # Arguments + /// + /// - `Pin<&mut Self>` - The pinned transport. + /// - `&mut task::Context<'_>` - The task context for flow-control backpressure. + /// - `&mut Response` - The response to emit directly. + /// - `bool` - Whether only the response head must be transmitted. + /// + /// # Returns + /// + /// - `Option>>` - Direct framing result, or `None` to fall back to wire serialization. + fn poll_write_response( + self: Pin<&mut Self>, + context: &mut task::Context<'_>, + response: &mut Response, + is_head_call: bool, + ) -> Option>> { + let state: &mut H2DirectState = &mut self.get_mut().state; + if state.failed { + return Some(Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY)))); + } + if state.direct_inflight { + return Some(match state.poll_drain_pending_body(context) { + Poll::Pending => Poll::Pending, + Poll::Ready(res) => { + state.direct_inflight = false; + Poll::Ready(res) + } + }); + } + if state.head_sent + || !state.pending_head.is_empty() + || state.pending_body_offset < state.pending_body.len() + { + return None; + } + let req_is_head: bool = state.is_head; + let parsed: ParsedProtocolHead = match build_h2_direct_head( + response, + is_head_call, + req_is_head, + &mut state.recycled_headers, + )? { + Ok(parsed) => parsed, + Err(error) => return Some(Poll::Ready(Err(state.fail(&error.to_string())))), + }; + let body: &[u8] = if parsed.suppress_body { + &[] + } else { + response.get_body().as_slice() + }; + let consumed: usize = match state.emit_parsed_head_and_inline_body(context, parsed, body) { + Ok(consumed) => consumed, + Err(error) => return Some(Poll::Ready(Err(error))), + }; + if !state.suppress_body && consumed < body.len() { + state.pending_body.clear(); + state.pending_body.extend_from_slice(&body[consumed..]); + state.pending_body_offset = 0; + state.direct_inflight = true; + return Some(match state.poll_drain_pending_body(context) { + Poll::Pending => Poll::Pending, + Poll::Ready(res) => { + state.direct_inflight = false; + Poll::Ready(res) + } + }); + } + Some(Poll::Ready(Ok(()))) } } @@ -617,9 +829,7 @@ impl AsyncWrite for H2DirectTransport { context: &mut task::Context<'_>, bytes: &[u8], ) -> Poll> { - let Ok(mut state) = self.get_mut().get_state().lock() else { - return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); - }; + let state: &mut H2DirectState = &mut self.get_mut().state; if state.failed { return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); } @@ -635,8 +845,9 @@ impl AsyncWrite for H2DirectTransport { } if !state.head_sent { if state.pending_head.is_empty() { + let is_head: bool = state.is_head; if let Some((parsed, body_start)) = - try_parse_fast_200_wire(bytes, state.get_is_head()) + try_parse_fast_200_wire(bytes, is_head, &mut state.recycled_headers) { let consumed_body: usize = match state.emit_parsed_head_and_inline_body( context, @@ -759,9 +970,7 @@ impl AsyncWrite for H2DirectTransport { /// /// - `Poll>` - Ready once flushed. fn poll_flush(self: Pin<&mut Self>, context: &mut task::Context<'_>) -> Poll> { - let Ok(mut state) = self.get_mut().get_state().lock() else { - return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); - }; + let state: &mut H2DirectState = &mut self.get_mut().state; if state.failed { return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); } @@ -782,9 +991,7 @@ impl AsyncWrite for H2DirectTransport { self: Pin<&mut Self>, context: &mut task::Context<'_>, ) -> Poll> { - let Ok(mut state) = self.get_mut().get_state().lock() else { - return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); - }; + let state: &mut H2DirectState = &mut self.get_mut().state; if state.failed { state.reset(); return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); diff --git a/core/src/protocol/http2/struct.rs b/core/src/protocol/http2/struct.rs index 1ba809ab..bab7cdab 100644 --- a/core/src/protocol/http2/struct.rs +++ b/core/src/protocol/http2/struct.rs @@ -63,26 +63,29 @@ pub(crate) struct H2DirectState { #[get_mut(pub(super))] #[set(pub(super))] pub(super) failed: bool, - /// The local and remote addresses of the carrying TCP connection. + /// Whether a direct `poll_write_response` call is currently draining backpressured body bytes. #[get(pub(super), type(copy))] #[get_mut(pub(super))] #[set(pub(super))] - pub(super) peers: StreamPeers, + pub(super) direct_inflight: bool, + /// Cleared `HeaderMap` recycled from the incoming HTTP/2 request to avoid per-response allocation. + #[get(skip)] + #[get_mut(pub(super))] + #[set(pub(super))] + pub(super) recycled_headers: HeaderMap, } -/// Direct `Transport` implementation that frames written HTTP/1.1 bytes straight -/// onto an HTTP/2 stream without a duplex pipe or background pump task. -#[derive(Data, Debug)] +/// Direct `Transport` implementation that frames responses straight onto an +/// HTTP/2 stream without a duplex pipe, `Arc`, or `Mutex`. pub(crate) struct H2DirectTransport { - /// Shared framing state recycled across requests via [`H2_STREAM_POOL`]. - #[get(pub(super))] - #[get_mut(pub(super))] - #[set(pub(super))] - pub(super) state: Arc>, + /// The local and remote addresses of the carrying TCP connection. + pub(super) peers: StreamPeers, + /// Direct framing state owned inline and accessed exclusively via `&mut self`. + pub(super) state: H2DirectState, } /// RAII guard borrowing a pooled boxed HTTP/2 `Stream` and returning it on drop. pub(crate) struct H2StreamGuard { - /// Pooled `(Stream, state)` pair released back to [`H2_STREAM_POOL`] on drop. - pub(super) inner: Option<(Stream, Arc>)>, + /// Pooled HTTP/2 `Stream` released back to [`H2_STREAM_POOL`] on drop. + pub(super) inner: Option, } diff --git a/core/src/protocol/http2/type.rs b/core/src/protocol/http2/type.rs index e00fed00..75b6c7b6 100644 --- a/core/src/protocol/http2/type.rs +++ b/core/src/protocol/http2/type.rs @@ -3,5 +3,5 @@ use super::*; /// The HTTP/2 connection half shared by every request stream of one connection. pub(crate) type ConnectionH2 = h2::server::Connection; -/// Pooled `(Stream, Arc>)` pair reused across HTTP/2 requests. -pub(crate) type PooledH2Stream = (Stream, Arc>); +/// Pooled boxed HTTP/2 `Stream` reused across requests without `Arc` or `Mutex`. +pub(crate) type PooledH2Stream = Stream; diff --git a/core/src/protocol/http3/qpack/fn.rs b/core/src/protocol/http3/qpack/fn.rs index 9448bacc..098de5b8 100644 --- a/core/src/protocol/http3/qpack/fn.rs +++ b/core/src/protocol/http3/qpack/fn.rs @@ -1121,6 +1121,205 @@ fn try_encode_fast_h3_200_head( }) } +/// Encodes an HTTP/3 `HEADERS` frame directly from a framework [`Response`] without HTTP/1.1 serialization. +/// +/// Returns `None` when active compression, `Transfer-Encoding`, or `Connection`-nominated headers +/// require falling back to the standard wire path. +/// +/// # Arguments +/// +/// - `&Response` - The framework response to encode. +/// - `bool` - Whether the caller invoked a head-only send (`try_send_response_head`). +/// - `bool` - Whether the incoming request method was `HEAD`. +/// - `&mut Vec` - Destination wire buffer receiving the complete HTTP/3 `HEADERS` frame. +/// +/// # Returns +/// +/// - `Option>` - Encoded framing metadata, or `None` to fall back. +#[inline(always)] +pub(crate) fn encode_h3_response_direct( + response: &Response, + is_head_call: bool, + req_is_head: bool, + out: &mut Vec, +) -> Option> { + let status_code: usize = response.get_status_code(); + if let Err(error) = validate_status_code(status_code) { + return Some(Err(error)); + } + let effective_is_head: bool = is_head_call || req_is_head; + let is_bodyless: bool = (100..=199).contains(&status_code) + || status_code == HttpStatus::NoContent.code() + || status_code == HttpStatus::ResetContent.code() + || status_code == HttpStatus::NotModified.code(); + let suppress_body: bool = is_bodyless_status(status_code, effective_is_head); + let hide_length: bool = hides_entity_length(status_code, effective_is_head); + let body_len: usize = response.get_body().len(); + let resp_headers: &ResponseHeaders = response.get_headers(); + if resp_headers.is_empty() && status_code == HttpStatus::Ok.code() && !is_head_call { + let mut digits_buf: [u8; B_20] = [0; B_20]; + let digits: &[u8] = format_usize_digits(body_len, &mut digits_buf); + let block_len: usize = if body_len == 0 { 5 } else { 6 + digits.len() }; + out.reserve(2 + block_len); + out.push(H3_FRAME_HEADERS as u8); + out.push(block_len as u8); + out.push(0x00); + out.push(0x00); + out.push(0xC0 | 25); + if body_len == 0 { + out.push(0xC0 | 4); + } else { + out.push(0x50 | 4); + out.push(digits.len() as u8); + out.extend_from_slice(digits); + } + out.push(0xC0 | 52); + return Some(Ok(H3EncodedResponseMeta { + announced_len: if suppress_body { None } else { Some(body_len) }, + suppress_body, + })); + } + for (name, values) in resp_headers { + if values.is_empty() { + continue; + } + match name.len() { + 10 if name.eq_ignore_ascii_case(CONNECTION) => { + for raw in values { + for token in raw.split(COMMA_U8 as char) { + let token: &str = token.trim(); + if !token.is_empty() + && !token.eq_ignore_ascii_case(KEEP_ALIVE) + && !token.eq_ignore_ascii_case(CLOSE) + { + return None; + } + } + } + } + 16 if name.eq_ignore_ascii_case(CONTENT_ENCODING) => { + if let Some(val) = values.back() + && !val.parse::().unwrap_or_default().is_unknown() + { + return None; + } + } + 17 if name.eq_ignore_ascii_case(TRANSFER_ENCODING) => { + return None; + } + _ => {} + } + } + let frame_start: usize = out.len(); + out.push(H3_FRAME_HEADERS as u8); + out.push(0); + let payload_start: usize = out.len(); + out.extend_from_slice(&[0, 0]); + encode_qpack_status(status_code, out); + let mut has_content_type: bool = false; + let mut is_event_stream: bool = false; + let mut lower_buf: [u8; 64] = [0; 64]; + for (name, values) in resp_headers { + if values.is_empty() { + continue; + } + let name_bytes: &[u8] = name.as_bytes(); + if name.starts_with(PSEUDO_HEADER_PREFIX) + || is_hop_by_hop_h3_header(name) + || !is_valid_response_header_name(name_bytes) + { + continue; + } + if name.len() == 14 && name.eq_ignore_ascii_case(CONTENT_LENGTH) { + continue; + } + if name.len() == 12 && name.eq_ignore_ascii_case(CONTENT_TYPE) { + has_content_type = true; + if let Some(last_val) = values.back() { + is_event_stream = last_val + .split(SEMICOLON_U8 as char) + .next() + .unwrap_or(EMPTY_STR) + .trim() + .eq_ignore_ascii_case(TEXT_EVENT_STREAM); + } + } + let has_upper: bool = name_bytes.iter().any(|b: &u8| b.is_ascii_uppercase()); + if !has_upper { + for raw_val in values { + let val_bytes: &[u8] = raw_val.trim().as_bytes(); + if is_valid_response_header_value(val_bytes) { + encode_qpack_header(name_bytes, val_bytes, out); + } + } + } else if name_bytes.len() <= lower_buf.len() { + for (idx, &b) in name_bytes.iter().enumerate() { + lower_buf[idx] = b.to_ascii_lowercase(); + } + let lower_name: &[u8] = &lower_buf[..name_bytes.len()]; + for raw_val in values { + let val_bytes: &[u8] = raw_val.trim().as_bytes(); + if is_valid_response_header_value(val_bytes) { + encode_qpack_header(lower_name, val_bytes, out); + } + } + } else { + let lowered: String = name.to_ascii_lowercase(); + for raw_val in values { + let val_bytes: &[u8] = raw_val.trim().as_bytes(); + if is_valid_response_header_value(val_bytes) { + encode_qpack_header(lowered.as_bytes(), val_bytes, out); + } + } + } + } + if !is_bodyless && !has_content_type { + out.push(0xC0 | 52); + } + let emit_cl: Option = if is_bodyless { + if status_code == HttpStatus::ResetContent.code() { + Some(0) + } else { + None + } + } else if is_event_stream { + None + } else if !is_head_call || body_len != 0 { + Some(body_len) + } else { + None + }; + if let Some(len) = emit_cl + && !hide_length + { + if len == 0 { + out.push(0xC0 | 4); + } else { + let mut digits_buf: [u8; B_20] = [0; B_20]; + let digits: &[u8] = format_usize_digits(len, &mut digits_buf); + out.push(0x50 | 4); + out.push(digits.len() as u8); + out.extend_from_slice(digits); + } + } + let block_len: usize = out.len() - payload_start; + if block_len < 64 { + out[frame_start + 1] = block_len as u8; + } else { + let mut len_buf: Vec = Vec::with_capacity(8); + encode_varint(block_len as u64, &mut len_buf); + let extra: usize = len_buf.len() - 1; + let old_len: usize = out.len(); + out.resize(old_len + extra, 0); + out.copy_within(payload_start..old_len, payload_start + extra); + out[frame_start + 1..frame_start + 1 + len_buf.len()].copy_from_slice(&len_buf); + } + Some(Ok(H3EncodedResponseMeta { + announced_len: if suppress_body { None } else { emit_cl }, + suppress_body, + })) +} + /// Parses an HTTP/1.1 response head and writes an HTTP/3 `HEADERS` frame directly into `out`. /// /// Validates status code, header names/values, rejects `transfer-encoding`, strips hop-by-hop diff --git a/core/src/protocol/http3/shard/fn.rs b/core/src/protocol/http3/shard/fn.rs index ef8967fa..ed4488b0 100644 --- a/core/src/protocol/http3/shard/fn.rs +++ b/core/src/protocol/http3/shard/fn.rs @@ -259,11 +259,14 @@ async fn run_quic_shard_dispatcher( /// - `Arc` - Shared transport configuration for every QUIC endpoint shard. fn build_quic_transport_config() -> Arc { let mut transport: TransportConfig = TransportConfig::default(); - transport.max_concurrent_bidi_streams(VarInt::from_u32(1024)); - transport.stream_receive_window(VarInt::from_u32(512 * 1024)); - transport.receive_window(VarInt::from_u32(4 * 1024 * 1024)); - transport.send_window(4 * 1024 * 1024); + transport.max_concurrent_bidi_streams(VarInt::from_u32(2048)); + transport.stream_receive_window(VarInt::from_u32(1024 * 1024)); + transport.receive_window(VarInt::from_u32(8 * 1024 * 1024)); + transport.send_window(8 * 1024 * 1024); transport.send_fairness(false); + transport.initial_rtt(Duration::from_millis(5)); + transport.mtu_discovery_config(None); + transport.allow_spin(false); transport.datagram_receive_buffer_size(None); Arc::new(transport) } diff --git a/core/src/protocol/http3/stream/impl.rs b/core/src/protocol/http3/stream/impl.rs index ecb3b6bd..76a2df09 100644 --- a/core/src/protocol/http3/stream/impl.rs +++ b/core/src/protocol/http3/stream/impl.rs @@ -7,10 +7,9 @@ impl H3DirectState { /// # Arguments /// /// - `SendStream` - The QUIC send half of the new request stream. - /// - `StreamPeers` - The local and remote addresses of the carrying QUIC connection. /// - `bool` - Whether the incoming request method was `HEAD`. #[inline(always)] - pub(super) fn reinit(&mut self, send_stream: SendStream, peers: StreamPeers, is_head: bool) { + pub(super) fn reinit(&mut self, send_stream: SendStream, is_head: bool) { self.set_send_stream(Some(send_stream)); self.get_mut_pending_wire().clear(); self.set_pending_wire_offset(0); @@ -22,7 +21,8 @@ impl H3DirectState { self.set_body_len(0); self.set_finished(false); self.set_failed(false); - self.set_peers(peers); + self.set_direct_inflight(false); + self.set_direct_complete(false); } /// Cleans up stream handles and trims oversized buffers before returning state to the pool. @@ -43,6 +43,8 @@ impl H3DirectState { self.get_mut_pending_head().clear(); } self.set_pending_wire_offset(0); + self.set_direct_inflight(false); + self.set_direct_complete(false); } /// Resets the underlying QUIC send stream with `H3_INTERNAL_ERROR`. @@ -199,20 +201,44 @@ impl H3DirectState { /// Inherent implementation of [`H3DirectTransport`]. impl H3DirectTransport { - /// Creates a direct HTTP/3 transport backed by a shared pooled state handle. + /// Creates a direct HTTP/3 transport owning its framing state inline. /// /// # Arguments /// - /// - `Arc>` - Shared framing state recycled across requests. + /// - `StreamPeers` - Local and remote addresses of the carrying QUIC connection. + /// - `H3DirectState` - Direct framing state for this stream. /// /// # Returns /// /// - `Self` - The direct HTTP/3 transport. - pub(crate) fn from_shared(state: Arc>) -> Self { - Self { state } + #[inline(always)] + pub(crate) fn new(peers: StreamPeers, state: H3DirectState) -> Self { + Self { peers, state } + } + + /// Reinitializes this transport in place for a new QUIC send stream. + /// + /// # Arguments + /// + /// - `SendStream` - The QUIC send half of the new request stream. + /// - `StreamPeers` - Local and remote addresses of the carrying QUIC connection. + /// - `bool` - Whether the incoming request method was `HEAD`. + #[inline(always)] + pub(super) fn reinit(&mut self, send_stream: SendStream, peers: StreamPeers, is_head: bool) { + let Self { + peers: slot_peers, + state, + } = self; + *slot_peers = peers; + state.reinit(send_stream, is_head); } } +// SAFETY: `H3DirectTransport` is `Send`, and every `&self` method (`Debug`, `peer_addr`, +// `local_addr`, `supports_direct_response`) accesses only `self.peers` (`Copy + Send + Sync`); +// `self.state` is accessed exclusively through `&mut self`. +unsafe impl Sync for H3DirectTransport {} + /// Inherent implementation of [`H3StreamGuard`]. impl H3StreamGuard { /// Takes a pooled boxed HTTP/3 `Stream` (or allocates one on first use) and binds it to the send stream. @@ -234,41 +260,71 @@ impl H3StreamGuard { request_config: RequestConfig, is_head: bool, ) -> Self { - let pooled: Option<(Stream, Arc>)> = + let pooled: Option = H3_STREAM_POOL.with(|pool: &RefCell>| pool.borrow_mut().pop()); - let pair: (Stream, Arc>) = match pooled { - Some((mut stream, state)) if *stream.get_request_config() == request_config => { - if let Ok(mut guard) = state.lock() { - guard.reinit(send_stream, peers, is_head); + let stream: Stream = match pooled { + Some(mut stream) if *stream.get_request_config() == request_config => { + if let Some(transport) = stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + transport.reinit(send_stream, peers, is_head); + stream.clear_cached_addrs(); + stream.set_closed(false); + return Self { + inner: Some(stream), + }; } - stream.clear_cached_addrs(); - stream.set_closed(false); - (stream, state) - } - _ => { - let state: Arc> = Arc::new(Mutex::new(H3DirectState { - send_stream: Some(send_stream), - pending_wire: Vec::with_capacity(H3_READ_CHUNK_SIZE), - pending_wire_offset: 0, - pending_head: Vec::new(), - head_sent: false, - suppress_body: is_head, - is_head, - announced_len: None, - body_len: 0, - finished: false, - failed: false, - peers, - })); - let stream: Stream = Stream::from_transport( - H3DirectTransport::from_shared(Arc::clone(&state)), + Stream::from_transport( + H3DirectTransport::new( + peers, + H3DirectState { + send_stream: Some(send_stream), + pending_wire: Vec::with_capacity(H3_READ_CHUNK_SIZE), + pending_wire_offset: 0, + pending_head: Vec::new(), + head_sent: false, + suppress_body: is_head, + is_head, + announced_len: None, + body_len: 0, + finished: false, + failed: false, + direct_inflight: false, + direct_complete: false, + }, + ), request_config, false, - ); - (stream, state) + ) } + _ => Stream::from_transport( + H3DirectTransport::new( + peers, + H3DirectState { + send_stream: Some(send_stream), + pending_wire: Vec::with_capacity(H3_READ_CHUNK_SIZE), + pending_wire_offset: 0, + pending_head: Vec::new(), + head_sent: false, + suppress_body: is_head, + is_head, + announced_len: None, + body_len: 0, + finished: false, + failed: false, + direct_inflight: false, + direct_complete: false, + }, + ), + request_config, + false, + ), }; - Self { inner: Some(pair) } + Self { + inner: Some(stream), + } } /// Returns a mutable reference to the pooled `Stream`. @@ -279,39 +335,45 @@ impl H3StreamGuard { #[inline(always)] pub(crate) fn stream_mut(&mut self) -> Option<&mut Stream> { let Self { inner } = self; - inner - .as_mut() - .map(|pair: &mut (Stream, Arc>)| &mut pair.0) + inner.as_mut() } /// Finalizes the QUIC send stream if not yet finished, then recycles the pooled `Stream`. #[inline(always)] pub(crate) async fn finish(mut self) { let Self { inner } = &mut self; - let Some((mut stream, state)) = inner.take() else { + let Some(mut stream) = inner.take() else { return; }; - let already_finished: bool = match state.lock() { - Ok(mut guard) if guard.get_finished() && !guard.get_failed() => { - guard.release(); + let already_finished: bool = match stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + Some(transport) if transport.state.finished && !transport.state.failed => { + transport.state.release(); true } - Ok(_) => false, - Err(_) => return, + Some(_) => false, + None => return, }; if !already_finished { let _: Result<(), io::Error> = stream.get_mut_stream().shutdown().await; - if let Ok(mut guard) = state.lock() { - guard.release(); + if let Some(transport) = stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + transport.state.release(); } else { return; } } stream.set_closed(false); H3_STREAM_POOL.with(|pool: &RefCell>| { - let mut pool: RefMut<'_, Vec<(Stream, Arc>)>> = pool.borrow_mut(); + let mut pool: RefMut<'_, Vec> = pool.borrow_mut(); if pool.len() < MAX_POOLED_CONTEXTS { - pool.push((stream, state)); + pool.push(stream); } }); } @@ -322,19 +384,23 @@ impl Drop for H3StreamGuard { /// Resets any unfinished stream and recycles the boxed `Stream` wrapper. fn drop(&mut self) { let Self { inner } = self; - let Some((mut stream, state)) = inner.take() else { + let Some(mut stream) = inner.take() else { return; }; - if let Ok(mut guard) = state.lock() { - guard.release(); + if let Some(transport) = stream + .get_mut_stream() + .as_any_mut() + .and_then(|any: &mut dyn Any| any.downcast_mut::()) + { + transport.state.release(); } else { return; } stream.set_closed(false); H3_STREAM_POOL.with(|pool: &RefCell>| { - let mut pool: RefMut<'_, Vec<(Stream, Arc>)>> = pool.borrow_mut(); + let mut pool: RefMut<'_, Vec> = pool.borrow_mut(); if pool.len() < MAX_POOLED_CONTEXTS { - pool.push((stream, state)); + pool.push(stream); } }); } @@ -352,7 +418,10 @@ impl fmt::Debug for H3DirectTransport { /// /// - `fmt::Result` - The formatting result. fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.debug_struct("H3DirectTransport").finish() + formatter + .debug_struct("H3DirectTransport") + .field("peers", &self.peers) + .finish() } } @@ -360,13 +429,12 @@ impl fmt::Debug for H3DirectTransport { impl Drop for H3DirectTransport { /// Resets the stream when dropped before finishing cleanly and recycles its wire buffer. fn drop(&mut self) { - if let Ok(mut state) = self.get_state().lock() { - if !state.finished { - state.reset(); - } - let wire: Vec = mem::take(state.get_mut_pending_wire()); - return_h3_buffer(wire); + let Self { state, .. } = self; + if !state.finished { + state.reset(); } + let wire: Vec = mem::take(state.get_mut_pending_wire()); + return_h3_buffer(wire); } } @@ -377,11 +445,10 @@ impl Transport for H3DirectTransport { /// # Returns /// /// - `Result` - The peer socket address. + #[inline(always)] fn peer_addr(&self) -> Result { - self.get_state() - .lock() - .map(|state: MutexGuard<'_, H3DirectState>| state.get_peers().remote) - .map_err(|_| io::Error::other(MISSING_SEND_CAPACITY)) + let Self { peers, .. } = self; + Ok(peers.remote) } /// Reports the local address of the carrying QUIC connection. @@ -389,11 +456,120 @@ impl Transport for H3DirectTransport { /// # Returns /// /// - `Result` - The local socket address. + #[inline(always)] fn local_addr(&self) -> Result { - self.get_state() - .lock() - .map(|state: MutexGuard<'_, H3DirectState>| state.get_peers().local) - .map_err(|_| io::Error::other(MISSING_SEND_CAPACITY)) + let Self { peers, .. } = self; + Ok(peers.local) + } + + /// Exposes a mutable dynamic reference for pooled transport reuse. + /// + /// # Returns + /// + /// - `Option<&mut dyn Any>` - Mutable reference to `self`. + #[inline(always)] + fn as_any_mut(&mut self) -> Option<&mut dyn Any> { + Some(self) + } + + /// Reports support for direct structured [`Response`] emission without HTTP/1.1 serialization. + /// + /// # Returns + /// + /// - `bool` - Always `true` for [`H3DirectTransport`]. + #[inline(always)] + fn supports_direct_response(&self) -> bool { + true + } + + /// Directly encodes and writes a [`Response`] into HTTP/3 `HEADERS` and `DATA` frames. + /// + /// # Arguments + /// + /// - `Pin<&mut Self>` - The pinned transport. + /// - `&mut task::Context<'_>` - The task context. + /// - `&mut Response` - The response to emit directly. + /// - `bool` - Whether only the response head must be transmitted. + /// + /// # Returns + /// + /// - `Option>>` - Direct framing result, or `None` to fall back. + fn poll_write_response( + self: Pin<&mut Self>, + context: &mut task::Context<'_>, + response: &mut Response, + is_head_call: bool, + ) -> Option>> { + let state: &mut H3DirectState = &mut self.get_mut().state; + if state.failed { + return Some(Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY)))); + } + if state.direct_inflight { + return Some(match state.poll_drain_pending_wire(context) { + Poll::Pending => Poll::Pending, + Poll::Ready(Ok(())) => { + state.direct_inflight = false; + if state.direct_complete && !state.finished { + state.finished = true; + let _: Option = state.send_stream.take(); + } + state.direct_complete = false; + Poll::Ready(Ok(())) + } + Poll::Ready(Err(error)) => { + state.direct_inflight = false; + state.direct_complete = false; + Poll::Ready(Err(error)) + } + }); + } + if state.head_sent + || !state.pending_head.is_empty() + || state.pending_wire_offset < state.pending_wire.len() + || response.get_body().len() > MAX_POOLED_BUFFER_CAPACITY + { + return None; + } + let req_is_head: bool = state.is_head; + let wire: &mut Vec = state.get_mut_pending_wire(); + wire.clear(); + let meta: H3EncodedResponseMeta = + match encode_h3_response_direct(response, is_head_call, req_is_head, wire)? { + Ok(meta) => meta, + Err(error) => return Some(Poll::Ready(Err(state.fail(&error.to_string())))), + }; + state.announced_len = meta.announced_len; + state.suppress_body = meta.suppress_body; + state.head_sent = true; + let body: &[u8] = if meta.suppress_body { + &[] + } else { + response.get_body().as_slice() + }; + if !body.is_empty() { + let wire: &mut Vec = state.get_mut_pending_wire(); + wire.push(H3_FRAME_DATA as u8); + encode_varint(body.len() as u64, wire); + wire.extend_from_slice(body); + state.body_len = body.len(); + } + state.pending_wire_offset = 0; + let is_complete: bool = meta.suppress_body || state.announced_len == Some(body.len()); + Some(match state.poll_drain_pending_wire(context) { + Poll::Ready(Err(error)) => Poll::Ready(Err(error)), + Poll::Ready(Ok(())) => { + if is_complete && !state.finished { + state.finished = true; + let _: Option = state.send_stream.take(); + } + Poll::Ready(Ok(())) + } + Poll::Pending => { + state.direct_inflight = true; + state.direct_complete = is_complete; + Poll::Pending + } + }) } } @@ -438,9 +614,7 @@ impl AsyncWrite for H3DirectTransport { context: &mut task::Context<'_>, bytes: &[u8], ) -> Poll> { - let Ok(mut state) = self.get_mut().get_state().lock() else { - return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); - }; + let state: &mut H3DirectState = &mut self.get_mut().state; if state.failed { return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); } @@ -548,9 +722,7 @@ impl AsyncWrite for H3DirectTransport { /// /// - `Poll>` - Ready once flushed. fn poll_flush(self: Pin<&mut Self>, context: &mut task::Context<'_>) -> Poll> { - let Ok(mut state) = self.get_mut().get_state().lock() else { - return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); - }; + let state: &mut H3DirectState = &mut self.get_mut().state; if state.failed { return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); } @@ -571,9 +743,7 @@ impl AsyncWrite for H3DirectTransport { self: Pin<&mut Self>, context: &mut task::Context<'_>, ) -> Poll> { - let Ok(mut state) = self.get_mut().get_state().lock() else { - return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); - }; + let state: &mut H3DirectState = &mut self.get_mut().state; if state.failed { state.reset(); return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))); diff --git a/core/src/protocol/http3/stream/struct.rs b/core/src/protocol/http3/stream/struct.rs index ec86936d..4d0a965c 100644 --- a/core/src/protocol/http3/stream/struct.rs +++ b/core/src/protocol/http3/stream/struct.rs @@ -58,28 +58,31 @@ pub(crate) struct H3DirectState { #[get_mut(pub(super))] #[set(pub(super))] pub(super) failed: bool, - /// The local and remote addresses of the carrying QUIC connection. + /// Whether a direct `poll_write_response` call is currently draining backpressured wire bytes. #[get(pub(super), type(copy))] #[get_mut(pub(super))] #[set(pub(super))] - pub(super) peers: StreamPeers, + pub(super) direct_inflight: bool, + /// Whether the direct in-flight write completes the stream once `pending_wire` drains. + #[get(pub(super), type(copy))] + #[get_mut(pub(super))] + #[set(pub(super))] + pub(super) direct_complete: bool, } -/// Direct `Transport` implementation that encodes HTTP/1.1 bytes straight into -/// HTTP/3 `HEADERS` and `DATA` frames on a `quinn::SendStream` with zero async boxing. -#[derive(Data)] +/// Direct `Transport` implementation that encodes responses straight into +/// HTTP/3 `HEADERS` and `DATA` frames on a `quinn::SendStream` without `Arc` or `Mutex`. pub(crate) struct H3DirectTransport { - /// Shared framing state recycled across requests via [`H3_STREAM_POOL`]. - #[get(pub(super))] - #[get_mut(pub(super))] - #[set(pub(super))] - pub(super) state: Arc>, + /// The local and remote addresses of the carrying QUIC connection. + pub(super) peers: StreamPeers, + /// Direct framing state owned inline and accessed exclusively via `&mut self`. + pub(super) state: H3DirectState, } /// RAII guard borrowing a pooled boxed HTTP/3 `Stream` and returning it on drop. pub(crate) struct H3StreamGuard { - /// Pooled `(Stream, state)` pair released back to [`H3_STREAM_POOL`] on drop. - pub(super) inner: Option<(Stream, Arc>)>, + /// Pooled HTTP/3 `Stream` released back to [`H3_STREAM_POOL`] on drop. + pub(super) inner: Option, } /// Shared per-connection atomic flags tracking peer-initiated HTTP/3 critical streams. diff --git a/core/src/protocol/http3/stream/type.rs b/core/src/protocol/http3/stream/type.rs index 9557735d..ae4f798f 100644 --- a/core/src/protocol/http3/stream/type.rs +++ b/core/src/protocol/http3/stream/type.rs @@ -1,4 +1,4 @@ use super::*; -/// Pooled `(Stream, Arc>)` pair reused across HTTP/3 requests. -pub(crate) type PooledH3Stream = (Stream, Arc>); +/// Pooled boxed HTTP/3 `Stream` reused across requests without `Arc` or `Mutex`. +pub(crate) type PooledH3Stream = Stream; diff --git a/core/src/protocol/inline/const.rs b/core/src/protocol/inline/const.rs index 5255b256..0afabae2 100644 --- a/core/src/protocol/inline/const.rs +++ b/core/src/protocol/inline/const.rs @@ -1,5 +1,11 @@ /// Number of machine words reserved for stack-allocated inline hook futures. pub(crate) const INLINE_FUTURE_WORDS: usize = 96; +/// Maximum path segment count stored inline on the stack during trie route matching. +pub(crate) const MAX_STACK_ROUTE_SEGS: usize = 16; + +/// Maximum static child edges kept in a flat vector before promoting a trie node to hash lookup. +pub(crate) const SMALL_TRIE_STATIC_LIMIT: usize = 4; + /// Maximum static route count served via direct linear scan instead of hashing. pub(crate) const SMALL_STATIC_ROUTE_LIMIT: usize = 8; diff --git a/core/src/protocol/inline/enum.rs b/core/src/protocol/inline/enum.rs index 6df3ef0c..83f998d5 100644 --- a/core/src/protocol/inline/enum.rs +++ b/core/src/protocol/inline/enum.rs @@ -32,6 +32,19 @@ pub(crate) enum InlineStartOutcome { PendingBoxed(FutureBox), } +/// Execution phase of a unified [`InlineRequestFuture`] pipeline. +#[derive(Clone, Copy, Eq, PartialEq)] +pub(crate) enum InlinePipelinePhase { + /// Executing registered request middleware hooks. + RequestMiddleware, + /// Resolving and executing the matched route hook. + Route, + /// Executing registered response middleware hooks. + ResponseMiddleware, + /// Pipeline completed or terminated. + Done, +} + /// Dispatch representation of a registered hook resolved once at server startup. #[derive(Clone)] pub(crate) enum CompiledHook { diff --git a/core/src/protocol/inline/fn.rs b/core/src/protocol/inline/fn.rs index bcab0ad3..7538e5bf 100644 --- a/core/src/protocol/inline/fn.rs +++ b/core/src/protocol/inline/fn.rs @@ -191,6 +191,11 @@ pub(crate) fn inline_start_hook( where R: ServerHook, { + let stream: &mut Stream = stream_addr.into(); + let ctx: &mut Context = ctx_addr.into(); + if let Some(status) = R::try_handle_sync(stream, ctx) { + return InlineStartOutcome::Ready(status); + } start_inline_future( execute_server_hook::(stream_addr, ctx_addr), slot, diff --git a/core/src/protocol/inline/impl.rs b/core/src/protocol/inline/impl.rs index 81d1cd52..010d3ce0 100644 --- a/core/src/protocol/inline/impl.rs +++ b/core/src/protocol/inline/impl.rs @@ -23,166 +23,289 @@ impl Drop for InlineDropGuard { } } -/// SAFETY: `InlineHookCall` only stores `Send` references, function pointers, -/// and `Send` futures constructed via `start_inline_future`. -unsafe impl Send for InlineHookCall<'_> {} - -/// Inherent implementation of [`InlineHookCall`]. -impl<'a> InlineHookCall<'a> { - /// Creates a new uninitialized inline hook call future. +/// Inherent implementation of [`RouteTrie`]. +impl RouteTrie { + /// Inserts one parsed [`RoutePattern`] and its [`CompiledHook`] into the trie. /// /// # Arguments /// - /// - `&'a mut Stream` - The active stream. - /// - `&'a mut Context` - The active context. - /// - `InlineStartFn` - The monomorphized fused hook starter. - /// - /// # Returns - /// - /// - `Self` - The future ready to be pinned and polled. - #[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, + /// - `&RoutePattern` - The parsed pattern segments to index. + /// - `CompiledHook` - The compiled route handler. + pub(super) fn insert(&mut self, pattern: &RoutePattern, hook: CompiledHook) { + let Self { nodes } = self; + if nodes.is_empty() { + nodes.push(RouteTrieNode::default()); + } + let mut node_idx: usize = 0; + for segment in pattern.get_0().iter() { + node_idx = match segment { + RouteSegment::Static(literal) => { + let existing: Option = nodes[node_idx] + .small_static + .iter() + .find(|(lit, _): &&(String, usize)| lit == literal) + .map(|(_, child): &(String, usize)| *child); + if let Some(child) = existing { + child + } else { + let next_idx: usize = nodes.len(); + nodes.push(RouteTrieNode::default()); + nodes[node_idx] + .small_static + .push((literal.clone(), next_idx)); + next_idx + } + } + RouteSegment::Dynamic(param_name) => { + let existing: Option = nodes[node_idx] + .dynamic_children + .iter() + .find(|(name, _): &&(String, usize)| name == param_name) + .map(|(_, child): &(String, usize)| *child); + if let Some(child) = existing { + child + } else { + let next_idx: usize = nodes.len(); + nodes.push(RouteTrieNode::default()); + nodes[node_idx] + .dynamic_children + .push((param_name.clone(), next_idx)); + next_idx + } + } + RouteSegment::Regex(param_name, regex) => { + let existing: Option = nodes[node_idx] + .regex_children + .iter() + .find(|(name, rx, _): &&(String, Regex, usize)| { + name == param_name && rx.as_str() == regex.as_str() + }) + .map(|(_, _, child): &(String, Regex, usize)| *child); + if let Some(child) = existing { + child + } else { + let next_idx: usize = nodes.len(); + nodes.push(RouteTrieNode::default()); + nodes[node_idx].regex_children.push(( + param_name.clone(), + regex.clone(), + next_idx, + )); + next_idx + } + } + }; + } + if nodes[node_idx].leaf.is_none() { + nodes[node_idx].leaf = Some(hook); } } -} -/// Drops any active inline future if cancelled or unwound before completion. -impl Drop for InlineHookCall<'_> { - /// Drops the in-place future when active. - #[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::(); - // SAFETY: `state` was `Inline`, so `storage` holds an initialized future dropped once. - unsafe { - drop_fn(ptr); + /// Promotes nodes with large static fan-out from linear scan to hash-map lookup. + pub(super) fn finalize(&mut self) { + let Self { nodes } = self; + for node in nodes { + if node.small_static.len() > SMALL_TRIE_STATIC_LIMIT { + let mut map: HashMapXxHash3_64 = hash_map_xx_hash3_64(); + map.reserve(node.small_static.len()); + for (literal, child_idx) in node.small_static.drain(..) { + map.insert(literal, child_idx); + } + node.static_map = map; } } } -} - -/// Polls the inline-or-boxed [`ServerHook`] future directly in pinned stack storage. -impl Future for InlineHookCall<'_> { - type Output = Status; - /// Constructs and polls the concrete future on first poll, driving it to completion. + /// Matches pre-split non-empty path segments recursively, recording captured parameters in `captured`. /// /// # Arguments /// - /// - `Pin<&mut Self>` - The pinned inline call future. - /// - `&mut task::Context<'_>` - The task waker context. + /// - `&'a self` - The route trie being traversed. + /// - `usize` - Current node index inside `self.nodes`. + /// - `&[&'p str]` - Non-empty path segments. + /// - `usize` - Current segment depth. + /// - `&mut [MaybeUninit<(&'a str, &'p str)>; MAX_STACK_ROUTE_SEGS]` - Stack capture buffer. + /// - `&mut usize` - Active count of initialized stack captures. + /// - `&mut Option>` - Overflow captures when depth exceeds stack capacity. /// /// # Returns /// - /// - `Poll` - The hook status once ready, or pending. - #[inline(always)] - fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll { - // SAFETY: We never move `storage` once initialized; all field projections respect pinning. - 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::(); - 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 + /// - `Option<&'a CompiledHook>` - The matched hook when a complete path reaches a leaf. + fn match_node<'a, 'p>( + &'a self, + node_idx: usize, + segments: &[&'p str], + depth: usize, + captured: &mut [MaybeUninit<(&'a str, &'p str)>; MAX_STACK_ROUTE_SEGS], + captured_len: &mut usize, + overflow: &mut Option>, + ) -> Option<&'a CompiledHook> { + let Self { nodes } = self; + let node: &RouteTrieNode = &nodes[node_idx]; + if depth == segments.len() { + return node.leaf.as_ref(); + } + let part: &'p str = segments[depth]; + if !node.small_static.is_empty() { + let part_bytes: &[u8] = part.as_bytes(); + for (literal, child_idx) in &node.small_static { + if literal.as_bytes() == part_bytes { + if let Some(hook) = self.match_node( + *child_idx, + segments, + depth + 1, + captured, + captured_len, + overflow, + ) { + return Some(hook); } + break; } } - 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::(); - // SAFETY: `storage` holds the pinned concrete future initialized above. - match unsafe { poll_entry(ptr, cx) } { - Poll::Ready(status) => { - *state = InlinePollState::Done; - // SAFETY: Completed future is dropped exactly once here. - unsafe { - drop_entry(ptr); - } - Poll::Ready(status) - } - Poll::Pending => Poll::Pending, - } + } else if !node.static_map.is_empty() + && let Some(&child_idx) = node.static_map.get(part) + && let Some(hook) = self.match_node( + child_idx, + segments, + depth + 1, + captured, + captured_len, + overflow, + ) + { + return Some(hook); + } + for (param_name, child_idx) in &node.dynamic_children { + let prev_len: usize = *captured_len; + let prev_overflow_len: usize = overflow.as_ref().map_or(0, Vec::len); + if *captured_len < MAX_STACK_ROUTE_SEGS { + captured[*captured_len].write((param_name.as_str(), part)); + *captured_len += 1; + } else { + overflow + .get_or_insert_with(Vec::new) + .push((param_name.as_str(), part)); + } + if let Some(hook) = self.match_node( + *child_idx, + segments, + depth + 1, + captured, + captured_len, + overflow, + ) { + return Some(hook); + } + *captured_len = prev_len; + if let Some(extra) = overflow.as_mut() { + extra.truncate(prev_overflow_len); + } + } + for (param_name, regex, child_idx) in &node.regex_children { + if !regex.is_match(part) { + continue; + } + let prev_len: usize = *captured_len; + let prev_overflow_len: usize = overflow.as_ref().map_or(0, Vec::len); + if *captured_len < MAX_STACK_ROUTE_SEGS { + captured[*captured_len].write((param_name.as_str(), part)); + *captured_len += 1; + } else { + overflow + .get_or_insert_with(Vec::new) + .push((param_name.as_str(), part)); + } + if let Some(hook) = self.match_node( + *child_idx, + segments, + depth + 1, + captured, + captured_len, + overflow, + ) { + return Some(hook); + } + *captured_len = prev_len; + if let Some(extra) = overflow.as_mut() { + extra.truncate(prev_overflow_len); } - 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()), } + None } -} - -/// SAFETY: `InlineHookChain` only stores `Send` references, slices of `Send + Sync` hooks, -/// and `Send` futures constructed via `start_inline_future` or `ServerHookHandler`. -unsafe impl Send for InlineHookChain<'_> {} -/// Inherent implementation of [`InlineHookChain`]. -impl<'a> InlineHookChain<'a> { - /// Creates a new hook chain future for a middleware slice. + /// Resolves pre-split non-empty path segments and fills `params` in place on match. /// /// # Arguments /// - /// - `&'a mut Stream` - The active stream. - /// - `&'a mut Context` - The active context. - /// - `&'a [CompiledHook]` - The middleware slice to execute in order. + /// - `&'a self` - The route trie being queried. + /// - `&[&str]` - Pre-split non-empty path segments. + /// - `&mut HashMapXxHash3_64` - Recycled parameter map populated on match. /// /// # Returns /// - /// - `Self` - The chain future ready to be pinned and polled. + /// - `Option<&'a CompiledHook>` - The matched compiled hook, if any. #[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, + pub(super) fn try_match_segments<'a>( + &'a self, + segments: &[&str], + params: &mut HashMapXxHash3_64, + ) -> Option<&'a CompiledHook> { + let Self { nodes } = self; + if nodes.is_empty() { + return None; + } + let mut captured: [MaybeUninit<(&str, &str)>; MAX_STACK_ROUTE_SEGS] = + [const { MaybeUninit::uninit() }; MAX_STACK_ROUTE_SEGS]; + let mut captured_len: usize = 0; + let mut overflow: Option> = None; + let hook: &CompiledHook = self.match_node( + 0, + segments, + 0, + &mut captured, + &mut captured_len, + &mut overflow, + )?; + if !params.is_empty() { + return_route_param_entries(params.drain()); + } + if captured_len > 0 || overflow.is_some() { + ROUTE_PARAM_POOL.with(|pool: &RefCell>| { + let mut pool: RefMut<'_, Vec<(String, String)>> = pool.borrow_mut(); + for slot in &captured[..captured_len] { + // SAFETY: Every slot in `0..captured_len` was initialized via `MaybeUninit::write`. + let (param_name, part): (&str, &str) = unsafe { slot.assume_init() }; + let (mut key, mut val): (String, String) = pool.pop().unwrap_or_default(); + key.clear(); + val.clear(); + key.push_str(param_name); + val.push_str(part); + params.insert(key, val); + } + if let Some(extra) = overflow { + for (param_name, part) in extra { + let (mut key, mut val): (String, String) = pool.pop().unwrap_or_default(); + key.clear(); + val.clear(); + key.push_str(param_name); + val.push_str(part); + params.insert(key, val); + } + } + }); } + Some(hook) } } -/// Drops any active pending inline future if the middleware chain is cancelled or unwound. -impl Drop for InlineHookChain<'_> { - /// Drops the active in-place future when present. +/// SAFETY: `InlineRequestFuture` only stores `Send` references, `Send + Sync` hooks, +/// and `Send` futures constructed via `start_inline_future` or `ServerHookHandler`. +unsafe impl Send for InlineRequestFuture<'_> {} + +/// Drops any active suspended inline future if the request pipeline is cancelled or unwound. +impl Drop for InlineRequestFuture<'_> { + /// Drops the in-place future when active. #[inline(always)] fn drop(&mut self) { let Self { state, storage, .. } = self; @@ -200,28 +323,31 @@ impl Drop for InlineHookChain<'_> { } } -/// Executes a slice of middleware hooks in a tight synchronous-first loop. -impl Future for InlineHookChain<'_> { - type Output = Status; +/// Drives request middleware, route matching/execution, and response middleware in one inline slot. +impl Future for InlineRequestFuture<'_> { + type Output = bool; - /// Resumes any pending hook and advances through remaining hooks without re-entering async state. + /// Resumes any pending hook and advances through all remaining phases synchronously when ready. /// /// # Arguments /// - /// - `Pin<&mut Self>` - The pinned hook chain future. + /// - `Pin<&mut Self>` - The pinned pipeline future. /// - `&mut task::Context<'_>` - The task waker context. /// /// # Returns /// - /// - `Poll` - `Status::Reject` on first rejecting hook, `Status::Continue` when complete, or pending. + /// - `Poll` - Whether the connection remains eligible for keep-alive once complete. #[inline(always)] fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll { // SAFETY: `storage` is never moved once initialized; field projections preserve pinning. let Self { + pipeline, stream, ctx, - hooks, + phase, index, + keep_alive, + check_keep_alive, state, storage, .. @@ -240,7 +366,12 @@ impl Future for InlineHookChain<'_> { drop_entry(ptr); } if status.is_reject() { - return Poll::Ready(status); + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive( + CompiledPipeline::response_allows_keep_alive(ctx, *keep_alive), + ); + return Poll::Ready(allowed); } } Poll::Pending => return Poll::Pending, @@ -250,78 +381,211 @@ impl Future for InlineHookChain<'_> { Poll::Ready(status) => { *state = InlinePollState::Uninit; if status.is_reject() { - return Poll::Ready(status); + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive(CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + )); + return Poll::Ready(allowed); } } Poll::Pending => return Poll::Pending, }, InlinePollState::Uninit => {} - InlinePollState::Done => return Poll::Ready(Status::Continue), + InlinePollState::Done => return Poll::Ready(false), } let stream_addr: usize = (&mut **stream).into(); let ctx_addr: usize = (&mut **ctx).into(); let slot: *mut u8 = storage.as_mut_ptr().cast::(); 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); + loop { + match *phase { + InlinePipelinePhase::RequestMiddleware => { + let hooks: &[CompiledHook] = pipeline.request_middleware.as_slice(); + 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() { + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive( + CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + ), + ); + return Poll::Ready(allowed); + } + } + 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 = handler(stream, ctx); + match future.as_mut().poll(cx) { + Poll::Ready(status) => { + if status.is_reject() { + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive( + CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + ), + ); + return Poll::Ready(allowed); + } + } + Poll::Pending => { + *state = InlinePollState::Boxed(future); + return Poll::Pending; + } + } } - } - 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; } } + *phase = InlinePipelinePhase::Route; + *index = 0; } - CompiledHook::Dynamic(handler) => { - let mut future: FutureBox = handler(stream, ctx); - match future.as_mut().poll(cx) { - Poll::Ready(status) => { - if status.is_reject() { - return Poll::Ready(status); + InlinePipelinePhase::Route => { + *phase = InlinePipelinePhase::ResponseMiddleware; + *index = 0; + let matched_hook: Option<&CompiledHook> = { + let path: &str = ctx.request.get_path().as_str(); + pipeline.resolve_route(&mut ctx.route_params, path) + }; + if let Some(hook) = matched_hook { + match hook { + CompiledHook::Inline(start) => { + match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) { + InlineStartOutcome::Ready(status) => { + if status.is_reject() { + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive( + CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + ), + ); + return Poll::Ready(allowed); + } + } + 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 = handler(stream, ctx); + match future.as_mut().poll(cx) { + Poll::Ready(status) => { + if status.is_reject() { + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive( + CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + ), + ); + return Poll::Ready(allowed); + } + } + Poll::Pending => { + *state = InlinePollState::Boxed(future); + return Poll::Pending; + } + } } } - Poll::Pending => { - *state = InlinePollState::Boxed(future); - return Poll::Pending; + } + } + InlinePipelinePhase::ResponseMiddleware => { + let hooks: &[CompiledHook] = pipeline.response_middleware.as_slice(); + 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() { + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive( + CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + ), + ); + return Poll::Ready(allowed); + } + } + 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 = handler(stream, ctx); + match future.as_mut().poll(cx) { + Poll::Ready(status) => { + if status.is_reject() { + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive( + CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + ), + ); + return Poll::Ready(allowed); + } + } + Poll::Pending => { + *state = InlinePollState::Boxed(future); + return Poll::Pending; + } + } + } } } + *phase = InlinePipelinePhase::Done; + let allowed: bool = *check_keep_alive + && stream.is_keep_alive(CompiledPipeline::response_allows_keep_alive( + ctx, + *keep_alive, + )); + return Poll::Ready(allowed); } + InlinePipelinePhase::Done => return Poll::Ready(false), } } - Poll::Ready(Status::Continue) - } -} - -/// Inherent implementation of [`CompiledHook`]. -impl CompiledHook { - /// Invokes the hook inline on the stack when possible, or dynamically otherwise. - /// - /// # Arguments - /// - /// - `&mut Stream` - The active stream. - /// - `&mut Context` - The active request context. - /// - /// # Returns - /// - /// - `Status` - The hook lifecycle decision. - #[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, - } } } @@ -370,38 +634,36 @@ impl CompiledPipeline { .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] + let mut dynamic_tries: CompiledRouteTries = if has_dynamic { + vec![RouteTrie::default(); 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 trie: &mut RouteTrie = &mut dynamic_tries[count]; + for (pattern, handler) in list.iter() { + trie.insert(pattern, lookup_inline_hook(handler)); + } + trie.finalize(); } 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] + let mut regex_tries: CompiledRouteTries = if has_regex { + vec![RouteTrie::default(); 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()); + let trie: &mut RouteTrie = &mut regex_tries[count]; 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)); + trie.insert(pattern, hook); } - regex_routes[count] = compiled; + trie.finalize(); } let request_middleware: Vec = server .get_request_middleware() @@ -418,9 +680,9 @@ impl CompiledPipeline { static_routes, min_static_len, max_static_len, - dynamic_routes, + dynamic_tries, has_dynamic, - regex_routes, + regex_tries, regex_tail_routes, has_regex, request_middleware, @@ -449,9 +711,9 @@ impl CompiledPipeline { static_routes, min_static_len, max_static_len, - dynamic_routes, + dynamic_tries, has_dynamic, - regex_routes, + regex_tries, regex_tail_routes, has_regex, .. @@ -473,38 +735,69 @@ impl CompiledPipeline { 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 mut stack_segs: [&str; MAX_STACK_ROUTE_SEGS] = [EMPTY_STR; MAX_STACK_ROUTE_SEGS]; + let mut overflow_segs: Option> = None; + let mut segment_count: usize = 0; + let mut has_empty_segment: bool = false; + if !trimmed.is_empty() { let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0]; - let mut count: usize = 1; - for &byte in trimmed.as_bytes() { + let trimmed_bytes: &[u8] = trimmed.as_bytes(); + let mut seg_start: usize = 0; + for (idx, &byte) in trimmed_bytes.iter().enumerate() { if byte == sep { - count += 1; + let part: &str = &trimmed[seg_start..idx]; + if part.is_empty() { + has_empty_segment = true; + } + if segment_count < MAX_STACK_ROUTE_SEGS { + stack_segs[segment_count] = part; + } else { + let vec: &mut Vec<&str> = + overflow_segs.get_or_insert_with(|| stack_segs.to_vec()); + vec.push(part); + } + segment_count += 1; + seg_start = idx + 1; } } - count + let last_part: &str = &trimmed[seg_start..]; + if last_part.is_empty() { + has_empty_segment = true; + } + if segment_count < MAX_STACK_ROUTE_SEGS { + stack_segs[segment_count] = last_part; + } else { + let vec: &mut Vec<&str> = overflow_segs.get_or_insert_with(|| stack_segs.to_vec()); + vec.push(last_part); + } + segment_count += 1; + } + let seg_slice: &[&str] = match overflow_segs.as_deref() { + Some(vec) => vec, + None => &stack_segs[..segment_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_empty_segment { + if *has_dynamic + && let Some(trie) = dynamic_tries.get(segment_count) + && let Some(hook) = trie.try_match_segments(seg_slice, params) + { + return Some(hook); + } + if *has_regex + && let Some(trie) = regex_tries.get(segment_count) + && let Some(hook) = trie.try_match_segments(seg_slice, 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) - { + let eligible: bool = if has_empty_segment { + *pattern_seg_count <= segment_count + 1 + } else { + *pattern_seg_count != segment_count && *pattern_seg_count <= segment_count + 1 + }; + if eligible && pattern.try_match_path_into(path, params) { return Some(hook); } } @@ -536,7 +829,7 @@ impl CompiledPipeline { if header_value == KEEP_ALIVE { continue; } - for token in header_value.split(COMMA) { + for token in header_value.split(COMMA_U8 as char) { if token.trim().eq_ignore_ascii_case(CLOSE) { return false; } @@ -545,9 +838,9 @@ impl CompiledPipeline { return true; } for (name, values) in headers { - if name.eq_ignore_ascii_case(CONNECTION) { + if name.len() == CONNECTION.len() && name.eq_ignore_ascii_case(CONNECTION) { for header_value in values { - for token in header_value.split(COMMA) { + for token in header_value.split(COMMA_U8 as char) { if token.trim().eq_ignore_ascii_case(CLOSE) { return false; } @@ -558,30 +851,31 @@ impl CompiledPipeline { true } - /// Executes the full request pipeline inline without per-hook `Box::pin` allocations. + /// Executes the full request pipeline inline in a single pinned storage slot. /// /// # Arguments /// - /// - `&mut Stream` - The active stream. - /// - `&mut Context` - The active request context. + /// - `&'a self` - The compiled request pipeline. + /// - `&'a mut Stream` - The active stream. + /// - `&'a mut Context` - The active request context. /// - `Option` - The original request target supplied by multiplexed protocols. /// /// # Returns /// - /// - `bool` - Whether the connection should remain open for keep-alive. + /// - `InlineRequestFuture<'a>` - Future resolving to whether keep-alive remains enabled. #[inline(always)] - pub(crate) async fn run_request( - &self, - stream: &mut Stream, - ctx: &mut Context, + pub(crate) fn run_request<'a>( + &'a self, + stream: &'a mut Stream, + ctx: &'a mut Context, target: Option, - ) -> bool { - let Self { - request_middleware, - response_middleware, - .. - } = self; - let keep_alive: bool = ctx.get_request().is_enable_keep_alive(); + ) -> InlineRequestFuture<'a> { + let check_keep_alive: bool = target.is_none(); + let keep_alive: bool = if check_keep_alive { + ctx.get_request().is_enable_keep_alive() + } else { + false + }; 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(); @@ -608,29 +902,25 @@ impl CompiledPipeline { } } 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) + let Self { + request_middleware, .. + } = self; + let initial_phase: InlinePipelinePhase = if request_middleware.is_empty() { + InlinePipelinePhase::Route + } else { + InlinePipelinePhase::RequestMiddleware }; - 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)); + InlineRequestFuture { + pipeline: self, + stream, + ctx, + phase: initial_phase, + index: 0, + keep_alive, + check_keep_alive, + state: InlinePollState::Uninit, + storage: MaybeUninit::uninit(), + _pinned: PhantomPinned, } - stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive)) } } diff --git a/core/src/protocol/inline/struct.rs b/core/src/protocol/inline/struct.rs index 8ac6c7e1..01e552c2 100644 --- a/core/src/protocol/inline/struct.rs +++ b/core/src/protocol/inline/struct.rs @@ -12,35 +12,47 @@ pub(crate) struct InlineDropGuard { pub(crate) ptr: *mut F, } -/// Stack-pinned future that runs a [`ServerHook`] inline without heap allocation when it fits. -pub(crate) struct InlineHookCall<'a> { - /// The stream passed to the hook. - pub(super) stream: &'a mut Stream, - /// The request context passed to the hook. - pub(super) ctx: &'a mut Context, - /// Monomorphized fused starter for the concrete hook type. - pub(super) start: InlineStartFn, - /// Current lifecycle state of the future in `storage`. - pub(super) state: InlinePollState, - /// Aligned inline storage for the pinned hook future. - pub(super) storage: MaybeUninit<[usize; INLINE_FUTURE_WORDS]>, - /// Prevents moving the future after pinning. - pub(super) _pinned: PhantomPinned, +/// Node inside a compiled segment-based [`RouteTrie`] preserving `Static > Dynamic > Regex` order. +#[derive(Clone, Default)] +pub(crate) struct RouteTrieNode { + /// Small flat list of `(literal, child_idx)` edges scanned linearly without hashing. + pub(super) small_static: Vec<(String, usize)>, + /// Hash map of `(literal -> child_idx)` used when a node has more than [`SMALL_TRIE_STATIC_LIMIT`] static edges. + pub(super) static_map: HashMapXxHash3_64, + /// Dynamic parameter child edges `(param_name, child_idx)` in deterministic pattern order. + pub(super) dynamic_children: Vec<(String, usize)>, + /// Regex segment child edges `(param_name, compiled_regex, child_idx)` in deterministic pattern order. + pub(super) regex_children: Vec<(String, Regex, usize)>, + /// Terminal route hook stored when a pattern ends at this node. + pub(super) leaf: Option, +} + +/// Compact arena-backed segment trie for O(depth) dynamic and regex route dispatch. +#[derive(Clone, Default)] +pub(crate) struct RouteTrie { + /// Arena of trie nodes; index `0` is the root when non-empty. + pub(super) nodes: Vec, } -/// Stack-pinned future that executes a slice of [`CompiledHook`] entries in a tight loop. -pub(crate) struct InlineHookChain<'a> { - /// The stream passed to each hook. +/// Unified single-slot stack-pinned future driving request middleware, route, and response middleware. +pub(crate) struct InlineRequestFuture<'a> { + /// Compiled pipeline dispatch table. + pub(super) pipeline: &'a CompiledPipeline, + /// The active connection stream. pub(super) stream: &'a mut Stream, - /// The request context passed to each hook. + /// The active request context. pub(super) ctx: &'a mut Context, - /// Slice of compiled middleware hooks to execute in registration order. - pub(super) hooks: &'a [CompiledHook], - /// Next hook index to invoke when no active hook future is pending. + /// Current pipeline execution phase. + pub(super) phase: InlinePipelinePhase, + /// Next hook index within the active middleware slice. pub(super) index: usize, - /// Current lifecycle state of the active pending hook future, if any. + /// Whether the incoming request allowed keep-alive. + pub(super) keep_alive: bool, + /// Whether response keep-alive inspection is required (HTTP/1.x only). + pub(super) check_keep_alive: bool, + /// Lifecycle state of the currently suspended hook future, if any. pub(super) state: InlinePollState, - /// Aligned inline storage for a pending pinned hook future. + /// Single aligned inline storage slot reused across all three pipeline phases. pub(super) storage: MaybeUninit<[usize; INLINE_FUTURE_WORDS]>, /// Prevents moving the future after pinning. pub(super) _pinned: PhantomPinned, @@ -57,12 +69,12 @@ pub(crate) struct CompiledPipeline { pub(super) min_static_len: usize, /// Maximum byte length among registered static route paths (`0` when empty). pub(super) max_static_len: usize, - /// Dynamic parameter routes indexed directly by segment count. - pub(super) dynamic_routes: CompiledPatternBuckets, + /// Dynamic parameter route tries indexed directly by segment count. + pub(super) dynamic_tries: CompiledRouteTries, /// Whether any dynamic routes are registered. pub(super) has_dynamic: bool, - /// Regex routes indexed directly by segment count. - pub(super) regex_routes: CompiledPatternBuckets, + /// Exact-segment-count regex route tries indexed directly by segment count. + pub(super) regex_tries: CompiledRouteTries, /// Tail-regex routes that can match paths with equal or more segments. pub(super) regex_tail_routes: CompiledTailRegexRoutes, /// Whether any regex routes are registered. diff --git a/core/src/protocol/inline/type.rs b/core/src/protocol/inline/type.rs index d4d69f4f..65e57dea 100644 --- a/core/src/protocol/inline/type.rs +++ b/core/src/protocol/inline/type.rs @@ -10,8 +10,8 @@ pub(crate) type InlineStartFn = /// Flat vector of static `(path, hook)` pairs scanned linearly when static route count is small. pub(crate) type SmallStaticRoutes = Vec<(String, CompiledHook)>; -/// Flat vector indexed by route segment count holding `(pattern, hook)` buckets for fixed-length dynamic routes. -pub(crate) type CompiledPatternBuckets = Vec>; +/// Flat vector indexed by route segment count holding compiled segment tries. +pub(crate) type CompiledRouteTries = Vec; /// Flat vector holding `(min_segment_count, pattern, hook)` entries for tail-regex routes. pub(crate) type CompiledTailRegexRoutes = Vec<(usize, RoutePattern, CompiledHook)>; diff --git a/core/src/protocol/response/fn.rs b/core/src/protocol/response/fn.rs index 5836748a..a23b4160 100644 --- a/core/src/protocol/response/fn.rs +++ b/core/src/protocol/response/fn.rs @@ -187,6 +187,7 @@ pub fn find_line_end(bytes: &[u8]) -> Option { /// /// - `&[u8]` - Candidate serialized response bytes (head + optional body). /// - `bool` - Whether the incoming request method was `HEAD`. +/// - `&mut HeaderMap` - Recycled header map reused for parsed response headers. /// /// # Returns /// @@ -195,6 +196,7 @@ pub fn find_line_end(bytes: &[u8]) -> Option { pub(crate) fn try_parse_fast_200_wire( bytes: &[u8], is_head: bool, + recycled_headers: &mut HeaderMap, ) -> Option<(ParsedProtocolHead, usize)> { let (prefix_len, rest): (usize, &[u8]) = if let Some(after) = bytes.strip_prefix(FAST_PROTOCOL_H2_200_PREFIX) { @@ -203,7 +205,7 @@ pub(crate) fn try_parse_fast_200_wire( (FAST_PROTOCOL_H11_200_PREFIX.len(), after) } else { let after: &[u8] = bytes.strip_prefix(FAST_PROTOCOL_H2_GRPC_PREFIX)?; - return try_parse_fast_grpc_wire(after, is_head); + return try_parse_fast_grpc_wire(after, is_head, recycled_headers); }; let max_digits: usize = rest.len().min(20); let mut digits_len: usize = 0; @@ -226,6 +228,10 @@ pub(crate) fn try_parse_fast_200_wire( let mut response: http::Response<()> = http::Response::new(()); *response.status_mut() = StatusCode::OK; let headers: &mut HeaderMap = response.headers_mut(); + if recycled_headers.capacity() > 0 { + *headers = mem::take(recycled_headers); + headers.clear(); + } headers.reserve(2); let cl_value: HeaderValue = if let Some(&static_len) = STATIC_CONTENT_LENGTHS.get(length) { HeaderValue::from_static(static_len) @@ -253,12 +259,17 @@ pub(crate) fn try_parse_fast_200_wire( /// /// - `&[u8]` - Remaining bytes starting at the decimal `content-length` digits. /// - `bool` - Whether the incoming request method was `HEAD`. +/// - `&mut HeaderMap` - Recycled header map taken from the incoming request when available. /// /// # Returns /// /// - `Option<(ParsedProtocolHead, usize)>` - Parsed gRPC protocol head and body start offset when matched. #[inline] -fn try_parse_fast_grpc_wire(after: &[u8], is_head: bool) -> Option<(ParsedProtocolHead, usize)> { +fn try_parse_fast_grpc_wire( + after: &[u8], + is_head: bool, + recycled_headers: &mut HeaderMap, +) -> Option<(ParsedProtocolHead, usize)> { let max_digits: usize = after.len().min(20); let mut digits_len: usize = 0; let mut length: usize = 0; @@ -281,6 +292,10 @@ fn try_parse_fast_grpc_wire(after: &[u8], is_head: bool) -> Option<(ParsedProtoc let mut response: http::Response<()> = http::Response::new(()); *response.status_mut() = StatusCode::OK; let headers: &mut HeaderMap = response.headers_mut(); + if recycled_headers.capacity() > 0 { + *headers = mem::take(recycled_headers); + headers.clear(); + } headers.reserve(3); headers.append( HeaderName::from_static(CONTENT_TYPE), @@ -312,12 +327,17 @@ fn try_parse_fast_grpc_wire(after: &[u8], is_head: bool) -> Option<(ParsedProtoc /// /// - `&[u8]` - Candidate serialized response head bytes. /// - `bool` - Whether the incoming request method was `HEAD`. +/// - `&mut HeaderMap` - Recycled header map taken from the incoming request when available. /// /// # Returns /// /// - `Option` - Prebuilt protocol head when `head` matches the canonical fast layout. #[inline(always)] -fn try_parse_fast_200_head(head: &[u8], is_head: bool) -> Option { +fn try_parse_fast_200_head( + head: &[u8], + is_head: bool, + recycled_headers: &mut HeaderMap, +) -> Option { let rest: &[u8] = head .strip_prefix(FAST_PROTOCOL_H2_200_PREFIX) .or_else(|| head.strip_prefix(FAST_PROTOCOL_H11_200_PREFIX))?; @@ -337,6 +357,10 @@ fn try_parse_fast_200_head(head: &[u8], is_head: bool) -> Option = http::Response::new(()); *response.status_mut() = StatusCode::OK; let headers: &mut HeaderMap = response.headers_mut(); + if recycled_headers.capacity() > 0 { + *headers = mem::take(recycled_headers); + headers.clear(); + } headers.reserve(2); let cl_value: HeaderValue = if let Some(&static_len) = STATIC_CONTENT_LENGTHS.get(length) { HeaderValue::from_static(static_len) @@ -355,6 +379,253 @@ fn try_parse_fast_200_head(head: &[u8], is_head: bool) -> Option &[u8] { + if value == 0 { + buf[B_20 - 1] = ZERO_STR_U8; + return &buf[B_20 - 1..]; + } + let mut pos: usize = B_20; + while value > 0 { + pos -= 1; + buf[pos] = ZERO_STR_U8 + (value % 10) as u8; + value /= 10; + } + &buf[pos..] +} + +/// Builds an HTTP/2 protocol head directly from a framework [`Response`] without HTTP/1.1 serialization. +/// +/// Returns `None` when compression, `Transfer-Encoding`, or `Connection`-nominated headers require +/// falling back to the standard serialized wire path. +/// +/// # Arguments +/// +/// - `&Response` - The framework response to frame. +/// - `bool` - Whether the caller invoked a head-only send (`try_send_response_head`). +/// - `bool` - Whether the incoming request method was `HEAD`. +/// - `&mut HeaderMap` - Recycled header map taken from the incoming request when available. +/// +/// # Returns +/// +/// - `Option>` - Direct protocol head, or `None` to fall back. +#[inline(always)] +pub(crate) fn build_h2_direct_head( + response: &Response, + is_head_call: bool, + req_is_head: bool, + recycled_headers: &mut HeaderMap, +) -> Option> { + let status_code: usize = response.get_status_code(); + if let Err(error) = validate_status_code(status_code) { + return Some(Err(error)); + } + let status: StatusCode = match StatusCode::from_u16(status_code as u16) { + Ok(code) => code, + Err(error) => return Some(Err(ResponseError::Send(error.to_string()))), + }; + let effective_is_head: bool = is_head_call || req_is_head; + let is_bodyless: bool = (100..=199).contains(&status_code) + || status_code == HttpStatus::NoContent.code() + || status_code == HttpStatus::ResetContent.code() + || status_code == HttpStatus::NotModified.code(); + let suppress_body: bool = is_bodyless_status(status_code, effective_is_head); + let hide_length: bool = hides_entity_length(status_code, effective_is_head); + let body_len: usize = response.get_body().len(); + let resp_headers: &ResponseHeaders = response.get_headers(); + if resp_headers.is_empty() { + let mut h2_resp: http::Response<()> = http::Response::new(()); + *h2_resp.status_mut() = status; + let headers: &mut HeaderMap = h2_resp.headers_mut(); + if recycled_headers.capacity() > 0 { + *headers = mem::take(recycled_headers); + headers.clear(); + } + headers.reserve(2); + let emit_cl: Option = if is_bodyless { + if status_code == HttpStatus::ResetContent.code() { + Some(0) + } else { + None + } + } else if !is_head_call || body_len != 0 { + Some(body_len) + } else { + None + }; + if let Some(len) = emit_cl + && !hide_length + { + let cl_val: HeaderValue = if let Some(&static_len) = STATIC_CONTENT_LENGTHS.get(len) { + HeaderValue::from_static(static_len) + } else { + let mut digits: [u8; B_20] = [0; B_20]; + let rendered: &[u8] = format_usize_digits(len, &mut digits); + match HeaderValue::from_bytes(rendered) { + Ok(val) => val, + Err(_) => { + return Some(Err(ResponseError::Send( + MALFORMED_RESPONSE_HEADER.to_owned(), + ))); + } + } + }; + headers.append(HeaderName::from_static(CONTENT_LENGTH), cl_val); + } + if !is_bodyless { + headers.append( + HeaderName::from_static(CONTENT_TYPE), + HeaderValue::from_static(STATIC_CT_HTML_UTF8), + ); + } + return Some(Ok(ParsedProtocolHead { + response: h2_resp, + announced_len: if suppress_body { None } else { emit_cl }, + suppress_body, + })); + } + for (name, values) in resp_headers { + if values.is_empty() { + continue; + } + match name.len() { + 10 if name.eq_ignore_ascii_case(CONNECTION) => { + for raw in values { + for token in raw.split(COMMA_U8 as char) { + let token: &str = token.trim(); + if !token.is_empty() + && !token.eq_ignore_ascii_case(KEEP_ALIVE) + && !token.eq_ignore_ascii_case(CLOSE) + { + return None; + } + } + } + } + 16 if name.eq_ignore_ascii_case(CONTENT_ENCODING) => { + if let Some(val) = values.back() + && !val.parse::().unwrap_or_default().is_unknown() + { + return None; + } + } + 17 if name.eq_ignore_ascii_case(TRANSFER_ENCODING) => { + return None; + } + _ => {} + } + } + let mut h2_resp: http::Response<()> = http::Response::new(()); + *h2_resp.status_mut() = status; + let headers: &mut HeaderMap = h2_resp.headers_mut(); + if recycled_headers.capacity() > 0 { + *headers = mem::take(recycled_headers); + headers.clear(); + } + headers.reserve(resp_headers.len() + 2); + let mut has_content_type: bool = false; + let mut is_event_stream: bool = false; + for (name, values) in resp_headers { + if values.is_empty() { + continue; + } + if name.starts_with(PSEUDO_HEADER_PREFIX) || is_hop_by_hop(name) { + continue; + } + if name.len() == 14 && name.eq_ignore_ascii_case(CONTENT_LENGTH) { + continue; + } + if name.len() == 12 && name.eq_ignore_ascii_case(CONTENT_TYPE) { + has_content_type = true; + if let Some(last_val) = values.back() { + is_event_stream = last_val + .split(SEMICOLON_U8 as char) + .next() + .unwrap_or(EMPTY_STR) + .trim() + .eq_ignore_ascii_case(TEXT_EVENT_STREAM); + } + for raw_val in values { + let trimmed: &str = raw_val.trim(); + let header_value: HeaderValue = match trimmed { + STATIC_CT_HTML_UTF8 => HeaderValue::from_static(STATIC_CT_HTML_UTF8), + STATIC_CT_PLAIN => HeaderValue::from_static(STATIC_CT_PLAIN), + STATIC_CT_PLAIN_UTF8 => HeaderValue::from_static(STATIC_CT_PLAIN_UTF8), + STATIC_CT_JSON => HeaderValue::from_static(STATIC_CT_JSON), + STATIC_CT_GRPC => HeaderValue::from_static(STATIC_CT_GRPC), + _ => match HeaderValue::from_bytes(trimmed.as_bytes()) { + Ok(val) => val, + Err(_) => continue, + }, + }; + headers.append(HeaderName::from_static(CONTENT_TYPE), header_value); + } + continue; + } + let Ok(header_name) = HeaderName::from_bytes(name.as_bytes()) else { + continue; + }; + for raw_val in values { + if let Ok(header_value) = HeaderValue::from_bytes(raw_val.trim().as_bytes()) { + headers.append(header_name.clone(), header_value); + } + } + } + if !is_bodyless && !has_content_type { + headers.append( + HeaderName::from_static(CONTENT_TYPE), + HeaderValue::from_static(STATIC_CT_HTML_UTF8), + ); + } + let emit_cl: Option = if is_bodyless { + if status_code == HttpStatus::ResetContent.code() { + Some(0) + } else { + None + } + } else if is_event_stream { + None + } else if !is_head_call || body_len != 0 { + Some(body_len) + } else { + None + }; + if let Some(len) = emit_cl + && !hide_length + { + let cl_val: HeaderValue = if let Some(&static_len) = STATIC_CONTENT_LENGTHS.get(len) { + HeaderValue::from_static(static_len) + } else { + let mut digits: [u8; B_20] = [0; B_20]; + let rendered: &[u8] = format_usize_digits(len, &mut digits); + match HeaderValue::from_bytes(rendered) { + Ok(val) => val, + Err(_) => { + return Some(Err(ResponseError::Send( + MALFORMED_RESPONSE_HEADER.to_owned(), + ))); + } + } + }; + headers.append(HeaderName::from_static(CONTENT_LENGTH), cl_val); + } + Some(Ok(ParsedProtocolHead { + response: h2_resp, + announced_len: if suppress_body { None } else { emit_cl }, + suppress_body, + })) +} + /// Parses, validates, and filters a serialized HTTP/1.1 response head into a /// protocol response in a single pass. /// @@ -366,6 +637,7 @@ fn try_parse_fast_200_head(head: &[u8], is_head: bool) -> Option Option Result { - if let Some(fast) = try_parse_fast_200_head(head, is_head) { + if let Some(fast) = try_parse_fast_200_head(head, is_head, recycled_headers) { return Ok(fast); } let text: &str = @@ -400,6 +673,10 @@ pub(crate) fn parse_protocol_response_head( let mut response: http::Response<()> = http::Response::new(()); *response.status_mut() = status; let headers: &mut HeaderMap = response.headers_mut(); + if recycled_headers.capacity() > 0 { + *headers = mem::take(recycled_headers); + headers.clear(); + } headers.reserve(4); let suppress_body: bool = is_bodyless_status(status_code, is_head); let hide_length: bool = hides_entity_length(status_code, is_head); diff --git a/core/src/protocol/transport/const.rs b/core/src/protocol/transport/const.rs index fa595677..adf9041a 100644 --- a/core/src/protocol/transport/const.rs +++ b/core/src/protocol/transport/const.rs @@ -1,26 +1,39 @@ +/// Maximum number of reusable TLS record buffers kept per worker thread. +pub(crate) const MAX_POOLED_TLS_BUFFERS: usize = 64; + /// Initial byte size of pooled TLS incoming/outgoing record buffers (fits one max 16 KiB TLS record + overhead). pub(crate) const TLS_RECORD_BUFFER_SIZE: usize = 18 * 1024; -/// Maximum plaintext bytes encrypted into a single TLS record. -pub(crate) const TLS_MAX_PLAINTEXT_CHUNK: usize = 16 * 1024; - /// Maximum incoming ciphertext buffer growth allowed during handshake or record framing. pub(crate) const TLS_MAX_INCOMING_BUFFER: usize = 64 * 1024; /// Maximum outgoing ciphertext buffer growth allowed before failing a stalled connection. pub(crate) const TLS_MAX_OUTGOING_BUFFER: usize = 256 * 1024; -/// Maximum consecutive empty TLS application-data records tolerated before rejecting the peer. -pub(crate) const TLS_MAX_EMPTY_APP_RECORDS: usize = 32; +/// Maximum plaintext bytes encrypted into a single TLS record. +pub(crate) const TLS_MAX_PLAINTEXT_CHUNK: usize = 16 * 1024; -/// Maximum number of reusable TLS record buffers kept per worker thread. -pub(crate) const MAX_POOLED_TLS_BUFFERS: usize = 64; +/// Size of the uninitialized stack buffer used for zero-pool single-record TLS reads. +pub(crate) const TLS_STACK_READ_BUF_SIZE: usize = 4 * 1024; /// Failure reported if the TCP socket accepts no bytes during TLS transmission. pub(crate) const TLS_TRANSMIT_WRITE_ZERO: &str = "tcp write zero during tls transmit"; -/// Failure reported if the outgoing TLS ciphertext buffer exceeds its safety bound. -pub(crate) const TLS_OUTGOING_BUFFER_EXCEEDED: &str = "tls outgoing buffer exceeds limit"; +/// Size of the stack buffer used to encrypt small TLS writes without borrowing the buffer pool. +pub(crate) const TLS_STACK_WRITE_BUF_SIZE: usize = 576; + +/// Maximum consecutive empty TLS application-data records tolerated before rejecting the peer. +pub(crate) const TLS_MAX_EMPTY_APP_RECORDS: usize = 32; /// Failure reported if a peer floods consecutive empty TLS application-data records. pub(crate) const TLS_EMPTY_RECORDS_EXCEEDED: &str = "tls empty application records exceeded"; + +/// Failure reported if the outgoing TLS ciphertext buffer exceeds its safety bound. +pub(crate) const TLS_OUTGOING_BUFFER_EXCEEDED: &str = "tls outgoing buffer exceeds limit"; + +/// Maximum plaintext length encrypted through the stack fast path in [`TlsTransport`]. +pub(crate) const TLS_STACK_WRITE_PLAINTEXT_CAP: usize = 512; + +/// Failure reported if the TLS peer closes TCP without sending a `close_notify` alert. +pub(crate) const TLS_PEER_CLOSED_WITHOUT_CLOSE_NOTIFY: &str = + "tls peer closed connection without close_notify"; diff --git a/core/src/protocol/transport/impl.rs b/core/src/protocol/transport/impl.rs index 5783a1df..13157f9b 100644 --- a/core/src/protocol/transport/impl.rs +++ b/core/src/protocol/transport/impl.rs @@ -147,6 +147,46 @@ where let UnbufferedStatus { state, .. } = conn.process_tls_records(&mut []); match state { Ok(ConnectionState::WriteTraffic(mut wt)) => { + if !close_notify + && out_buf.is_empty() + && chunk.len() <= TLS_STACK_WRITE_PLAINTEXT_CAP + { + let mut stack_out: [u8; TLS_STACK_WRITE_BUF_SIZE] = + [0; TLS_STACK_WRITE_BUF_SIZE]; + if let Ok(encrypted_len) = wt.encrypt(chunk, &mut stack_out) { + match Pin::new(&mut *tcp) + .poll_write(context, &stack_out[..encrypted_len]) + { + Poll::Ready(Ok(0)) => { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::WriteZero, + TLS_TRANSMIT_WRITE_ZERO, + ))); + } + Poll::Ready(Ok(written)) => { + if written < encrypted_len { + let rem: usize = encrypted_len - written; + *out_buf = take_tls_buffer(TLS_RECORD_BUFFER_SIZE.max(rem)); + out_buf[..rem] + .copy_from_slice(&stack_out[written..encrypted_len]); + *out_pos = 0; + *out_len = rem; + } + return Poll::Ready(Ok(chunk.len())); + } + Poll::Pending => { + *out_buf = + take_tls_buffer(TLS_RECORD_BUFFER_SIZE.max(encrypted_len)); + out_buf[..encrypted_len] + .copy_from_slice(&stack_out[..encrypted_len]); + *out_pos = 0; + *out_len = encrypted_len; + return Poll::Ready(Ok(chunk.len())); + } + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + } + } + } if out_buf.is_empty() { *out_buf = take_tls_buffer(TLS_RECORD_BUFFER_SIZE); } @@ -552,6 +592,189 @@ where Err(error) => return Poll::Ready(Err(error)), } } + let in_buf_empty: bool = { + let Self { in_buf, .. } = this; + in_buf.is_empty() + }; + if in_buf_empty { + let mut stack_in: [MaybeUninit; TLS_STACK_READ_BUF_SIZE] = + [const { MaybeUninit::uninit() }; TLS_STACK_READ_BUF_SIZE]; + let mut tcp_buf: ReadBuf<'_> = ReadBuf::uninit(&mut stack_in); + let poll_result: Poll> = { + let Self { tcp, .. } = this; + Pin::new(&mut *tcp).poll_read(context, &mut tcp_buf) + }; + match poll_result { + Poll::Pending => return Poll::Pending, + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Ready(Ok(())) => { + let filled: &mut [u8] = tcp_buf.filled_mut(); + let filled_len: usize = filled.len(); + if filled_len == 0 { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + TLS_PEER_CLOSED_WITHOUT_CLOSE_NOTIFY, + ))); + } + let mut stack_pos: usize = 0; + let mut flush_out_needed: bool = false; + while stack_pos < filled_len { + let Self { + conn, + plain_buf, + out_buf, + out_len, + peer_closed, + .. + } = this; + let UnbufferedStatus { discard, state } = + conn.process_tls_records(&mut filled[stack_pos..]); + let step: Result = match state { + Ok(ConnectionState::ReadTraffic(mut rt)) => { + let mut err: Option = None; + let mut saw_non_empty: bool = false; + while let Some(rec) = rt.next_record() { + match rec { + Ok(app) => { + let payload: &[u8] = app.payload; + if payload.is_empty() { + empty_app_records += 1; + if empty_app_records > TLS_MAX_EMPTY_APP_RECORDS + { + err = Some(io::Error::other( + TLS_EMPTY_RECORDS_EXCEEDED, + )); + break; + } + continue; + } + saw_non_empty = true; + if plain_buf.is_empty() && buffer.remaining() > 0 { + let direct: usize = + payload.len().min(buffer.remaining()); + buffer.put_slice(&payload[..direct]); + if direct < payload.len() { + plain_buf + .extend_from_slice(&payload[direct..]); + } + } else { + plain_buf.extend_from_slice(payload); + } + } + Err(error) => { + err = Some(io::Error::other(error)); + break; + } + } + } + if saw_non_empty { + empty_app_records = 0; + } + match err { + Some(error) => Err(error), + None => Ok(1), + } + } + Ok(ConnectionState::EncodeTlsData(mut enc)) => { + if out_buf.is_empty() { + *out_buf = take_tls_buffer(TLS_RECORD_BUFFER_SIZE); + } + loop { + match enc.encode(&mut out_buf[*out_len..]) { + Ok(n) => { + *out_len += n; + break Ok(2); + } + Err(EncodeError::InsufficientSize(need)) => { + let next_len: usize = + out_len.saturating_add(need.required_size); + if next_len > TLS_MAX_OUTGOING_BUFFER { + break Err(io::Error::other( + TLS_OUTGOING_BUFFER_EXCEEDED, + )); + } + out_buf.resize(next_len, 0); + } + Err(error) => { + break Err(io::Error::other(format!("{error:?}"))); + } + } + } + } + Ok(ConnectionState::TransmitTlsData(transmit)) => { + if *out_len == 0 { + transmit.done(); + Ok(2) + } else { + Ok(3) + } + } + Ok(ConnectionState::PeerClosed | ConnectionState::Closed) => { + *peer_closed = true; + Ok(4) + } + Ok(ConnectionState::ReadEarlyData(mut red)) => { + while red.next_record().is_some() {} + Ok(2) + } + Ok(_) => Ok(0), + Err(error) => Err(io::Error::other(error)), + }; + stack_pos = stack_pos.saturating_add(discard).min(filled_len); + match step { + Ok(1) => { + if stack_pos >= filled_len + && buffer.filled().len() > initial_filled + { + return Poll::Ready(Ok(())); + } + if discard == 0 { + break; + } + } + Ok(2) => continue, + Ok(3) => { + flush_out_needed = true; + break; + } + Ok(4) => return Poll::Ready(Ok(())), + Ok(_) => break, + Err(error) => return Poll::Ready(Err(error)), + } + } + if stack_pos < filled_len { + let rem: usize = filled_len - stack_pos; + let mut pooled: Vec = + take_tls_buffer(TLS_RECORD_BUFFER_SIZE.max(rem)); + pooled[..rem].copy_from_slice(&filled[stack_pos..filled_len]); + let Self { + in_buf, + in_pos, + in_len, + .. + } = this; + *in_buf = pooled; + *in_pos = 0; + *in_len = rem; + } + if flush_out_needed { + { + let Self { needs_process, .. } = this; + *needs_process = true; + } + match this.poll_flush_out(context) { + Poll::Ready(Ok(())) => {} + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending => return Poll::Pending, + } + } + if buffer.filled().len() > initial_filled { + return Poll::Ready(Ok(())); + } + continue; + } + } + } let Self { tcp, in_buf, @@ -560,11 +783,7 @@ where needs_process, .. } = this; - if in_buf.is_empty() { - *in_buf = take_tls_buffer(TLS_RECORD_BUFFER_SIZE); - *in_pos = 0; - *in_len = 0; - } else if *in_len == in_buf.len() { + if *in_len == in_buf.len() { if *in_pos > 0 { in_buf.copy_within(*in_pos..*in_len, 0); *in_len -= *in_pos; @@ -607,7 +826,7 @@ where } return Poll::Ready(Err(io::Error::new( io::ErrorKind::UnexpectedEof, - "tls peer closed connection without close_notify", + TLS_PEER_CLOSED_WITHOUT_CLOSE_NOTIFY, ))); } *in_len += read_len; diff --git a/macros/src/common/fn.rs b/macros/src/common/fn.rs index 84222744..ee535773 100644 --- a/macros/src/common/fn.rs +++ b/macros/src/common/fn.rs @@ -63,13 +63,21 @@ where Ok(stream) => { let after_code: proc_macro2::TokenStream = after_fn(&context, &stream); let stmts: &Vec = &block.stmts; - let (leading_stmts, tail_expr) = if let Some((last, leading)) = stmts.split_last() { + let (leading_stmts, tail_expr, tail_is_trivial): ( + &[Stmt], + Option, + bool, + ) = if let Some((last, leading)) = stmts.split_last() { match last { - Stmt::Expr(expr, None) => (leading, Some(quote! { #expr })), - _ => (stmts.as_slice(), None), + Stmt::Expr(expr, None) => { + let trivial: bool = matches!(expr, Expr::Lit(_)) + || matches!(expr, Expr::Path(path) if path.path.segments.len() >= 2); + (leading, Some(quote! { #expr }), trivial) + } + _ => (stmts.as_slice(), None, false), } } else { - (stmts.as_slice(), None) + (stmts.as_slice(), None, false) }; let normalized_leading: Vec = leading_stmts .iter() @@ -87,6 +95,14 @@ where #after_code } }, + Some(expr) if tail_is_trivial => quote! { + #(#attrs)* + #vis #sig { + #(#normalized_leading)* + #after_code + #expr + } + }, Some(expr) => quote! { #(#attrs)* #vis #sig { diff --git a/macros/src/inject/fn.rs b/macros/src/inject/fn.rs index 94f99a19..986a2f8f 100644 --- a/macros/src/inject/fn.rs +++ b/macros/src/inject/fn.rs @@ -67,6 +67,65 @@ fn apply_macro(macro_meta: &Meta, item_stream: TokenStream, position: Position) .into() } +/// Parses a `response_header(key => value)` meta entry when it uses `HeaderOperation::Set`. +/// +/// # Arguments +/// +/// - `&Meta` - The macro metadata entry to inspect. +/// +/// # Returns +/// +/// - `Option<(Expr, Expr)>` - `(key, value)` expressions when the entry is a set-header directive. +fn try_parse_set_response_header(meta: &Meta) -> Option<(Expr, Expr)> { + let Meta::List(meta_list) = meta else { + return None; + }; + let ident: &Ident = meta_list.path.get_ident()?; + if ident != INJECTABLE_MACRO_NAME_RESPONSE_HEADER { + return None; + } + let header_data: ResponseHeaderData = parse2(meta_list.tokens.clone()).ok()?; + if !matches!(header_data.operation, HeaderOperation::Set) { + return None; + } + Some((header_data.key, header_data.value)) +} + +/// Applies a contiguous run of `response_header(key => value)` set directives in one batched call. +/// +/// # Arguments +/// +/// - `&[(Expr, Expr)]` - Contiguous `(key, value)` expressions in execution order. +/// - `TokenStream` - The input token stream to inject into. +/// - `Position` - The position to inject the batched call. +/// +/// # Returns +/// +/// - `TokenStream` - The resulting token stream with one `set_headers_batch` statement. +fn apply_response_header_batch( + pairs: &[(Expr, Expr)], + item_stream: TokenStream, + position: Position, +) -> TokenStream { + inject(position, item_stream, |context: &Ident, _: &Ident| { + let new_context: proc_macro2::TokenStream = leak_mut_context(false, context); + let pair_tokens: Vec = pairs + .iter() + .map(|(key, value): &(Expr, Expr)| { + quote! { + ( + ::core::convert::AsRef::::as_ref(&#key), + ::core::convert::AsRef::::as_ref(&#value), + ) + } + }) + .collect(); + quote! { + #new_context.get_mut_response().set_headers_batch(&[#(#pair_tokens),*]); + } + }) +} + /// Injects a list of macros before the decorated function. /// /// The macros are applied in head-insertion order, meaning the first macro in the list @@ -86,9 +145,31 @@ pub(crate) fn prologue_macros_macro(attr: TokenStream, item: TokenStream) -> Tok Ok(metas) => metas, Err(error) => return error.to_compile_error().into(), }; + let meta_list: Vec<&Meta> = metas.iter().collect(); let mut current_stream: TokenStream = item; - for meta in metas.iter().rev() { - current_stream = apply_macro(meta, current_stream, Position::Prologue); + let mut idx: usize = meta_list.len(); + while idx > 0 { + if let Some(pair) = try_parse_set_response_header(meta_list[idx - 1]) { + let mut batch: Vec<(Expr, Expr)> = vec![pair]; + let mut run_start: usize = idx - 1; + while run_start > 0 { + if let Some(prev_pair) = try_parse_set_response_header(meta_list[run_start - 1]) { + batch.push(prev_pair); + run_start -= 1; + } else { + break; + } + } + if batch.len() >= 2 { + batch.reverse(); + current_stream = + apply_response_header_batch(&batch, current_stream, Position::Prologue); + idx = run_start; + continue; + } + } + idx -= 1; + current_stream = apply_macro(meta_list[idx], current_stream, Position::Prologue); } current_stream } @@ -112,9 +193,30 @@ pub(crate) fn epilogue_macros_macro(attr: TokenStream, item: TokenStream) -> Tok Ok(metas) => metas, Err(error) => return error.to_compile_error().into(), }; + let meta_list: Vec<&Meta> = metas.iter().collect(); let mut current_stream: TokenStream = item; - for meta in metas.iter() { - current_stream = apply_macro(meta, current_stream, Position::Epilogue); + let mut idx: usize = 0; + while idx < meta_list.len() { + if let Some(pair) = try_parse_set_response_header(meta_list[idx]) { + let mut batch: Vec<(Expr, Expr)> = vec![pair]; + let mut run_end: usize = idx + 1; + while run_end < meta_list.len() { + if let Some(next_pair) = try_parse_set_response_header(meta_list[run_end]) { + batch.push(next_pair); + run_end += 1; + } else { + break; + } + } + if batch.len() >= 2 { + current_stream = + apply_response_header_batch(&batch, current_stream, Position::Epilogue); + idx = run_end; + continue; + } + } + current_stream = apply_macro(meta_list[idx], current_stream, Position::Epilogue); + idx += 1; } current_stream } diff --git a/macros/src/method/fn.rs b/macros/src/method/fn.rs index 84ce36fa..50a8d235 100644 --- a/macros/src/method/fn.rs +++ b/macros/src/method/fn.rs @@ -43,38 +43,27 @@ pub(crate) fn methods_macro( position: Position, ) -> TokenStream { let methods: RequestMethods = parse_macro_input!(attr as RequestMethods); - let input_fn: ItemFn = parse_macro_input!(item as ItemFn); - let sig: &Signature = &input_fn.sig; - match parse_context_from_signature(sig) { - Ok(context) => { - let method_checks: Vec = methods - .methods - .iter() - .map(|method: &Ident| { - let method_str: String = method.to_string(); - let check_fn: Ident = Ident::new(&format!("is_{method_str}"), method.span()); - quote! { - __hyperlane_method.#check_fn() - } - }) - .collect(); - inject( - position, - TokenStream::from(quote! { #input_fn }), - |_: &Ident, _: &Ident| { - quote! { - if { - let __hyperlane_method: &::hyperlane::Method = #context.get_request().get_method(); - !(#(#method_checks)||*) - } { - return ::hyperlane::Status::Continue; - } - } - }, - ) + let method_checks: Vec = methods + .methods + .iter() + .map(|method: &Ident| { + let method_str: String = method.to_string(); + let check_fn: Ident = Ident::new(&format!("is_{method_str}"), method.span()); + quote! { + __hyperlane_method.#check_fn() + } + }) + .collect(); + inject(position, item, |context: &Ident, _: &Ident| { + quote! { + if { + let __hyperlane_method: &::hyperlane::Method = #context.get_request().get_method(); + !(#(#method_checks)||*) + } { + return ::hyperlane::Status::Continue; + } } - Err(err) => err.to_compile_error().into(), - } + }) } /// Implements an HTTP method macro. diff --git a/macros/src/request/fn.rs b/macros/src/request/fn.rs index bbb6251d..d2cded92 100644 --- a/macros/src/request/fn.rs +++ b/macros/src/request/fn.rs @@ -97,6 +97,54 @@ pub(crate) fn request_body_json_macro( }) } +/// Preformats a plain ASCII compile-time attribute key literal into `"External(\"\")"`. +/// +/// # Arguments +/// +/// - `&Expr` - Candidate key expression. +/// +/// # Returns +/// +/// - `Option` - Preformatted map key when safe for direct lookup. +fn try_preformat_external_attr_key(key_expr: &Expr) -> Option { + let Expr::Lit(expr_lit) = key_expr else { + return None; + }; + let Lit::Str(lit_str) = &expr_lit.lit else { + return None; + }; + let raw: String = lit_str.value(); + if raw.starts_with("__") { + return None; + } + if !raw + .bytes() + .all(|b: u8| (0x20..=0x7e).contains(&b) && b != b'"' && b != b'\\') + { + return None; + } + Some(format!("External(\"{raw}\")")) +} + +/// Lowers a compile-time string literal header key to lowercase to hit the O(1) lookup path. +/// +/// # Arguments +/// +/// - `&Expr` - Candidate header key expression. +/// +/// # Returns +/// +/// - `proc_macro2::TokenStream` - Lowercased string literal or original expression tokens. +fn lower_header_key_tokens(key_expr: &Expr) -> proc_macro2::TokenStream { + if let Expr::Lit(expr_lit) = key_expr + && let Lit::Str(lit_str) = &expr_lit.lit + { + let lowered: String = lit_str.value().to_ascii_lowercase(); + return quote! { #lowered }; + } + quote! { #key_expr } +} + /// Gets request attribute by key and assigns to specified variable. /// Supports both single and multiple attribute extraction. /// @@ -120,8 +168,20 @@ pub(crate) fn try_get_attribute_macro( .params .iter() .map(|(key_name, variable, type_name): &(Expr, Ident, Type)| { - quote! { - let #variable: Option<#type_name> = #context.try_get_attribute(&#key_name); + if let Some(preformatted) = try_preformat_external_attr_key(key_name) { + quote! { + let #variable: Option<#type_name> = #context + .get_attributes() + .get(#preformatted) + .and_then(|__hyperlane_attr: &::hyperlane::ArcAnySendSync| { + __hyperlane_attr.downcast_ref::<#type_name>() + }) + .cloned(); + } + } else { + quote! { + let #variable: Option<#type_name> = #context.try_get_attribute(&#key_name); + } } }) .collect(); @@ -154,8 +214,21 @@ pub(crate) fn attribute_macro( .params .iter() .map(|(key_name, variable, type_name): &(Expr, Ident, Type)| { - quote! { - let #variable: #type_name = #context.get_attribute(&#key_name); + if let Some(preformatted) = try_preformat_external_attr_key(key_name) { + quote! { + let #variable: #type_name = #context + .get_attributes() + .get(#preformatted) + .and_then(|__hyperlane_attr: &::hyperlane::ArcAnySendSync| { + __hyperlane_attr.downcast_ref::<#type_name>() + }) + .cloned() + .unwrap(); + } + } else { + quote! { + let #variable: #type_name = #context.get_attribute(&#key_name); + } } }) .collect(); @@ -537,11 +610,16 @@ pub(crate) fn try_get_request_header_macro( ) -> TokenStream { let multi_header: MultiHeaderData = parse_macro_input!(attr as MultiHeaderData); inject(position, item, |context: &Ident, _: &Ident| { - let statements: Vec = multi_header.params.iter().map(|(key_name, variable): &(Expr, Ident)| { - quote! { - let #variable: Option<::std::string::String> = #context.get_request().try_get_header_back(#key_name); - } - }).collect(); + let statements: Vec = multi_header + .params + .iter() + .map(|(key_name, variable): &(Expr, Ident)| { + let lowered: proc_macro2::TokenStream = lower_header_key_tokens(key_name); + quote! { + let #variable: Option<::std::string::String> = #context.get_request().try_get_header_back(#lowered); + } + }) + .collect(); quote! { #(#statements)* } @@ -567,11 +645,16 @@ pub(crate) fn request_header_macro( ) -> TokenStream { let multi_header: MultiHeaderData = parse_macro_input!(attr as MultiHeaderData); inject(position, item, |context: &Ident, _: &Ident| { - let statements: Vec = multi_header.params.iter().map(|(key_name, variable): &(Expr, Ident)| { - quote! { - let #variable: ::std::string::String = #context.get_request().get_header_back(#key_name); - } - }).collect(); + let statements: Vec = multi_header + .params + .iter() + .map(|(key_name, variable): &(Expr, Ident)| { + let lowered: proc_macro2::TokenStream = lower_header_key_tokens(key_name); + quote! { + let #variable: ::std::string::String = #context.get_request().get_header_back(#lowered); + } + }) + .collect(); quote! { #(#statements)* } @@ -628,11 +711,45 @@ pub(crate) fn try_get_request_cookie_macro( ) -> TokenStream { let multi_cookie: MultiCookieData = parse_macro_input!(attr as MultiCookieData); inject(position, item, |context: &Ident, _: &Ident| { - let statements: Vec = multi_cookie.params.iter().map(|(key_name, variable): &(Expr, Ident)| { - quote! { - let #variable: Option<::std::string::String> = #context.get_request().try_get_cookie(#key_name); - } - }).collect(); + if multi_cookie.params.len() >= 2 { + let statements: Vec = multi_cookie + .params + .iter() + .map(|(key_name, variable): &(Expr, Ident)| { + quote! { + let #variable: Option<::std::string::String> = + __hyperlane_cookie_values.and_then( + |__hyperlane_vals: &::std::collections::VecDeque<::std::string::String>| { + let __hyperlane_key: &str = + ::core::convert::AsRef::::as_ref(&#key_name); + for __hyperlane_hdr in __hyperlane_vals { + if let Some(__hyperlane_found) = + ::hyperlane::Cookie::find_value(__hyperlane_hdr, __hyperlane_key) + { + return Some(::std::borrow::ToOwned::to_owned(__hyperlane_found)); + } + } + None + }, + ); + } + }) + .collect(); + return quote! { + let __hyperlane_cookie_values: Option<&::std::collections::VecDeque<::std::string::String>> = + #context.get_request().get_headers().get(::hyperlane::COOKIE); + #(#statements)* + }; + } + let statements: Vec = multi_cookie + .params + .iter() + .map(|(key_name, variable): &(Expr, Ident)| { + quote! { + let #variable: Option<::std::string::String> = #context.get_request().try_get_cookie(#key_name); + } + }) + .collect(); quote! { #(#statements)* } @@ -658,11 +775,47 @@ pub(crate) fn request_cookie_macro( ) -> TokenStream { let multi_cookie: MultiCookieData = parse_macro_input!(attr as MultiCookieData); inject(position, item, |context: &Ident, _: &Ident| { - let statements: Vec = multi_cookie.params.iter().map(|(key_name, variable): &(Expr, Ident)| { - quote! { - let #variable: ::std::string::String = #context.get_request().get_cookie(#key_name); - } - }).collect(); + if multi_cookie.params.len() >= 2 { + let statements: Vec = multi_cookie + .params + .iter() + .map(|(key_name, variable): &(Expr, Ident)| { + quote! { + let #variable: ::std::string::String = + __hyperlane_cookie_values + .and_then( + |__hyperlane_vals: &::std::collections::VecDeque<::std::string::String>| { + let __hyperlane_key: &str = + ::core::convert::AsRef::::as_ref(&#key_name); + for __hyperlane_hdr in __hyperlane_vals { + if let Some(__hyperlane_found) = + ::hyperlane::Cookie::find_value(__hyperlane_hdr, __hyperlane_key) + { + return Some(::std::borrow::ToOwned::to_owned(__hyperlane_found)); + } + } + None + }, + ) + .unwrap(); + } + }) + .collect(); + return quote! { + let __hyperlane_cookie_values: Option<&::std::collections::VecDeque<::std::string::String>> = + #context.get_request().get_headers().get(::hyperlane::COOKIE); + #(#statements)* + }; + } + let statements: Vec = multi_cookie + .params + .iter() + .map(|(key_name, variable): &(Expr, Ident)| { + quote! { + let #variable: ::std::string::String = #context.get_request().get_cookie(#key_name); + } + }) + .collect(); quote! { #(#statements)* } diff --git a/macros/src/send/fn.rs b/macros/src/send/fn.rs index 4f727d7d..3248d219 100644 --- a/macros/src/send/fn.rs +++ b/macros/src/send/fn.rs @@ -75,9 +75,7 @@ pub(crate) fn send_macro(attr: TokenStream, item: TokenStream, position: Positio } None => { quote! { - if #context.try_send_response(#stream).await.is_err() { - #stream.send(b"\0").await; - } + let _: () = #context.try_send_response(#stream).await.unwrap(); } } }, diff --git a/macros/src/stream/fn.rs b/macros/src/stream/fn.rs index 485352be..0d522022 100644 --- a/macros/src/stream/fn.rs +++ b/macros/src/stream/fn.rs @@ -34,8 +34,7 @@ pub(crate) fn generate_http_stream( } None => { quote! { - while let Ok(_request) = #stream.#method_ident().await { - #context.set_request(_request); + while #stream.try_fill_http_request(#context.get_mut_request()).await.is_ok() { #(#stmts)* } ::hyperlane::Status::Continue diff --git a/macros/src/upgrade/fn.rs b/macros/src/upgrade/fn.rs index d3c77b9d..509ccc7f 100644 --- a/macros/src/upgrade/fn.rs +++ b/macros/src/upgrade/fn.rs @@ -14,9 +14,12 @@ pub(crate) fn create_protocol_check( ) -> impl FnOnce(&Ident, &Ident) -> proc_macro2::TokenStream { let upgrade_type_str: String = upgrade_type.to_string(); move |context: &Ident, _: &Ident| { - let check_fn: Ident = Ident::new(&format!("is_{upgrade_type_str}"), context.span()); + let check_fn: Ident = Ident::new( + &format!("is_{upgrade_type_str}_upgrade_type"), + context.span(), + ); quote! { - if !#context.get_request().get_upgrade_type().#check_fn() { + if !#context.get_request().#check_fn() { return ::hyperlane::Status::Continue; } } diff --git a/plugin/audit/src/const.rs b/plugin/audit/src/const.rs index 6a93b332..98b3c0db 100644 --- a/plugin/audit/src/const.rs +++ b/plugin/audit/src/const.rs @@ -26,6 +26,9 @@ pub const DEFAULT_REQUEST_ID_HEADER: &str = "x-request-id"; /// Lowercase hexadecimal encoding alphabet. pub(crate) const HEX_LOWER: &[u8; 16] = b"0123456789abcdef"; +/// Preformatted internal map key for zero-allocation lookup of request entry timestamp. +pub(crate) const ATTR_AUDIT_START_MAP_KEY: &str = "External(\"hyperlane_plugin_audit.start\")"; + /// Initial SHA-256 hash values (FIPS 180-4). pub(crate) const SHA256_H0: [u32; 8] = [ 0x6a09_e667, diff --git a/plugin/audit/src/impl.rs b/plugin/audit/src/impl.rs index a7e416b4..e636053e 100644 --- a/plugin/audit/src/impl.rs +++ b/plugin/audit/src/impl.rs @@ -494,7 +494,9 @@ impl AuditPlugin { } = self; let request: &Request = ctx.get_request(); let latency_us: u64 = ctx - .try_get_attribute_ref::(ATTR_AUDIT_START) + .get_attributes() + .get(ATTR_AUDIT_START_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) .map(|started: &Instant| started.elapsed().as_micros() as u64) .unwrap_or(0); let actor_ref: &str = ctx @@ -596,6 +598,28 @@ impl AuditPlugin { record } + /// Stores the audit start timestamp in `ctx`, reusing any unique existing `Arc` slot in place. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// - `Instant` - Request start timestamp. + #[inline(always)] + pub(crate) fn put_audit_start(ctx: &mut Context, started: Instant) { + if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_AUDIT_START_MAP_KEY) { + if let Some(any_mut) = Arc::get_mut(slot) + && let Some(existing) = any_mut.downcast_mut::() + { + *existing = started; + return; + } + *slot = Arc::new(started); + return; + } + ctx.get_mut_attributes() + .insert(ATTR_AUDIT_START_MAP_KEY.to_owned(), Arc::new(started)); + } + /// Builds, hash-chains, and moves an [`AuditRecord`] directly to the sink without cloning. /// /// # Arguments @@ -626,26 +650,41 @@ impl ServerHook for AuditRequestHook { Self } - /// Stamps the entry timestamp when the request qualifies for auditing. + /// Synchronously stamps the entry timestamp when the request qualifies for auditing. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = AuditPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; if plugin.should_audit(ctx.get_request()) { - ctx.set_attribute(ATTR_AUDIT_START, Instant::now()); + AuditPlugin::put_audit_start(ctx, Instant::now()); } - Status::Continue + Some(Status::Continue) + } + + /// Stamps the entry timestamp when the request qualifies for auditing. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } @@ -666,25 +705,40 @@ impl ServerHook for AuditResponseHook { Self } - /// Emits a finalized hash-chained [`AuditRecord`] for audited requests. + /// Synchronously emits a finalized hash-chained [`AuditRecord`] for audited requests. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = AuditPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; if plugin.should_audit(ctx.get_request()) { plugin.record_context_hook(ctx); } - Status::Continue + Some(Status::Continue) + } + + /// Emits a finalized hash-chained [`AuditRecord`] for audited requests. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/audit/src/lib.rs b/plugin/audit/src/lib.rs index 991a9c9e..f15e24a8 100644 --- a/plugin/audit/src/lib.rs +++ b/plugin/audit/src/lib.rs @@ -30,7 +30,9 @@ use std::{ }; use { - hyperlane::{AUTHORIZATION, COOKIE, Context, Method, Request, ServerHook, Status, Stream}, + hyperlane::{ + AUTHORIZATION, ArcAnySendSync, COOKIE, Context, Method, Request, ServerHook, Status, Stream, + }, lombok_macros::*, serde::{Deserialize, Serialize}, }; diff --git a/plugin/auth/src/const.rs b/plugin/auth/src/const.rs index f4d1c039..f82d2a8e 100644 --- a/plugin/auth/src/const.rs +++ b/plugin/auth/src/const.rs @@ -16,6 +16,10 @@ pub const JWT_TYP_JWT: &str = "JWT"; /// Prefix for HTTP `Authorization: Bearer ` headers. pub(crate) const PREFIX_BEARER: &str = "bearer "; +/// Preformatted internal map key for zero-allocation storage of [`crate::AuthPrincipal`]. +pub(crate) const ATTR_AUTH_PRINCIPAL_MAP_KEY: &str = + "External(\"hyperlane_plugin_auth_principal\")"; + /// Prefix for HTTP `Authorization: Basic ` headers. pub(crate) const PREFIX_BASIC: &str = "basic "; diff --git a/plugin/auth/src/impl.rs b/plugin/auth/src/impl.rs index 4b68be57..0caa2af0 100644 --- a/plugin/auth/src/impl.rs +++ b/plugin/auth/src/impl.rs @@ -803,17 +803,18 @@ impl JwtCodec { String::from_utf8(token_bytes).map_err(|_| AuthError::InvalidCredentials) } - /// Verifies and decodes a compact HS256 JWT at timestamp `now_secs`. + /// Verifies and decodes a compact HS256 JWT, lazily querying system time only when `exp`/`nbf` claims exist. /// /// # Arguments /// /// - `&str` - Compact JWT string (`header.payload.signature`). - /// - `u64` - Current Unix timestamp in seconds. + /// - `Option` - Explicit Unix timestamp override, or `None` to query system time lazily. /// /// # Returns /// /// - `Result` - Verified [`JwtClaims`] or detailed [`AuthError`]. - pub fn decode_at(&self, token: &str, now_secs: u64) -> Result { + #[inline] + fn decode_inner(&self, token: &str, now_override: Option) -> Result { let Self { default_hmac, default_kid, @@ -896,15 +897,18 @@ impl JwtCodec { let JwtClaims { iss, aud, exp, nbf, .. } = &claims; - if let Some(exp_val) = *exp - && now_secs > exp_val.saturating_add(*leeway_secs) - { - return Err(AuthError::TokenExpired); - } - if let Some(nbf_val) = *nbf - && now_secs.saturating_add(*leeway_secs) < nbf_val - { - return Err(AuthError::TokenNotYetValid); + if exp.is_some() || nbf.is_some() { + let now_secs: u64 = now_override.unwrap_or_else(auth_now_secs); + if let Some(exp_val) = *exp + && now_secs > exp_val.saturating_add(*leeway_secs) + { + return Err(AuthError::TokenExpired); + } + if let Some(nbf_val) = *nbf + && now_secs.saturating_add(*leeway_secs) < nbf_val + { + return Err(AuthError::TokenNotYetValid); + } } if let Some(expected_iss) = required_issuer && iss.as_deref() != Some(expected_iss.as_str()) @@ -919,6 +923,20 @@ impl JwtCodec { Ok(claims) } + /// Verifies and decodes a compact HS256 JWT at timestamp `now_secs`. + /// + /// # Arguments + /// + /// - `&str` - Compact JWT string (`header.payload.signature`). + /// - `u64` - Current Unix timestamp in seconds. + /// + /// # Returns + /// + /// - `Result` - Verified [`JwtClaims`] or detailed [`AuthError`]. + pub fn decode_at(&self, token: &str, now_secs: u64) -> Result { + self.decode_inner(token, Some(now_secs)) + } + /// Verifies and decodes a compact HS256 JWT against current system time. /// /// # Arguments @@ -929,7 +947,7 @@ impl JwtCodec { /// /// - `Result` - Verified [`JwtClaims`] or [`AuthError`]. pub fn decode(&self, token: &str) -> Result { - self.decode_at(token, auth_now_secs()) + self.decode_inner(token, None) } } @@ -1336,7 +1354,13 @@ impl Authenticator for CompositeAuthenticator { Box::pin(async move { let mut last_err: AuthError = AuthError::MissingCredentials; for auth in chain { - match auth.authenticate(ctx).await { + let outcome: Result = + if let Some(sync_res) = auth.authenticate_sync(ctx) { + sync_res + } else { + auth.authenticate(ctx).await + }; + match outcome { Ok(principal) => return Ok(principal), Err(AuthError::MissingCredentials) => {} Err(err) => last_err = err, @@ -1345,6 +1369,30 @@ impl Authenticator for CompositeAuthenticator { Err(last_err) }) } + + /// Evaluates the authenticator chain synchronously when all visited inner authenticators support sync execution. + /// + /// # Arguments + /// + /// - `&Self` - Shared reference to self. + /// - `&Context` - Incoming request context. + /// + /// # Returns + /// + /// - `Option>` - Synchronous outcome when no async authenticator is needed. + #[inline] + fn authenticate_sync(&self, ctx: &Context) -> Option> { + let Self { chain } = self; + let mut last_err: AuthError = AuthError::MissingCredentials; + for auth in chain { + match auth.authenticate_sync(ctx)? { + Ok(principal) => return Some(Ok(principal)), + Err(AuthError::MissingCredentials) => {} + Err(err) => last_err = err, + } + } + Some(Err(last_err)) + } } /// Default construction for [`AuthConfig`]. @@ -1511,6 +1559,31 @@ impl AuthPlugin { ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL) } + /// Stores [`AuthPrincipal`] in `ctx`, reusing any unique existing `Arc` slot in place. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// - `AuthPrincipal` - Verified principal. + #[inline(always)] + pub(crate) fn put_principal(ctx: &mut Context, principal: AuthPrincipal) { + if let Some(slot) = ctx + .get_mut_attributes() + .get_mut(ATTR_AUTH_PRINCIPAL_MAP_KEY) + { + if let Some(any_mut) = Arc::get_mut(slot) + && let Some(existing) = any_mut.downcast_mut::() + { + *existing = principal; + return; + } + *slot = Arc::new(principal); + return; + } + ctx.get_mut_attributes() + .insert(ATTR_AUTH_PRINCIPAL_MAP_KEY.to_owned(), Arc::new(principal)); + } + /// Checks whether `principal` satisfies the configured RBAC role requirements. /// /// # Arguments @@ -1554,6 +1627,34 @@ impl ServerHook for AuthHook { Self } + /// Synchronously authenticates unconfigured, exempt, and sync-authenticated authorized requests without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when admitted synchronously, or `None` for rejection/async auth. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = AuthPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.is_exempt_path(ctx.get_request().get_path()) { + return Some(Status::Continue); + } + let Ok(principal) = plugin.get_authenticator().authenticate_sync(ctx)? else { + return None; + }; + if !plugin.is_authorized(&principal) { + return None; + } + AuthPlugin::put_principal(ctx, principal); + Some(Status::Continue) + } + /// Authenticates protected requests, verifies required roles, and attaches [`AuthPrincipal`]. /// /// # Arguments diff --git a/plugin/body_limit/src/impl.rs b/plugin/body_limit/src/impl.rs index 73661761..c39b5e82 100644 --- a/plugin/body_limit/src/impl.rs +++ b/plugin/body_limit/src/impl.rs @@ -334,6 +334,27 @@ impl ServerHook for BodyLimitHook { Self } + /// Synchronously enforces request body size limits on admitted/unconfigured paths without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured or permitted, or `None` when rejected. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = BodyLimitPlugin::get() else { + return Some(Status::Continue); + }; + match plugin.evaluate(ctx.get_request()) { + BodyLimitDecision::Allow { .. } => Some(Status::Continue), + BodyLimitDecision::Reject { .. } => None, + } + } + /// Checks request body and declared `Content-Length` against configured caps. /// /// # Arguments diff --git a/plugin/cache/src/const.rs b/plugin/cache/src/const.rs index 50dfa3a6..95d0b236 100644 --- a/plugin/cache/src/const.rs +++ b/plugin/cache/src/const.rs @@ -31,9 +31,6 @@ pub(crate) const AGE_STACK_BUF_LEN: usize = 20; /// Fast-path stack wire assembly capacity for small HTTP/1.1 cache hit responses. pub(crate) const CACHE_WIRE_FAST_STACK_CAP: usize = 512; -/// Maximum prebuilt HTTP/1.1 cache hit response length assembled on the stack without heap allocation. -pub(crate) const CACHE_WIRE_STACK_CAP: usize = 4096; - /// FNV-1a 64-bit offset basis used for fast cache shard selection. pub(crate) const CACHE_FNV1A_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; diff --git a/plugin/cache/src/impl.rs b/plugin/cache/src/impl.rs index 8622a765..cf7ad2e7 100644 --- a/plugin/cache/src/impl.rs +++ b/plugin/cache/src/impl.rs @@ -741,14 +741,6 @@ impl ServerHook for CacheRequestHook { .copy_from_slice(&wire_parts.with_diag_suffix); let _: Result<(), ResponseError> = stream.try_send(&stack[..total_len]).await; - } else if total_len <= CACHE_WIRE_STACK_CAP { - let mut stack: [u8; CACHE_WIRE_STACK_CAP] = [0u8; CACHE_WIRE_STACK_CAP]; - stack[..prefix_len].copy_from_slice(&wire_parts.with_diag_prefix); - stack[prefix_len..prefix_len + age_bytes.len()].copy_from_slice(age_bytes); - stack[prefix_len + age_bytes.len()..total_len] - .copy_from_slice(&wire_parts.with_diag_suffix); - let _: Result<(), ResponseError> = - stream.try_send(&stack[..total_len]).await; } else { let mut wire: Vec = Vec::with_capacity(total_len); wire.extend_from_slice(&wire_parts.with_diag_prefix); @@ -807,6 +799,55 @@ impl ServerHook for CacheRequestHook { ctx.set_attribute(ATTR_HTTP_CACHE_KEY, key); Status::Continue } + + /// Synchronous fast path avoiding future construction when unconfigured, non-cacheable, or local-store miss. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when handled synchronously, or `None` on hit/async store. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = CachePlugin::get() else { + return Some(Status::Continue); + }; + let req: &Request = ctx.get_request(); + let is_get: bool = req.get_method().is_get(); + let is_head: bool = !is_get && req.get_method().is_head(); + if !is_get && !is_head { + return Some(Status::Continue); + } + let config: &CacheConfig = plugin.get_config(); + let has_auth: bool = config.get_bypass_authenticated() + && (req.get_headers().contains_key(AUTHORIZATION) + || req.get_headers().contains_key(COOKIE)); + let req_cacheable: bool = if has_auth { + false + } else { + let (ok, _): (bool, Option) = + parse_cache_control(request_header_back(req, CACHE_CONTROL)); + ok + }; + if !req_cacheable || has_auth { + if config.get_emit_diagnostic_headers() { + ctx.get_mut_response() + .set_header(HEADER_X_CACHE, X_CACHE_BYPASS); + } + return Some(Status::Continue); + } + if let Some(local) = plugin.get_local_store() { + let key_cow: Cow<'_, str> = build_http_cache_key_cow(ctx); + if local.get_entry_sync(&key_cow).is_none() { + ctx.set_attribute(ATTR_HTTP_CACHE_KEY, key_cow.into_owned()); + return Some(Status::Continue); + } + } + None + } } /// Implements [`ServerHook`] for [`CacheResponseHook`]. @@ -882,4 +923,58 @@ impl ServerHook for CacheResponseHook { } Status::Continue } + + /// Synchronous fast path for unconfigured, unkeyed, or local-store cache fills. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when handled synchronously, or `None` for async stores. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = CachePlugin::get() else { + return Some(Status::Continue); + }; + let Some(key) = ctx.try_get_attribute::(ATTR_HTTP_CACHE_KEY) else { + return Some(Status::Continue); + }; + let local: &ShardedMemoryCache = plugin.get_local_store()?; + let config: &CacheConfig = plugin.get_config(); + let resp: &Response = ctx.get_response(); + let status: usize = resp.get_status_code(); + let body_len: usize = resp.get_body().len(); + if status == HttpStatus::Ok.code() && body_len <= config.get_max_entry_bytes() { + let (cc_ok, ttl_override): (bool, Option) = + parse_cache_control(response_header_back(resp, CACHE_CONTROL)); + let vary_star: bool = + response_header_back(resp, VARY).is_some_and(|val: &str| val.trim() == "*"); + if cc_ok && !vary_star { + let ttl_ms: u64 = ttl_override.unwrap_or(config.get_default_ttl_ms()); + if ttl_ms > 0 { + let mut headers: Vec<(String, String)> = + Vec::with_capacity(resp.get_headers().len()); + for (name, values) in resp.get_headers() { + if !name.eq_ignore_ascii_case(HEADER_X_CACHE) + && !name.eq_ignore_ascii_case(AGE) + && let Some(last) = values.back() + { + headers.push((name.clone(), last.clone())); + } + } + let cached: CachedValue = + CachedValue::new(status, headers, resp.get_body().clone()); + local.put_sync(key, cached, ttl_ms); + } + } + } + if config.get_emit_diagnostic_headers() && !ctx.get_response().has_header(HEADER_X_CACHE) { + ctx.get_mut_response() + .set_header(HEADER_X_CACHE, X_CACHE_MISS); + } + Some(Status::Continue) + } } diff --git a/plugin/canary/src/const.rs b/plugin/canary/src/const.rs index b7b3d868..f4ecf00d 100644 --- a/plugin/canary/src/const.rs +++ b/plugin/canary/src/const.rs @@ -15,3 +15,10 @@ pub const DEFAULT_VARIANT_HEADER: &str = "x-variant"; /// Root slash constant. pub(crate) const ROOT_SLASH: &str = "/"; + +/// Preformatted internal map key for zero-allocation lookup/update of [`CanaryDecision`]. +pub(crate) const ATTR_CANARY_DECISION_MAP_KEY: &str = + "External(\"hyperlane_plugin_canary.decision\")"; + +/// Stack copy buffer capacity for emitting `X-Variant` response header without heap allocation. +pub(crate) const VARIANT_STACK_CAP: usize = 64; diff --git a/plugin/canary/src/impl.rs b/plugin/canary/src/impl.rs index 9c442a54..7c796c8c 100644 --- a/plugin/canary/src/impl.rs +++ b/plugin/canary/src/impl.rs @@ -327,6 +327,138 @@ impl CanaryPlugin { }) } + /// Evaluates matching experiment rules and writes [`CanaryDecision`] directly into `ctx`, reusing unique attribute buffers. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + #[inline] + pub(crate) fn evaluate_into_context(&self, ctx: &mut Context) { + let Self { + config, + rules, + sticky_header_lower, + override_header_lower, + .. + } = self; + let matched: Option = { + let request: &Request = ctx.get_request(); + let path: &str = request.get_path(); + if let Some((rule_idx, rule)) = rules + .iter() + .enumerate() + .find(|(_, r): &(usize, &CompiledExperiment)| path_matches_prefix(path, &r.prefix)) + { + if let Some(ov_header) = override_header_lower + && let Some(ov_val) = request + .get_headers() + .get(ov_header.as_str()) + .and_then(|vals: &VecDeque| vals.back()) + && !ov_val.trim().is_empty() + { + Some(CanaryRuleMatch { + rule_idx, + arm_idx: None, + override_variant: Some(ov_val.trim().to_owned()), + bucket: 0, + overridden: true, + }) + } else { + let subject: &str = if !sticky_header_lower.is_empty() + && let Some(val) = request + .get_headers() + .get(sticky_header_lower.as_str()) + .and_then(|vals: &VecDeque| vals.back()) + { + val.trim() + } else if let Some(cookie_name) = config.try_get_sticky_cookie() + && let Some(raw_cookie) = request + .get_headers() + .get(COOKIE) + .and_then(|vals: &VecDeque| vals.back()) + && let Some(found) = find_cookie_slice(raw_cookie, cookie_name) + { + found + } else { + path + }; + let bucket: u16 = bucket_basis_points(&rule.name, subject); + let mut arm_idx: Option = None; + for (idx, (upper, _)) in rule.cumulative.iter().enumerate() { + if bucket < *upper { + arm_idx = Some(idx); + break; + } + } + Some(CanaryRuleMatch { + rule_idx, + arm_idx, + override_variant: None, + bucket, + overridden: false, + }) + } + } else { + None + } + }; + let Some(CanaryRuleMatch { + rule_idx, + arm_idx, + override_variant, + bucket, + overridden, + }) = matched + else { + return; + }; + let rule: &CompiledExperiment = &rules[rule_idx]; + let rule_variant_ref: &str = if let Some(idx) = arm_idx { + rule.cumulative[idx].1.as_str() + } else { + rule.default_variant.as_str() + }; + if let Some(slot) = ctx + .get_mut_attributes() + .get_mut(ATTR_CANARY_DECISION_MAP_KEY) + { + if let Some(any_mut) = Arc::get_mut(slot) + && let Some(existing) = any_mut.downcast_mut::() + { + existing.experiment.clear(); + existing.experiment.push_str(&rule.name); + if let Some(ov) = override_variant { + existing.variant = ov; + } else { + existing.variant.clear(); + existing.variant.push_str(rule_variant_ref); + } + existing.bucket = bucket; + existing.overridden = overridden; + return; + } + let variant_owned: String = + override_variant.unwrap_or_else(|| rule_variant_ref.to_owned()); + *slot = Arc::new(CanaryDecision { + experiment: rule.name.clone(), + variant: variant_owned, + bucket, + overridden, + }); + return; + } + let variant_owned: String = override_variant.unwrap_or_else(|| rule_variant_ref.to_owned()); + ctx.get_mut_attributes().insert( + ATTR_CANARY_DECISION_MAP_KEY.to_owned(), + Arc::new(CanaryDecision { + experiment: rule.name.clone(), + variant: variant_owned, + bucket, + overridden, + }), + ); + } + /// Emits `X-Variant` and optional `Vary` response headers when a [`CanaryDecision`] is present. /// /// # Arguments @@ -343,16 +475,45 @@ impl CanaryPlugin { if variant_header_lower.is_empty() { return; } - let Some(variant_copy): Option = ctx - .try_get_attribute_ref::(ATTR_CANARY_DECISION) - .map(|d: &CanaryDecision| d.get_variant().clone()) - else { + let mut stack_buf: [u8; VARIANT_STACK_CAP] = [0u8; VARIANT_STACK_CAP]; + let mut stack_len: Option = None; + let mut heap_copy: Option = None; + { + let Some(decision) = ctx + .get_attributes() + .get(ATTR_CANARY_DECISION_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) + else { + return; + }; + let var_bytes: &[u8] = decision.get_variant().as_bytes(); + if var_bytes.len() <= VARIANT_STACK_CAP { + stack_buf[..var_bytes.len()].copy_from_slice(var_bytes); + stack_len = Some(var_bytes.len()); + } else { + heap_copy = Some(decision.get_variant().clone()); + } + } + let variant_str: &str = if let Some(len) = stack_len { + from_utf8(&stack_buf[..len]).unwrap_or_default() + } else if let Some(ref owned) = heap_copy { + owned.as_str() + } else { return; }; let response: &mut Response = ctx.get_mut_response(); - response.set_header(variant_header_lower.as_str(), variant_copy.as_str()); if config.get_emit_vary() && !sticky_header_lower.is_empty() { - merge_vary_header(response, sticky_header_lower); + if !response.get_headers().contains_key(VARY) { + response.set_headers_batch(&[ + (variant_header_lower.as_str(), variant_str), + (VARY, sticky_header_lower.as_str()), + ]); + } else { + response.set_header(variant_header_lower.as_str(), variant_str); + merge_vary_header(response, sticky_header_lower); + } + } else { + response.set_header(variant_header_lower.as_str(), variant_str); } } } @@ -374,6 +535,25 @@ impl ServerHook for CanaryRequestHook { Self } + /// Synchronously evaluates matching experiment rules and attaches [`CanaryDecision`] without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = CanaryPlugin::get() else { + return Some(Status::Continue); + }; + plugin.evaluate_into_context(ctx); + Some(Status::Continue) + } + /// Evaluates matching experiment rules and attaches [`CanaryDecision`] to `ctx`. /// /// # Arguments @@ -386,14 +566,8 @@ impl ServerHook for CanaryRequestHook { /// /// - `Status` - Always `Status::Continue`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { - let Some(plugin) = CanaryPlugin::get() else { - return Status::Continue; - }; - if let Some(decision) = plugin.evaluate(ctx.get_request()) { - ctx.set_attribute(ATTR_CANARY_DECISION, decision); - } - Status::Continue + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } @@ -414,23 +588,38 @@ impl ServerHook for CanaryResponseHook { Self } - /// Writes configured variant and `Vary` headers onto the outgoing response. + /// Synchronously writes configured variant and `Vary` headers onto the outgoing response without async futures. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = CanaryPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; plugin.apply_response_headers(ctx); - Status::Continue + Some(Status::Continue) + } + + /// Writes configured variant and `Vary` headers onto the outgoing response. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/canary/src/lib.rs b/plugin/canary/src/lib.rs index 399a0e79..28c87c60 100644 --- a/plugin/canary/src/lib.rs +++ b/plugin/canary/src/lib.rs @@ -18,9 +18,17 @@ pub use {r#const::*, r#fn::*, r#struct::*}; pub(crate) use r#static::*; -use std::{collections::VecDeque, hash::Hasher, sync::OnceLock}; +use std::{ + collections::VecDeque, + hash::Hasher, + str::from_utf8, + sync::{Arc, OnceLock}, +}; use { - hyperlane::{COOKIE, Context, Request, Response, ServerHook, Status, Stream, VARY, XxHash3_64}, + hyperlane::{ + ArcAnySendSync, COOKIE, Context, Request, Response, ServerHook, Status, Stream, VARY, + XxHash3_64, + }, lombok_macros::*, }; diff --git a/plugin/canary/src/struct.rs b/plugin/canary/src/struct.rs index a9f04019..bc8a2765 100644 --- a/plugin/canary/src/struct.rs +++ b/plugin/canary/src/struct.rs @@ -93,3 +93,18 @@ pub struct CanaryRequestHook; #[derive(Clone, Copy, Debug, Default)] #[hyperlane::response_middleware(-68)] pub struct CanaryResponseHook; + +/// Internal canary rule evaluation result prior to populating [`CanaryDecision`]. +#[derive(Debug)] +pub(crate) struct CanaryRuleMatch { + /// Matched experiment index in `CanaryPlugin::rules`. + pub(crate) rule_idx: usize, + /// Optional matched cumulative arm index. + pub(crate) arm_idx: Option, + /// Optional forced override variant string. + pub(crate) override_variant: Option, + /// Computed basis-point bucket. + pub(crate) bucket: u16, + /// Whether the variant came from a forced override header. + pub(crate) overridden: bool, +} diff --git a/plugin/circuit_breaker/src/const.rs b/plugin/circuit_breaker/src/const.rs index fa202040..f1225fe5 100644 --- a/plugin/circuit_breaker/src/const.rs +++ b/plugin/circuit_breaker/src/const.rs @@ -34,6 +34,10 @@ pub const DEFAULT_OPEN_CONTENT_TYPE: &str = "text/plain; charset=utf-8"; /// Atomic state tag representing [`CircuitState::Closed`]. pub(crate) const STATE_CLOSED: u8 = 0; +/// Preformatted internal map key for zero-allocation lookup of half-open probe tokens. +pub(crate) const ATTR_CIRCUIT_BREAKER_TOKEN_MAP_KEY: &str = + "External(\"hyperlane_plugin_circuit_breaker_token\")"; + /// Atomic state tag representing [`CircuitState::Open`]. pub(crate) const STATE_OPEN: u8 = 1; diff --git a/plugin/circuit_breaker/src/impl.rs b/plugin/circuit_breaker/src/impl.rs index a7bdd5ff..d5455d95 100644 --- a/plugin/circuit_breaker/src/impl.rs +++ b/plugin/circuit_breaker/src/impl.rs @@ -689,6 +689,28 @@ impl CompiledBreaker { } } + /// Records a completed response outcome for a closed-circuit request without permit indirection. + /// + /// # Arguments + /// + /// - `usize` - Final HTTP response status code. + #[inline] + pub(crate) fn record_closed_outcome(&self, status_code: usize) { + let Self { state, rule, .. } = self; + let is_failure: bool = self.is_failure_status(status_code); + let current_slot: u64 = self.current_slot_fast(); + self.record_window_sample_slot(current_slot, is_failure); + if is_failure && state.load(Ordering::Relaxed) == STATE_CLOSED { + let (total, failures): (u64, u64) = self.read_window_totals_for_slot(current_slot); + if total >= rule.get_minimum_requests() { + let ratio: f64 = (failures as f64) / (total as f64); + if ratio >= rule.get_failure_rate_threshold() { + self.trip_open(STATE_CLOSED, self.now_ms()); + } + } + } + } + /// Records the final HTTP response outcome for an admitted request or probe. /// /// # Arguments @@ -703,23 +725,12 @@ impl CompiledBreaker { half_open_successes, .. } = self; - let is_failure: bool = self.is_failure_status(status_code); match permit { BreakerPermit::Closed { .. } => { - let current_slot: u64 = self.current_slot_fast(); - self.record_window_sample_slot(current_slot, is_failure); - if is_failure && state.load(Ordering::Relaxed) == STATE_CLOSED { - let (total, failures): (u64, u64) = - self.read_window_totals_for_slot(current_slot); - if total >= rule.get_minimum_requests() { - let ratio: f64 = (failures as f64) / (total as f64); - if ratio >= rule.get_failure_rate_threshold() { - self.trip_open(STATE_CLOSED, self.now_ms()); - } - } - } + self.record_closed_outcome(status_code); } BreakerPermit::HalfOpenProbe(guard) => { + let is_failure: bool = self.is_failure_status(status_code); if !guard.mark_completed() { return; } @@ -827,6 +838,38 @@ impl CircuitBreakerEngine { None } + /// Checks lock-free whether `path` has no matching rule or its matched breaker is currently `Closed`. + /// + /// # Arguments + /// + /// - `&str` - Incoming request path. + /// + /// # Returns + /// + /// - `bool` - `true` when the request may proceed synchronously without attribute or probe allocation. + #[inline(always)] + pub(crate) fn try_admit_closed_sync(&self, path: &str) -> bool { + let Self { breakers, .. } = self; + let Some(slot_idx) = self.match_slot(path) else { + return true; + }; + breakers[slot_idx].state.load(Ordering::Relaxed) == STATE_CLOSED + } + + /// Records the final HTTP `status_code` directly for a closed-circuit request matching `path`. + /// + /// # Arguments + /// + /// - `&str` - Request path. + /// - `usize` - Final HTTP response status code. + #[inline] + pub(crate) fn record_closed_for_path(&self, path: &str, status_code: usize) { + let Self { breakers, .. } = self; + if let Some(slot_idx) = self.match_slot(path) { + breakers[slot_idx].record_closed_outcome(status_code); + } + } + /// Checks whether a request for `path` is admitted by the matched circuit breaker. /// /// Returns `Ok(None)` when no rule matches `path`, `Ok(Some(permit))` when admitted, or @@ -943,6 +986,30 @@ impl ServerHook for CircuitBreakerRequestHook { Self } + /// Synchronously admits closed-circuit and unmatched requests without async futures or context attributes. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured, unmatched, or closed; `None` when open/half-open. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = CircuitBreakerPlugin::get() else { + return Some(Status::Continue); + }; + if plugin + .get_engine() + .try_admit_closed_sync(ctx.get_request().get_path()) + { + return Some(Status::Continue); + } + None + } + /// Gates incoming requests against the matched breaker, short-circuiting open circuits with `503`. /// /// # Arguments @@ -960,11 +1027,14 @@ impl ServerHook for CircuitBreakerRequestHook { }; let path: &str = ctx.get_request().get_path(); match plugin.get_engine().before_request(path) { + Ok(Some(BreakerPermit::Closed { .. })) | Ok(None) => Status::Continue, Ok(Some(permit)) => { - ctx.set_attribute(ATTR_CIRCUIT_BREAKER_TOKEN, permit); + ctx.get_mut_attributes().insert( + ATTR_CIRCUIT_BREAKER_TOKEN_MAP_KEY.to_owned(), + Arc::new(permit), + ); Status::Continue } - Ok(None) => Status::Continue, Err(prebuilt_wire) => { let _: Result<(), ResponseError> = stream.try_send(prebuilt_wire).await; Status::Reject @@ -989,28 +1059,48 @@ impl ServerHook for CircuitBreakerResponseHook { Self } - /// Observes the final response status code and updates the matched circuit breaker state machine. + /// Synchronously observes the final response status code and updates the matched circuit breaker. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = CircuitBreakerPlugin::get() else { - return Status::Continue; - }; - let Some(permit) = ctx.try_get_attribute::(ATTR_CIRCUIT_BREAKER_TOKEN) - else { - return Status::Continue; + return Some(Status::Continue); }; let status_code: usize = ctx.get_response().get_status_code(); - plugin.get_engine().after_response(&permit, status_code); - ctx.remove_attribute(ATTR_CIRCUIT_BREAKER_TOKEN); - Status::Continue + let engine: &CircuitBreakerEngine = plugin.get_engine(); + if !ctx.get_attributes().is_empty() + && let Some(raw_token) = ctx + .get_mut_attributes() + .remove(ATTR_CIRCUIT_BREAKER_TOKEN_MAP_KEY) + && let Some(permit) = raw_token.downcast_ref::() + { + engine.after_response(permit, status_code); + return Some(Status::Continue); + } + engine.record_closed_for_path(ctx.get_request().get_path(), status_code); + Some(Status::Continue) + } + + /// Observes the final response status code and updates the matched circuit breaker state machine. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/circuit_breaker/src/struct.rs b/plugin/circuit_breaker/src/struct.rs index e7a22e2a..2c335610 100644 --- a/plugin/circuit_breaker/src/struct.rs +++ b/plugin/circuit_breaker/src/struct.rs @@ -56,7 +56,8 @@ pub(crate) struct FastDiv64 { pub(crate) shift: u32, } -/// One lock-free time-slice bucket inside a circuit breaker's sliding-window ring. +/// One cache-line-aligned lock-free time-slice bucket inside a circuit breaker's sliding-window ring. +#[repr(align(64))] pub(crate) struct WindowBucket { /// Monotonic time-slice identifier (`(now_ms / bucket_ms) + 1`, `0` = empty). pub(crate) epoch_slot: AtomicU64, diff --git a/plugin/compression/src/impl.rs b/plugin/compression/src/impl.rs index 09957c21..81b37316 100644 --- a/plugin/compression/src/impl.rs +++ b/plugin/compression/src/impl.rs @@ -162,18 +162,20 @@ impl CompressionPlugin { if !config.get_decompress_requests() || request.get_body().is_empty() { return Ok(false); } - let encoding_raw: String = match request - .get_headers() - .get(CONTENT_ENCODING) - .and_then(|vals: &VecDeque| vals.back()) - { - Some(v) => v.trim().to_owned(), - None => return Ok(false), + let codec: Compress = { + let Some(raw) = request + .get_headers() + .get(CONTENT_ENCODING) + .and_then(|vals: &VecDeque| vals.back()) + else { + return Ok(false); + }; + let trimmed: &str = raw.trim(); + if trimmed.is_empty() || trimmed.eq_ignore_ascii_case(CONTENT_ENCODING_IDENTITY) { + return Ok(false); + } + trimmed.parse::().unwrap_or_default() }; - if encoding_raw.is_empty() || encoding_raw.eq_ignore_ascii_case(CONTENT_ENCODING_IDENTITY) { - return Ok(false); - } - let codec: Compress = encoding_raw.parse::().unwrap_or_default(); if codec.is_unknown() { if config.get_reject_unknown_encoding() { return Err(HttpStatus::UnsupportedMediaType); @@ -279,6 +281,27 @@ impl ServerHook for CompressionRequestHook { Self } + /// Synchronously decompresses valid inbound request bodies and bypasses uncompressed traffic without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured or accepted, or `None` on `413`/`415` error. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = CompressionPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.decompress_request(ctx.get_mut_request()).is_ok() { + return Some(Status::Continue); + } + None + } + /// Decompresses inbound compressed request bodies with size and codec safety guards. /// /// # Arguments @@ -330,23 +353,38 @@ impl ServerHook for CompressionResponseHook { Self } - /// Negotiates response content-encoding and ensures `Vary: Accept-Encoding`. + /// Synchronously negotiates response content-encoding and ensures `Vary: Accept-Encoding` without async futures. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = CompressionPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; let _: bool = plugin.apply_response_compression(ctx); - Status::Continue + Some(Status::Continue) + } + + /// Negotiates response content-encoding and ensures `Vary: Accept-Encoding`. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/concurrency/src/impl.rs b/plugin/concurrency/src/impl.rs index 15647332..d93ece8a 100644 --- a/plugin/concurrency/src/impl.rs +++ b/plugin/concurrency/src/impl.rs @@ -885,6 +885,35 @@ impl ServerHook for ConcurrencyRequestHook { } } } + + /// Synchronous fast path avoiding future construction when unconfigured, exempt, or admitted without queueing. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when handled synchronously, or `None` to await queue/shedding. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = ConcurrencyPlugin::get() else { + return Some(Status::Continue); + }; + let limiter: &ConcurrencyLimiter = plugin.get_limiter(); + let path: &str = ctx.get_request().get_path(); + if limiter.is_path_exempt(path) { + return Some(Status::Continue); + } + if !limiter.has_wait_queue() + && let Ok(permit) = limiter.try_acquire(path) + { + ctx.set_attribute(ATTR_CONCURRENCY_PERMIT, permit); + return Some(Status::Continue); + } + None + } } /// Implements [`ServerHook`] for [`ConcurrencyResponseHook`]. @@ -915,6 +944,9 @@ impl ServerHook for ConcurrencyResponseHook { /// /// - `Status` - Always `Status::Continue`. async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + if ConcurrencyPlugin::get().is_none() { + return Status::Continue; + } if let Some(permit) = ctx.try_get_attribute_ref::(ATTR_CONCURRENCY_PERMIT) { @@ -923,4 +955,28 @@ impl ServerHook for ConcurrencyResponseHook { } Status::Continue } + + /// Releases any held concurrency permit synchronously without constructing a future. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + if ConcurrencyPlugin::get().is_none() { + return Some(Status::Continue); + } + if let Some(permit) = + ctx.try_get_attribute_ref::(ATTR_CONCURRENCY_PERMIT) + { + permit.release(); + ctx.remove_attribute(ATTR_CONCURRENCY_PERMIT); + } + Some(Status::Continue) + } } diff --git a/plugin/cors/src/impl.rs b/plugin/cors/src/impl.rs index 0e3a5123..1d93d207 100644 --- a/plugin/cors/src/impl.rs +++ b/plugin/cors/src/impl.rs @@ -890,7 +890,9 @@ impl ServerHook for CorsRequestHook { return Status::Continue; }; let compiled: &CompiledCors = plugin.get_compiled(); - if compiled.try_send_fast_preflight(stream, ctx).await == Some(true) { + if ctx.get_request().get_method().is_options() + && compiled.try_send_fast_preflight(stream, ctx).await == Some(true) + { return Status::Reject; } if compiled.apply_request(ctx) { @@ -899,6 +901,28 @@ impl ServerHook for CorsRequestHook { } Status::Continue } + + /// Synchronous fast path for unconfigured and non-`OPTIONS` CORS requests. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for non-preflight requests, or `None` for `OPTIONS`. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = CorsPlugin::get() else { + return Some(Status::Continue); + }; + if ctx.get_request().get_method().is_options() { + return None; + } + let _: bool = plugin.get_compiled().apply_request(ctx); + Some(Status::Continue) + } } /// Implements [`ServerHook`] for [`CorsResponseHook`]. @@ -936,4 +960,23 @@ impl ServerHook for CorsResponseHook { plugin.get_compiled().ensure_response_headers(ctx); Status::Continue } + + /// Ensures CORS response headers synchronously without constructing a future. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = CorsPlugin::get() else { + return Some(Status::Continue); + }; + plugin.get_compiled().ensure_response_headers(ctx); + Some(Status::Continue) + } } diff --git a/plugin/env/src/const.rs b/plugin/env/src/const.rs index b8473335..cb7bf1bf 100644 --- a/plugin/env/src/const.rs +++ b/plugin/env/src/const.rs @@ -75,3 +75,6 @@ pub(crate) const ERR_INVALID_KEY: &str = "invalid variable name"; /// Error reason for unclosed quoted value in `.env`. pub(crate) const ERR_UNCLOSED_QUOTE: &str = "unterminated quoted value"; + +/// Stack buffer capacity for zero-allocation prefixed environment key lookups. +pub(crate) const ENV_KEY_STACK_CAP: usize = 128; diff --git a/plugin/env/src/impl.rs b/plugin/env/src/impl.rs index 0b10c7ea..6b9ef400 100644 --- a/plugin/env/src/impl.rs +++ b/plugin/env/src/impl.rs @@ -249,7 +249,7 @@ impl EnvPlugin { } } - /// Looks up a raw string value by key (honoring any configured prefix). + /// Looks up a raw string value by key (honoring any configured prefix) without heap allocation on common keys. /// /// # Arguments /// @@ -258,8 +258,21 @@ impl EnvPlugin { /// # Returns /// /// - `Option<&str>` - Stored string value if present. + #[inline] pub fn get_str(&self, key: &str) -> Option<&str> { - let Self { values, .. } = self; + let Self { prefix, values } = self; + if prefix.is_empty() { + return values.get(key).map(String::as_str); + } + let total: usize = prefix.len() + key.len(); + if total <= ENV_KEY_STACK_CAP { + let mut stack: [u8; ENV_KEY_STACK_CAP] = [0u8; ENV_KEY_STACK_CAP]; + stack[..prefix.len()].copy_from_slice(prefix.as_bytes()); + stack[prefix.len()..total].copy_from_slice(key.as_bytes()); + if let Ok(resolved) = from_utf8(&stack[..total]) { + return values.get(resolved).map(String::as_str); + } + } let resolved: String = self.full_key(key); values.get(&resolved).map(String::as_str) } @@ -332,14 +345,24 @@ impl EnvPlugin { let Some(raw) = self.get_str(key) else { return Ok(None); }; - let lower: String = raw.trim().to_ascii_lowercase(); - match lower.as_str() { - BOOL_TRUE | "1" | "yes" | "on" => Ok(Some(true)), - BOOL_FALSE | "0" | "no" | "off" => Ok(Some(false)), - _ => Err(EnvError::Parse { + let trimmed: &str = raw.trim(); + if trimmed.eq_ignore_ascii_case(BOOL_TRUE) + || trimmed == "1" + || trimmed.eq_ignore_ascii_case("yes") + || trimmed.eq_ignore_ascii_case("on") + { + Ok(Some(true)) + } else if trimmed.eq_ignore_ascii_case(BOOL_FALSE) + || trimmed == "0" + || trimmed.eq_ignore_ascii_case("no") + || trimmed.eq_ignore_ascii_case("off") + { + Ok(Some(false)) + } else { + Err(EnvError::Parse { key: self.full_key(key), reason: ERR_INVALID_BOOL.to_owned(), - }), + }) } } @@ -403,16 +426,18 @@ impl EnvPlugin { cfg.set_ttl(Some(ttl_val)); } if let Some(proto_raw) = self.get_str(KEY_PROTOCOL) { - let proto: ServerProtocol = match proto_raw.trim().to_ascii_lowercase().as_str() { - PROTO_HTTP1 => ServerProtocol::Http1, - PROTO_HTTP2 => ServerProtocol::Http2, - PROTO_HTTP3 => ServerProtocol::Http3, - _ => { - return Err(EnvError::Parse { - key: self.full_key(KEY_PROTOCOL), - reason: ERR_INVALID_PROTOCOL.to_owned(), - }); - } + let trimmed: &str = proto_raw.trim(); + let proto: ServerProtocol = if trimmed.eq_ignore_ascii_case(PROTO_HTTP1) { + ServerProtocol::Http1 + } else if trimmed.eq_ignore_ascii_case(PROTO_HTTP2) { + ServerProtocol::Http2 + } else if trimmed.eq_ignore_ascii_case(PROTO_HTTP3) { + ServerProtocol::Http3 + } else { + return Err(EnvError::Parse { + key: self.full_key(KEY_PROTOCOL), + reason: ERR_INVALID_PROTOCOL.to_owned(), + }); }; cfg.set_protocol(proto); } diff --git a/plugin/env/src/lib.rs b/plugin/env/src/lib.rs index b4e7e3fd..f2d7dc25 100644 --- a/plugin/env/src/lib.rs +++ b/plugin/env/src/lib.rs @@ -26,7 +26,7 @@ use std::{ fmt::{self, Debug, Display, Formatter}, fs, io, path::Path, - str::{Chars, FromStr}, + str::{Chars, FromStr, from_utf8}, sync::OnceLock, time::Duration, }; diff --git a/plugin/etag/src/impl.rs b/plugin/etag/src/impl.rs index 313fc0cd..0301b3e8 100644 --- a/plugin/etag/src/impl.rs +++ b/plugin/etag/src/impl.rs @@ -139,6 +139,27 @@ impl EtagPlugin { ETAG_PLUGIN.get() } + /// Reports whether `If-Match` precondition validation is bypassed for `request` without side effects. + /// + /// # Arguments + /// + /// - `&Request` - Incoming HTTP request. + /// + /// # Returns + /// + /// - `bool` - `true` when `If-Match` enforcement does not apply to this request. + #[inline(always)] + pub(crate) fn is_if_match_bypassed(&self, request: &Request) -> bool { + let Self { + config, validator, .. + } = self; + if !config.get_enforce_if_match() || validator.is_none() { + return true; + } + let method: &Method = request.get_method(); + method.is_get() || method.is_head() || method.is_options() + } + /// Evaluates `If-Match` precondition on a mutating request; returns `false` when `412` must be sent. /// /// # Arguments @@ -271,6 +292,27 @@ impl ServerHook for EtagRequestHook { Self } + /// Synchronously short-circuits unconfigured, safe-method, or validator-free requests without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when bypassed, or `None` to evaluate `If-Match` asynchronously. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = EtagPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.is_if_match_bypassed(ctx.get_request()) { + return Some(Status::Continue); + } + None + } + /// Enforces `If-Match` preconditions on mutating requests when an [`EtagValidator`] is configured. /// /// # Arguments @@ -316,23 +358,38 @@ impl ServerHook for EtagResponseHook { Self } - /// Generates `ETag` headers and converts matching `If-None-Match` responses to `304 Not Modified`. + /// Synchronously generates `ETag` headers and converts matching `If-None-Match` responses to `304 Not Modified`. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = EtagPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; let _: bool = plugin.apply_response(ctx); - Status::Continue + Some(Status::Continue) + } + + /// Generates `ETag` headers and converts matching `If-None-Match` responses to `304 Not Modified`. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/gateway/src/impl.rs b/plugin/gateway/src/impl.rs index 30d06ed1..d64768ab 100644 --- a/plugin/gateway/src/impl.rs +++ b/plugin/gateway/src/impl.rs @@ -895,6 +895,27 @@ impl ServerHook for GatewayHook { Self } + /// Synchronously passes through unconfigured and non-matching routes without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured or no route matches; `None` when matched. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = GatewayPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.get_runtime().match_route_for_ctx(ctx).is_none() { + return Some(Status::Continue); + } + None + } + /// Forwards matched requests to configured upstreams via [`GatewayPlugin`]. /// /// # Arguments diff --git a/plugin/graphql/src/impl.rs b/plugin/graphql/src/impl.rs index 01524925..fc587811 100644 --- a/plugin/graphql/src/impl.rs +++ b/plugin/graphql/src/impl.rs @@ -403,6 +403,27 @@ impl ServerHook for GraphqlHook { Self } + /// Synchronously passes through unconfigured and non-GraphQL requests without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for unmatched routes, or `None` for the GraphQL endpoint. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = GraphqlPlugin::get() else { + return Some(Status::Continue); + }; + if ctx.get_request().get_path() != plugin.endpoint() { + return Some(Status::Continue); + } + None + } + /// Dispatches requests matching the configured GraphQL endpoint and bypasses all other routes. /// /// # Arguments diff --git a/plugin/grpc/src/impl.rs b/plugin/grpc/src/impl.rs index 00231f86..1c66171e 100644 --- a/plugin/grpc/src/impl.rs +++ b/plugin/grpc/src/impl.rs @@ -762,4 +762,26 @@ impl ServerHook for GrpcHook { let _: Result<(), ResponseError> = ctx.try_send_response(stream).await; Status::Reject } + + /// Synchronous fast path avoiding future construction when unconfigured or request is not gRPC. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for non-gRPC traffic, or `None` to dispatch gRPC. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + if GrpcPlugin::get().is_none() { + return Some(Status::Continue); + } + let req: &Request = ctx.get_request(); + if !request_header_back(req, CONTENT_TYPE).is_some_and(is_grpc_content_type) { + return Some(Status::Continue); + } + None + } } diff --git a/plugin/health/src/impl.rs b/plugin/health/src/impl.rs index 2ce7eb93..d4b07089 100644 --- a/plugin/health/src/impl.rs +++ b/plugin/health/src/impl.rs @@ -575,6 +575,32 @@ impl ServerHook for HealthHook { Self } + /// Synchronously passes through unconfigured or non-probe requests without constructing an async future. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for non-probe/unconfigured requests, or `None` for probe endpoints. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = HealthPlugin::get() else { + return Some(Status::Continue); + }; + let config: &HealthConfig = plugin.get_config(); + let path: &str = ctx.get_request().get_path(); + if path != config.get_live_path() + && path != config.get_ready_path() + && path != config.get_health_path() + { + return Some(Status::Continue); + } + None + } + /// Intercepts `/healthz`, `/livez`, and `/readyz` probes and returns JSON status payloads. /// /// # Arguments diff --git a/plugin/idempotency/src/impl.rs b/plugin/idempotency/src/impl.rs index ee5d5d00..a115ea3a 100644 --- a/plugin/idempotency/src/impl.rs +++ b/plugin/idempotency/src/impl.rs @@ -976,6 +976,34 @@ impl ServerHook for IdempotencyRequestHook { } } } + + /// Synchronous fast path avoiding future construction when unconfigured or method is not guarded. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when bypassed, or `None` when guarded. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = IdempotencyPlugin::get() else { + return Some(Status::Continue); + }; + let req: &Request = ctx.get_request(); + if !plugin.is_guarded_method(req.get_method()) { + return Some(Status::Continue); + } + let config: &IdempotencyConfig = plugin.get_config(); + let raw_key: Option<&str> = + find_header_back_ref(req.get_headers(), config.get_header_name()); + if raw_key.is_none() && !plugin.requires_key(req.get_path()) { + return Some(Status::Continue); + } + None + } } /// Implements [`ServerHook`] for [`IdempotencyResponseHook`]. @@ -1010,6 +1038,9 @@ impl ServerHook for IdempotencyResponseHook { let Some(plugin) = IdempotencyPlugin::get() else { return Status::Continue; }; + if !plugin.is_guarded_method(ctx.get_request().get_method()) { + return Status::Continue; + } let Some(guard) = ctx.try_get_attribute::(ATTR_IDEMPOTENCY_GUARD) else { @@ -1047,4 +1078,31 @@ impl ServerHook for IdempotencyResponseHook { } Status::Continue } + + /// Synchronous fast path avoiding future construction when unconfigured or request had no idempotency guard. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when bypassed, or `None` when a guard must settle. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = IdempotencyPlugin::get() else { + return Some(Status::Continue); + }; + if !plugin.is_guarded_method(ctx.get_request().get_method()) { + return Some(Status::Continue); + } + if ctx + .try_get_attribute_ref::(ATTR_IDEMPOTENCY_GUARD) + .is_none() + { + return Some(Status::Continue); + } + None + } } diff --git a/plugin/ip_filter/src/const.rs b/plugin/ip_filter/src/const.rs index 3b78bd98..5602f9b5 100644 --- a/plugin/ip_filter/src/const.rs +++ b/plugin/ip_filter/src/const.rs @@ -13,6 +13,9 @@ pub const DEFAULT_MAX_TRUSTED_HOPS: usize = 16; /// Number of `/8` radix buckets in [`CidrTable`]. pub(crate) const CIDR_BUCKET_COUNT: usize = 256; +/// Preformatted internal map key for zero-allocation lookup/update of [`ClientIp`]. +pub(crate) const ATTR_CLIENT_IP_MAP_KEY: &str = "External(\"hyperlane_plugin_client_ip\")"; + /// Length of the CSR `/8` bucket offset table (`CIDR_BUCKET_COUNT + 1`). pub(crate) const CIDR_OFFSET_LEN: usize = CIDR_BUCKET_COUNT + 1; diff --git a/plugin/ip_filter/src/impl.rs b/plugin/ip_filter/src/impl.rs index fb6b183b..b22157e8 100644 --- a/plugin/ip_filter/src/impl.rs +++ b/plugin/ip_filter/src/impl.rs @@ -883,6 +883,28 @@ impl CompiledIpFilter { true } + /// Stores [`ClientIp`] in `ctx`, reusing any unique existing `Arc` slot in place. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// - `ClientIp` - Resolved client IP metadata. + #[inline(always)] + pub(crate) fn put_client_ip(ctx: &mut Context, resolved: ClientIp) { + if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_CLIENT_IP_MAP_KEY) { + if let Some(any_mut) = Arc::get_mut(slot) + && let Some(existing) = any_mut.downcast_mut::() + { + *existing = resolved; + return; + } + *slot = Arc::new(resolved); + return; + } + ctx.get_mut_attributes() + .insert(ATTR_CLIENT_IP_MAP_KEY.to_owned(), Arc::new(resolved)); + } + /// Resolves `ClientIp`, stores it in `ctx` under [`ATTR_CLIENT_IP`], and enforces allow/deny rules. /// /// # Arguments @@ -984,6 +1006,43 @@ impl ServerHook for IpFilterHook { Self } + /// Synchronously resolves client IP and admits allowed/exempt/unconfigured peers without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when admitted/exempt/unconfigured; `None` when denied. + #[inline(always)] + fn try_handle_sync(stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = IpFilterPlugin::get() else { + return Some(Status::Continue); + }; + let compiled: &CompiledIpFilter = plugin.get_compiled(); + let peer_ip: Option = stream + .get_peer_addr() + .ok() + .map(|addr: SocketAddr| addr.ip()); + let client_ip: Option = + compiled.resolve_client_ip(peer_ip, ctx.get_request().get_headers()); + let exempt: bool = compiled.is_path_exempt(ctx.get_request().get_path()); + let allowed: bool = exempt + || match client_ip { + Some(resolved) => compiled.is_ip_allowed(resolved.get_ip()), + None => compiled.allowlist.is_empty(), + }; + if !allowed { + return None; + } + if let Some(resolved) = client_ip { + CompiledIpFilter::put_client_ip(ctx, resolved); + } + Some(Status::Continue) + } + /// Extracts client IP into `Context` and short-circuits disallowed peers with prebuilt wire bytes. /// /// # Arguments @@ -1007,7 +1066,7 @@ impl ServerHook for IpFilterHook { let client_ip: Option = compiled.resolve_client_ip(peer_ip, ctx.get_request().get_headers()); if let Some(resolved) = client_ip { - ctx.set_attribute(ATTR_CLIENT_IP, resolved); + CompiledIpFilter::put_client_ip(ctx, resolved); } if compiled.is_path_exempt(ctx.get_request().get_path()) { return Status::Continue; diff --git a/plugin/ip_filter/src/lib.rs b/plugin/ip_filter/src/lib.rs index 511698c4..a709425d 100644 --- a/plugin/ip_filter/src/lib.rs +++ b/plugin/ip_filter/src/lib.rs @@ -26,7 +26,7 @@ use std::{ fmt::{self, Display, Formatter}, net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, str::{FromStr, from_utf8}, - sync::OnceLock, + sync::{Arc, OnceLock}, }; use { diff --git a/plugin/logger/src/const.rs b/plugin/logger/src/const.rs index b27722aa..82990987 100644 --- a/plugin/logger/src/const.rs +++ b/plugin/logger/src/const.rs @@ -28,8 +28,9 @@ pub(crate) const DEBUG_FIELD_CHANNEL_CAPACITY: &str = "channel_capacity"; /// Debug field name indicating custom sink presence. pub(crate) const DEBUG_FIELD_HAS_SINK: &str = "has_sink"; -/// The name of the attribute that carries the moment a request arrived. -pub(crate) const ATTRIBUTE_STARTED_AT: &str = "hyperlane-plugin-logger-started-at"; +/// Preformatted internal map key for zero-allocation lookup of the request arrival `Instant`. +pub(crate) const ATTRIBUTE_STARTED_AT_MAP_KEY: &str = + "External(\"hyperlane-plugin-logger-started-at\")"; /// The text that stands for a request that carries no path. pub(crate) const PATH_UNKNOWN: &str = "-"; diff --git a/plugin/logger/src/impl.rs b/plugin/logger/src/impl.rs index 12acc97d..e16a19ec 100644 --- a/plugin/logger/src/impl.rs +++ b/plugin/logger/src/impl.rs @@ -565,6 +565,31 @@ impl LoggerPlugin { log::debug!("{}", data.as_ref()); } + /// Stores the request arrival `Instant` in `ctx`, reusing any unique existing `Arc` slot in place. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// - `Instant` - Arrival timestamp. + #[inline(always)] + pub(crate) fn put_started_at(ctx: &mut Context, started: Instant) { + if let Some(slot) = ctx + .get_mut_attributes() + .get_mut(ATTRIBUTE_STARTED_AT_MAP_KEY) + { + if let Some(any_mut) = Arc::get_mut(slot) + && let Some(existing) = any_mut.downcast_mut::() + { + *existing = started; + return; + } + *slot = Arc::new(started); + return; + } + ctx.get_mut_attributes() + .insert(ATTRIBUTE_STARTED_AT_MAP_KEY.to_owned(), Arc::new(started)); + } + /// Writes a line at the trace level. /// /// # Arguments @@ -595,6 +620,25 @@ impl ServerHook for RequestLogger { Self } + /// Synchronously notes when the request arrived without constructing an async future. + /// + /// # Arguments + /// + /// - `&mut Stream` - The stream the request arrived on. + /// - `&mut Context` - The context of the request. + /// + /// # Returns + /// + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + if CONFIG.get().is_none() || !log_enabled!(Level::Info) { + return Some(Status::Continue); + } + LoggerPlugin::put_started_at(ctx, Instant::now()); + Some(Status::Continue) + } + /// Notes when the request arrived. /// /// # Arguments @@ -606,12 +650,8 @@ impl ServerHook for RequestLogger { /// # Returns /// /// - `Status` - Whether the pipeline continues. - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { - if CONFIG.get().is_none() || !log_enabled!(Level::Info) { - return Status::Continue; - } - ctx.set_attribute(ATTRIBUTE_STARTED_AT, Instant::now()); - Status::Continue + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } @@ -632,26 +672,26 @@ impl ServerHook for ResponseLogger { Self } - /// Writes the line of the answered request. + /// Synchronously writes the log line of the answered request without constructing an async future. /// /// # Arguments /// - /// - `Self` - The middleware. /// - `&mut Stream` - The stream the request arrived on. /// - `&mut Context` - The context of the request. /// /// # Returns /// - /// - `Status` - Whether the pipeline continues. - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { if CONFIG.get().is_none() || !log_enabled!(Level::Info) { - return Status::Continue; + return Some(Status::Continue); } - let started_at: Option<&Instant> = ctx.try_get_attribute_ref(ATTRIBUTE_STARTED_AT); - let elapsed: u128 = match started_at { - Some(started_at) => started_at.elapsed().as_millis(), - None => 0, - }; + let elapsed: u128 = ctx + .get_attributes() + .get(ATTRIBUTE_STARTED_AT_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) + .map_or(0, |started_at: &Instant| started_at.elapsed().as_millis()); let method_text: &str = request_method_str(ctx.get_request().get_method()); let path: &str = ctx.get_request().get_path().as_str(); let status: usize = ctx.get_response().get_status_code(); @@ -662,6 +702,21 @@ impl ServerHook for ResponseLogger { status, elapsed ); - Status::Continue + Some(Status::Continue) + } + + /// Writes the line of the answered request. + /// + /// # Arguments + /// + /// - `Self` - The middleware. + /// - `&mut Stream` - The stream the request arrived on. + /// - `&mut Context` - The context of the request. + /// + /// # Returns + /// + /// - `Status` - Whether the pipeline continues. + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/logger/src/lib.rs b/plugin/logger/src/lib.rs index 80c5b3fe..9f5b4d09 100644 --- a/plugin/logger/src/lib.rs +++ b/plugin/logger/src/lib.rs @@ -39,8 +39,8 @@ use std::{ use { hyperlane::{ - CONNECT, Context, DELETE, GET, HEAD, Method, OPTIONS, PATCH, POST, PUT, ServerHook, Status, - Stream, TRACE, + ArcAnySendSync, CONNECT, Context, DELETE, GET, HEAD, Method, OPTIONS, PATCH, POST, PUT, + ServerHook, Status, Stream, TRACE, }, log::{Level, Metadata, Record, SetLoggerError, log_enabled, set_logger, set_max_level}, }; diff --git a/plugin/maintenance/src/impl.rs b/plugin/maintenance/src/impl.rs index 6ed6241e..379d925d 100644 --- a/plugin/maintenance/src/impl.rs +++ b/plugin/maintenance/src/impl.rs @@ -251,7 +251,7 @@ impl MaintenancePlugin { #[inline(always)] pub fn current_mode(&self) -> MaintenanceMode { let Self { mode, .. } = self; - mode_from_u8(mode.load(Ordering::Acquire)) + mode_from_u8(mode.load(Ordering::Relaxed)) } /// Atomically switches the live [`MaintenanceMode`] without restarting the server. @@ -416,6 +416,27 @@ impl ServerHook for MaintenanceHook { Self } + /// Synchronously admits active, unconfigured, exempt, and bypassed requests without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when admitted, or `None` when blocked. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = MaintenancePlugin::get() else { + return Some(Status::Continue); + }; + match plugin.evaluate(ctx.get_request()) { + MaintenanceDecision::Allow | MaintenanceDecision::Bypassed => Some(Status::Continue), + MaintenanceDecision::RejectReadOnly | MaintenanceDecision::RejectMaintenance => None, + } + } + /// Fast-path checks the atomic maintenance mode and short-circuits blocked requests with prebuilt `503` wire bytes. /// /// # Arguments diff --git a/plugin/mcp/src/impl.rs b/plugin/mcp/src/impl.rs index 3ab96eaa..dbf1c673 100644 --- a/plugin/mcp/src/impl.rs +++ b/plugin/mcp/src/impl.rs @@ -1990,6 +1990,27 @@ impl ServerHook for McpHook { Self } + /// Synchronously passes through unconfigured and non-MCP paths without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for unmatched requests, or `None` for the MCP endpoint. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = McpPlugin::get() else { + return Some(Status::Continue); + }; + if ctx.get_request().get_path() != plugin.get_config().get_endpoint() { + return Some(Status::Continue); + } + None + } + /// Handles MCP Streamable HTTP (`POST` and `DELETE`) requests on the configured endpoint. /// /// # Arguments diff --git a/plugin/metrics/src/const.rs b/plugin/metrics/src/const.rs index 505bff99..cb4c512e 100644 --- a/plugin/metrics/src/const.rs +++ b/plugin/metrics/src/const.rs @@ -40,8 +40,37 @@ pub(crate) const LINEAR_SCAN_BUCKET_LIMIT: usize = 16; /// Predefined HTTP status class labels emitted by Prometheus exposition. pub(crate) const STATUS_CLASS_LABELS: [&str; 6] = ["1xx", "2xx", "3xx", "4xx", "5xx", "other"]; -/// Context attribute key storing request start `Instant` for latency observation. -pub(crate) const ATTR_METRICS_STARTED_AT: &str = "hyperlane_plugin_metrics_started_at"; +/// Preformatted internal map key for zero-allocation borrowed lookup of request start `Instant`. +pub(crate) const ATTR_METRICS_STARTED_AT_MAP_KEY: &str = + "External(\"hyperlane_plugin_metrics_started_at\")"; + +/// Number of cache-line-aligned per-worker shards for built-in HTTP metrics (`16`, power of two). +pub(crate) const METRICS_SHARD_COUNT: usize = 16; + +/// Bitmask mapping worker IDs into `0..METRICS_SHARD_COUNT`. +pub(crate) const METRICS_SHARD_MASK: usize = METRICS_SHARD_COUNT - 1; + +/// Integer nanosecond upper bounds matching [`DEFAULT_LATENCY_BUCKETS`] for branchless hot-path bucketing. +pub(crate) const DEFAULT_LATENCY_BUCKETS_NS: [u64; 12] = [ + 1_000_000, + 5_000_000, + 10_000_000, + 25_000_000, + 50_000_000, + 100_000_000, + 250_000_000, + 500_000_000, + 1_000_000_000, + 2_500_000_000, + 5_000_000_000, + 10_000_000_000, +]; + +/// Nanoseconds per second as `f64` for converting integer latency totals back to seconds. +pub(crate) const NANOS_PER_SEC_F64: f64 = 1_000_000_000.0; + +/// Maximum duration in seconds converted into integer nanosecond shard accumulators. +pub(crate) const MAX_SHARD_DURATION_SECS: f64 = 1_000_000_000.0; /// `Cache-Control` directive preventing caching of live Prometheus scrapes. pub(crate) const CACHE_CONTROL_NO_STORE: &str = "no-store"; diff --git a/plugin/metrics/src/fn.rs b/plugin/metrics/src/fn.rs index 195c9e54..ab8fdb7b 100644 --- a/plugin/metrics/src/fn.rs +++ b/plugin/metrics/src/fn.rs @@ -176,3 +176,66 @@ pub(crate) fn atomic_f64_add(target: &AtomicU64, delta: f64) { } } } + +/// Returns a stable per-thread shard index in `0..METRICS_SHARD_COUNT`. +/// +/// # Returns +/// +/// - `usize` - Thread-local built-in metrics shard index. +#[inline(always)] +pub(crate) fn worker_metrics_shard_index() -> usize { + WORKER_METRICS_SHARD.with(|slot: &Cell| { + let current: usize = slot.get(); + if current != usize::MAX { + return current; + } + let assigned: usize = + METRICS_NEXT_SHARD_ID.fetch_add(1, Ordering::Relaxed) & METRICS_SHARD_MASK; + slot.set(assigned); + assigned + }) +} + +/// Stores the request entry `Instant` in `ctx`, reusing any unique existing `Arc` slot in place. +/// +/// # Arguments +/// +/// - `&mut Context` - Incoming request context. +/// - `Instant` - Request start timestamp. +#[inline(always)] +pub(crate) fn put_metrics_started_at(ctx: &mut Context, started: Instant) { + if let Some(slot) = ctx + .get_mut_attributes() + .get_mut(ATTR_METRICS_STARTED_AT_MAP_KEY) + { + if let Some(any_mut) = Arc::get_mut(slot) + && let Some(existing) = any_mut.downcast_mut::() + { + *existing = started; + return; + } + *slot = Arc::new(started); + return; + } + ctx.get_mut_attributes().insert( + ATTR_METRICS_STARTED_AT_MAP_KEY.to_owned(), + Arc::new(started), + ); +} + +/// Reads the request entry `Instant` from `ctx` without key formatting or allocation. +/// +/// # Arguments +/// +/// - `&Context` - Active request context. +/// +/// # Returns +/// +/// - `Option` - Stored request start timestamp, if present. +#[inline(always)] +pub(crate) fn get_metrics_started_at(ctx: &Context) -> Option { + ctx.get_attributes() + .get(ATTR_METRICS_STARTED_AT_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) + .copied() +} diff --git a/plugin/metrics/src/impl.rs b/plugin/metrics/src/impl.rs index 78bd14ca..e29bed2d 100644 --- a/plugin/metrics/src/impl.rs +++ b/plugin/metrics/src/impl.rs @@ -334,6 +334,25 @@ impl MetricsConfig { } } +/// Inherent constructors for [`BuiltinMetricsShard`]. +impl BuiltinMetricsShard { + /// Creates a zero-initialized cache-line-aligned [`BuiltinMetricsShard`]. + /// + /// # Returns + /// + /// - `Self` - Zeroed shard. + pub(crate) fn new() -> Self { + Self { + status_class_counts: from_fn(|_: usize| AtomicU64::new(0)), + in_flight: AtomicI64::new(0), + response_bytes_total: AtomicU64::new(0), + duration_buckets: from_fn(|_: usize| AtomicU64::new(0)), + duration_count: AtomicU64::new(0), + duration_nanos_sum: AtomicU64::new(0), + } + } +} + /// Default construction for [`MetricsRegistry`]. impl Default for MetricsRegistry { /// Constructs a default [`MetricsRegistry`] under namespace `"hyperlane"`. @@ -358,7 +377,6 @@ impl MetricsRegistry { N: Into, { let ns: String = namespace.into(); - let duration_seconds: Histogram = Histogram::new(&DEFAULT_LATENCY_BUCKETS); let prom_req_header: String = format!( "# HELP {ns}_http_requests_total Total HTTP requests partitioned by status class.\n# TYPE {ns}_http_requests_total counter\n" ); @@ -377,10 +395,9 @@ impl MetricsRegistry { let dur_name: String = format!("{ns}_http_request_duration_seconds"); let prom_dur_header: String = format!("# HELP {dur_name} {HELP_HTTP_DURATION}\n# TYPE {dur_name} histogram\n"); - let prom_dur_bucket_prefixes: Box<[String]> = duration_seconds - .bound_labels + let prom_dur_bucket_prefixes: Box<[String]> = DEFAULT_LATENCY_BUCKETS .iter() - .map(|label: &String| format!("{dur_name}_bucket{{le=\"{label}\"}} ")) + .map(|bound: &f64| format!("{dur_name}_bucket{{le=\"{bound}\"}} ")) .collect::>() .into_boxed_slice(); let prom_dur_inf_prefix: String = format!("{dur_name}_bucket{{le=\"+Inf\"}} "); @@ -405,6 +422,8 @@ impl MetricsRegistry { for bucket_prefix in prom_dur_bucket_prefixes.iter() { builtin_est_bytes += bucket_prefix.len() + PROM_EST_DIGITS_PER_LINE; } + let builtin_shards: Box<[BuiltinMetricsShard; METRICS_SHARD_COUNT]> = + Box::new(from_fn(|_: usize| BuiltinMetricsShard::new())); Self { inner: Arc::new(MetricsRegistryInner { builtin_est_bytes, @@ -417,17 +436,8 @@ impl MetricsRegistry { prom_dur_inf_prefix, prom_dur_sum_prefix, prom_dur_count_prefix, - status_class_counts: [ - Counter::new(), - Counter::new(), - Counter::new(), - Counter::new(), - Counter::new(), - Counter::new(), - ], - in_flight: Gauge::new(), - response_bytes_total: Counter::new(), - duration_seconds, + builtin_shards, + duration_extra_sum_bits: AtomicU64::new(0.0_f64.to_bits()), custom_counter_count: AtomicUsize::new(0), custom_gauge_count: AtomicUsize::new(0), custom_histogram_count: AtomicUsize::new(0), @@ -607,7 +617,49 @@ impl MetricsRegistry { #[inline(always)] pub fn record_request_start(&self) { let Self { inner } = self; - inner.in_flight.inc(); + inner.builtin_shards[worker_metrics_shard_index()] + .in_flight + .fetch_add(1, Ordering::Relaxed); + } + + /// Records a completed HTTP exchange directly from integer nanoseconds without float or CAS loops. + /// + /// # Arguments + /// + /// - `usize` - HTTP status code. + /// - `usize` - Response body length in bytes. + /// - `u64` - Request duration in integer nanoseconds. + #[inline] + pub(crate) fn record_request_finish_nanos( + &self, + status_code: usize, + response_bytes: usize, + duration_ns: u64, + ) { + let Self { inner } = self; + let shard: &BuiltinMetricsShard = &inner.builtin_shards[worker_metrics_shard_index()]; + shard.in_flight.fetch_sub(1, Ordering::Relaxed); + let class_idx: usize = match status_code / 100 { + 2 => 1, + 4 => 3, + 3 => 2, + 5 => 4, + 1 => 0, + _ => 5, + }; + shard.status_class_counts[class_idx].fetch_add(1, Ordering::Relaxed); + shard + .response_bytes_total + .fetch_add(response_bytes as u64, Ordering::Relaxed); + let mut bucket_idx: usize = 0; + for &bound_ns in &DEFAULT_LATENCY_BUCKETS_NS { + bucket_idx += usize::from(bound_ns < duration_ns); + } + shard.duration_buckets[bucket_idx].fetch_add(1, Ordering::Relaxed); + shard.duration_count.fetch_add(1, Ordering::Relaxed); + shard + .duration_nanos_sum + .fetch_add(duration_ns, Ordering::Relaxed); } /// Records a completed HTTP exchange in lock-free built-in counters and latency histogram. @@ -625,7 +677,8 @@ impl MetricsRegistry { duration_secs: f64, ) { let Self { inner } = self; - inner.in_flight.dec(); + let shard: &BuiltinMetricsShard = &inner.builtin_shards[worker_metrics_shard_index()]; + shard.in_flight.fetch_sub(1, Ordering::Relaxed); let class_idx: usize = match status_code / 100 { 2 => 1, 4 => 3, @@ -634,9 +687,24 @@ impl MetricsRegistry { 1 => 0, _ => 5, }; - inner.status_class_counts[class_idx].inc(); - inner.response_bytes_total.inc_by(response_bytes as u64); - inner.duration_seconds.observe(duration_secs); + shard.status_class_counts[class_idx].fetch_add(1, Ordering::Relaxed); + shard + .response_bytes_total + .fetch_add(response_bytes as u64, Ordering::Relaxed); + if duration_secs.is_finite() { + let mut bucket_idx: usize = 0; + for &bound in &DEFAULT_LATENCY_BUCKETS { + bucket_idx += usize::from(bound < duration_secs); + } + shard.duration_buckets[bucket_idx].fetch_add(1, Ordering::Relaxed); + shard.duration_count.fetch_add(1, Ordering::Relaxed); + if (0.0..MAX_SHARD_DURATION_SECS).contains(&duration_secs) { + let nanos: u64 = (duration_secs * NANOS_PER_SEC_F64) as u64; + shard.duration_nanos_sum.fetch_add(nanos, Ordering::Relaxed); + } else { + atomic_f64_add(&inner.duration_extra_sum_bits, duration_secs); + } + } } /// Returns total HTTP requests observed across all status classes. @@ -647,7 +715,13 @@ impl MetricsRegistry { #[inline] pub fn total_http_requests(&self) -> u64 { let Self { inner } = self; - inner.status_class_counts.iter().map(Counter::get).sum() + let mut total: u64 = 0; + for shard in inner.builtin_shards.iter() { + for counter in &shard.status_class_counts { + total = total.wrapping_add(counter.load(Ordering::Relaxed)); + } + } + total } /// Renders all built-in and custom metrics into Prometheus text exposition format 0.0.4. @@ -660,27 +734,88 @@ impl MetricsRegistry { let capacity: usize = inner.builtin_est_bytes + inner.custom_est_bytes.load(Ordering::Relaxed); let mut out: String = String::with_capacity(capacity); + let mut status_totals: [u64; 6] = [0; 6]; + let mut in_flight_total: i64 = 0; + let mut resp_bytes_total: u64 = 0; + let mut bucket_totals: [u64; 12] = [0; 12]; + let mut dur_count_total: u64 = 0; + let mut dur_nanos_total: u128 = 0; + for shard in inner.builtin_shards.iter() { + for idx in 0..6 { + status_totals[idx] = status_totals[idx] + .wrapping_add(shard.status_class_counts[idx].load(Ordering::Relaxed)); + } + in_flight_total = in_flight_total.wrapping_add(shard.in_flight.load(Ordering::Relaxed)); + resp_bytes_total = + resp_bytes_total.wrapping_add(shard.response_bytes_total.load(Ordering::Relaxed)); + for idx in 0..12 { + bucket_totals[idx] = bucket_totals[idx] + .wrapping_add(shard.duration_buckets[idx].load(Ordering::Relaxed)); + } + dur_count_total = + dur_count_total.wrapping_add(shard.duration_count.load(Ordering::Relaxed)); + dur_nanos_total = dur_nanos_total + .wrapping_add(u128::from(shard.duration_nanos_sum.load(Ordering::Relaxed))); + } + let dur_sum_secs: f64 = ((dur_nanos_total as f64) / NANOS_PER_SEC_F64) + + f64::from_bits(inner.duration_extra_sum_bits.load(Ordering::Relaxed)); out.push_str(&inner.prom_req_header); - for (line_prefix, counter) in inner - .prom_req_lines - .iter() - .zip(inner.status_class_counts.iter()) - { + for (line_prefix, count) in inner.prom_req_lines.iter().zip(status_totals.iter()) { out.push_str(line_prefix); - push_u64_nl(counter.get(), &mut out); + push_u64_nl(*count, &mut out); } out.push_str(&inner.prom_in_flight_prefix); - push_i64_nl(inner.in_flight.get(), &mut out); + push_i64_nl(in_flight_total, &mut out); out.push_str(&inner.prom_resp_bytes_prefix); - push_u64_nl(inner.response_bytes_total.get(), &mut out); - inner.duration_seconds.write_prometheus_preformatted( - &inner.prom_dur_header, - &inner.prom_dur_bucket_prefixes, - &inner.prom_dur_inf_prefix, - &inner.prom_dur_sum_prefix, - &inner.prom_dur_count_prefix, - &mut out, - ); + push_u64_nl(resp_bytes_total, &mut out); + out.push_str(&inner.prom_dur_header); + let mut cumulative: u64 = 0; + let mut num_buf: [u8; INT_STACK_BUF_LEN] = [0u8; INT_STACK_BUF_LEN]; + let mut num_start: usize = INT_STACK_BUF_LEN; + let mut formatted_val: u64 = 0; + for (bucket_prefix, bucket_count) in inner + .prom_dur_bucket_prefixes + .iter() + .zip(bucket_totals.iter()) + { + cumulative = cumulative.wrapping_add(*bucket_count); + out.push_str(bucket_prefix); + if cumulative < 100 { + out.push_str(PROM_DEC_0_99_NL[cumulative as usize]); + } else { + if cumulative != formatted_val { + num_start = format_u64_nl_into(cumulative, &mut num_buf); + formatted_val = cumulative; + } + if let Ok(text) = from_utf8(&num_buf[num_start..]) { + out.push_str(text); + } + } + } + out.push_str(&inner.prom_dur_inf_prefix); + if dur_count_total < 100 { + let total_str: &str = PROM_DEC_0_99_NL[dur_count_total as usize]; + out.push_str(total_str); + out.push_str(&inner.prom_dur_sum_prefix); + push_f64_nl(dur_sum_secs, &mut out); + out.push_str(&inner.prom_dur_count_prefix); + out.push_str(total_str); + } else { + if dur_count_total != formatted_val { + num_start = format_u64_nl_into(dur_count_total, &mut num_buf); + } + if let Ok(text) = from_utf8(&num_buf[num_start..]) { + out.push_str(text); + out.push_str(&inner.prom_dur_sum_prefix); + push_f64_nl(dur_sum_secs, &mut out); + out.push_str(&inner.prom_dur_count_prefix); + out.push_str(text); + } else { + out.push_str(&inner.prom_dur_sum_prefix); + push_f64_nl(dur_sum_secs, &mut out); + out.push_str(&inner.prom_dur_count_prefix); + } + } if inner.custom_counter_count.load(Ordering::Acquire) != 0 && let Ok(counters) = inner.custom_counters.read() { @@ -793,6 +928,29 @@ impl ServerHook for MetricsRequestHook { Self } + /// Synchronously handles normal non-scrape requests and unconfigured pass-through without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for pass-through/normal requests, or `None` for `/metrics` scrapes. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = MetricsPlugin::get() else { + return Some(Status::Continue); + }; + if ctx.get_request().get_path() == plugin.get_config().get_endpoint() { + return None; + } + plugin.get_registry().record_request_start(); + put_metrics_started_at(ctx, Instant::now()); + Some(Status::Continue) + } + /// Answers `/metrics` scrapes or starts request timing and increments in-flight gauge. /// /// # Arguments @@ -830,7 +988,7 @@ impl ServerHook for MetricsRequestHook { return Status::Reject; } plugin.get_registry().record_request_start(); - ctx.set_attribute(ATTR_METRICS_STARTED_AT, Instant::now()); + put_metrics_started_at(ctx, Instant::now()); Status::Continue } } @@ -852,31 +1010,45 @@ impl ServerHook for MetricsResponseHook { Self } - /// Records HTTP status class, response payload bytes, and latency histogram observation. + /// Synchronously records HTTP status class, response bytes, and integer-nanosecond latency without async futures. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = MetricsPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; - let Some(started_at) = ctx.try_get_attribute_ref::(ATTR_METRICS_STARTED_AT) - else { - return Status::Continue; + let Some(started_at) = get_metrics_started_at(ctx) else { + return Some(Status::Continue); }; let status: usize = ctx.get_response().get_status_code(); let bytes: usize = ctx.get_response().get_body().len(); - let duration_secs: f64 = started_at.elapsed().as_secs_f64(); + let duration_ns: u64 = started_at.elapsed().as_nanos().min(u64::MAX as u128) as u64; plugin .get_registry() - .record_request_finish(status, bytes, duration_secs); - Status::Continue + .record_request_finish_nanos(status, bytes, duration_ns); + Some(Status::Continue) + } + + /// Records HTTP status class, response payload bytes, and latency histogram observation. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/metrics/src/lib.rs b/plugin/metrics/src/lib.rs index b0ffaf9a..58536103 100644 --- a/plugin/metrics/src/lib.rs +++ b/plugin/metrics/src/lib.rs @@ -20,6 +20,7 @@ pub(crate) use {r#fn::*, r#static::*}; use std::{ array::from_fn, + cell::Cell, collections::VecDeque, fmt::{self, Write}, str::from_utf8, @@ -32,8 +33,8 @@ use std::{ use { hyperlane::{ - AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, Context, HashMapXxHash3_64, HttpStatus, - Request, ResponseError, ServerHook, Status, Stream, hash_map_xx_hash3_64, + AUTHORIZATION, ArcAnySendSync, CACHE_CONTROL, CONTENT_TYPE, Context, HashMapXxHash3_64, + HttpStatus, Request, ResponseError, ServerHook, Status, Stream, hash_map_xx_hash3_64, }, lombok_macros::*, }; diff --git a/plugin/metrics/src/static.rs b/plugin/metrics/src/static.rs index 40771abb..e155ba9f 100644 --- a/plugin/metrics/src/static.rs +++ b/plugin/metrics/src/static.rs @@ -2,3 +2,11 @@ use super::*; /// Global process-wide [`MetricsPlugin`] singleton initialized via [`MetricsPlugin::init`]. pub(crate) static METRICS_PLUGIN: OnceLock = OnceLock::new(); + +/// Monotonic counter assigning stable shard indices across worker threads. +pub(crate) static METRICS_NEXT_SHARD_ID: AtomicUsize = AtomicUsize::new(0); + +thread_local! { + /// Cached per-thread shard index into [`MetricsRegistryInner::builtin_shards`]. + pub(crate) static WORKER_METRICS_SHARD: Cell = const { Cell::new(usize::MAX) }; +} diff --git a/plugin/metrics/src/struct.rs b/plugin/metrics/src/struct.rs index ca6d0390..0b68fa98 100644 --- a/plugin/metrics/src/struct.rs +++ b/plugin/metrics/src/struct.rs @@ -73,6 +73,23 @@ pub struct MetricsConfig { pub(crate) bearer_token: Option, } +/// Cache-line-aligned per-worker shard eliminating cross-core contention on built-in HTTP metrics. +#[repr(align(64))] +pub(crate) struct BuiltinMetricsShard { + /// HTTP request counters partitioned by status class (`[1xx, 2xx, 3xx, 4xx, 5xx, other]`). + pub(crate) status_class_counts: [AtomicU64; 6], + /// Signed delta gauge tracking active in-flight HTTP requests on this shard. + pub(crate) in_flight: AtomicI64, + /// Cumulative HTTP response payload bytes recorded on this shard. + pub(crate) response_bytes_total: AtomicU64, + /// Per-bucket latency observation counts (`12` finite bounds plus `+Inf`). + pub(crate) duration_buckets: [AtomicU64; 13], + /// Total latency observations recorded on this shard. + pub(crate) duration_count: AtomicU64, + /// Cumulative observed latency in integer nanoseconds on this shard. + pub(crate) duration_nanos_sum: AtomicU64, +} + /// Shared interior state of [`MetricsRegistry`]. pub(crate) struct MetricsRegistryInner { /// Precomputed byte capacity estimate covering all built-in Prometheus lines. @@ -95,14 +112,10 @@ pub(crate) struct MetricsRegistryInner { pub(crate) prom_dur_sum_prefix: String, /// Pre-formatted `_count ` prefix for built-in latency histogram. pub(crate) prom_dur_count_prefix: String, - /// Lock-free HTTP request counters partitioned by status class (`[1xx, 2xx, 3xx, 4xx, 5xx, other]`). - pub(crate) status_class_counts: [Counter; 6], - /// Lock-free gauge tracking active in-flight HTTP requests. - pub(crate) in_flight: Gauge, - /// Lock-free counter tracking total response payload bytes emitted. - pub(crate) response_bytes_total: Counter, - /// Lock-free HTTP request latency histogram in seconds. - pub(crate) duration_seconds: Histogram, + /// Cache-line-aligned per-worker built-in HTTP metric shards. + pub(crate) builtin_shards: Box<[BuiltinMetricsShard; METRICS_SHARD_COUNT]>, + /// Overflow IEEE-754 `f64::to_bits` latency sum for negative or ultra-large manual observations. + pub(crate) duration_extra_sum_bits: AtomicU64, /// Lock-free count of registered custom counters (skips read lock when zero). pub(crate) custom_counter_count: AtomicUsize, /// Lock-free count of registered custom gauges (skips read lock when zero). diff --git a/plugin/mq/src/impl.rs b/plugin/mq/src/impl.rs index 8dd8aa08..5be2d7e6 100644 --- a/plugin/mq/src/impl.rs +++ b/plugin/mq/src/impl.rs @@ -22,7 +22,22 @@ impl Hasher for FnvHasher { fn write(&mut self, bytes: &[u8]) { let Self { state } = self; let mut h: u64 = *state; - for &b in bytes { + let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>(); + for chunk in chunks { + h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K); + } + let mut tail: &[u8] = rem; + if tail.len() >= 4 { + let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]); + h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K); + tail = &tail[4..]; + } + if tail.len() >= 2 { + let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]); + h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K); + tail = &tail[2..]; + } + if let Some(&b) = tail.first() { h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K); } *state = h; diff --git a/plugin/multipart/src/impl.rs b/plugin/multipart/src/impl.rs index 16837adf..0d9f2a81 100644 --- a/plugin/multipart/src/impl.rs +++ b/plugin/multipart/src/impl.rs @@ -282,10 +282,22 @@ impl MultipartPlugin { } let boundary: &str = extract_boundary(content_type).ok_or(MultipartError::MissingBoundary)?; - let mut delim: Vec = Vec::with_capacity(boundary.len() + 2); - delim.extend_from_slice(DOUBLE_DASH); - delim.extend_from_slice(boundary.as_bytes()); - let first_pos: usize = find_bytes(body, &delim).ok_or(MultipartError::MalformedBody)?; + let boundary_bytes: &[u8] = boundary.as_bytes(); + let mut delim_stack: [u8; 72] = [0u8; 72]; + let delim_heap: Vec; + let delim: &[u8] = if boundary_bytes.len() <= 70 { + delim_stack[0] = b'-'; + delim_stack[1] = b'-'; + delim_stack[2..2 + boundary_bytes.len()].copy_from_slice(boundary_bytes); + &delim_stack[..2 + boundary_bytes.len()] + } else { + let mut vec: Vec = Vec::with_capacity(boundary_bytes.len() + 2); + vec.extend_from_slice(DOUBLE_DASH); + vec.extend_from_slice(boundary_bytes); + delim_heap = vec; + &delim_heap + }; + let first_pos: usize = find_bytes(body, delim).ok_or(MultipartError::MalformedBody)?; let mut cursor: usize = first_pos + delim.len(); let mut parsed: ParsedMultipart = ParsedMultipart::default(); let mut part_count: usize = 0; @@ -306,7 +318,7 @@ impl MultipartPlugin { } let remaining: &[u8] = &body[cursor..]; let next_rel: usize = - find_bytes(remaining, &delim).ok_or(MultipartError::MalformedBody)?; + find_bytes(remaining, delim).ok_or(MultipartError::MalformedBody)?; let mut part_slice: &[u8] = &remaining[..next_rel]; if part_slice.ends_with(b"\r\n") { part_slice = &part_slice[..part_slice.len() - 2]; @@ -393,6 +405,42 @@ impl ServerHook for MultipartHook { Self } + /// Synchronously skips non-multipart requests and parses valid multipart uploads without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured, non-multipart, or valid; `None` on upload error. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = MultipartPlugin::get() else { + return Some(Status::Continue); + }; + let is_multipart: bool = ctx + .get_request() + .get_headers() + .get(CONTENT_TYPE) + .and_then(|vals: &VecDeque| vals.back()) + .is_some_and(|ct: &String| { + let t: &str = ct.trim(); + t.len() >= MULTIPART_FORM_DATA_PREFIX.len() + && t.as_bytes()[..MULTIPART_FORM_DATA_PREFIX.len()] + .eq_ignore_ascii_case(MULTIPART_FORM_DATA_PREFIX.as_bytes()) + }); + if !is_multipart { + return Some(Status::Continue); + } + let Ok(form) = plugin.parse_request(ctx.get_request()) else { + return None; + }; + ctx.set_attribute(ATTR_PARSED_MULTIPART, form); + Some(Status::Continue) + } + /// Fast-path skips non-multipart requests and parses/validates `multipart/form-data` payloads into [`Context`]. /// /// # Arguments diff --git a/plugin/negotiate/src/impl.rs b/plugin/negotiate/src/impl.rs index 6cdb3aa8..341482c0 100644 --- a/plugin/negotiate/src/impl.rs +++ b/plugin/negotiate/src/impl.rs @@ -242,6 +242,46 @@ impl ServerHook for CompressMiddleware { } Status::Continue } + + /// Negotiates content coding synchronously without constructing a future. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let response: &Response = ctx.get_response(); + if has_no_body(response.get_status_code()) + || response.get_body().len() < Self::config().get_min_length() + { + return Some(Status::Continue); + } + let Some(coding) = Self::negotiated_coding(ctx.get_request()) else { + return Some(Status::Continue); + }; + let state: u8 = inspect_response_for_compress(ctx.get_response()); + if state == COMPRESS_STATE_SKIP { + return Some(Status::Continue); + } + let response_mut: &mut Response = ctx.get_mut_response(); + if state == COMPRESS_STATE_SET_VARY { + response_mut.set_headers_batch(&[ + (CONTENT_ENCODING, coding.as_str()), + (VARY, VARY_ACCEPT_ENCODING), + ]); + } else if state == COMPRESS_STATE_ADD_VARY { + response_mut.set_header(CONTENT_ENCODING, coding.as_str()); + response_mut.add_header(VARY, VARY_ACCEPT_ENCODING); + } else { + response_mut.set_header(CONTENT_ENCODING, coding.as_str()); + } + Some(Status::Continue) + } } /// Inherent implementation of [`EntityTag`]. @@ -490,4 +530,42 @@ impl ServerHook for ConditionalMiddleware { } Status::Continue } + + /// Evaluates conditional validators synchronously without constructing a future. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let method: &Method = ctx.get_request().get_method(); + if !method.is_get() && !method.is_head() { + return Some(Status::Continue); + } + let status_code: usize = ctx.get_response().get_status_code(); + if !(200..300).contains(&status_code) || has_no_body(status_code) { + return Some(Status::Continue); + } + let matched: bool = if let Some(existing) = Self::existing_etag(ctx.get_response()) { + matches_if_none_match_fast(ctx.get_request(), existing) + } else { + let digest: u64 = xxhash3_64_oneshot(ctx.get_response().get_body()); + let buf: [u8; 18] = EntityTag::format_strong_bytes(digest); + let etag_str: &str = from_utf8(&buf).unwrap_or_default(); + let is_match: bool = matches_if_none_match_fast(ctx.get_request(), etag_str); + ctx.get_mut_response().set_header(ETAG, etag_str); + is_match + }; + if matched { + let response: &mut Response = ctx.get_mut_response(); + response.set_status_code(HttpStatus::NotModified.code()); + response.get_mut_body().clear(); + } + Some(Status::Continue) + } } diff --git a/plugin/openapi/src/impl.rs b/plugin/openapi/src/impl.rs index 614df022..83f599df 100644 --- a/plugin/openapi/src/impl.rs +++ b/plugin/openapi/src/impl.rs @@ -385,6 +385,38 @@ impl ServerHook for OpenapiHook { Self } + /// Synchronously passes through unconfigured, non-GET/HEAD, and non-OpenAPI paths without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for unmatched requests, or `None` for OpenAPI endpoints. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = OpenApiPlugin::get() else { + return Some(Status::Continue); + }; + let OpenApiPlugin { config, .. } = plugin; + let method: &Method = ctx.get_request().get_method(); + if !method.is_get() && !method.is_head() { + return Some(Status::Continue); + } + let path: &str = ctx.get_request().get_path(); + if path == config.get_spec_path().as_str() { + return None; + } + if let Some(docs_path) = config.try_get_docs_path() + && path == docs_path.as_str() + { + return None; + } + Some(Status::Continue) + } + /// Serves pre-serialized `/openapi.json` (with `304` support) and `/docs` with zero allocations. /// /// # Arguments diff --git a/plugin/problem_details/src/impl.rs b/plugin/problem_details/src/impl.rs index 2f8829f0..0e537c2f 100644 --- a/plugin/problem_details/src/impl.rs +++ b/plugin/problem_details/src/impl.rs @@ -143,10 +143,12 @@ impl ProblemDetails { /// /// - `&mut Context` - Active Hyperlane context. pub fn apply(&self, ctx: &mut Context) { - let mut owned: Self = self.clone(); - if owned.try_get_instance().is_none() { - owned.set_instance(Some(ctx.get_request().get_path().to_owned())); + if self.try_get_instance().is_some() { + self.write_to_response(ctx.get_mut_response()); + return; } + let mut owned: Self = self.clone(); + owned.set_instance(Some(ctx.get_request().get_path().to_owned())); owned.write_to_response(ctx.get_mut_response()); } } @@ -343,23 +345,38 @@ impl ServerHook for ProblemDetailsHook { Self } - /// Converts bare `4xx`/`5xx` error responses into structured RFC 9457 `application/problem+json`. + /// Synchronously normalizes bare `4xx`/`5xx` responses and skips `2xx`/`3xx` responses without async futures. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = ProblemDetailsPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; let _: bool = plugin.normalize_context(ctx); - Status::Continue + Some(Status::Continue) + } + + /// Converts bare `4xx`/`5xx` error responses into structured RFC 9457 `application/problem+json`. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/rate_limit/src/impl.rs b/plugin/rate_limit/src/impl.rs index ee408596..f5a9ea44 100644 --- a/plugin/rate_limit/src/impl.rs +++ b/plugin/rate_limit/src/impl.rs @@ -1016,6 +1016,50 @@ impl RateLimitPlugin { *use_default_ip_fast_path } + /// Synchronously evaluates `key` when using the built-in sharded limiter and admitted without side effects on rejection. + /// + /// # Arguments + /// + /// - `&str` - Partition key. + /// - `&mut Context` - Request and response context. + /// + /// # Returns + /// + /// - `Option` - `Some(true)` when admitted, or `None` to fall back to the async path. + #[inline] + pub(crate) fn try_evaluate_key_sync(&self, key: &str, ctx: &mut Context) -> Option { + let Self { + policy, + fast_store, + preformatted_limit, + expected_limit, + .. + } = self; + let limiter: &ShardedRateLimiter = fast_store.as_ref()?; + let decision: RateLimitDecision = limiter.check_direct(key); + if !decision.get_allowed() { + return None; + } + if policy.get_include_headers() { + let mut limit_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN]; + let mut rem_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN]; + let mut reset_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN]; + let limit_str: &str = if decision.get_limit() == *expected_limit { + preformatted_limit.as_str() + } else { + format_u64_stack(decision.get_limit(), &mut limit_buf) + }; + let rem_str: &str = format_u64_stack(decision.get_remaining(), &mut rem_buf); + let reset_str: &str = format_u64_stack(decision.get_reset_after_secs(), &mut reset_buf); + ctx.get_mut_response().set_headers_batch(&[ + (HEADER_RATE_LIMIT_LIMIT, limit_str), + (HEADER_RATE_LIMIT_REMAINING, rem_str), + (HEADER_RATE_LIMIT_RESET, reset_str), + ]); + } + Some(true) + } + /// Evaluates one request against `key` and attaches standard `RateLimit-*` response headers. /// /// # Arguments @@ -1052,10 +1096,11 @@ impl RateLimitPlugin { }; let rem_str: &str = format_u64_stack(decision.get_remaining(), &mut rem_buf); let reset_str: &str = format_u64_stack(decision.get_reset_after_secs(), &mut reset_buf); - response - .set_header(HEADER_RATE_LIMIT_LIMIT, limit_str) - .set_header(HEADER_RATE_LIMIT_REMAINING, rem_str) - .set_header(HEADER_RATE_LIMIT_RESET, reset_str); + response.set_headers_batch(&[ + (HEADER_RATE_LIMIT_LIMIT, limit_str), + (HEADER_RATE_LIMIT_REMAINING, rem_str), + (HEADER_RATE_LIMIT_RESET, reset_str), + ]); } if !decision.get_allowed() { let mut retry_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN]; @@ -1085,6 +1130,46 @@ impl ServerHook for RateLimitHook { Self } + /// Synchronously enforces built-in sharded rate limiting on admitted/exempt/unconfigured paths without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured, exempt, or admitted; `None` on rejection or custom store. + #[inline(always)] + fn try_handle_sync(stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = RateLimitPlugin::get() else { + return Some(Status::Continue); + }; + let exempt_paths: &Vec = plugin.get_policy().get_exempt_paths(); + if !exempt_paths.is_empty() { + let path: &str = ctx.get_request().get_path(); + if exempt_paths.iter().any(|exempt: &String| exempt == path) { + return Some(Status::Continue); + } + } + let admitted: Option = if plugin.is_default_ip_fast_path() { + let mut ip_buf: [u8; IP_STACK_BUF_LEN] = [0u8; IP_STACK_BUF_LEN]; + let peer_key: &str = if let Ok(addr) = stream.get_peer_addr() { + format_ip_stack(addr.ip(), &mut ip_buf) + } else { + FALLBACK_CLIENT_KEY + }; + plugin.try_evaluate_key_sync(peer_key, ctx) + } else { + let key: String = plugin.get_key_extractor().extract(stream, ctx); + plugin.try_evaluate_key_sync(&key, ctx) + }; + if admitted.is_some() { + return Some(Status::Continue); + } + None + } + /// Enforces the configured rate limit and rejects excess traffic with `429 Too Many Requests`. /// /// # Arguments diff --git a/plugin/rewrite/src/impl.rs b/plugin/rewrite/src/impl.rs index ba180cf3..7f0af3d8 100644 --- a/plugin/rewrite/src/impl.rs +++ b/plugin/rewrite/src/impl.rs @@ -1139,4 +1139,108 @@ impl ServerHook for RewriteHook { }; plugin.get_compiled().apply_and_send_hook(stream, ctx).await } + + /// Synchronous fast path avoiding future construction when unconfigured or when no redirect is emitted. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unchanged or internally rewritten; `None` on redirect. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = RewritePlugin::get() else { + return Some(Status::Continue); + }; + let compiled: &CompiledRewrite = plugin.get_compiled(); + let config: &RewriteConfig = compiled.get_config(); + if config.get_force_https() || compiled.canonical_host_lower.is_some() { + let headers: &RequestHeaders = ctx.get_request().get_headers(); + let req_https: bool = is_request_https(headers, config.get_trust_forwarded_proto()); + let needs_https: bool = config.get_force_https() && !req_https; + let req_host_ref: Option<&str> = find_header_back_ref(headers, HOST); + let needs_host_redirect: bool = + match (compiled.canonical_host_lower.as_deref(), req_host_ref) { + (Some(canonical), Some(incoming)) => { + !host_matches_canonical(incoming, canonical) + } + (Some(_), None) => true, + (None, _) => false, + }; + if needs_https || needs_host_redirect { + return None; + } + } + let original_path: &str = ctx.get_request().get_path(); + let after_slash: Cow<'_, str> = if config.get_collapse_duplicate_slashes() { + collapse_slashes(original_path) + } else { + Cow::Borrowed(original_path) + }; + let slash_collapsed: bool = matches!(after_slash, Cow::Owned(_)); + let (normalized_path, trailing_changed): (Cow<'_, str>, bool) = + normalize_trailing_slash_borrowed(after_slash, config.get_trailing_slash()); + let normalized_changed: bool = slash_collapsed || trailing_changed; + if normalized_changed + && matches!( + config.get_normalization_action(), + RewriteAction::Redirect(_) + ) + { + if has_unsafe_header_chars(normalized_path.as_ref()) { + return Some(Status::Continue); + } + return None; + } + let working_path: &str = normalized_path.as_ref(); + if !compiled.exact_map.is_empty() + && let Some(hit) = compiled.exact_map.get(working_path) + { + return match hit.action { + RewriteAction::Redirect(_) => None, + RewriteAction::InternalRewrite => { + let target: String = hit.to.clone(); + apply_internal_rewrite_owned(ctx, target); + Some(Status::Continue) + } + }; + } + let mut matched: Option<(String, RewriteAction)> = None; + for rule in &compiled.prefix_rules { + if let Some(rest) = strip_prefix_segment(working_path, &rule.from) { + let replaced: String = join_prefix_replacement(&rule.to, rest); + matched = Some((replaced, rule.action)); + break; + } + } + if matched.is_none() + && !compiled.regex_rules.is_empty() + && let Some((replaced, action, _)) = compiled.match_regex_rules(working_path) + { + matched = Some((replaced, action)); + } + if let Some((target, action)) = matched { + return match action { + RewriteAction::Redirect(_) => { + if has_unsafe_header_chars(&target) { + Some(Status::Continue) + } else { + None + } + } + RewriteAction::InternalRewrite => { + apply_internal_rewrite_owned(ctx, target); + Some(Status::Continue) + } + }; + } + if normalized_changed { + let owned_norm: String = normalized_path.into_owned(); + apply_internal_rewrite_owned(ctx, owned_norm); + } + Some(Status::Continue) + } } diff --git a/plugin/rpc/src/impl.rs b/plugin/rpc/src/impl.rs index db19dfc3..33fec2ed 100644 --- a/plugin/rpc/src/impl.rs +++ b/plugin/rpc/src/impl.rs @@ -1588,4 +1588,25 @@ impl ServerHook for RpcHook { let _: Result<(), ResponseError> = stream.try_send(&wire).await; Status::Reject } + + /// Synchronous fast path avoiding future construction when unconfigured or path does not match. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` for non-RPC paths, or `None` to dispatch RPC. + #[inline(always)] + fn try_handle_sync(_stream: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = RpcPlugin::get() else { + return Some(Status::Continue); + }; + if ctx.get_request().get_path() != plugin.get_config().get_endpoint() { + return Some(Status::Continue); + } + None + } } diff --git a/plugin/scheduler/src/impl.rs b/plugin/scheduler/src/impl.rs index 6b65dd23..c80b62a4 100644 --- a/plugin/scheduler/src/impl.rs +++ b/plugin/scheduler/src/impl.rs @@ -102,13 +102,54 @@ impl CronMask { /// /// - `Option` - Next matching UTC Unix timestamp aligned to `:00` seconds. pub fn next_unix_secs_after(&self, unix_secs: i64) -> Option { - let mut candidate: i64 = (unix_secs.div_euclid(60) + 1) * 60; - let max_steps: usize = 527_040; - for _ in 0..max_steps { - if self.matches_unix_secs(candidate) { - return Some(candidate); + let Self { + minutes, + hours, + days, + months, + weekdays, + } = self; + if *minutes == 0 || *hours == 0 || *days == 0 || *months == 0 || *weekdays == 0 { + return None; + } + let start: i64 = (unix_secs.div_euclid(60) + 1) * 60; + let limit: i64 = start + 527_040 * 60; + let mut candidate: i64 = start; + while candidate < limit { + let epoch_days: i64 = candidate.div_euclid(86_400); + let (_, month, day): (i32, u8, u8) = civil_from_days(epoch_days); + let dow: u8 = (epoch_days + 4).rem_euclid(7) as u8; + if ((*months & (1u16 << u32::from(month))) == 0) + || ((*days & (1u32 << u32::from(day))) == 0) + || ((*weekdays & (1u8 << u32::from(dow))) == 0) + { + candidate = (epoch_days + 1) * 86_400; + continue; + } + let sod: u32 = candidate.rem_euclid(86_400) as u32; + let hour: u32 = sod / 3600; + let minute: u32 = (sod % 3600) / 60; + let remaining_hours: u32 = *hours >> hour; + if remaining_hours == 0 { + candidate = (epoch_days + 1) * 86_400; + continue; + } + let hour_delta: u32 = remaining_hours.trailing_zeros(); + let eff_hour: u32 = hour + hour_delta; + let eff_min: u32 = if hour_delta > 0 { 0 } else { minute }; + let remaining_mins: u64 = *minutes >> eff_min; + if remaining_mins == 0 { + candidate = epoch_days * 86_400 + i64::from(eff_hour + 1) * 3600; + continue; + } + let min_delta: u32 = remaining_mins.trailing_zeros(); + let final_ts: i64 = epoch_days * 86_400 + + i64::from(eff_hour) * 3600 + + i64::from(eff_min + min_delta) * 60; + if final_ts < limit { + return Some(final_ts); } - candidate += 60; + return None; } None } diff --git a/plugin/security/src/impl.rs b/plugin/security/src/impl.rs index c220bc82..5b08082c 100644 --- a/plugin/security/src/impl.rs +++ b/plugin/security/src/impl.rs @@ -466,6 +466,28 @@ impl ServerHook for SecurityRequestHook { Self } + /// Synchronously enforces request security guards and seeds response headers when admitted. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured or permitted, or `None` on violation. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = SecurityPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.inspect_request(ctx).is_err() { + return None; + } + plugin.apply_headers(ctx.get_mut_response()); + Some(Status::Continue) + } + /// Enforces request security guards, CSRF validation, and custom rules, and seeds response security headers. /// /// # Arguments @@ -509,22 +531,37 @@ impl ServerHook for SecurityResponseHook { Self } - /// Ensures configured security headers remain present and removes `X-Powered-By`. + /// Synchronously ensures configured security headers remain present and removes `X-Powered-By`. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = SecurityPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; plugin.apply_headers(ctx.get_mut_response()); - Status::Continue + Some(Status::Continue) + } + + /// Ensures configured security headers remain present and removes `X-Powered-By`. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/session/src/impl.rs b/plugin/session/src/impl.rs index dd741558..69d26851 100644 --- a/plugin/session/src/impl.rs +++ b/plugin/session/src/impl.rs @@ -164,7 +164,7 @@ impl SessionHandle { } } - /// Returns the current session identifier. + /// Returns the current session identifier, lazily minting one for anonymous sessions on first access. /// /// # Returns /// @@ -174,7 +174,12 @@ impl SessionHandle { inner .state .lock() - .map(|guard: MutexGuard<'_, SessionState>| guard.id.clone()) + .map(|mut guard: MutexGuard<'_, SessionState>| { + if guard.id.is_empty() { + guard.id = generate_session_id(); + } + guard.id.clone() + }) .unwrap_or_default() } @@ -209,6 +214,9 @@ impl SessionHandle { { let Self { inner } = self; if let Ok(mut guard) = inner.state.lock() { + if guard.id.is_empty() { + guard.id = generate_session_id(); + } Arc::make_mut(&mut guard.values).insert(key.into(), value.into()); guard.dirty = true; guard.destroyed = false; @@ -919,6 +927,90 @@ impl SessionPlugin { handle } + /// Synchronously loads or initializes the [`SessionHandle`] when backed by the built-in [`InMemorySessionStore`]. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// - `&InMemorySessionStore` - Built-in sharded in-memory store. + /// + /// # Returns + /// + /// - `SessionHandle` - Active session handle attached to `ctx`. + #[inline] + fn load_into_context_sync( + &self, + ctx: &mut Context, + mem_store: &InMemorySessionStore, + ) -> SessionHandle { + let Self { + config, compiled, .. + } = self; + let mut sid_stack: [u8; SID_STACK_CAP] = [0u8; SID_STACK_CAP]; + let mut sid_len: usize = 0; + let mut owned_sid: Option = None; + let mut loaded_values: Option>> = None; + if let Some(raw_cookie) = ctx + .get_request() + .get_headers() + .get(COOKIE) + .and_then(|values: &VecDeque| values.back()) + .map(String::as_str) + && let Some(raw_val) = find_cookie_value_trusted( + raw_cookie, + config.get_cookie_name(), + compiled.valid_cookie_name, + ) + { + let verified_sid: Option<&str> = match &compiled.hmac_key { + Some(key) => verify_session_cookie_with_key(raw_val, key), + None => { + if raw_val.is_empty() { + None + } else { + Some(raw_val) + } + } + }; + if let Some(sid) = verified_sid + && let Some(values) = mem_store.load_sync_shared(sid) + { + let sid_bytes: &[u8] = sid.as_bytes(); + if sid_bytes.len() <= SID_STACK_CAP { + sid_stack[..sid_bytes.len()].copy_from_slice(sid_bytes); + sid_len = sid_bytes.len(); + } else { + owned_sid = Some(sid.to_owned()); + } + loaded_values = Some(values); + } + } + if let Some(values) = loaded_values { + let sid_ref: &str = from_utf8(&sid_stack[..sid_len]).unwrap_or_default(); + return Self::install_handle(ctx, sid_ref, owned_sid, values, true); + } + Self::install_handle(ctx, "", None, Arc::clone(empty_session_values()), false) + } + + /// Attempts to load the per-request session synchronously when backed by the built-in in-memory store. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// + /// # Returns + /// + /// - `bool` - `true` when loaded synchronously; `false` when an async custom store is configured. + #[inline(always)] + pub(crate) fn try_load_sync(&self, ctx: &mut Context) -> bool { + let Self { fast_store, .. } = self; + let Some(mem_store) = fast_store else { + return false; + }; + let _: SessionHandle = self.load_into_context_sync(ctx, mem_store); + true + } + /// Loads or initializes the [`SessionHandle`] on `ctx` from the incoming `Cookie` header. /// /// # Arguments @@ -935,6 +1027,9 @@ impl SessionPlugin { compiled, fast_store, } = self; + if let Some(mem_store) = fast_store { + return self.load_into_context_sync(ctx, mem_store); + } let mut sid_stack: [u8; SID_STACK_CAP] = [0u8; SID_STACK_CAP]; let mut sid_len: usize = 0; let mut owned_sid: Option = None; @@ -961,38 +1056,118 @@ impl SessionPlugin { } } }; - if let Some(sid) = verified_sid { - let maybe_values: Option>> = - if let Some(mem_store) = fast_store { - mem_store.load_sync_shared(sid) - } else { - store.load(sid).await.map(Arc::new) - }; - if let Some(values) = maybe_values { - let sid_bytes: &[u8] = sid.as_bytes(); - if sid_bytes.len() <= SID_STACK_CAP { - sid_stack[..sid_bytes.len()].copy_from_slice(sid_bytes); - sid_len = sid_bytes.len(); - } else { - owned_sid = Some(sid.to_owned()); - } - loaded_values = Some(values); + if let Some(sid) = verified_sid + && let Some(values) = store.load(sid).await.map(Arc::new) + { + let sid_bytes: &[u8] = sid.as_bytes(); + if sid_bytes.len() <= SID_STACK_CAP { + sid_stack[..sid_bytes.len()].copy_from_slice(sid_bytes); + sid_len = sid_bytes.len(); + } else { + owned_sid = Some(sid.to_owned()); } + loaded_values = Some(values); } } if let Some(values) = loaded_values { let sid_ref: &str = from_utf8(&sid_stack[..sid_len]).unwrap_or_default(); return Self::install_handle(ctx, sid_ref, owned_sid, values, true); } - let fresh_id: [u8; 32] = generate_session_id_bytes(); - let fresh_str: &str = from_utf8(&fresh_id).unwrap_or_default(); - Self::install_handle( - ctx, - fresh_str, - None, - Arc::clone(empty_session_values()), - false, - ) + Self::install_handle(ctx, "", None, Arc::clone(empty_session_values()), false) + } + + /// Synchronously persists dirty session state for the built-in [`InMemorySessionStore`]. + /// + /// # Arguments + /// + /// - `&mut Context` - Outgoing request/response context. + /// - `&InMemorySessionStore` - Built-in sharded in-memory store. + #[inline] + fn persist_from_context_sync(&self, ctx: &mut Context, mem_store: &InMemorySessionStore) { + let Self { + config, compiled, .. + } = self; + let Some(handle) = ctx + .get_attributes() + .get(ATTR_SESSION_HANDLE_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) + else { + return; + }; + if !handle.inner.dirty.load(Ordering::Acquire) { + return; + } + let mut cookie_buf: [u8; SET_COOKIE_STACK_CAP] = [0u8; SET_COOKIE_STACK_CAP]; + let mut cookie_len: Option = None; + let mut cookie_fallback: Option = None; + let mut emit_clear: bool = false; + { + let Ok(mut guard) = handle.inner.state.lock() else { + return; + }; + if !guard.dirty { + return; + } + if let Some(old_id) = guard.previous_id.as_deref() { + let _: bool = mem_store.delete_sync(old_id); + } + if guard.destroyed { + if !guard.id.is_empty() { + let _: bool = mem_store.delete_sync(&guard.id); + } + emit_clear = compiled.valid_cookie_config; + } else { + if guard.id.is_empty() { + guard.id = generate_session_id(); + } + mem_store.save_sync_shared( + &guard.id, + Arc::clone(&guard.values), + config.get_ttl_secs(), + ); + if let Some(cookie_str) = + self.format_live_set_cookie_stack(&guard.id, &mut cookie_buf) + { + cookie_len = Some(cookie_str.len()); + } else { + cookie_fallback = Some(self.build_set_cookie(&guard.id, false)); + } + } + } + if emit_clear { + ctx.get_mut_response() + .add_header(SET_COOKIE, &compiled.clear_cookie); + } else if let Some(len) = cookie_len { + if let Ok(cookie_str) = from_utf8(&cookie_buf[..len]) { + ctx.get_mut_response().add_header(SET_COOKIE, cookie_str); + } + } else if let Some(set_cookie) = cookie_fallback { + ctx.get_mut_response().add_header(SET_COOKIE, set_cookie); + } + } + + /// Attempts to persist or skip clean session state synchronously without spawning async futures. + /// + /// # Arguments + /// + /// - `&mut Context` - Outgoing request/response context. + /// + /// # Returns + /// + /// - `bool` - `true` when completed synchronously; `false` when a dirty custom async store must run. + #[inline(always)] + pub(crate) fn try_persist_sync(&self, ctx: &mut Context) -> bool { + let Self { fast_store, .. } = self; + if let Some(mem_store) = fast_store { + self.persist_from_context_sync(ctx, mem_store); + return true; + } + let is_dirty: bool = ctx + .get_attributes() + .get(ATTR_SESSION_HANDLE_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) + .is_some_and(SessionHandle::is_dirty); + !is_dirty } /// Persists dirty, regenerated, or destroyed session state and emits `Set-Cookie` on `ctx`. @@ -1008,61 +1183,10 @@ impl SessionPlugin { fast_store, } = self; if let Some(mem_store) = fast_store { - let mut cookie_buf: [u8; SET_COOKIE_STACK_CAP] = [0u8; SET_COOKIE_STACK_CAP]; - let mut cookie_len: Option = None; - let mut cookie_fallback: Option = None; - let mut emit_clear: bool = false; - { - let Some(handle) = ctx - .get_attributes() - .get(ATTR_SESSION_HANDLE_MAP_KEY) - .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) - else { - return; - }; - if !handle.inner.dirty.load(Ordering::Acquire) { - return; - } - let Ok(guard) = handle.inner.state.lock() else { - return; - }; - if !guard.dirty { - return; - } - if let Some(old_id) = guard.previous_id.as_deref() { - let _: bool = mem_store.delete_sync(old_id); - } - if guard.destroyed { - let _: bool = mem_store.delete_sync(&guard.id); - emit_clear = compiled.valid_cookie_config; - } else { - mem_store.save_sync_shared( - &guard.id, - Arc::clone(&guard.values), - config.get_ttl_secs(), - ); - if let Some(cookie_str) = - self.format_live_set_cookie_stack(&guard.id, &mut cookie_buf) - { - cookie_len = Some(cookie_str.len()); - } else { - cookie_fallback = Some(self.build_set_cookie(&guard.id, false)); - } - } - } - if emit_clear { - ctx.get_mut_response() - .add_header(SET_COOKIE, &compiled.clear_cookie); - } else if let Some(len) = cookie_len { - if let Ok(cookie_str) = from_utf8(&cookie_buf[..len]) { - ctx.get_mut_response().add_header(SET_COOKIE, cookie_str); - } - } else if let Some(set_cookie) = cookie_fallback { - ctx.get_mut_response().add_header(SET_COOKIE, set_cookie); - } + self.persist_from_context_sync(ctx, mem_store); return; } - let Some(state) = ctx + let Some(mut state) = ctx .get_attributes() .get(ATTR_SESSION_HANDLE_MAP_KEY) .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) @@ -1074,13 +1198,18 @@ impl SessionPlugin { let _: bool = store.delete(&old_id).await; } if state.destroyed { - let _: bool = store.delete(&state.id).await; + if !state.id.is_empty() { + let _: bool = store.delete(&state.id).await; + } if compiled.valid_cookie_config { ctx.get_mut_response() .add_header(SET_COOKIE, &compiled.clear_cookie); } return; } + if state.id.is_empty() { + state.id = generate_session_id(); + } let mut cookie_buf: [u8; SET_COOKIE_STACK_CAP] = [0u8; SET_COOKIE_STACK_CAP]; let stack_len: Option = self .format_live_set_cookie_stack(&state.id, &mut cookie_buf) @@ -1121,6 +1250,27 @@ impl ServerHook for SessionRequestHook { Self } + /// Synchronously loads or initializes the session when unconfigured or using the built-in in-memory store. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when handled synchronously, or `None` for custom async stores. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = SessionPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.try_load_sync(ctx) { + return Some(Status::Continue); + } + None + } + /// Loads or initializes the per-request [`SessionHandle`] into `ctx`. /// /// # Arguments @@ -1157,6 +1307,27 @@ impl ServerHook for SessionResponseHook { Self } + /// Synchronously persists built-in sessions or skips unmodified sessions without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when handled synchronously, or `None` for dirty custom async stores. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = SessionPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.try_persist_sync(ctx) { + return Some(Status::Continue); + } + None + } + /// Persists modified session state and attaches `Set-Cookie` only when dirty. /// /// # Arguments diff --git a/plugin/sse/src/impl.rs b/plugin/sse/src/impl.rs index 57548b17..523ef0f5 100644 --- a/plugin/sse/src/impl.rs +++ b/plugin/sse/src/impl.rs @@ -1354,10 +1354,11 @@ impl SseStream { /// /// - `&mut Context` - Active Hyperlane request context. pub fn prepare(ctx: &mut Context) { - ctx.get_mut_response() - .set_header(CONTENT_TYPE, SSE_CONTENT_TYPE) - .set_header(CACHE_CONTROL, SSE_CACHE_CONTROL) - .set_header(SSE_ACCEL_BUFFERING_HEADER, SSE_ACCEL_BUFFERING_VALUE); + ctx.get_mut_response().set_headers_batch(&[ + (CONTENT_TYPE, SSE_CONTENT_TYPE), + (CACHE_CONTROL, SSE_CACHE_CONTROL), + (SSE_ACCEL_BUFFERING_HEADER, SSE_ACCEL_BUFFERING_VALUE), + ]); } /// Writes one [`SseEvent`] frame directly onto `stream`, using a zero-allocation stack buffer for frames `<= 512` bytes. diff --git a/plugin/static_files/src/impl.rs b/plugin/static_files/src/impl.rs index 03bd5f39..37d8138f 100644 --- a/plugin/static_files/src/impl.rs +++ b/plugin/static_files/src/impl.rs @@ -650,6 +650,23 @@ impl StaticFilesRuntime { true } + /// Reports whether `request` cannot match any mounted static asset by method or mount prefix. + /// + /// # Arguments + /// + /// - `&Request` - Incoming HTTP request. + /// + /// # Returns + /// + /// - `bool` - `true` when the request definitely bypasses static file serving. + #[inline(always)] + pub(crate) fn is_bypassed_sync(&self, request: &Request) -> bool { + if !request.get_method().is_get() && !request.get_method().is_head() { + return true; + } + self.strip_mount(request.get_path()).is_none() + } + /// Serves a matching static asset directly to `stream` using zero-copy prebuilt HTTP/1.1 wire buffers when eligible. /// /// # Arguments @@ -754,6 +771,27 @@ impl ServerHook for StaticFilesHook { Self } + /// Synchronously passes through unconfigured, non-GET/HEAD, and non-mounted paths without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when bypassed, or `None` to resolve static assets asynchronously. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = StaticFilesPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.get_runtime().is_bypassed_sync(ctx.get_request()) { + return Some(Status::Continue); + } + None + } + /// Serves matching static files and short-circuits the pipeline once answered. /// /// # Arguments diff --git a/plugin/tenant/src/const.rs b/plugin/tenant/src/const.rs index 8768384d..704e86c9 100644 --- a/plugin/tenant/src/const.rs +++ b/plugin/tenant/src/const.rs @@ -24,3 +24,7 @@ pub const DEFAULT_SUSPENDED_TENANT_BODY: &[u8] = /// Root slash constant. pub(crate) const ROOT_SLASH: &str = "/"; + +/// Preformatted internal map key for zero-allocation lookup/update of [`TenantContext`]. +pub(crate) const ATTR_TENANT_CONTEXT_MAP_KEY: &str = + "External(\"hyperlane_plugin_tenant.context\")"; diff --git a/plugin/tenant/src/impl.rs b/plugin/tenant/src/impl.rs index 9a918924..b52c898f 100644 --- a/plugin/tenant/src/impl.rs +++ b/plugin/tenant/src/impl.rs @@ -203,7 +203,38 @@ impl TenantPlugin { .collect::>() .into_boxed_slice(); let mut registry: HashMapXxHash3_64 = hash_map_xx_hash3_64(); + let mut prebuilt_contexts: HashMapXxHash3_64 = + hash_map_xx_hash3_64(); for rec in config.get_tenants() { + if rec.get_status() == TenantStatus::Active { + let tenant_id: &String = rec.get_id(); + let plan: &String = rec.get_plan(); + prebuilt_contexts.insert( + tenant_id.clone(), + [ + Arc::new(TenantContext { + tenant_id: tenant_id.clone(), + plan: plan.clone(), + source: TenantSource::Header, + }), + Arc::new(TenantContext { + tenant_id: tenant_id.clone(), + plan: plan.clone(), + source: TenantSource::Subdomain, + }), + Arc::new(TenantContext { + tenant_id: tenant_id.clone(), + plan: plan.clone(), + source: TenantSource::PathPrefix, + }), + Arc::new(TenantContext { + tenant_id: tenant_id.clone(), + plan: plan.clone(), + source: TenantSource::Default, + }), + ], + ); + } registry.insert(rec.get_id().clone(), rec.clone()); } let missing_wire: Vec = @@ -219,6 +250,7 @@ impl TenantPlugin { normalized_path_prefix, exempt_prefixes, registry, + prebuilt_contexts, resolver, missing_wire, unknown_wire, @@ -266,6 +298,120 @@ impl TenantPlugin { TENANT_PLUGIN.get() } + /// Stores a prebuilt `ArcAnySendSync` [`TenantContext`] in `ctx`, reusing the attribute map entry in place. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// - `ArcAnySendSync` - Shared [`TenantContext`] attribute value. + #[inline(always)] + fn put_tenant_arc(ctx: &mut Context, arc: ArcAnySendSync) { + if let Some(slot) = ctx + .get_mut_attributes() + .get_mut(ATTR_TENANT_CONTEXT_MAP_KEY) + { + *slot = arc; + return; + } + ctx.get_mut_attributes() + .insert(ATTR_TENANT_CONTEXT_MAP_KEY.to_owned(), arc); + } + + /// Attempts to resolve and attach [`TenantContext`] synchronously without cloning static strings or spawning futures. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when exempt or resolved synchronously; `None` on rejection or custom resolver. + #[inline] + pub(crate) fn try_resolve_into_context_sync(&self, ctx: &mut Context) -> Option { + let Self { + config, + header_lower, + dot_base_domain, + normalized_path_prefix, + exempt_prefixes, + registry, + prebuilt_contexts, + resolver, + .. + } = self; + let outcome: Option, TenantContext>> = { + let request: &Request = ctx.get_request(); + let path: &str = request.get_path(); + if exempt_prefixes + .iter() + .any(|p: &String| path_matches_prefix(path, p)) + { + Some(Ok(None)) + } else { + let extracted: Option<(&str, TenantSource)> = if !header_lower.is_empty() + && let Some(val) = request + .get_headers() + .get(header_lower.as_str()) + .and_then(|vals: &VecDeque| vals.back()) + && is_valid_tenant_id(val.trim()) + { + Some((val.trim(), TenantSource::Header)) + } else if let Some(dot_base) = dot_base_domain + && let Some(host_val) = request + .get_headers() + .get(HOST) + .and_then(|vals: &VecDeque| vals.back()) + && let Some(sub) = extract_subdomain(host_val, dot_base) + { + Some((sub, TenantSource::Subdomain)) + } else if let Some(prefix) = normalized_path_prefix + && let Some(seg) = extract_path_tenant(path, prefix) + { + Some((seg, TenantSource::PathPrefix)) + } else if let Some(default_id) = config.try_get_default_tenant() { + Some((default_id.as_str(), TenantSource::Default)) + } else { + None + }; + if let Some((tenant_id, source)) = extracted { + if let Some(arcs) = prebuilt_contexts.get(tenant_id) { + let source_idx: usize = match source { + TenantSource::Header => 0, + TenantSource::Subdomain => 1, + TenantSource::PathPrefix => 2, + TenantSource::Default => 3, + }; + Some(Ok(Some(Arc::clone(&arcs[source_idx])))) + } else if registry.contains_key(tenant_id) + || resolver.is_some() + || config.get_require_known() + { + None + } else { + Some(Err(TenantContext { + tenant_id: tenant_id.to_owned(), + plan: String::new(), + source, + })) + } + } else { + None + } + } + }; + match outcome? { + Ok(Some(arc)) => { + Self::put_tenant_arc(ctx, arc); + Some(Status::Continue) + } + Ok(None) => Some(Status::Continue), + Err(dynamic_ctx) => { + Self::put_tenant_arc(ctx, Arc::new(dynamic_ctx)); + Some(Status::Continue) + } + } + } + /// Resolves tenant identity and status for `request`. /// /// # Arguments @@ -373,6 +519,24 @@ impl ServerHook for TenantHook { Self } + /// Synchronously resolves static/unregistered active tenants and exempt paths without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured, exempt, or admitted; `None` on rejection or custom resolver. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = TenantPlugin::get() else { + return Some(Status::Continue); + }; + plugin.try_resolve_into_context_sync(ctx) + } + /// Resolves tenant identity, rejects invalid/unknown/suspended tenants, and attaches [`TenantContext`]. /// /// # Arguments diff --git a/plugin/tenant/src/lib.rs b/plugin/tenant/src/lib.rs index 51fd3b7f..66737308 100644 --- a/plugin/tenant/src/lib.rs +++ b/plugin/tenant/src/lib.rs @@ -28,8 +28,8 @@ use std::{ use { hyperlane::{ - CONTENT_TYPE, Context, HOST, HashMapXxHash3_64, HttpStatus, Request, Response, - ResponseError, ServerHook, Status, Stream, hash_map_xx_hash3_64, + ArcAnySendSync, CONTENT_TYPE, Context, HOST, HashMapXxHash3_64, HttpStatus, Request, + Response, ResponseError, ServerHook, Status, Stream, hash_map_xx_hash3_64, }, lombok_macros::*, }; diff --git a/plugin/tenant/src/struct.rs b/plugin/tenant/src/struct.rs index ca03556e..63545ff2 100644 --- a/plugin/tenant/src/struct.rs +++ b/plugin/tenant/src/struct.rs @@ -58,6 +58,8 @@ pub struct TenantPlugin { pub(crate) exempt_prefixes: Box<[String]>, /// `XxHash3_64` static tenant directory. pub(crate) registry: HashMapXxHash3_64, + /// Pre-allocated `Arc` per active tenant for each [`TenantSource`] variant. + pub(crate) prebuilt_contexts: HashMapXxHash3_64, /// Optional custom dynamic resolver. pub(crate) resolver: Option>, /// Prebuilt `400 Bad Request` wire bytes. diff --git a/plugin/timeout/src/const.rs b/plugin/timeout/src/const.rs index 632b49bc..c1932cb6 100644 --- a/plugin/timeout/src/const.rs +++ b/plugin/timeout/src/const.rs @@ -22,3 +22,7 @@ pub(crate) const ERR_DEADLINE_EXCEEDED: &str = "request deadline exceeded"; /// Root slash path constant. pub(crate) const ROOT_SLASH: &str = "/"; + +/// Preformatted internal map key for zero-allocation lookup/update of [`RequestDeadline`]. +pub(crate) const ATTR_REQUEST_DEADLINE_MAP_KEY: &str = + "External(\"hyperlane_plugin_timeout.deadline\")"; diff --git a/plugin/timeout/src/impl.rs b/plugin/timeout/src/impl.rs index 54e534d8..3629c7f8 100644 --- a/plugin/timeout/src/impl.rs +++ b/plugin/timeout/src/impl.rs @@ -297,6 +297,31 @@ impl TimeoutPlugin { base_ms } + /// Stores [`RequestDeadline`] in `ctx`, reusing any unique existing `Arc` slot in place. + /// + /// # Arguments + /// + /// - `&mut Context` - Incoming request context. + /// - `RequestDeadline` - Computed request deadline. + #[inline(always)] + pub(crate) fn put_deadline(ctx: &mut Context, deadline: RequestDeadline) { + if let Some(slot) = ctx + .get_mut_attributes() + .get_mut(ATTR_REQUEST_DEADLINE_MAP_KEY) + { + if let Some(any_mut) = Arc::get_mut(slot) + && let Some(existing) = any_mut.downcast_mut::() + { + *existing = deadline; + return; + } + *slot = Arc::new(deadline); + return; + } + ctx.get_mut_attributes() + .insert(ATTR_REQUEST_DEADLINE_MAP_KEY.to_owned(), Arc::new(deadline)); + } + /// Applies timeout error status and body onto `response` when a request deadline has expired. /// /// # Arguments @@ -307,7 +332,7 @@ impl TimeoutPlugin { response .set_status_code(config.get_timeout_status().code()) .set_header(CONTENT_TYPE, config.get_timeout_content_type()) - .set_body(config.get_timeout_body().clone()); + .set_body(config.get_timeout_body().as_slice()); } } @@ -328,29 +353,44 @@ impl ServerHook for TimeoutRequestHook { Self } - /// Computes and attaches [`RequestDeadline`] to `ctx`. + /// Synchronously computes and attaches [`RequestDeadline`] to `ctx` without async futures. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = TimeoutPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; let budget_ms: u64 = plugin.resolve_budget_ms(ctx.get_request()); if budget_ms > 0 { let deadline: RequestDeadline = RequestDeadline::from_instant(Instant::now(), budget_ms); - ctx.set_attribute(ATTR_REQUEST_DEADLINE, deadline); + TimeoutPlugin::put_deadline(ctx, deadline); } - Status::Continue + Some(Status::Continue) + } + + /// Computes and attaches [`RequestDeadline`] to `ctx`. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } @@ -371,30 +411,38 @@ impl ServerHook for TimeoutResponseHook { Self } - /// Checks deadline expiration and optionally attaches remaining-budget headers. + /// Synchronously checks deadline expiration with a single clock read and optionally attaches remaining-budget headers. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. + /// - `Option` - Always `Some(Status::Continue)`. #[inline(always)] - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = TimeoutPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; - let Some(deadline) = ctx.try_get_attribute_ref::(ATTR_REQUEST_DEADLINE) + let Some(deadline) = ctx + .get_attributes() + .get(ATTR_REQUEST_DEADLINE_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) + .copied() else { - return Status::Continue; + return Some(Status::Continue); }; - if deadline.is_expired() { + let now: Instant = Instant::now(); + if now >= deadline.get_deadline() { plugin.apply_timeout_response(ctx.get_mut_response()); } else if plugin.get_config().get_expose_remaining_header() { - let mut rem_ms: u64 = deadline.remaining().as_millis().min(u64::MAX as u128) as u64; + let mut rem_ms: u64 = deadline + .get_deadline() + .saturating_duration_since(now) + .as_millis() + .min(u64::MAX as u128) as u64; let mut buf: [u8; 20] = [0u8; 20]; let mut pos: usize = buf.len(); if rem_ms == 0 { @@ -412,6 +460,22 @@ impl ServerHook for TimeoutResponseHook { .set_header(HEADER_TIMEOUT_REMAINING_MS, rem_str); } } - Status::Continue + Some(Status::Continue) + } + + /// Checks deadline expiration and optionally attaches remaining-budget headers. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + #[inline(always)] + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/timeout/src/lib.rs b/plugin/timeout/src/lib.rs index 24b76bca..7c033cf5 100644 --- a/plugin/timeout/src/lib.rs +++ b/plugin/timeout/src/lib.rs @@ -25,14 +25,14 @@ use std::{ fmt::{self, Display, Formatter}, future::Future, str::from_utf8, - sync::OnceLock, + sync::{Arc, OnceLock}, time::{Duration, Instant}, }; use { hyperlane::{ - CONTENT_TYPE, Context, HttpStatus, Request, Response, ServerHook, Status, Stream, - tokio::time::timeout, + ArcAnySendSync, CONTENT_TYPE, Context, HttpStatus, Request, Response, ServerHook, Status, + Stream, tokio::time::timeout, }, lombok_macros::*, }; diff --git a/plugin/tracing/src/const.rs b/plugin/tracing/src/const.rs index 4e23b67b..4e84472e 100644 --- a/plugin/tracing/src/const.rs +++ b/plugin/tracing/src/const.rs @@ -11,9 +11,6 @@ pub const ATTR_TRACE_CONTEXT: &str = "hyperlane_plugin_tracing_context"; pub(crate) const ATTR_TRACE_CONTEXT_MAP_KEY: &str = "External(\"hyperlane_plugin_tracing_context\")"; -/// Context attribute key storing request start `Instant`. -pub(crate) const ATTR_TRACE_STARTED_AT: &str = "hyperlane_plugin_tracing_started_at"; - /// Preformatted internal map key for zero-clone borrowed lookup of request start `Instant`. pub(crate) const ATTR_TRACE_STARTED_AT_MAP_KEY: &str = "External(\"hyperlane_plugin_tracing_started_at\")"; diff --git a/plugin/tracing/src/impl.rs b/plugin/tracing/src/impl.rs index 7f99065c..c342ef45 100644 --- a/plugin/tracing/src/impl.rs +++ b/plugin/tracing/src/impl.rs @@ -150,22 +150,33 @@ impl TracingPlugin { .map(str::to_owned); let emit_tp: bool = config.get_emit_traceparent(); let emit_req: bool = config.get_emit_request_id(); - if emit_tp || emit_req { + if emit_tp && emit_req { + let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN]; + let req_str: &str = incoming_req_id + .as_deref() + .unwrap_or_else(|| from_utf8(&trace_bytes).unwrap_or_default()); let response: &mut Response = ctx.get_mut_response(); - if emit_tp { - let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN]; - if let Some(tp_str) = - format_traceparent_stack(&trace_bytes, &span_bytes, sampled, &mut tp_buf) - { - response.set_header(HEADER_TRACEPARENT, tp_str); - } - } - if emit_req { - let req_str: &str = incoming_req_id - .as_deref() - .unwrap_or_else(|| from_utf8(&trace_bytes).unwrap_or_default()); + if let Some(tp_str) = + format_traceparent_stack(&trace_bytes, &span_bytes, sampled, &mut tp_buf) + { + response + .set_headers_batch(&[(HEADER_TRACEPARENT, tp_str), (X_REQUEST_ID, req_str)]); + } else { response.set_header(X_REQUEST_ID, req_str); } + } else if emit_tp { + let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN]; + if let Some(tp_str) = + format_traceparent_stack(&trace_bytes, &span_bytes, sampled, &mut tp_buf) + { + ctx.get_mut_response() + .set_header(HEADER_TRACEPARENT, tp_str); + } + } else if emit_req { + let req_str: &str = incoming_req_id + .as_deref() + .unwrap_or_else(|| from_utf8(&trace_bytes).unwrap_or_default()); + ctx.get_mut_response().set_header(X_REQUEST_ID, req_str); } PreparedTraceStart { trace_bytes, @@ -294,7 +305,7 @@ impl TracingPlugin { prepared.tracestate, ); if config.get_emit_server_timing() || !exporters.is_empty() { - ctx.set_attribute(ATTR_TRACE_STARTED_AT, Instant::now()); + Self::put_preformatted_attr(ctx, ATTR_TRACE_STARTED_AT_MAP_KEY, Instant::now()); } } @@ -366,51 +377,63 @@ impl TracingPlugin { if !need_tp && !need_req_id && !need_timing && !has_exporters { return; } - let has_trace_ctx: bool = ctx - .get_attributes() - .get(ATTR_TRACE_CONTEXT_MAP_KEY) - .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) - .is_some(); - if !has_trace_ctx { - return; - } - let duration_us: u64 = if need_timing || has_exporters { - ctx.get_attributes() - .get(ATTR_TRACE_STARTED_AT_MAP_KEY) - .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) - .map(|started: &Instant| started.elapsed().as_micros().min(u64::MAX as u128) as u64) - .unwrap_or(0) - } else { - 0 - }; - if need_tp || need_req_id { - let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN]; - let mut tp_fallback: Option = None; - let mut tp_stack_ok: bool = false; - let mut req_id_copy: Option = None; - if let Some(trace_ctx) = ctx - .get_attributes() + let mut tp_buf: [u8; TRACEPARENT_LEN] = [0u8; TRACEPARENT_LEN]; + let mut tp_fallback: Option = None; + let mut tp_stack_ok: bool = false; + let mut req_id_copy: Option = None; + let mut export_record: Option = None; + let duration_us: u64 = { + let attrs: &HashMap = ctx.get_attributes(); + let Some(trace_ctx) = attrs .get(ATTR_TRACE_CONTEXT_MAP_KEY) .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) - { - if need_tp { - if format_traceparent_stack( - trace_ctx.get_trace_id().as_bytes(), - trace_ctx.get_span_id().as_bytes(), - trace_ctx.get_sampled(), - &mut tp_buf, - ) - .is_some() - { - tp_stack_ok = true; - } else { - tp_fallback = Some(trace_ctx.to_traceparent()); - } - } - if need_req_id { - req_id_copy = Some(trace_ctx.get_request_id().clone()); + else { + return; + }; + let elapsed_us: u64 = if need_timing || has_exporters { + attrs + .get(ATTR_TRACE_STARTED_AT_MAP_KEY) + .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) + .map(|started: &Instant| { + started.elapsed().as_micros().min(u64::MAX as u128) as u64 + }) + .unwrap_or(0) + } else { + 0 + }; + if need_tp { + if format_traceparent_stack( + trace_ctx.get_trace_id().as_bytes(), + trace_ctx.get_span_id().as_bytes(), + trace_ctx.get_sampled(), + &mut tp_buf, + ) + .is_some() + { + tp_stack_ok = true; + } else { + tp_fallback = Some(trace_ctx.to_traceparent()); } } + if need_req_id { + req_id_copy = Some(trace_ctx.get_request_id().clone()); + } + if has_exporters { + export_record = Some(SpanRecord { + trace_id: trace_ctx.get_trace_id().clone(), + span_id: trace_ctx.get_span_id().clone(), + parent_span_id: trace_ctx.get_parent_span_id(), + request_id: trace_ctx.get_request_id().clone(), + method: ctx.get_request().get_method().to_string(), + path: ctx.get_request().get_path().clone(), + status_code: ctx.get_response().get_status_code(), + duration_us: elapsed_us, + sampled: trace_ctx.get_sampled(), + }); + } + elapsed_us + }; + if need_tp || need_req_id { let response: &mut Response = ctx.get_mut_response(); if need_tp { if tp_stack_ok { @@ -441,23 +464,7 @@ impl TracingPlugin { response.set_header(SERVER_TIMING, &header_val); } } - if has_exporters - && let Some(trace_ctx) = ctx - .get_attributes() - .get(ATTR_TRACE_CONTEXT_MAP_KEY) - .and_then(|arc: &ArcAnySendSync| arc.downcast_ref::()) - { - let record: SpanRecord = SpanRecord { - trace_id: trace_ctx.get_trace_id().clone(), - span_id: trace_ctx.get_span_id().clone(), - parent_span_id: trace_ctx.get_parent_span_id(), - request_id: trace_ctx.get_request_id().clone(), - method: ctx.get_request().get_method().to_string(), - path: ctx.get_request().get_path().clone(), - status_code: ctx.get_response().get_status_code(), - duration_us, - sampled: trace_ctx.get_sampled(), - }; + if let Some(record) = export_record { for exporter in exporters.iter() { exporter.export(&record); } @@ -481,23 +488,38 @@ impl ServerHook for TracingRequestHook { Self } - /// Initializes W3C Trace Context and correlation headers at the very start of the pipeline. + /// Synchronously initializes W3C Trace Context and correlation headers without async futures. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = TracingPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; plugin.start_request_hook(ctx); - Status::Continue + Some(Status::Continue) + } + + /// Initializes W3C Trace Context and correlation headers at the very start of the pipeline. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } @@ -517,22 +539,37 @@ impl ServerHook for TracingResponseHook { Self } - /// Records `Server-Timing` and exports the completed request span. + /// Synchronously records `Server-Timing` and exports the completed request span without async futures. /// /// # Arguments /// - /// - `Self` - Hook instance. /// - `&mut Stream` - Connection stream. /// - `&mut Context` - Request context. /// /// # Returns /// - /// - `Status` - Always `Status::Continue`. - async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status { + /// - `Option` - Always `Some(Status::Continue)`. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { let Some(plugin) = TracingPlugin::get() else { - return Status::Continue; + return Some(Status::Continue); }; plugin.finish_request(ctx); - Status::Continue + Some(Status::Continue) + } + + /// Records `Server-Timing` and exports the completed request span. + /// + /// # Arguments + /// + /// - `Self` - Hook instance. + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Status` - Always `Status::Continue`. + async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status { + Self::try_handle_sync(stream, ctx).unwrap_or(Status::Continue) } } diff --git a/plugin/tracing/src/lib.rs b/plugin/tracing/src/lib.rs index d039af1f..89dee608 100644 --- a/plugin/tracing/src/lib.rs +++ b/plugin/tracing/src/lib.rs @@ -21,7 +21,7 @@ pub(crate) use r#static::*; use std::{ cell::Cell, - collections::VecDeque, + collections::{HashMap, VecDeque}, process, str::from_utf8, sync::{ diff --git a/plugin/webhook/src/impl.rs b/plugin/webhook/src/impl.rs index baffb4a2..22a1e9b9 100644 --- a/plugin/webhook/src/impl.rs +++ b/plugin/webhook/src/impl.rs @@ -1141,6 +1141,27 @@ impl ServerHook for WebhookHook { Self } + /// Synchronously passes through unconfigured, unmatched, and verified inbound webhooks without async futures. + /// + /// # Arguments + /// + /// - `&mut Stream` - Connection stream. + /// - `&mut Context` - Request context. + /// + /// # Returns + /// + /// - `Option` - `Some(Status::Continue)` when unconfigured, unmatched, or verified; `None` when rejected. + #[inline(always)] + fn try_handle_sync(_: &mut Stream, ctx: &mut Context) -> Option { + let Some(plugin) = WebhookPlugin::get() else { + return Some(Status::Continue); + }; + if plugin.get_verifier().verify_context_hook(ctx).is_ok() { + return Some(Status::Continue); + } + None + } + /// Verifies matched inbound webhooks in constant time and short-circuits invalid/replayed requests. /// /// # Arguments diff --git a/request/src/lib.rs b/request/src/lib.rs index d63e245f..5be3a2e2 100644 --- a/request/src/lib.rs +++ b/request/src/lib.rs @@ -63,7 +63,7 @@ use std::{ cell::{RefCell, RefMut}, future::poll_fn, mem::MaybeUninit, - net::{SocketAddr, ToSocketAddrs}, + net::{IpAddr, SocketAddr, ToSocketAddrs}, slice, str::from_utf8_unchecked, sync::{ diff --git a/request/src/pool/const.rs b/request/src/pool/const.rs index c14d1b65..2f294d43 100644 --- a/request/src/pool/const.rs +++ b/request/src/pool/const.rs @@ -1,23 +1,29 @@ /// Number of independent lock stripes in the HTTP/1.1 connection pool (must be a power of two <= 64). pub(crate) const H1_POOL_STRIPES: usize = 16; -/// Maximum idle HTTP/1.1 connections cached per `(origin, proxy)` inside one pool stripe. -pub(crate) const POOL_MAX_IDLE_PER_STRIPE_HOST: usize = 16; - -/// Maximum idle HTTP/1.1 connections cached per stripe across all origins (`16 * 64 = 1024` total). -pub(crate) const POOL_MAX_IDLE_PER_STRIPE: usize = 64; +/// Idle keep-alive timeout before a pooled connection is discarded (seconds). +pub(crate) const POOL_IDLE_TTL_SECS: u64 = 60; /// Maximum total idle HTTP/2 senders retained across all origins. pub(crate) const POOL_MAX_IDLE_TOTAL: usize = 1024; +/// Size of the uninitialized stack buffer used for single-read async HTTP/1.1 responses. +pub(crate) const ASYNC_READ_STACK_CAP: usize = 4 * 1024; + /// Number of alternate stripes probed via `try_lock` before blocking on the preferred stripe. pub(crate) const H1_POOL_PROBE_ATTEMPTS: usize = 4; -/// Idle keep-alive timeout before a pooled connection is discarded (seconds). -pub(crate) const POOL_IDLE_TTL_SECS: u64 = 60; +/// Maximum idle HTTP/1.1 connections cached per stripe across all origins (`16 * 64 = 1024` total). +pub(crate) const POOL_MAX_IDLE_PER_STRIPE: usize = 64; /// Maximum number of reusable byte buffers kept in each worker's thread-local pool. pub(crate) const CLIENT_MAX_POOLED_BUFFERS: usize = 32; +/// Maximum number of HTTP/2 senders cached in each worker thread's lock-free L1 cache. +pub(crate) const H2_LOCAL_CACHE_MAX_ENTRIES: usize = 32; + /// Largest byte buffer capacity retained in the worker-local buffer pool. pub(crate) const CLIENT_MAX_POOLED_BUFFER_CAP: usize = 64 * 1024; + +/// Maximum idle HTTP/1.1 connections cached per `(origin, proxy)` inside one pool stripe. +pub(crate) const POOL_MAX_IDLE_PER_STRIPE_HOST: usize = 16; diff --git a/request/src/pool/fn.rs b/request/src/pool/fn.rs index c1afd691..a9cd50a2 100644 --- a/request/src/pool/fn.rs +++ b/request/src/pool/fn.rs @@ -241,11 +241,39 @@ pub(crate) fn put_sync_h1_conn( /// - `Option>` - Cloned HTTP/2 request sender, or `None`. #[inline(always)] pub(crate) fn get_h2_sender(lookup: PoolLookup<'_>) -> Option> { + let generation: u64 = H2_POOL_GEN.load(Ordering::Acquire); + let local_hit: Option> = + H2_LOCAL_CACHE.with(|cache: &RefCell<(u64, H2PoolList)>| { + let mut guard: RefMut<'_, (u64, H2PoolList)> = cache.borrow_mut(); + if guard.0 != generation { + guard.0 = generation; + guard.1.clear(); + return None; + } + guard + .1 + .iter() + .find(|(k, _): &&(PoolKey, SendRequest)| { + pool_key_matches( + k, + lookup.is_https, + lookup.host, + lookup.port, + lookup.proxy, + lookup.root_fp, + 0, + ) + }) + .map(|(_, sender): &(PoolKey, SendRequest)| sender.clone()) + }); + if local_hit.is_some() { + return local_hit; + } let lock: &RwLock = ASYNC_H2_POOL.get_or_init(|| RwLock::new(Vec::new())); let Ok(entries) = lock.read() else { return None; }; - entries + let found: Option<(PoolKey, SendRequest)> = entries .iter() .find(|(k, _): &&(PoolKey, SendRequest)| { pool_key_matches( @@ -258,7 +286,21 @@ pub(crate) fn get_h2_sender(lookup: PoolLookup<'_>) -> Option 0, ) }) - .map(|(_, sender): &(PoolKey, SendRequest)| sender.clone()) + .map(|(k, sender): &(PoolKey, SendRequest)| (k.clone(), sender.clone())); + drop(entries); + if let Some((key, sender)) = found { + H2_LOCAL_CACHE.with(|cache: &RefCell<(u64, H2PoolList)>| { + let mut guard: RefMut<'_, (u64, H2PoolList)> = cache.borrow_mut(); + if guard.0 == generation { + if guard.1.len() >= H2_LOCAL_CACHE_MAX_ENTRIES { + guard.1.clear(); + } + guard.1.push((key, sender.clone())); + } + }); + return Some(sender); + } + None } /// Stores or replaces an active multiplexed HTTP/2 sender in the pool. @@ -288,6 +330,7 @@ pub(crate) fn put_h2_sender(lookup: PoolLookup<'_>, sender: SendRequest) }) { *existing = sender; + H2_POOL_GEN.fetch_add(1, Ordering::Release); return; } if entries.len() >= POOL_MAX_IDLE_TOTAL { @@ -302,6 +345,7 @@ pub(crate) fn put_h2_sender(lookup: PoolLookup<'_>, sender: SendRequest) 0, ); entries.push((key, sender)); + H2_POOL_GEN.fetch_add(1, Ordering::Release); } /// Removes a closed or broken HTTP/2 sender matching `lookup` from the pool. @@ -327,6 +371,7 @@ pub(crate) fn remove_h2_sender(lookup: PoolLookup<'_>) { }) { let _: (PoolKey, SendRequest) = entries.swap_remove(pos); + H2_POOL_GEN.fetch_add(1, Ordering::Release); } } diff --git a/request/src/pool/impl.rs b/request/src/pool/impl.rs index cf1a9571..99daaa78 100644 --- a/request/src/pool/impl.rs +++ b/request/src/pool/impl.rs @@ -213,7 +213,9 @@ impl StripedH1Pool { /// - `Self` - Initialized pool with `H1_POOL_STRIPES` empty lock stripes. pub(crate) fn new() -> Self { Self { - stripes: array::from_fn(|_: usize| Mutex::new(H1PoolStripe::new())), + stripes: array::from_fn(|_: usize| CachePaddedStripe { + lock: Mutex::new(H1PoolStripe::new()), + }), non_empty_mask: AtomicU64::new(0), } } @@ -234,7 +236,7 @@ impl StripedH1Pool { stripes, non_empty_mask, } = self; - let Ok(mut stripe) = stripes[stripe_idx].lock() else { + let Ok(mut stripe) = stripes[stripe_idx].lock.lock() else { return None; }; if stripe.total == 0 { @@ -325,7 +327,7 @@ impl StripedH1Pool { let mut locked: Option>> = None; for probe in 0..H1_POOL_PROBE_ATTEMPTS { let idx: usize = (pref + probe) & (H1_POOL_STRIPES - 1); - if let Ok(guard) = stripes[idx].try_lock() { + if let Ok(guard) = stripes[idx].lock.try_lock() { chosen_idx = idx; locked = Some(guard); break; @@ -333,7 +335,7 @@ impl StripedH1Pool { } let mut stripe: MutexGuard<'_, H1PoolStripe> = match locked { Some(guard) => guard, - None => match stripes[pref].lock() { + None => match stripes[pref].lock.lock() { Ok(guard) => guard, Err(_) => return, }, @@ -389,7 +391,10 @@ impl StripedH1Pool { idle_since: now, }); *total += 1; - non_empty_mask.fetch_or(1u64 << chosen_idx, Ordering::Release); + let bit: u64 = 1u64 << chosen_idx; + if (non_empty_mask.load(Ordering::Relaxed) & bit) == 0 { + non_empty_mask.fetch_or(bit, Ordering::Release); + } } /// Reports whether any stripe currently retains a bucket for `port`. @@ -405,7 +410,7 @@ impl StripedH1Pool { pub(crate) fn contains_port(&self, port: u16) -> bool { let Self { stripes, .. } = self; for stripe_lock in stripes { - if let Ok(stripe) = stripe_lock.lock() + if let Ok(stripe) = stripe_lock.lock.lock() && stripe .entries .iter() @@ -429,7 +434,7 @@ impl StripedH1Pool { stripes, non_empty_mask, } = self; - if let Ok(mut stripe) = stripes[0].lock() { + if let Ok(mut stripe) = stripes[0].lock.lock() { let mut queue: VecDeque> = VecDeque::new(); queue.push_back(conn); stripe.entries.push((key, queue)); diff --git a/request/src/pool/static.rs b/request/src/pool/static.rs index 794aef8f..61f70957 100644 --- a/request/src/pool/static.rs +++ b/request/src/pool/static.rs @@ -9,6 +9,9 @@ pub(crate) static SYNC_H1_POOL: OnceLock> = O /// Process-wide pool of multiplexed asynchronous HTTP/2 connection senders using read-mostly locking. pub(crate) static ASYNC_H2_POOL: OnceLock> = OnceLock::new(); +/// Monotonic generation bumped whenever [`ASYNC_H2_POOL`] changes, validating worker-local caches. +pub(crate) static H2_POOL_GEN: AtomicU64 = AtomicU64::new(0); + /// Global counter assigning each worker thread a stable initial stripe index. pub(crate) static NEXT_H1_STRIPE_ID: AtomicUsize = AtomicUsize::new(0); @@ -22,4 +25,8 @@ thread_local! { /// Pre-zeroed thread-local scratch buffer eliminating per-request zero-fill in synchronous reads. pub(crate) static SYNC_READ_SCRATCH: RefCell> = const { RefCell::new(Vec::new()) }; + + /// Generation-stamped worker-local L1 cache of multiplexed HTTP/2 senders. + pub(crate) static H2_LOCAL_CACHE: RefCell<(u64, H2PoolList)> = + const { RefCell::new((0, Vec::new())) }; } diff --git a/request/src/pool/struct.rs b/request/src/pool/struct.rs index d08b7d27..58ea7762 100644 --- a/request/src/pool/struct.rs +++ b/request/src/pool/struct.rs @@ -67,10 +67,17 @@ pub(crate) struct H1PoolStripe { pub(crate) total: usize, } +/// Cache-line padded wrapper preventing false sharing between adjacent HTTP/1.1 pool stripes. +#[repr(align(64))] +pub(crate) struct CachePaddedStripe { + /// Independent mutex guarding one HTTP/1.1 pool stripe. + pub(crate) lock: Mutex>, +} + /// Bitmask-indexed multi-stripe HTTP/1.1 connection pool minimizing cross-thread mutex contention. pub(crate) struct StripedH1Pool { - /// Independent per-stripe mutexes. - pub(crate) stripes: [Mutex>; H1_POOL_STRIPES], + /// Independent cache-line-isolated per-stripe mutexes. + pub(crate) stripes: [CachePaddedStripe; H1_POOL_STRIPES], /// Bit `i` is set while stripe `i` contains at least one idle connection. pub(crate) non_empty_mask: AtomicU64, } diff --git a/request/src/protocol/fn.rs b/request/src/protocol/fn.rs index c5a64b72..bfd5d56f 100644 --- a/request/src/protocol/fn.rs +++ b/request/src/protocol/fn.rs @@ -983,7 +983,7 @@ async fn run_h2_request_on_sender( } if body.is_empty() && recv_stream.is_end_stream() { let release_len: usize = chunk.len(); - body = chunk.to_vec(); + body = Vec::from(chunk); let _: Result<(), h2::Error> = recv_stream.flow_control().release_capacity(release_len); break; diff --git a/request/src/request/http_request/impl.rs b/request/src/request/http_request/impl.rs index 956c24ca..42222bae 100644 --- a/request/src/request/http_request/impl.rs +++ b/request/src/request/http_request/impl.rs @@ -1006,10 +1006,16 @@ impl HttpRequest { ) }; let write_res: Result<(), RequestError> = match stream.write_all(request_bytes).await { - Ok(()) => stream - .flush() - .await - .map_err(|e: io::Error| RequestError::Request(e.to_string())), + Ok(()) => { + if matches!(stream, AsyncClientTransport::Tcp(_)) { + Ok(()) + } else { + stream + .flush() + .await + .map_err(|e: io::Error| RequestError::Request(e.to_string())) + } + } Err(error) => Err(RequestError::Request(error.to_string())), }; if let Err(error) = write_res { @@ -1058,7 +1064,16 @@ impl HttpRequest { let clean_host: &str = Self::strip_ipv6_brackets(host); let connect_ms: u64 = self.effective_connect_timeout_ms(); let io_timeout_ms: u64 = self.get_config().get_timeout(); - let tcp: TcpStream = if connect_ms > 0 { + let tcp: TcpStream = if let Ok(ip) = clean_host.parse::() { + let addr: SocketAddr = SocketAddr::new(ip, port); + if connect_ms > 0 { + TcpStream::connect_timeout(&addr, Duration::from_millis(connect_ms)) + .map_err(|e: io::Error| RequestError::Request(e.to_string()))? + } else { + TcpStream::connect(addr) + .map_err(|e: io::Error| RequestError::Request(e.to_string()))? + } + } else if connect_ms > 0 { let connect_dur: Duration = Duration::from_millis(connect_ms); let addrs: Vec = (clean_host, port) .to_socket_addrs() @@ -1117,20 +1132,38 @@ impl HttpRequest { host: &str, port: u16, ) -> Result { - let clean_host: String = Self::strip_ipv6_brackets(host).to_owned(); + let clean_host: &str = Self::strip_ipv6_brackets(host); let connect_ms: u64 = self.effective_connect_timeout_ms(); - let tcp: tokio::net::TcpStream = if connect_ms > 0 { - tokio::time::timeout( - Duration::from_millis(connect_ms), - tokio::net::TcpStream::connect((clean_host, port)), - ) - .await - .map_err(|_| RequestError::ReadTimeout(HttpStatus::RequestTimeout))? - .map_err(|e: io::Error| RequestError::Request(e.to_string()))? + let tcp: tokio::net::TcpStream = if let Ok(ip) = clean_host.parse::() { + let addr: SocketAddr = SocketAddr::new(ip, port); + if connect_ms > 0 { + tokio::time::timeout( + Duration::from_millis(connect_ms), + tokio::net::TcpStream::connect(addr), + ) + .await + .map_err(|_| RequestError::ReadTimeout(HttpStatus::RequestTimeout))? + .map_err(|e: io::Error| RequestError::Request(e.to_string()))? + } else { + tokio::net::TcpStream::connect(addr) + .await + .map_err(|e: io::Error| RequestError::Request(e.to_string()))? + } } else { - tokio::net::TcpStream::connect((clean_host, port)) + let owned_host: String = clean_host.to_owned(); + if connect_ms > 0 { + tokio::time::timeout( + Duration::from_millis(connect_ms), + tokio::net::TcpStream::connect((owned_host, port)), + ) .await + .map_err(|_| RequestError::ReadTimeout(HttpStatus::RequestTimeout))? .map_err(|e: io::Error| RequestError::Request(e.to_string()))? + } else { + tokio::net::TcpStream::connect((owned_host, port)) + .await + .map_err(|e: io::Error| RequestError::Request(e.to_string()))? + } }; let _: Result<(), io::Error> = tcp.set_nodelay(true); Ok(tcp) @@ -1559,13 +1592,120 @@ impl HttpRequest { disable_keep_alive: bool, ) -> ReadOnceResult { let buffer_size: usize = self.effective_buffer_size(); - let mut response_bytes: Vec = take_client_buffer(buffer_size.max(8192)); + let fast_outcome: FastReadOutcome = poll_fn(|cx: &mut Context<'_>| { + let mut stack: [MaybeUninit; ASYNC_READ_STACK_CAP] = + [const { MaybeUninit::uninit() }; ASYNC_READ_STACK_CAP]; + let mut read_buf: ReadBuf<'_> = ReadBuf::uninit(&mut stack); + match Pin::new(&mut *stream).poll_read(cx, &mut read_buf) { + Poll::Pending => Poll::Pending, + Poll::Ready(Err(error)) => { + Poll::Ready(Err((None, Some(RequestError::Request(error.to_string()))))) + } + Poll::Ready(Ok(())) => { + let filled: &[u8] = read_buf.filled(); + let first_n: usize = filled.len(); + if first_n == 0 { + return Poll::Ready(Ok(None)); + } + if let Some(pos) = find_double_crlf(filled, 0) { + let head_end: usize = pos + HTTP_BR_BYTES.len() * 2; + if head_end <= MAX_RESPONSE_HEAD_BYTES + && let Ok(Some(parsed_head)) = + parse_final_response_head(&filled[..head_end], head_end, is_head) + && let ResponseFraming::Fixed(len) = parsed_head.framing + && first_n >= head_end + len + { + let body_slice: &[u8] = &filled[head_end..first_n]; + let has_trailing: bool = body_slice.len() != len; + let body: Vec = if len == 0 { + Vec::new() + } else { + body_slice[..len].to_vec() + }; + let reusable: bool = !disable_keep_alive + && !has_trailing + && parsed_head.allows_keep_alive; + let response: HttpResponse = HttpResponse { + version: parsed_head.version, + status_code: parsed_head.status_code, + reason_phrase: parsed_head.reason_phrase, + headers: parsed_head.headers, + body, + }; + return Poll::Ready(Ok(Some(( + response, + parsed_head.redirect_url, + reusable, + )))); + } + } + let mut spill: Vec = take_client_buffer(buffer_size.max(8192).max(first_n)); + spill.extend_from_slice(filled); + Poll::Ready(Err((Some(spill), None))) + } + } + }) + .await; + let mut response_bytes: Vec = match fast_outcome { + Ok(Some(done)) => return Ok(done), + Ok(None) => { + return Err(( + RequestError::HttpRequestPartsInsufficient(HttpStatus::BadRequest), + 0, + )); + } + Err((None, Some(err))) => return Err((err, 0)), + Err((Some(spill), _)) => spill, + Err((None, None)) => take_client_buffer(buffer_size.max(8192)), + }; let mut head: Option = None; let mut chunked: Option = None; let mut interim_count: usize = 0; - let mut total_read: usize = 0; + let mut total_read: usize = response_bytes.len(); let mut read_error: Option = None; - loop { + match find_parsed_final_head(&mut response_bytes, 0, is_head, &mut interim_count) { + Ok(found) => { + if let Some(ref parsed) = found + && parsed.framing == ResponseFraming::Chunked + { + chunked = Some(ChunkedDecoder::new()); + } + head = found; + } + Err(error) => read_error = Some(error), + } + let mut already_done: bool = false; + if read_error.is_none() + && let Some(ref parsed) = head + { + let body_slice: &[u8] = &response_bytes[parsed.head_end..]; + match parsed.framing { + ResponseFraming::Fixed(length) => { + if body_slice.len() > MAX_RESPONSE_BODY_BYTES { + read_error = + Some(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest)); + } else if body_slice.len() >= length { + already_done = true; + } + } + ResponseFraming::Chunked => { + if let Some(ref mut decoder) = chunked { + match decoder.advance(body_slice) { + Ok(true) => already_done = true, + Ok(false) => {} + Err(error) => read_error = Some(error), + } + } + } + ResponseFraming::Close => { + if body_slice.len() > MAX_RESPONSE_BODY_BYTES { + read_error = + Some(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest)); + } + } + } + } + while read_error.is_none() && !already_done { if response_bytes.capacity() - response_bytes.len() < buffer_size.min(4096) { let new_cap: usize = calculate_buffer_capacity( &response_bytes, diff --git a/request/src/request/http_request/type.rs b/request/src/request/http_request/type.rs index d2b21270..b83afee7 100644 --- a/request/src/request/http_request/type.rs +++ b/request/src/request/http_request/type.rs @@ -3,3 +3,12 @@ use super::*; /// Outcome of reading a single HTTP/1 response from a stream, tracking bytes read on error. pub(crate) type ReadOnceResult = Result<(HttpResponse, Option>, bool), (RequestError, usize)>; + +/// Parsed response payload returned by the stack-buffered single-read fast path. +pub(crate) type FastReadSuccess = (HttpResponse, Option>, bool); + +/// Partial read or transport failure returned by the stack-buffered fast path. +pub(crate) type FastReadFallback = (Option>, Option); + +/// Outcome of the stack-buffered single-read fast path. +pub(crate) type FastReadOutcome = Result, FastReadFallback>; diff --git a/request/src/request/parser/fn.rs b/request/src/request/parser/fn.rs index 2054ecec..0e2f0c8c 100644 --- a/request/src/request/parser/fn.rs +++ b/request/src/request/parser/fn.rs @@ -468,33 +468,7 @@ pub(crate) fn is_valid_header_name(name: &[u8]) -> bool { .all(|byte: &u8| HEADER_NAME_TOKEN_TABLE[usize::from(*byte)]) } -/// Validates an HTTP header name and reports whether all ASCII letters are already lowercase. -/// -/// # Arguments -/// -/// - `&[u8]` - Candidate header name bytes. -/// -/// # Returns -/// -/// - `Option` - `Some(true)` if valid and already lowercase, `Some(false)` if valid with uppercase, or `None` if invalid. -#[inline(always)] -pub(crate) fn validate_header_name_lower(name: &[u8]) -> Option { - if name.is_empty() { - return None; - } - let mut has_upper: bool = false; - for &byte in name { - if !HEADER_NAME_TOKEN_TABLE[usize::from(byte)] { - return None; - } - if byte.is_ascii_uppercase() { - has_upper = true; - } - } - Some(!has_upper) -} - -/// Check a field value for forbidden control bytes, permitting horizontal tabs. +/// Check a field value for forbidden control bytes and report whether it is pure ASCII. /// /// Uses an 8-byte SWAR fast path for printable ASCII slices (`0x20..=0x7E`) of length `>= 8`. /// @@ -504,11 +478,12 @@ pub(crate) fn validate_header_name_lower(name: &[u8]) -> Option { /// /// # Returns /// -/// - `bool` - Whether the value can be serialized as one header line. +/// - `Option` - `Some(true)` if valid pure ASCII, `Some(false)` if valid with non-ASCII bytes, or `None` if invalid. #[inline(always)] -pub(crate) fn is_valid_header_value(value: &[u8]) -> bool { +pub(crate) fn validate_header_value_ascii(value: &[u8]) -> Option { let len: usize = value.len(); let mut idx: usize = 0; + let mut high_or: u8 = 0; if len >= 8 { while idx + 8 <= len { let chunk: [u8; 8] = [ @@ -529,8 +504,9 @@ pub(crate) fn is_valid_header_value(value: &[u8]) -> bool { if non_printable != 0 { for &byte in &chunk { if byte.is_ascii_control() && byte != TAB_U8 { - return false; + return None; } + high_or |= byte; } } idx += 8; @@ -539,11 +515,28 @@ pub(crate) fn is_valid_header_value(value: &[u8]) -> bool { while idx < len { let byte: u8 = value[idx]; if byte.is_ascii_control() && byte != TAB_U8 { - return false; + return None; } + high_or |= byte; idx += 1; } - true + Some((high_or & 0x80) == 0) +} + +/// Check a field value for forbidden control bytes, permitting horizontal tabs. +/// +/// Uses an 8-byte SWAR fast path for printable ASCII slices (`0x20..=0x7E`) of length `>= 8`. +/// +/// # Arguments +/// +/// - `&[u8]` - The field value bytes. +/// +/// # Returns +/// +/// - `bool` - Whether the value can be serialized as one header line. +#[inline(always)] +pub(crate) fn is_valid_header_value(value: &[u8]) -> bool { + validate_header_value_ascii(value).is_some() } /// Validate every outgoing field before opening a stream or serializing headers. @@ -892,18 +885,28 @@ pub(crate) fn parse_final_response_head( if line.is_empty() { break; } - let separator: usize = line - .iter() - .position(|byte: &u8| *byte == COLON_U8) - .ok_or_else(|| RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned()))?; + let mut separator: usize = line.len(); + let mut has_upper: bool = false; + for (scan_idx, &byte) in line.iter().enumerate() { + if byte == COLON_U8 { + separator = scan_idx; + break; + } + if !HEADER_NAME_TOKEN_TABLE[usize::from(byte)] { + return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned())); + } + if byte.is_ascii_uppercase() { + has_upper = true; + } + } + if separator == 0 || separator == line.len() { + return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned())); + } let name: &[u8] = &line[..separator]; let raw_value: &[u8] = &line[separator + 1..]; - let Some(already_lower) = validate_header_name_lower(name) else { + let Some(is_ascii_val) = validate_header_value_ascii(raw_value) else { return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned())); }; - if !is_valid_header_value(raw_value) { - return Err(RequestError::Request(INVALID_RESPONSE_FRAMING.to_owned())); - } let trimmed_value: &[u8] = raw_value.trim_ascii(); match name.len() { 14 if !is_head && name.eq_ignore_ascii_case(cl_name) => { @@ -936,23 +939,29 @@ pub(crate) fn parse_final_response_head( } _ => {} } - if !is_interim - && separator > 0 - && separator + 1 < line.len() - && let (Ok(key_str), Ok(val_str)) = (from_utf8(name), from_utf8(trimmed_value)) - { - let key_owned: String = if already_lower { - key_str.to_owned() + if !is_interim && separator + 1 < line.len() { + let val_opt: Option<&str> = if is_ascii_val { + // SAFETY: `is_ascii_val` guarantees every byte in `trimmed_value` is `< 0x80`. + Some(unsafe { from_utf8_unchecked(trimmed_value) }) } else { - key_str.to_ascii_lowercase() + from_utf8(trimmed_value).ok() }; - if key_owned == SET_COOKIE - && let Some(existing) = headers.get_mut(SET_COOKIE) - { - existing.push(SET_COOKIE_DELIMITER); - existing.push_str(val_str); - } else { - headers.insert(key_owned, val_str.to_owned()); + if let Some(val_str) = val_opt { + // SAFETY: Every byte in `name` passed `HEADER_NAME_TOKEN_TABLE`, which only accepts ASCII. + let key_str: &str = unsafe { from_utf8_unchecked(name) }; + let key_owned: String = if !has_upper { + key_str.to_owned() + } else { + key_str.to_ascii_lowercase() + }; + if key_owned == SET_COOKIE + && let Some(existing) = headers.get_mut(SET_COOKIE) + { + existing.push(SET_COOKIE_DELIMITER); + existing.push_str(val_str); + } else { + headers.insert(key_owned, val_str.to_owned()); + } } } if end == headers_bytes.len() { diff --git a/type/src/cookie/impl.rs b/type/src/cookie/impl.rs index 1047efa9..eaba2114 100644 --- a/type/src/cookie/impl.rs +++ b/type/src/cookie/impl.rs @@ -79,12 +79,12 @@ impl CookieBuilder { C: AsRef, { let mut cookie_builder: Self = Self::default(); - let mut parts: Split<'_, &str> = cookie.as_ref().split(SEMICOLON); + let mut parts: Split<'_, char> = cookie.as_ref().split(SEMICOLON_U8 as char); let Some(first_part) = parts.next() else { return cookie_builder; }; let name_value_pair: &str = first_part.trim(); - if let Some((name, value)) = name_value_pair.split_once(EQUAL) { + if let Some((name, value)) = name_value_pair.split_once(EQUAL_U8 as char) { let name: &str = name.trim(); let value: &str = value.trim(); if is_cookie_name_valid(name) && !value.bytes().any(is_control_byte) { @@ -97,7 +97,7 @@ impl CookieBuilder { if part.is_empty() { continue; } - if let Some((key, value)) = part.split_once(EQUAL) { + if let Some((key, value)) = part.split_once(EQUAL_U8 as char) { let key: &str = key.trim(); let value: &str = value.trim(); if !is_cookie_attribute_valid(value) { @@ -424,12 +424,12 @@ impl Cookie { if target_name.is_empty() || !is_cookie_name_valid(target_name) { return None; } - for part in cookie.split(SEMICOLON) { + for part in cookie.split(SEMICOLON_U8 as char) { let trimmed: &str = part.trim(); if trimmed.is_empty() { continue; } - if let Some((name, value)) = trimmed.split_once(EQUAL) { + if let Some((name, value)) = trimmed.split_once(EQUAL_U8 as char) { let name: &str = name.trim(); if name == target_name { let value: &str = value.trim(); @@ -475,12 +475,12 @@ impl Cookie { + 1; let mut cookies: HashMapXxHash3_64 = HashMap::with_capacity_and_hasher(estimated, BuildHasherDefault::default()); - for part in cookie_ref.split(SEMICOLON) { + for part in cookie_ref.split(SEMICOLON_U8 as char) { let part: &str = part.trim(); if part.is_empty() { continue; } - if let Some((name, value)) = part.split_once(EQUAL) { + if let Some((name, value)) = part.split_once(EQUAL_U8 as char) { let name: &str = name.trim(); let value: &str = value.trim(); if is_cookie_name_valid(name) diff --git a/type/src/request/fn.rs b/type/src/request/fn.rs index cc42cc0a..ca51aba7 100644 --- a/type/src/request/fn.rs +++ b/type/src/request/fn.rs @@ -16,7 +16,7 @@ pub(super) fn parse_transfer_encoding( let mut chunked: bool = false; let mut unsupported: bool = false; for value in values { - for item in value.split(COMMA) { + for item in value.split(COMMA_U8 as char) { let coding: &str = item.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE); if coding.is_empty() { continue; @@ -66,7 +66,31 @@ where R: AsyncBufReadExt + Unpin, { out.clear(); - let mut raw: Vec = Vec::new(); + let available: &[u8] = reader.fill_buf().await?; + if available.is_empty() { + return Ok(0); + } + let scan_len: usize = available.len().min(max_len); + if let Some(newline) = find_byte_swar(&available[..scan_len], BR_U8) { + let consumed: usize = newline + 1; + let line_bytes: &[u8] = &available[..consumed]; + let text: &str = if line_bytes.is_ascii() { + // SAFETY: `is_ascii()` guarantees every byte is `< 0x80`, which is valid UTF-8. + unsafe { from_utf8_unchecked(line_bytes) } + } else { + from_utf8(line_bytes) + .map_err(|_| RequestError::ReadConnection(HttpStatus::BadRequest))? + }; + out.push_str(text); + reader.consume(consumed); + return Ok(consumed); + } + if scan_len >= max_len && max_len != usize::MAX { + return Err(overflow_error); + } + let mut raw: Vec = Vec::with_capacity(scan_len.saturating_add(64)); + raw.extend_from_slice(&available[..scan_len]); + reader.consume(scan_len); loop { let available: &[u8] = reader.fill_buf().await?; if available.is_empty() { @@ -77,9 +101,7 @@ where return Err(overflow_error); } let scan_len: usize = available.len().min(budget); - let newline: Option = available[..scan_len] - .iter() - .position(|byte: &u8| *byte == BR_U8); + let newline: Option = find_byte_swar(&available[..scan_len], BR_U8); let consumed: usize = newline.map_or(scan_len, |index: usize| index + 1); raw.extend_from_slice(&available[..consumed]); reader.consume(consumed); diff --git a/type/src/request/impl.rs b/type/src/request/impl.rs index c72bf333..a584ebc2 100644 --- a/type/src/request/impl.rs +++ b/type/src/request/impl.rs @@ -551,41 +551,42 @@ impl Request { } } - /// Parses a query string into key-value pairs in the given map with an upper entry bound. - /// - /// Expects format "key1=value1&key2=value2". Empty values are allowed, and a - /// key that repeats keeps every value instead of letting the last one win. - /// The target map is expected to be empty; entries are inserted without - /// reallocating the map when it already has sufficient capacity. + /// Parses query parameters into the destination map using an already-borrowed worker-local entry pool. /// /// # Arguments /// - /// - `&str` - The query string to parse. - /// - `&mut RequestQuerys` - The map to insert parsed parameters into. + /// - `&str` - The raw query string without a leading `?`. + /// - `&mut RequestQuerys` - Destination query parameter map. + /// - `&mut Vec<(String, VecDeque)>` - Borrowed worker-local entry pool. /// - `usize` - The maximum allowed number of query parameters (`usize::MAX` disables the cap). /// /// # Returns /// /// - `Result<(), RequestError>` - Ok on success, or `QueryTooLong` when the limit is exceeded. #[inline(always)] - pub(crate) fn fill_http_querys( + fn fill_http_querys_from_pool( query: &str, querys: &mut RequestQuerys, + pool: &mut Vec<(String, VecDeque)>, max_count: usize, ) -> Result<(), RequestError> { if query.is_empty() { return Ok(()); } + if querys.capacity() == 0 { + querys.reserve(4); + } let mut count: usize = 0; - for pair in query.split(AND) { - if let Some((key, value)) = pair.split_once(EQUAL) { + for pair in query.split(AND_U8 as char) { + if let Some((key, value)) = pair.split_once(EQUAL_U8 as char) { if !key.is_empty() { count += 1; if count > max_count { return Err(RequestError::QueryTooLong(HttpStatus::URITooLong)); } - let (mut pooled_key, mut pooled_values): (String, VecDeque) = - take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new())); + let (mut pooled_key, mut pooled_values): (String, VecDeque) = pool + .pop() + .unwrap_or_else(|| (String::new(), VecDeque::new())); pooled_key.clear(); pooled_key.push_str(key); match querys.entry(pooled_key) { @@ -595,6 +596,11 @@ impl Request { val_slot.clear(); val_slot.push_str(value); occupied.get_mut().push_back(val_slot); + if pooled_values.capacity() <= MAX_POOLED_HEADER_VALUE_CAPACITY + && pool.len() < MAX_POOLED_HEADER_ENTRIES + { + pool.push((String::new(), pooled_values)); + } } Entry::Vacant(vacant) => { if pooled_values.len() == 1 { @@ -624,8 +630,9 @@ impl Request { if count > max_count { return Err(RequestError::QueryTooLong(HttpStatus::URITooLong)); } - let (mut pooled_key, mut pooled_values): (String, VecDeque) = - take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new())); + let (mut pooled_key, mut pooled_values): (String, VecDeque) = pool + .pop() + .unwrap_or_else(|| (String::new(), VecDeque::new())); pooled_key.clear(); pooled_key.push_str(pair); pooled_values.clear(); @@ -635,6 +642,34 @@ impl Request { Ok(()) } + /// Parses an HTTP query string into `querys` using the thread-local entry pool. + /// + /// # Arguments + /// + /// - `&str` - Raw query string without the leading `?`. + /// - `&mut RequestQuerys` - Destination query parameter map. + /// - `usize` - Maximum number of query entries allowed. + /// + /// # Returns + /// + /// - `Result<(), RequestError>` - `Ok(())` when parsed within bounds, or a [`RequestError`]. + #[inline(always)] + pub(crate) fn fill_http_querys( + query: &str, + querys: &mut RequestQuerys, + max_count: usize, + ) -> Result<(), RequestError> { + if query.is_empty() { + return Ok(()); + } + HEADER_ENTRY_POOL.with( + |pool: &RefCell)>>| -> Result<(), RequestError> { + let mut pool: RefMut<'_, Vec<(String, VecDeque)>> = pool.borrow_mut(); + Self::fill_http_querys_from_pool(query, querys, &mut pool, max_count) + }, + ) + } + /// Checks if the header count exceeds the maximum allowed. /// /// # Arguments @@ -788,12 +823,12 @@ impl Request { } else { HTTP_MAX_QUERY_PARAM_COUNT }; - Self::fill_http_querys(query, self.get_mut_querys(), max_query_count)?; let path_slice: &str = Self::get_http_path(full_path, query_index, hash_index); self.get_mut_path().push_str(path_slice); self.set_version(version); self.set_method(method); let Request { + querys, headers, host, version, @@ -810,9 +845,15 @@ impl Request { let mut host_seen: bool = false; let mut pos: usize = first_line_end; let mut incomplete_head: bool = false; + if headers.capacity() == 0 { + headers.reserve(8); + } let header_result: Result<(), RequestError> = HEADER_ENTRY_POOL.with( |pool: &RefCell)>>| -> Result<(), RequestError> { let mut pool: RefMut<'_, Vec<(String, VecDeque)>> = pool.borrow_mut(); + if !query.is_empty() { + Self::fill_http_querys_from_pool(query, querys, &mut pool, max_query_count)?; + } loop { let rest: &[u8] = &buffer[pos..]; let Some(rel_lf) = r#fn::find_byte_swar(rest, BR_U8) else { @@ -1117,9 +1158,22 @@ impl Request { .pop() .unwrap_or_else(|| (String::new(), VecDeque::new())); name.clear(); - name.push_str(key); if has_upper { - name.make_ascii_lowercase(); + let bytes: &[u8] = key.as_bytes(); + let len: usize = bytes.len(); + // SAFETY: `bytes` is valid ASCII; lowercasing ASCII uppercase bytes preserves UTF-8. + let name_vec: &mut Vec = unsafe { name.as_mut_vec() }; + name_vec.reserve(len); + let dst: *mut u8 = name_vec.as_mut_ptr(); + // SAFETY: `name_vec` is empty with capacity `>= len`, so `0..len` writes are valid and fully initialized before `set_len`. + unsafe { + for (idx, &byte) in bytes.iter().enumerate() { + dst.add(idx).write(byte.to_ascii_lowercase()); + } + name_vec.set_len(len); + } + } else { + name.push_str(key); } match headers.entry(name) { Entry::Occupied(mut occupied) => { @@ -1915,7 +1969,10 @@ impl Request { /// - `bool` - Whether WebSocket upgrade is enabled. #[inline(always)] pub fn is_ws_upgrade_type(&self) -> bool { - self.get_upgrade_type().is_ws() + self.get_headers() + .get(UPGRADE) + .and_then(|values: &VecDeque| values.back()) + .is_some_and(|value: &String| value.eq_ignore_ascii_case(WEBSOCKET)) } /// Checks whether the request declares a `multipart/form-data` body. @@ -2053,7 +2110,10 @@ impl Request { /// - `bool` - Whether the upgrade type is h2c. #[inline(always)] pub fn is_h2c_upgrade_type(&self) -> bool { - self.get_upgrade_type().is_h2c() + self.get_headers() + .get(UPGRADE) + .and_then(|values: &VecDeque| values.back()) + .is_some_and(|value: &String| value.eq_ignore_ascii_case(H2C_LOWERCASE)) } /// Checks if the current upgrade type is TLS (any version). @@ -2063,7 +2123,14 @@ impl Request { /// - `bool` - Whether the upgrade type is TLS. #[inline(always)] pub fn is_tls_upgrade_type(&self) -> bool { - self.get_upgrade_type().is_tls() + self.get_headers() + .get(UPGRADE) + .and_then(|values: &VecDeque| values.back()) + .is_some_and(|value: &String| { + value.len() >= TLS_LOWERCASE.len() + && value.as_bytes()[..TLS_LOWERCASE.len()] + .eq_ignore_ascii_case(TLS_LOWERCASE.as_bytes()) + }) } /// Checks whether the upgrade type is unknown. @@ -2073,7 +2140,19 @@ impl Request { /// - `bool` - Whether the upgrade type is unknown. #[inline(always)] pub fn is_unknown_upgrade_type(&self) -> bool { - self.get_upgrade_type().is_unknown() + let Some(value) = self + .get_headers() + .get(UPGRADE) + .and_then(|values: &VecDeque| values.back()) + else { + return true; + }; + if value.eq_ignore_ascii_case(WEBSOCKET) || value.eq_ignore_ascii_case(H2C_LOWERCASE) { + return false; + } + !(value.len() >= TLS_LOWERCASE.len() + && value.as_bytes()[..TLS_LOWERCASE.len()] + .eq_ignore_ascii_case(TLS_LOWERCASE.as_bytes())) } /// Determines if a keep-alive connection should be enabled for this request. @@ -2093,14 +2172,17 @@ impl Request { /// - `bool` - Whether keep-alive should be enabled. #[inline(always)] pub fn is_enable_keep_alive(&self) -> bool { - if let Some(values) = self.get_headers().get(CONNECTION) { + let headers: &RequestHeaders = self.get_headers(); + if !headers.is_empty() + && let Some(values) = headers.get(CONNECTION) + { let mut has_keep_alive: bool = false; for header_value in values { if header_value == KEEP_ALIVE { has_keep_alive = true; continue; } - for token in header_value.split(COMMA) { + for token in header_value.split(COMMA_U8 as char) { let token: &str = token.trim_matches(HTTP_HEADER_OPTIONAL_WHITESPACE); if token.eq_ignore_ascii_case(CLOSE) { return self.is_ws_upgrade_type(); diff --git a/type/src/response/const.rs b/type/src/response/const.rs index 2f900733..e306bd61 100644 --- a/type/src/response/const.rs +++ b/type/src/response/const.rs @@ -1,5 +1,18 @@ -/// Pre-encoded HTTP/1.1 200 OK status line. -pub(crate) const FAST_HTTP11_200_LINE: &[u8] = b"HTTP/1.1 200 OK\r\n"; +/// Two-digit ASCII decimal lookup table for fast integer formatting. +pub(crate) const DIGITS_200: &[u8; 200] = b"\ +00010203040506070809\ +10111213141516171819\ +20212223242526272829\ +30313233343536373839\ +40414243444546474849\ +50515253545556575859\ +60616263646566676869\ +70717273747576777879\ +80818283848586878889\ +90919293949596979899"; + +/// Pre-encoded content-length field prefix after a custom status line. +pub(crate) const FAST_CL_PREFIX: &[u8] = b"\r\ncontent-length:"; /// Pre-encoded HTTP/2 200 OK status line. pub(crate) const FAST_HTTP2_200_LINE: &[u8] = b"HTTP/2 200 OK\r\n"; @@ -7,8 +20,8 @@ pub(crate) const FAST_HTTP2_200_LINE: &[u8] = b"HTTP/2 200 OK\r\n"; /// Pre-encoded HTTP/3 200 OK status line. pub(crate) const FAST_HTTP3_200_LINE: &[u8] = b"HTTP/3 200 OK\r\n"; -/// Pre-encoded HTTP/1.1 200 OK status line and content-length field prefix. -pub(crate) const FAST_HTTP11_200_CL_PREFIX: &[u8] = b"HTTP/1.1 200 OK\r\ncontent-length:"; +/// Pre-encoded HTTP/1.1 200 OK status line. +pub(crate) const FAST_HTTP11_200_LINE: &[u8] = b"HTTP/1.1 200 OK\r\n"; /// Pre-encoded HTTP/2 200 OK status line and content-length field prefix. pub(crate) const FAST_HTTP2_200_CL_PREFIX: &[u8] = b"HTTP/2 200 OK\r\ncontent-length:"; @@ -16,25 +29,25 @@ pub(crate) const FAST_HTTP2_200_CL_PREFIX: &[u8] = b"HTTP/2 200 OK\r\ncontent-le /// Pre-encoded HTTP/3 200 OK status line and content-length field prefix. pub(crate) const FAST_HTTP3_200_CL_PREFIX: &[u8] = b"HTTP/3 200 OK\r\ncontent-length:"; -/// Pre-encoded default keep-alive header line. -pub(crate) const FAST_CONNECTION_KEEP_ALIVE_LINE: &[u8] = b"connection:keep-alive\r\n"; +/// Pre-encoded HTTP/1.1 200 OK status line and content-length field prefix. +pub(crate) const FAST_HTTP11_200_CL_PREFIX: &[u8] = b"HTTP/1.1 200 OK\r\ncontent-length:"; -/// Pre-encoded default `Content-Type` header line. -pub(crate) const FAST_DEFAULT_CONTENT_TYPE_LINE: &[u8] = - b"content-type:text/html; charset=utf-8\r\n"; +/// Static default `Content-Type` header value avoiding runtime `OnceLock` overhead. +pub(crate) const DEFAULT_CONTENT_TYPE_VALUE: &str = "text/html; charset=utf-8"; /// Pre-encoded `content-length:` header prefix. pub(crate) const FAST_CONTENT_LENGTH_PREFIX: &[u8] = b"content-length:"; -/// Pre-encoded zero-length `content-length:0\r\n` header line. -pub(crate) const FAST_CONTENT_LENGTH_ZERO_LINE: &[u8] = b"content-length:0\r\n"; - /// Pre-encoded default keep-alive and text/html headers terminating the fast-path head. pub(crate) const FAST_DEFAULT_HEADERS_SUFFIX: &[u8] = b"\r\nconnection:keep-alive\r\ncontent-type:text/html; charset=utf-8\r\n\r\n"; -/// Pre-encoded content-length field prefix after a custom status line. -pub(crate) const FAST_CL_PREFIX: &[u8] = b"\r\ncontent-length:"; +/// Pre-encoded zero-length `content-length:0\r\n` header line. +pub(crate) const FAST_CONTENT_LENGTH_ZERO_LINE: &[u8] = b"content-length:0\r\n"; -/// Static default `Content-Type` header value avoiding runtime `OnceLock` overhead. -pub(crate) const DEFAULT_CONTENT_TYPE_VALUE: &str = "text/html; charset=utf-8"; +/// Pre-encoded default `Content-Type` header line. +pub(crate) const FAST_DEFAULT_CONTENT_TYPE_LINE: &[u8] = + b"content-type:text/html; charset=utf-8\r\n"; + +/// Pre-encoded default keep-alive header line. +pub(crate) const FAST_CONNECTION_KEEP_ALIVE_LINE: &[u8] = b"connection:keep-alive\r\n"; diff --git a/type/src/response/fn.rs b/type/src/response/fn.rs index 545f0d90..f33116fb 100644 --- a/type/src/response/fn.rs +++ b/type/src/response/fn.rs @@ -28,13 +28,35 @@ pub(crate) fn default_content_type() -> &'static str { pub(crate) fn render_length(length: usize, buffer: &mut [u8]) -> &str { let mut cursor: usize = buffer.len(); let mut remaining: usize = length; - loop { + if remaining < 10 { cursor -= 1; - buffer[cursor] = (B_48 + remaining % B_10) as u8; - remaining /= B_10; - if remaining == 0 { - break; - } + buffer[cursor] = (B_48 + remaining) as u8; + // SAFETY: `buffer[cursor]` is an ASCII digit (`b'0'..=b'9'`). + return unsafe { from_utf8_unchecked(&buffer[cursor..]) }; + } + if remaining < 100 { + let pair: usize = remaining * 2; + cursor -= 2; + buffer[cursor] = DIGITS_200[pair]; + buffer[cursor + 1] = DIGITS_200[pair + 1]; + // SAFETY: Both bytes from `DIGITS_200` are ASCII digits (`b'0'..=b'9'`). + return unsafe { from_utf8_unchecked(&buffer[cursor..]) }; + } + while remaining >= 100 { + let pair: usize = (remaining % 100) * 2; + remaining /= 100; + cursor -= 2; + buffer[cursor] = DIGITS_200[pair]; + buffer[cursor + 1] = DIGITS_200[pair + 1]; + } + if remaining < 10 { + cursor -= 1; + buffer[cursor] = (B_48 + remaining) as u8; + } else { + let pair: usize = remaining * 2; + cursor -= 2; + buffer[cursor] = DIGITS_200[pair]; + buffer[cursor + 1] = DIGITS_200[pair + 1]; } // SAFETY: Every byte written into `buffer[cursor..]` is an ASCII digit (`b'0'..=b'9'`). unsafe { from_utf8_unchecked(&buffer[cursor..]) } diff --git a/type/src/response/impl.rs b/type/src/response/impl.rs index c9c9306b..070b04f1 100644 --- a/type/src/response/impl.rs +++ b/type/src/response/impl.rs @@ -119,10 +119,27 @@ impl Response { /// - `&str` - The header value as a string slice (`&str`). #[inline(always)] fn push_header(response_bytes: &mut Vec, key: &str, value: &str) { - response_bytes.extend_from_slice(key.as_bytes()); - response_bytes.extend_from_slice(COLON.as_bytes()); - response_bytes.extend_from_slice(value.as_bytes()); - response_bytes.extend_from_slice(HTTP_BR.as_bytes()); + let key_bytes: &[u8] = key.as_bytes(); + let val_bytes: &[u8] = value.as_bytes(); + let key_len: usize = key_bytes.len(); + let val_len: usize = val_bytes.len(); + let total: usize = key_len + 1 + val_len + 2; + let base: usize = response_bytes.len(); + response_bytes.reserve(total); + // SAFETY: `response_bytes` has at least `total` spare bytes after `base`; + // all four segments are contiguous and non-overlapping. + unsafe { + let mut dst: *mut u8 = response_bytes.as_mut_ptr().add(base); + ptr::copy_nonoverlapping(key_bytes.as_ptr(), dst, key_len); + dst = dst.add(key_len); + dst.write(COLON_U8); + dst = dst.add(1); + ptr::copy_nonoverlapping(val_bytes.as_ptr(), dst, val_len); + dst = dst.add(val_len); + dst.write(b'\r'); + dst.add(1).write(b'\n'); + response_bytes.set_len(base + total); + } } /// Tries to retrieve the value of a response header by its key. @@ -1334,6 +1351,9 @@ impl Response { #[inline(always)] fn populate_default_headers_batch(&mut self, content_type: &str, rendered_len: &str) { let headers: &mut ResponseHeaders = self.get_mut_headers(); + if headers.capacity() < 3 { + headers.reserve(3); + } let pairs: [(&str, &str); 3] = [ (CONNECTION, KEEP_ALIVE), (CONTENT_TYPE, content_type), diff --git a/type/src/stream/const.rs b/type/src/stream/const.rs index 7c57ac20..1fc8fea0 100644 --- a/type/src/stream/const.rs +++ b/type/src/stream/const.rs @@ -25,7 +25,7 @@ pub(crate) const MAX_POOLED_HEADER_STRING_CAPACITY: usize = 4 * 1024; pub(crate) const MAX_POOLED_HEADER_VALUE_CAPACITY: usize = B_4; /// Size of the stack-allocated read buffer used by the zero-pool HTTP/1.1 fast path. -pub(crate) const STACK_READ_BUF_SIZE: usize = DEFAULT_BUFFER_SIZE; +pub(crate) const STACK_READ_BUF_SIZE: usize = DEFAULT_BUFFER_SIZE * 2; /// Maximum coalesced outbound response bytes buffered while pipelined input remains queued. pub(crate) const PIPELINED_WRITE_FLUSH_THRESHOLD: usize = 16 * 1024; diff --git a/type/src/stream/fn.rs b/type/src/stream/fn.rs index 3543fbef..6c9a0597 100644 --- a/type/src/stream/fn.rs +++ b/type/src/stream/fn.rs @@ -164,10 +164,11 @@ where { HEADER_ENTRY_POOL.with(|pool: &RefCell)>>| { let mut pool: RefMut<'_, Vec<(String, VecDeque)>> = pool.borrow_mut(); + let mut remaining: usize = MAX_POOLED_HEADER_ENTRIES.saturating_sub(pool.len()); + if remaining == 0 { + return; + } for entry in entries { - if pool.len() >= MAX_POOLED_HEADER_ENTRIES { - break; - } if entry.0.capacity() > MAX_POOLED_HEADER_STRING_CAPACITY || entry.1.capacity() > MAX_POOLED_HEADER_VALUE_CAPACITY { @@ -185,6 +186,10 @@ where continue; } pool.push(entry); + remaining -= 1; + if remaining == 0 { + break; + } } }); } diff --git a/type/src/stream/impl.rs b/type/src/stream/impl.rs index 5cc90870..cd2974d0 100644 --- a/type/src/stream/impl.rs +++ b/type/src/stream/impl.rs @@ -561,7 +561,11 @@ impl Stream { return_read_buffer(buffer); } self.flush_write_buffer_io().await?; - let read_cap: usize = buffer_size.clamp(1, STACK_READ_BUF_SIZE); + let read_cap: usize = if buffer_size >= DEFAULT_BUFFER_SIZE { + STACK_READ_BUF_SIZE + } else { + buffer_size.clamp(1, STACK_READ_BUF_SIZE) + }; let fast_outcome: FastHttpRead = { let Stream { stream, @@ -733,7 +737,91 @@ impl Stream { start += consumed; pre_parsed_framing = Some(RequestFraming::Chunked); } - None => {} + None => { + self.flush_write_buffer_io().await?; + if start > 0 { + buffer.copy_within(start..end, 0); + end -= start; + start = 0; + } + let target_len: usize = if buffer_size >= DEFAULT_BUFFER_SIZE { + STACK_READ_BUF_SIZE + } else { + buffer_size.max(1) + }; + if buffer.len() < target_len { + buffer.resize(target_len, 0); + } + if end < buffer.len() { + let stream_ref: &mut Box = self.get_mut_stream(); + let filled_delta: usize = future::poll_fn(|cx: &mut Context<'_>| { + let mut read_buf: ReadBuf<'_> = ReadBuf::new(&mut buffer[end..]); + match Pin::new(&mut **stream_ref).poll_read(cx, &mut read_buf) { + Poll::Pending => Poll::Pending, + Poll::Ready(Err(error)) => { + Poll::Ready(Err(RequestError::from(error))) + } + Poll::Ready(Ok(())) => Poll::Ready(Ok(read_buf.filled().len())), + } + }) + .await?; + if filled_delta > 0 { + end += filled_delta; + let Stream { + line_buffer, + line_target_start, + line_target_end, + .. + } = self; + line_buffer.clear(); + *line_target_start = 0; + *line_target_end = 0; + match request.parse_http_head_from_slice( + &buffer[..end], + &config, + line_buffer, + )? { + Some(( + RequestFraming::Fixed(content_size), + consumed, + t_start, + t_end, + )) => { + *line_target_start = t_start; + *line_target_end = t_end; + let avail: usize = end - consumed; + if content_size <= avail { + if content_size > 0 { + let body: &mut Vec = request.get_mut_body(); + body.clear(); + body.extend_from_slice( + &buffer[consumed..consumed + content_size], + ); + } + let next_start: usize = consumed + content_size; + if next_start < end { + self.set_leftover(buffer); + self.set_leftover_start(next_start); + self.set_leftover_end(end); + } else { + return_read_buffer(buffer); + } + return Ok(()); + } + start = consumed; + pre_parsed_framing = Some(RequestFraming::Fixed(content_size)); + } + Some((RequestFraming::Chunked, consumed, t_start, t_end)) => { + *line_target_start = t_start; + *line_target_end = t_end; + start = consumed; + pre_parsed_framing = Some(RequestFraming::Chunked); + } + None => {} + } + } + } + } } } // Any fallback past this point may await socket reads; flush buffered responses first. @@ -871,6 +959,71 @@ impl Stream { Ok(()) } + /// Attempts to parse one complete fixed-length HTTP/1.1 request synchronously from `leftover`. + /// + /// Avoids timer swapping and async state transitions on pipelined requests already in memory. + /// + /// # Arguments + /// + /// - `&mut Request` - The request object to reset and fill. + /// + /// # Returns + /// + /// - `Option>` - Completed result when satisfied synchronously, or `None` to fall back. + #[inline(always)] + fn try_fill_http_from_leftover( + &mut self, + request: &mut Request, + ) -> Option> { + let start: usize = self.get_leftover_start(); + let end: usize = self.get_leftover_end(); + if start >= end { + return None; + } + request.reset(); + let config: RequestConfig = *self.get_request_config(); + let Stream { + leftover, + leftover_start, + leftover_end, + line_buffer, + line_target_start, + line_target_end, + .. + } = self; + line_buffer.clear(); + *line_target_start = 0; + *line_target_end = 0; + let slice: &[u8] = &leftover[start..end]; + match request.parse_http_head_from_slice(slice, &config, line_buffer) { + Err(error) => Some(Err(error)), + Ok(Some((RequestFraming::Fixed(content_size), consumed, t_start, t_end))) => { + let body_start: usize = start + consumed; + let avail: usize = end - body_start; + if content_size > avail { + return None; + } + *line_target_start = t_start; + *line_target_end = t_end; + if content_size > 0 { + let body: &mut Vec = request.get_mut_body(); + body.clear(); + body.extend_from_slice(&leftover[body_start..body_start + content_size]); + } + let next_start: usize = body_start + content_size; + if next_start < end { + *leftover_start = next_start; + } else { + *leftover_start = 0; + *leftover_end = 0; + return_read_buffer(mem::take(leftover)); + } + Some(Ok(())) + } + Ok(Some((RequestFraming::Chunked, _, _, _))) | Ok(None) => None, + } + } + /// Parses an HTTP request from a TCP stream into the given request. /// /// The request is reset and filled in place, reusing its allocations. @@ -893,6 +1046,9 @@ impl Stream { if self.get_closed() { return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest)); } + if let Some(result) = self.try_fill_http_from_leftover(request) { + return result; + } let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms(); if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS { return self.fill_http_from_stream(request).await; @@ -1339,6 +1495,21 @@ impl Stream { if self.get_closed() { return Err(ResponseError::ConnectionClosed); } + if self.get_write_buffer().is_empty() && self.get_stream().supports_direct_response() { + let direct: Option> = future::poll_fn(|cx: &mut Context<'_>| { + match Pin::new(&mut **self.get_mut_stream()) + .poll_write_response(cx, response, false) + { + Some(Poll::Ready(res)) => Poll::Ready(Some(res)), + Some(Poll::Pending) => Poll::Pending, + None => Poll::Ready(None), + } + }) + .await; + if let Some(res) = direct { + return Ok(res?); + } + } response.build_into(self.get_mut_write_buffer()); let has_pipelined: bool = self.get_leftover_start() < self.get_leftover_end(); if has_pipelined && self.get_write_buffer().len() < PIPELINED_WRITE_FLUSH_THRESHOLD { @@ -1364,6 +1535,20 @@ impl Stream { if self.get_closed() { return Err(ResponseError::ConnectionClosed); } + if self.get_write_buffer().is_empty() && self.get_stream().supports_direct_response() { + let direct: Option> = future::poll_fn(|cx: &mut Context<'_>| { + match Pin::new(&mut **self.get_mut_stream()).poll_write_response(cx, response, true) + { + Some(Poll::Ready(res)) => Poll::Ready(Some(res)), + Some(Poll::Pending) => Poll::Pending, + None => Poll::Ready(None), + } + }) + .await; + if let Some(res) = direct { + return Ok(res?); + } + } response.build_head_into(self.get_mut_write_buffer()); let has_pipelined: bool = self.get_leftover_start() < self.get_leftover_end(); if has_pipelined && self.get_write_buffer().len() < PIPELINED_WRITE_FLUSH_THRESHOLD { diff --git a/type/src/stream/trait.rs b/type/src/stream/trait.rs index 5459e8b3..b1b7aaa2 100644 --- a/type/src/stream/trait.rs +++ b/type/src/stream/trait.rs @@ -26,4 +26,51 @@ pub trait Transport: AsyncRead + AsyncWrite + Debug + Unpin + Send + Sync { /// - `Result` - The local address, or an error when the /// transport has no socket identity. fn local_addr(&self) -> Result; + + /// Exposes a mutable dynamic reference for internal protocol transport downcasting. + /// + /// # Returns + /// + /// - `Option<&mut dyn Any>` - Concrete transport handle when supported. + #[doc(hidden)] + #[inline(always)] + fn as_any_mut(&mut self) -> Option<&mut dyn Any> { + None + } + + /// Reports whether this transport can frame a [`Response`] directly without HTTP/1.1 serialization. + /// + /// # Returns + /// + /// - `bool` - `true` when [`Transport::poll_write_response`] is implemented. + #[doc(hidden)] + #[inline(always)] + fn supports_direct_response(&self) -> bool { + false + } + + /// Directly frames and writes an HTTP [`Response`] onto a structured transport (HTTP/2 or HTTP/3). + /// + /// Returns `None` when the transport prefers falling back to standard wire serialization. + /// + /// # Arguments + /// + /// - `Pin<&mut Self>` - The pinned transport. + /// - `&mut Context<'_>` - The async task waker context. + /// - `&mut Response` - The response to emit directly. + /// - `bool` - Whether only the response head (`HEAD` request) must be transmitted. + /// + /// # Returns + /// + /// - `Option>>` - Direct framing poll result, or `None` to fall back. + #[doc(hidden)] + #[inline(always)] + fn poll_write_response( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + _response: &mut Response, + _is_head: bool, + ) -> Option>> { + None + } }