use super::*;
#[inline]
pub(crate) fn idempotency_now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|dur: Duration| dur.as_millis() as u64)
.unwrap_or(0)
}
#[inline(always)]
pub(crate) fn idempotency_shard_index(key: &str) -> usize {
let bytes: &[u8] = key.as_bytes();
let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
let mut hash: u64 = FP_SECRET0 ^ (bytes.len() as u64);
for chunk in chunks {
hash = (hash ^ u64::from_ne_bytes(*chunk)).wrapping_mul(IDEMP_SHARD_MUL1);
}
if !rem.is_empty() {
let mut tail: u64 = 0;
for &b in rem {
tail = (tail << 8) | u64::from(b);
}
hash = (hash ^ tail).wrapping_mul(IDEMP_SHARD_MUL2);
}
((hash ^ (hash >> 32)) as usize) & (IDEMPOTENCY_SHARD_COUNT - 1)
}
#[inline(always)]
pub(crate) fn fp_mix(a: u64, b: u64) -> u64 {
let prod: u128 = u128::from(a).wrapping_mul(u128::from(b));
(prod as u64) ^ ((prod >> 64) as u64)
}
#[inline]
pub(crate) fn fp_hash_bytes(mut seed: u64, data: &[u8]) -> u64 {
let len: usize = data.len();
seed = fp_mix(seed ^ FP_SECRET0, (len as u64) ^ FP_SECRET1);
let (blocks, rem): (&[[u8; 16]], &[u8]) = data.as_chunks::<16>();
for chunk in blocks {
let lo: u64 = u64::from_le_bytes([
chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
]);
let hi: u64 = u64::from_le_bytes([
chunk[8], chunk[9], chunk[10], chunk[11], chunk[12], chunk[13], chunk[14], chunk[15],
]);
seed = fp_mix(lo ^ FP_SECRET1, hi ^ seed);
}
let rem_len: usize = rem.len();
if rem_len >= 8 {
let lo: u64 = u64::from_le_bytes([
rem[0], rem[1], rem[2], rem[3], rem[4], rem[5], rem[6], rem[7],
]);
let tail: &[u8] = &rem[rem_len - 8..];
let hi: u64 = u64::from_le_bytes([
tail[0], tail[1], tail[2], tail[3], tail[4], tail[5], tail[6], tail[7],
]);
seed = fp_mix(lo ^ FP_SECRET2, hi ^ seed);
} else if rem_len >= 4 {
let lo: u64 = u64::from(u32::from_le_bytes([rem[0], rem[1], rem[2], rem[3]]));
let tail: &[u8] = &rem[rem_len - 4..];
let hi: u64 = u64::from(u32::from_le_bytes([tail[0], tail[1], tail[2], tail[3]]));
seed = fp_mix(lo ^ FP_SECRET2, hi ^ seed);
} else if rem_len > 0 {
let packed: u64 = (u64::from(rem[0]) << 16)
| (u64::from(rem[rem_len >> 1]) << 8)
| u64::from(rem[rem_len - 1]);
seed = fp_mix(packed ^ FP_SECRET2, seed ^ FP_SECRET3);
}
fp_mix(seed ^ FP_SECRET3, (len as u64) ^ FP_SECRET0)
}
#[inline]
pub fn compute_request_fingerprint(method: &Method, path: &str, body: &[u8]) -> u64 {
let seed: u64 = match method {
Method::Get => 1 ^ FP_SECRET0,
Method::Post => 2 ^ FP_SECRET0,
Method::Put => 3 ^ FP_SECRET0,
Method::Delete => 4 ^ FP_SECRET0,
Method::Patch => 5 ^ FP_SECRET0,
Method::Head => 6 ^ FP_SECRET0,
Method::Options => 7 ^ FP_SECRET0,
Method::Connect => 8 ^ FP_SECRET0,
Method::Trace => 9 ^ FP_SECRET0,
Method::Unknown(raw) => fp_hash_bytes(10 ^ FP_SECRET0, raw.as_bytes()),
};
let after_path: u64 = fp_hash_bytes(seed, path.as_bytes());
fp_hash_bytes(after_path ^ FP_SECRET1, body)
}
#[inline(always)]
pub(crate) fn method_as_str(method: &Method) -> &str {
match method {
Method::Get => GET,
Method::Post => POST,
Method::Put => PUT,
Method::Delete => DELETE,
Method::Patch => PATCH,
Method::Head => HEAD,
Method::Options => OPTIONS,
Method::Connect => CONNECT,
Method::Trace => TRACE,
Method::Unknown(raw) => raw.as_str(),
}
}
#[inline(always)]
pub(crate) fn method_bit(method: &Method) -> u16 {
match method {
Method::Get => 1 << 0,
Method::Post => 1 << 1,
Method::Put => 1 << 2,
Method::Delete => 1 << 3,
Method::Patch => 1 << 4,
Method::Head => 1 << 5,
Method::Options => 1 << 6,
Method::Connect => 1 << 7,
Method::Trace => 1 << 8,
Method::Unknown(_) => 0,
}
}
#[inline]
pub(crate) fn build_storage_key(method: &Method, path: &str, client_key: &str) -> String {
let method_str: &str = method_as_str(method);
let mut out: String =
String::with_capacity(method_str.len() + path.len() + client_key.len() + 2);
out.push_str(method_str);
out.push('|');
out.push_str(path);
out.push('|');
out.push_str(client_key);
out
}
#[inline]
pub(crate) fn build_storage_key_stack<'a>(
method: &Method,
path: &str,
client_key: &str,
buf: &'a mut [u8; STACK_STORAGE_KEY_CAP],
) -> Option<&'a str> {
let m: &[u8] = method_as_str(method).as_bytes();
let p: &[u8] = path.as_bytes();
let k: &[u8] = client_key.as_bytes();
let total: usize = m.len() + 1 + p.len() + 1 + k.len();
if total > STACK_STORAGE_KEY_CAP {
return None;
}
let mut off: usize = 0;
buf[off..off + m.len()].copy_from_slice(m);
off += m.len();
buf[off] = ASCII_PIPE;
off += 1;
buf[off..off + p.len()].copy_from_slice(p);
off += p.len();
buf[off] = ASCII_PIPE;
off += 1;
buf[off..off + k.len()].copy_from_slice(k);
from_utf8(&buf[..total]).ok()
}
#[inline(always)]
pub(crate) fn format_usize_stack(mut value: usize, buf: &mut [u8; DEC_STACK_BUF_LEN]) -> &[u8] {
let mut pos: usize = DEC_STACK_BUF_LEN;
if value == 0 {
pos -= 1;
buf[pos] = ASCII_ZERO;
} else {
while value > 0 {
pos -= 1;
buf[pos] = ASCII_ZERO + (value % 10) as u8;
value /= 10;
}
}
&buf[pos..]
}
#[inline(always)]
pub(crate) fn is_wire_safe_header(name: &str, val: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|b: u8| b > 0x20 && b < 0x7F && b != ASCII_COLON)
&& val
.bytes()
.all(|b: u8| b >= 0x20 && b != 0x7F || b == b'\t')
}
pub(crate) fn build_replayed_wire(
status_code: usize,
headers: &[(String, String)],
body: &[u8],
) -> Vec<u8> {
let mut has_connection: bool = false;
let mut has_content_type: bool = false;
let mut extra_headers_bytes: usize = 0;
let mut can_fast_path: bool = true;
for (name, val) in headers {
if name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
continue;
}
if !is_wire_safe_header(name, val) {
can_fast_path = false;
break;
}
if name.eq_ignore_ascii_case(CONTENT_ENCODING)
|| name.eq_ignore_ascii_case(TRANSFER_ENCODING)
|| name.eq_ignore_ascii_case(CONTENT_LENGTH)
{
can_fast_path = false;
break;
}
if name.eq_ignore_ascii_case(CONNECTION) {
has_connection = true;
} else if name.eq_ignore_ascii_case(CONTENT_TYPE) {
has_content_type = true;
let media: &str = val.split(';').next().unwrap_or("").trim();
if media.eq_ignore_ascii_case(TEXT_EVENT_STREAM) {
can_fast_path = false;
break;
}
}
extra_headers_bytes += name.len() + 1 + val.len() + WIRE_CRLF.len();
}
if !can_fast_path {
let mut replay_resp: Response = Response::default();
replay_resp.set_status_code(status_code);
for (name, val) in headers {
if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
replay_resp.set_header(name, val);
}
}
replay_resp
.set_header(HEADER_IDEMPOTENT_REPLAYED, HEADER_VALUE_REPLAYED_TRUE)
.set_body(body);
return replay_resp.build();
}
let phrase: &str = HttpStatus::phrase_ref(status_code);
let mut code_buf: [u8; DEC_STACK_BUF_LEN] = [0u8; DEC_STACK_BUF_LEN];
let code_bytes: &[u8] = format_usize_stack(status_code, &mut code_buf);
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 mut cl_buf: [u8; DEC_STACK_BUF_LEN] = [0u8; DEC_STACK_BUF_LEN];
let cl_bytes: &[u8] = if is_bodyless {
&[]
} else {
format_usize_stack(body.len(), &mut cl_buf)
};
let wire_body: &[u8] = if is_bodyless { &[] } else { body };
let framing_len: usize = if !is_bodyless {
WIRE_CL_PREFIX.len() + cl_bytes.len() + WIRE_CRLF.len()
} else if status_code == HttpStatus::ResetContent.code() {
WIRE_CL_ZERO.len()
} else {
0
};
let total_len: usize = WIRE_HTTP11_PREFIX.len()
+ code_bytes.len()
+ 1
+ phrase.len()
+ WIRE_CRLF.len()
+ extra_headers_bytes
+ WIRE_REPLAYED_LINE.len()
+ if has_connection {
0
} else {
WIRE_CONN_KEEP_ALIVE.len()
}
+ if is_bodyless || has_content_type {
0
} else {
WIRE_DEFAULT_CONTENT_TYPE.len()
}
+ framing_len
+ WIRE_CRLF.len()
+ wire_body.len();
let mut out: Vec<u8> = Vec::with_capacity(total_len);
out.extend_from_slice(WIRE_HTTP11_PREFIX);
out.extend_from_slice(code_bytes);
out.push(b' ');
out.extend_from_slice(phrase.as_bytes());
out.extend_from_slice(WIRE_CRLF);
for (name, val) in headers {
if !name.eq_ignore_ascii_case(HEADER_IDEMPOTENT_REPLAYED) {
out.extend_from_slice(name.as_bytes());
out.push(ASCII_COLON);
out.extend_from_slice(val.as_bytes());
out.extend_from_slice(WIRE_CRLF);
}
}
out.extend_from_slice(WIRE_REPLAYED_LINE);
if !has_connection {
out.extend_from_slice(WIRE_CONN_KEEP_ALIVE);
}
if !is_bodyless && !has_content_type {
out.extend_from_slice(WIRE_DEFAULT_CONTENT_TYPE);
}
if !is_bodyless {
out.extend_from_slice(WIRE_CL_PREFIX);
out.extend_from_slice(cl_bytes);
out.extend_from_slice(WIRE_CRLF);
} else if status_code == HttpStatus::ResetContent.code() {
out.extend_from_slice(WIRE_CL_ZERO);
}
out.extend_from_slice(WIRE_CRLF);
out.extend_from_slice(wire_body);
out
}
#[inline]
pub(crate) fn find_header_back_ref<'a>(
headers: &'a RequestHeaders,
lower_name: &str,
) -> Option<&'a str> {
if let Some(vals) = headers.get(lower_name) {
return vals.back().map(String::as_str);
}
headers
.iter()
.find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
.and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}
#[inline]
pub(crate) fn is_valid_idempotency_key(key: &str, max_len: usize) -> bool {
!key.is_empty() && key.len() <= max_len && key.bytes().all(|b: u8| b >= 0x20 && b != 0x7F)
}
pub(crate) fn normalize_prefix(prefix: &str) -> String {
let trimmed: &str = prefix.trim();
if trimmed == "/" {
return "/".to_owned();
}
let stripped: &str = trimmed.trim_end_matches('/');
if stripped.is_empty() {
"/".to_owned()
} else {
stripped.to_owned()
}
}
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
if prefix == "/" {
return true;
}
let Some(rest) = path.strip_prefix(prefix) else {
return false;
};
rest.is_empty() || rest.starts_with('/')
}
pub(crate) fn estimate_response_bytes(key: &str, resp: &StoredIdempotentResponse) -> usize {
let header_bytes: usize = resp
.get_headers()
.iter()
.map(|(k, v): &(String, String)| k.len() + v.len())
.sum();
key.len()
+ header_bytes
+ resp.get_body().len()
+ resp.get_replayed_wire().len()
+ ENTRY_OVERHEAD_BYTES
}
pub(crate) fn build_static_error_wire(
status: HttpStatus,
body: &[u8],
retry_after: Option<&str>,
) -> Vec<u8> {
let mut resp: Response = Response::default();
resp.set_status_code(status.code())
.set_header(CONTENT_TYPE, ERROR_CONTENT_TYPE)
.set_body(body);
if let Some(retry) = retry_after {
resp.set_header(RETRY_AFTER, retry);
}
resp.build()
}