use std::collections::BTreeMap;
pub const PRECONDITION_OR_BOUNDARY_VIOLATION: i32 = 5;
pub const VCARD_PARAMETER_PREFIX: &str = "urn:vcard:contract:param:";
pub const CONTRACT_NET_DIGEST: &str = "b9a3f6b5ffd122e9a2dca16b7b8d106ba0494fcf2c38ad2f8253eec5274c4f9c";
pub const PARAMETER_TYPES: [(&str, &str); 14] = [
("sqlite.busy_timeout_ms", "u32"),
("sqlite.compaction_busy_timeout_ms", "u32"),
("sqlite.lock_retry_max", "u32"),
("sqlite.lock_retry_backoff_ms", "u32"),
("codec.b64_chunk_bytes", "usize"),
("text.encoding", "string"),
("network.gateway_timeout_ms", "u32"),
("term.reduction_fuel", "u32"),
("runtime.adapter_timeout_s", "u32"),
("petri.binding_timeout_s", "u32"),
("petri.binding_attempts", "u32"),
("cel.test_suite_timeout_s", "u32"),
("petri.function_pool_db", "string"),
("membrane.continuation_park_ttl_ms", "u32"),
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParameterContext {
pub sqlite_busy_timeout_ms: u32,
pub sqlite_compaction_busy_timeout_ms: u32,
pub sqlite_lock_retry_max: u32,
pub sqlite_lock_retry_backoff_ms: u32,
pub codec_b64_chunk_bytes: usize,
pub text_encoding: String,
pub network_gateway_timeout_ms: u32,
pub term_reduction_fuel: u32,
pub runtime_adapter_timeout_s: u32,
pub petri_binding_timeout_s: u32,
pub petri_binding_attempts: u32,
pub cel_test_suite_timeout_s: u32,
pub petri_function_pool_db: String,
pub membrane_continuation_park_ttl_ms: u32,
}
impl Default for ParameterContext {
fn default() -> Self {
Self {
sqlite_busy_timeout_ms: 5000,
sqlite_compaction_busy_timeout_ms: 30000,
sqlite_lock_retry_max: 5,
sqlite_lock_retry_backoff_ms: 50,
codec_b64_chunk_bytes: 12288,
text_encoding: "utf-8".to_string(),
network_gateway_timeout_ms: 10000,
term_reduction_fuel: 1000,
runtime_adapter_timeout_s: 10,
petri_binding_timeout_s: 60,
petri_binding_attempts: 2,
cel_test_suite_timeout_s: 300,
petri_function_pool_db: "db/layer0_function_memory.mcard.db".to_string(),
membrane_continuation_park_ttl_ms: 300000,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParameterBoundaryError {
pub key: String,
pub raw: String,
pub reason: String,
pub source: &'static str,
}
impl ParameterBoundaryError {
pub const EXIT_CODE: i32 = PRECONDITION_OR_BOUNDARY_VIOLATION;
fn new(key: &str, raw: &str, reason: String, source: &'static str) -> Self {
Self { key: key.to_string(), raw: raw.to_string(), reason, source }
}
pub fn vcard(&self) -> String {
format!("{VCARD_PARAMETER_PREFIX}{}", self.key)
}
}
impl std::fmt::Display for ParameterBoundaryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}={:?} from {}: {} ({})", self.key, self.raw, self.source, self.reason, self.vcard())
}
}
impl std::error::Error for ParameterBoundaryError {}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParameterValue {
Int(u64),
Text(String),
Bool(bool),
}
struct Spec {
key: &'static str,
env: &'static str,
low: u64,
high: u64,
multiple_of: u64,
allowed: Option<&'static [&'static str]>,
}
struct Layers<'a> {
env: &'a BTreeMap<String, String>,
cli: &'a BTreeMap<String, String>,
card: &'a BTreeMap<String, String>,
}
impl<'a> Layers<'a> {
fn raw(&self, spec: &Spec) -> Option<(&'a str, &'static str)> {
if let Some(raw) = self.cli.get(spec.key) {
return Some((raw.as_str(), "cli"));
}
if let Some(raw) = self.env.get(spec.env) {
return Some((raw.as_str(), "env"));
}
self.card.get(spec.key).map(|raw| (raw.as_str(), "card"))
}
}
fn narrow_int(spec: &Spec, raw: &str, source: &'static str) -> Result<u64, ParameterBoundaryError> {
let bottom = |reason: String| ParameterBoundaryError::new(spec.key, raw, reason, source);
if raw.is_empty() || !raw.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(bottom("not an unsigned decimal integer".to_string()));
}
let value: u64 = raw.parse().map_err(|_| bottom(format!("outside [{}, {}]", spec.low, spec.high)))?;
if value < spec.low || value > spec.high {
return Err(bottom(format!("outside [{}, {}]", spec.low, spec.high)));
}
if !value.is_multiple_of(spec.multiple_of) {
return Err(bottom(format!("not a multiple of {}", spec.multiple_of)));
}
Ok(value)
}
fn narrow_text(spec: &Spec, raw: &str, source: &'static str) -> Result<String, ParameterBoundaryError> {
if raw.is_empty() || spec.allowed.is_some_and(|allowed| !allowed.contains(&raw)) {
return Err(ParameterBoundaryError::new(spec.key, raw, "outside allowed_values".to_string(), source));
}
Ok(raw.to_string())
}
#[allow(dead_code)]
fn narrow_bool(spec: &Spec, raw: &str, source: &'static str) -> Result<bool, ParameterBoundaryError> {
match raw {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(ParameterBoundaryError::new(spec.key, raw, "not a boolean".to_string(), source)),
}
}
fn reject_unknown(layer: &BTreeMap<String, String>, source: &'static str) -> Result<(), ParameterBoundaryError> {
match layer.iter().find(|(key, _)| !SPECS.iter().any(|spec| spec.key == key.as_str())) {
Some((key, raw)) => Err(ParameterBoundaryError::new(key, raw, "unknown parameter".to_string(), source)),
None => Ok(()),
}
}
const SPECS: [Spec; 14] = [
Spec { key: "sqlite.busy_timeout_ms", env: "CLM_SQLITE_BUSY_TIMEOUT_MS", low: 100, high: 120000, multiple_of: 1, allowed: None },
Spec { key: "sqlite.compaction_busy_timeout_ms", env: "CLM_SQLITE_COMPACTION_BUSY_TIMEOUT_MS", low: 1000, high: 600000, multiple_of: 1, allowed: None },
Spec { key: "sqlite.lock_retry_max", env: "CLM_SQLITE_LOCK_RETRY_MAX", low: 0, high: 100, multiple_of: 1, allowed: None },
Spec { key: "sqlite.lock_retry_backoff_ms", env: "CLM_SQLITE_LOCK_RETRY_BACKOFF_MS", low: 1, high: 1000, multiple_of: 1, allowed: None },
Spec { key: "codec.b64_chunk_bytes", env: "CLM_CODEC_B64_CHUNK_BYTES", low: 3, high: 1048576, multiple_of: 3, allowed: None },
Spec { key: "text.encoding", env: "CLM_TEXT_ENCODING", low: 0, high: 0, multiple_of: 1, allowed: Some(&["utf-8"]) },
Spec { key: "network.gateway_timeout_ms", env: "CLM_NETWORK_GATEWAY_TIMEOUT_MS", low: 100, high: 120000, multiple_of: 1, allowed: None },
Spec { key: "term.reduction_fuel", env: "CLM_TERM_REDUCTION_FUEL", low: 1, high: 1000000, multiple_of: 1, allowed: None },
Spec { key: "runtime.adapter_timeout_s", env: "CLM_RUNTIME_ADAPTER_TIMEOUT_S", low: 1, high: 600, multiple_of: 1, allowed: None },
Spec { key: "petri.binding_timeout_s", env: "CLM_PETRI_BINDING_TIMEOUT_S", low: 1, high: 600, multiple_of: 1, allowed: None },
Spec { key: "petri.binding_attempts", env: "CLM_PETRI_BINDING_ATTEMPTS", low: 1, high: 20, multiple_of: 1, allowed: None },
Spec { key: "cel.test_suite_timeout_s", env: "CLM_CEL_TEST_SUITE_TIMEOUT_S", low: 1, high: 3600, multiple_of: 1, allowed: None },
Spec { key: "petri.function_pool_db", env: "CLM_PETRI_FUNCTION_POOL_DB", low: 0, high: 0, multiple_of: 1, allowed: None },
Spec { key: "membrane.continuation_park_ttl_ms", env: "CLM_MEMBRANE_CONTINUATION_PARK_TTL_MS", low: 1000, high: 86400000, multiple_of: 1, allowed: None },
];
impl ParameterContext {
pub fn from_mapping(env: &BTreeMap<String, String>, cli: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
Self::from_layers(env, cli, &BTreeMap::new())
}
pub fn from_layers(env: &BTreeMap<String, String>, cli: &BTreeMap<String, String>, card: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
Self::default().with_layers(&Layers { env, cli, card })
}
pub fn with_overrides(&self, cli: &BTreeMap<String, String>) -> Result<Self, ParameterBoundaryError> {
let empty = BTreeMap::new();
self.with_layers(&Layers { env: &empty, cli, card: &empty })
}
fn with_layers(&self, layers: &Layers<'_>) -> Result<Self, ParameterBoundaryError> {
reject_unknown(layers.cli, "cli")?;
reject_unknown(layers.card, "card")?;
let mut context = self.clone();
if let Some((raw, source)) = layers.raw(&SPECS[0]) { context.sqlite_busy_timeout_ms = u32::try_from(narrow_int(&SPECS[0], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[1]) { context.sqlite_compaction_busy_timeout_ms = u32::try_from(narrow_int(&SPECS[1], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[2]) { context.sqlite_lock_retry_max = u32::try_from(narrow_int(&SPECS[2], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[3]) { context.sqlite_lock_retry_backoff_ms = u32::try_from(narrow_int(&SPECS[3], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[4]) { context.codec_b64_chunk_bytes = usize::try_from(narrow_int(&SPECS[4], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[5]) { context.text_encoding = narrow_text(&SPECS[5], raw, source)?; }
if let Some((raw, source)) = layers.raw(&SPECS[6]) { context.network_gateway_timeout_ms = u32::try_from(narrow_int(&SPECS[6], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[7]) { context.term_reduction_fuel = u32::try_from(narrow_int(&SPECS[7], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[8]) { context.runtime_adapter_timeout_s = u32::try_from(narrow_int(&SPECS[8], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[9]) { context.petri_binding_timeout_s = u32::try_from(narrow_int(&SPECS[9], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[10]) { context.petri_binding_attempts = u32::try_from(narrow_int(&SPECS[10], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[11]) { context.cel_test_suite_timeout_s = u32::try_from(narrow_int(&SPECS[11], raw, source)?).expect("range fits the field"); }
if let Some((raw, source)) = layers.raw(&SPECS[12]) { context.petri_function_pool_db = narrow_text(&SPECS[12], raw, source)?; }
if let Some((raw, source)) = layers.raw(&SPECS[13]) { context.membrane_continuation_park_ttl_ms = u32::try_from(narrow_int(&SPECS[13], raw, source)?).expect("range fits the field"); }
Ok(context)
}
pub fn as_mapping(&self) -> BTreeMap<&'static str, ParameterValue> {
let mut mapping = BTreeMap::new();
mapping.insert("sqlite.busy_timeout_ms", ParameterValue::Int(u64::from(self.sqlite_busy_timeout_ms)));
mapping.insert("sqlite.compaction_busy_timeout_ms", ParameterValue::Int(u64::from(self.sqlite_compaction_busy_timeout_ms)));
mapping.insert("sqlite.lock_retry_max", ParameterValue::Int(u64::from(self.sqlite_lock_retry_max)));
mapping.insert("sqlite.lock_retry_backoff_ms", ParameterValue::Int(u64::from(self.sqlite_lock_retry_backoff_ms)));
mapping.insert("codec.b64_chunk_bytes", ParameterValue::Int(self.codec_b64_chunk_bytes as u64));
mapping.insert("text.encoding", ParameterValue::Text(self.text_encoding.clone()));
mapping.insert("network.gateway_timeout_ms", ParameterValue::Int(u64::from(self.network_gateway_timeout_ms)));
mapping.insert("term.reduction_fuel", ParameterValue::Int(u64::from(self.term_reduction_fuel)));
mapping.insert("runtime.adapter_timeout_s", ParameterValue::Int(u64::from(self.runtime_adapter_timeout_s)));
mapping.insert("petri.binding_timeout_s", ParameterValue::Int(u64::from(self.petri_binding_timeout_s)));
mapping.insert("petri.binding_attempts", ParameterValue::Int(u64::from(self.petri_binding_attempts)));
mapping.insert("cel.test_suite_timeout_s", ParameterValue::Int(u64::from(self.cel_test_suite_timeout_s)));
mapping.insert("petri.function_pool_db", ParameterValue::Text(self.petri_function_pool_db.clone()));
mapping.insert("membrane.continuation_park_ttl_ms", ParameterValue::Int(u64::from(self.membrane_continuation_park_ttl_ms)));
mapping
}
}