use std::collections::BTreeMap;
use legit_hashes::{Algorithm, DECODE_MAX_ALLOC, DECODE_MAX_DIMENSION, DECODE_MAX_INPUT};
use serde::Serialize;
use crate::definition::{Definition, Input, MAX_SHINGLE};
use crate::inspect::DECODED_FORMATS;
use crate::outcome::{RUNNER, Runner};
use crate::{FORMAT, MAX_DEFINITIONS, MAX_OPTIONS_BYTES, Settings};
pub const PEAK_BYTES_PER_PIXEL: u64 = 14;
#[derive(Debug, Clone, Serialize)]
pub struct Info {
pub format: u32,
pub runner: Runner,
pub definitions: Vec<DefinitionInfo>,
pub image_formats: &'static [&'static str],
pub limits: Limits,
pub cpu: Cpu,
pub pdq_arithmetic: &'static str,
pub malloc: Malloc,
#[serde(skip_serializing_if = "Option::is_none")]
pub serve: Option<ServeInfo>,
}
pub const MALLOC_VARIABLE: &str = "LEGIT_HASHER_MALLOC";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Malloc {
Tuned,
Tunables,
Default,
System,
}
impl Malloc {
#[must_use]
pub fn detect() -> Self {
if !cfg!(all(
target_os = "linux",
target_env = "gnu",
target_pointer_width = "64"
)) {
Self::System
} else if std::env::var_os("GLIBC_TUNABLES").is_some() {
Self::Tunables
} else if std::env::var_os(MALLOC_VARIABLE).is_some_and(|value| value == "default") {
Self::Default
} else {
Self::Tuned
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ServeInfo {
pub kind: &'static str,
pub contract: &'static str,
pub stream: String,
pub group: String,
pub results: String,
pub fast_stream: String,
pub task_fields: &'static [&'static str],
pub distance_fields: &'static [&'static str],
pub fast_sources: &'static [&'static str],
pub result_fields: &'static [&'static str],
pub model_name: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct DefinitionInfo {
pub id: &'static str,
pub input: Input,
#[serde(skip_serializing_if = "Option::is_none")]
pub bits: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub values: Option<u32>,
pub returns: Vec<&'static str>,
pub parameters: &'static [&'static str],
}
#[derive(Debug, Clone, Serialize)]
pub struct Limits {
pub max_file_bytes: u64,
pub max_side: u32,
pub max_decoder_bytes: u64,
pub max_metadata_bytes: u64,
pub max_pixels: Option<u64>,
pub max_text_bytes: Option<u64>,
pub max_definitions: usize,
pub max_options_bytes: usize,
pub max_shingle: u32,
pub max_line_bytes: u64,
pub max_inline_bytes: u64,
pub worker_peak_bytes: u64,
}
#[derive(Debug, Clone, Serialize)]
pub struct Cpu {
pub arch: &'static str,
pub model: Option<String>,
pub logical_cores: usize,
pub features: BTreeMap<&'static str, bool>,
}
impl Info {
#[must_use]
pub fn detect(settings: Settings, max_line_bytes: usize) -> Self {
let max_line_bytes = max_line_bytes as u64;
let side = u64::from(DECODE_MAX_DIMENSION);
let pixels = (side * side)
.min(DECODE_MAX_ALLOC)
.min(settings.max_pixels.unwrap_or(u64::MAX));
let metadata = if settings.max_pixels.is_some() {
crate::MAX_METADATA_BYTES
} else {
DECODE_MAX_ALLOC
};
Self {
format: FORMAT,
runner: RUNNER,
definitions: Definition::ALL.iter().map(|&definition| describe(definition)).collect(),
image_formats: &DECODED_FORMATS,
limits: Limits {
max_file_bytes: DECODE_MAX_INPUT as u64,
max_side: DECODE_MAX_DIMENSION,
max_decoder_bytes: DECODE_MAX_ALLOC,
max_metadata_bytes: metadata,
max_pixels: settings.max_pixels,
max_text_bytes: settings.max_text_bytes,
max_definitions: MAX_DEFINITIONS,
max_options_bytes: MAX_OPTIONS_BYTES,
max_shingle: MAX_SHINGLE,
max_line_bytes,
max_inline_bytes: (max_line_bytes / 4 * 3).min(DECODE_MAX_INPUT as u64),
worker_peak_bytes: DECODE_MAX_INPUT as u64 + metadata + PEAK_BYTES_PER_PIXEL * pixels + max_line_bytes,
},
cpu: Cpu {
arch: std::env::consts::ARCH,
model: cpu_model(),
logical_cores: std::thread::available_parallelism().map_or(1, usize::from),
features: features(),
},
pdq_arithmetic: if cfg!(any(target_arch = "x86_64", target_arch = "aarch64")) {
"native-f32"
} else {
"software-f32"
},
malloc: Malloc::detect(),
serve: serve_info(),
}
}
}
#[cfg(feature = "serve")]
fn serve_info() -> Option<ServeInfo> {
serve_kind().into()
}
#[cfg(feature = "serve")]
fn serve_kind() -> ServeInfo {
use crate::serve::{self, KIND};
ServeInfo {
kind: KIND,
contract: legit_streams::VERSION,
stream: serve::task_stream(KIND),
group: serve::group(KIND),
results: serve::result_stream(KIND),
fast_stream: serve::fast_stream(KIND),
task_fields: &serve::TASK_FIELDS,
distance_fields: &serve::DISTANCE_FIELDS,
fast_sources: &serve::FAST_SOURCES,
result_fields: &serve::RESULT_FIELDS,
model_name: serve::MODEL_NAME,
user_agent: None,
}
}
#[cfg(not(feature = "serve"))]
const fn serve_info() -> Option<ServeInfo> {
None
}
fn describe(definition: Definition) -> DefinitionInfo {
let (bits, values) = match definition {
Definition::Bit(algorithm) => (Some(algorithm.bits()), None),
Definition::Signature(algorithm) => (None, Some(algorithm.value_count())),
};
let returns = match definition {
Definition::Bit(Algorithm::PdqV1) => vec!["value", "quality", "chunk_keys"],
Definition::Bit(_) => vec!["value", "chunk_keys"],
Definition::Signature(_) => vec!["value", "empty", "band_keys"],
};
DefinitionInfo {
id: definition.id(),
input: definition.input(),
bits,
values,
returns,
parameters: definition.parameters(),
}
}
fn cpu_model() -> Option<String> {
let cpuinfo = std::fs::read_to_string("/proc/cpuinfo").ok()?;
cpuinfo.lines().find_map(|line| {
let (name, value) = line.split_once(':')?;
matches!(name.trim(), "model name" | "Model" | "cpu model").then(|| value.trim().to_owned())
})
}
#[cfg(target_arch = "x86_64")]
fn features() -> BTreeMap<&'static str, bool> {
BTreeMap::from([
("sse2", std::arch::is_x86_feature_detected!("sse2")),
("sse4.2", std::arch::is_x86_feature_detected!("sse4.2")),
("popcnt", std::arch::is_x86_feature_detected!("popcnt")),
("fma", std::arch::is_x86_feature_detected!("fma")),
("avx2", std::arch::is_x86_feature_detected!("avx2")),
("avx512f", std::arch::is_x86_feature_detected!("avx512f")),
(
"avx512vpopcntdq",
std::arch::is_x86_feature_detected!("avx512vpopcntdq"),
),
])
}
#[cfg(target_arch = "aarch64")]
fn features() -> BTreeMap<&'static str, bool> {
BTreeMap::from([("neon", std::arch::is_aarch64_feature_detected!("neon"))])
}
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn features() -> BTreeMap<&'static str, bool> {
BTreeMap::new()
}