use bytes::Bytes;
use http_body_util::Full;
use hyper::{Response, StatusCode};
use std::time::{SystemTime, UNIX_EPOCH};
pub mod fastmap {
pub type FastMap<K, V> = std::collections::HashMap<K, V, foldhash::fast::RandomState>;
pub type FastSet<K> = std::collections::HashSet<K, foldhash::fast::RandomState>;
pub type OrderedMap<K, V> = indexmap::IndexMap<K, V, foldhash::fast::RandomState>;
}
pub use fastmap::{FastMap, FastSet, OrderedMap};
pub fn http2_disabled() -> bool {
static DISABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*DISABLED
.get_or_init(|| http2_disabled_from(std::env::var("RIFT_DISABLE_HTTP2").ok().as_deref()))
}
fn http2_disabled_from(val: Option<&str>) -> bool {
val.map(|v| v.trim().to_ascii_lowercase())
.is_some_and(|v| matches!(v.as_str(), "1" | "true" | "yes" | "on"))
}
pub fn strict_behaviors_env() -> bool {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ENABLED.get_or_init(|| {
strict_behaviors_from(std::env::var("RIFT_STRICT_BEHAVIORS").ok().as_deref())
})
}
fn strict_behaviors_from(val: Option<&str>) -> bool {
val.map(|v| v.trim().to_ascii_lowercase())
.is_some_and(|v| matches!(v.as_str(), "1" | "true" | "yes" | "on"))
}
pub fn rift_debug_env() -> bool {
static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ENABLED.get_or_init(|| rift_debug_from(std::env::var("RIFT_DEBUG").ok().as_deref()))
}
fn rift_debug_from(val: Option<&str>) -> bool {
val.map(|v| v.trim().to_ascii_lowercase())
.is_some_and(|v| matches!(v.as_str(), "1" | "true" | "yes" | "on"))
}
pub fn decode_form_component(value: &str) -> String {
let spaced = value.replace('+', " ");
urlencoding::decode(&spaced)
.map(|decoded| decoded.into_owned())
.unwrap_or(spaced)
}
pub type MultiValueMap = OrderedMap<String, Vec<String>>;
#[must_use]
pub fn parse_query_string(query: &str) -> MultiValueMap {
let mut map = MultiValueMap::default();
for pair in query.split('&').filter(|s| !s.is_empty()) {
let (key, value) = match pair.split_once('=') {
Some((k, v)) => (k, v),
None => (pair, ""),
};
map.entry(decode_form_component(key))
.or_default()
.push(decode_form_component(value));
}
map
}
#[must_use]
pub fn comma_joined(map: &MultiValueMap) -> OrderedMap<String, String> {
map.iter().map(|(k, v)| (k.clone(), v.join(","))).collect()
}
fn is_array_index(key: &str) -> bool {
key.parse::<u32>()
.is_ok_and(|n| n != u32::MAX && n.to_string() == key)
}
#[must_use]
pub fn js_key_order<V, S>(map: &indexmap::IndexMap<String, V, S>) -> Vec<(&String, &V)> {
let (mut indexed, other): (Vec<_>, Vec<_>) =
map.iter().partition(|(key, _)| is_array_index(key));
indexed.sort_by_key(|(key, _)| key.parse::<u32>().unwrap_or(u32::MAX));
indexed.extend(other);
indexed
}
pub struct JsKeyOrder<'a, V, S>(pub &'a indexmap::IndexMap<String, V, S>);
impl<V: serde::Serialize, S> serde::Serialize for JsKeyOrder<'_, V, S> {
fn serialize<Ser: serde::Serializer>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error> {
serializer.collect_map(js_key_order(self.0))
}
}
#[must_use]
pub fn values_as_json(values: &[String]) -> serde_json::Value {
match values {
[one] => serde_json::Value::String(one.clone()),
many => serde_json::Value::Array(
many.iter()
.map(|v| serde_json::Value::String(v.clone()))
.collect(),
),
}
}
#[must_use]
pub fn map_values_as_json(map: &MultiValueMap) -> OrderedMap<String, serde_json::Value> {
map.iter()
.map(|(k, v)| (k.clone(), values_as_json(v)))
.collect()
}
fn internal_error_fallback(e: &hyper::http::Error) -> Response<Full<Bytes>> {
tracing::error!(error = %e, "response build failed; serving a 500");
let mut resp = Response::new(Full::new(Bytes::from("Internal Server Error")));
*resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
resp
}
pub fn build_response(status: StatusCode, body: impl Into<Bytes>) -> Response<Full<Bytes>> {
Response::builder()
.status(status)
.body(Full::new(body.into()))
.unwrap_or_else(|e| internal_error_fallback(&e))
}
pub fn build_response_with_headers(
status: StatusCode,
headers: impl IntoIterator<Item = (impl AsRef<str>, impl AsRef<str>)>,
body: impl Into<Bytes>,
) -> Response<Full<Bytes>> {
let mut builder = Response::builder().status(status);
for (key, value) in headers {
builder = builder.header(key.as_ref(), value.as_ref());
}
builder
.body(Full::new(body.into()))
.unwrap_or_else(|e| internal_error_fallback(&e))
}
pub fn is_hop_by_hop_header(name: &str) -> bool {
let lower = name.to_lowercase();
lower == "transfer-encoding" || lower == "connection" || lower == "keep-alive"
}
pub fn encode_body_for_stub(body: &[u8]) -> (Option<serde_json::Value>, bool) {
if body.is_empty() {
return (None, false);
}
match std::str::from_utf8(body) {
Ok(text) => {
let val = if let Ok(json_val) = serde_json::from_str::<serde_json::Value>(text) {
json_val
} else {
serde_json::Value::String(text.to_string())
};
(Some(val), false)
}
Err(_) => {
use base64::Engine;
let encoded = base64::engine::general_purpose::STANDARD.encode(body);
(Some(serde_json::Value::String(encoded)), true)
}
}
}
pub fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
mod tests {
use super::{
FastMap, FastSet, build_response, build_response_with_headers, http2_disabled_from,
rift_debug_from, strict_behaviors_from,
};
use hyper::StatusCode;
#[test]
fn fastmap_is_foldhash_backed_and_default_constructible() {
fn assert_foldhash<K, V>(_: &std::collections::HashMap<K, V, foldhash::fast::RandomState>) {
}
let mut map: FastMap<String, i32> = FastMap::default();
assert_foldhash(&map);
map.insert("k".to_string(), 1);
assert_eq!(map.get("k"), Some(&1));
let mut set: FastSet<String> = FastSet::default();
set.insert("a".to_string());
assert!(set.contains("a"));
}
#[test]
fn build_response_with_headers_falls_back_to_500_on_builder_failure() {
let resp = build_response_with_headers(StatusCode::OK, [("bad\nname", "v")], "x");
assert_eq!(
resp.status(),
StatusCode::INTERNAL_SERVER_ERROR,
"a builder failure must surface as 500, not a 200 carrying an error string"
);
}
#[test]
fn build_response_preserves_the_requested_status() {
assert_eq!(
build_response(StatusCode::NOT_FOUND, "x").status(),
StatusCode::NOT_FOUND
);
}
#[test]
fn strict_behaviors_env_parsing() {
for on in ["1", "true", "TRUE", " yes ", "On"] {
assert!(
strict_behaviors_from(Some(on)),
"{on:?} should enable strict behaviors"
);
}
for off in [
None,
Some(""),
Some("0"),
Some("false"),
Some("no"),
Some("2"),
] {
assert!(
!strict_behaviors_from(off),
"{off:?} should keep behaviors lenient"
);
}
}
#[test]
fn http2_disable_env_parsing() {
for on in ["1", "true", "TRUE", " yes ", "On"] {
assert!(
http2_disabled_from(Some(on)),
"{on:?} should disable HTTP/2"
);
}
for off in [
None,
Some(""),
Some("0"),
Some("false"),
Some("no"),
Some("2"),
] {
assert!(
!http2_disabled_from(off),
"{off:?} should keep HTTP/2 enabled"
);
}
}
#[test]
fn rift_debug_env_parsing() {
for on in ["1", "true", "TRUE", " yes ", "On"] {
assert!(rift_debug_from(Some(on)), "{on:?} should enable debug mode");
}
for off in [
None,
Some(""),
Some("0"),
Some("false"),
Some("no"),
Some("2"),
] {
assert!(!rift_debug_from(off), "{off:?} should keep debug mode off");
}
}
}
#[cfg(test)]
mod key_order_tests {
use super::{JsKeyOrder, OrderedMap, js_key_order, parse_query_string};
#[test]
fn parsing_keeps_first_occurrence_order() {
let params = parse_query_string("b=1&a=2&c=3&a=4");
let keys: Vec<&str> = params.keys().map(String::as_str).collect();
assert_eq!(keys, ["b", "a", "c"]);
assert_eq!(params["a"], ["2", "4"]);
}
fn json_of(keys: &[&str]) -> String {
let map: OrderedMap<String, u8> = keys.iter().map(|k| (k.to_string(), 0)).collect();
serde_json::to_string(&JsKeyOrder(&map)).expect("serializes")
}
#[test]
fn array_index_keys_come_first_ascending_then_insertion_order() {
assert_eq!(
json_of(&["b", "10", "2", "a"]),
r#"{"2":0,"10":0,"b":0,"a":0}"#
);
}
#[test]
fn only_canonical_array_indexes_sort_first() {
assert_eq!(
json_of(&["01", "-1", "+1", "1.5", "4294967295", "4294967294", "0"]),
r#"{"0":0,"4294967294":0,"01":0,"-1":0,"+1":0,"1.5":0,"4294967295":0}"#
);
}
#[test]
fn an_empty_map_has_no_entries() {
let map: OrderedMap<String, u8> = OrderedMap::default();
assert!(js_key_order(&map).is_empty());
}
}
#[cfg(test)]
mod parse_query_string_tests {
use super::parse_query_string;
#[test]
fn an_undecodable_value_passes_through_raw() {
let params = parse_query_string("k=%FF");
assert_eq!(one(¶ms, "k"), Some("%FF"));
}
#[test]
fn an_encoded_key_is_decoded_and_an_undecodable_one_stays_raw() {
let params = parse_query_string("first%20name=bob");
assert_eq!(one(¶ms, "first name"), Some("bob"));
let undecodable = parse_query_string("%FF=v");
assert_eq!(one(&undecodable, "%FF"), Some("v"));
}
#[test]
fn a_plus_is_a_space_in_keys_and_values() {
let cases = [
("q=x+y%21", "q", "x y!"),
("a+b=1", "a b", "1"),
("q=1%2B1", "q", "1+1"),
("q=1+1", "q", "1 1"),
("q=%2B+%20", "q", "+ "),
("r=a+%ZZ", "r", "a %ZZ"),
("k=%FF", "k", "%FF"),
];
for (query, key, expected) in cases {
let params = parse_query_string(query);
assert_eq!(one(¶ms, key), Some(expected), "query {query:?}");
}
}
#[test]
fn a_bare_parameter_key_is_decoded() {
let params = parse_query_string("first%20name");
assert_eq!(one(¶ms, "first name"), Some(""));
}
fn one<'a>(params: &'a super::MultiValueMap, key: &str) -> Option<&'a str> {
match params.get(key).map(Vec::as_slice) {
Some([value]) => Some(value.as_str()),
_ => None,
}
}
#[test]
fn a_repeated_key_keeps_every_value_in_order() {
let params = parse_query_string("color=red&color=green&color=blue&one=1");
assert_eq!(
params.get("color").map(Vec::as_slice),
Some(["red", "green", "blue"].map(String::from).as_slice())
);
assert_eq!(one(¶ms, "one"), Some("1"));
let joined = super::comma_joined(¶ms);
assert_eq!(
joined.get("color").map(String::as_str),
Some("red,green,blue")
);
assert_eq!(joined.get("one").map(String::as_str), Some("1"));
}
#[test]
fn values_render_as_a_string_or_an_array() {
assert_eq!(super::values_as_json(&["a".into()]), serde_json::json!("a"));
assert_eq!(
super::values_as_json(&["a".into(), "b".into()]),
serde_json::json!(["a", "b"])
);
}
}