use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use nitr_core::{Error, Result};
const DEFAULT_MEMORY_LIMIT: usize = 8 * 1024 * 1024;
const DEFAULT_EXEC_TIMEOUT_MS: u64 = 30_000;
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StdConfig {
pub features: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct TestingConfig {
pub dir: PathBuf,
pub database: Option<PathBuf>,
pub seed: Option<PathBuf>,
pub capture: bool,
pub slow_ms: u64,
}
impl Default for TestingConfig {
fn default() -> Self {
Self {
dir: PathBuf::from("tests"),
database: None,
seed: None,
capture: true,
slow_ms: 1000,
}
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct EnvConfig {
pub file: Option<PathBuf>,
pub allow: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct LuaConfig {
pub stdlib: Vec<String>,
pub memory_limit: usize,
pub exec_timeout_ms: u64,
}
impl Default for LuaConfig {
fn default() -> Self {
Self {
stdlib: ["math", "table", "string", "utf8", "coroutine", "package"]
.map(String::from)
.to_vec(),
memory_limit: DEFAULT_MEMORY_LIMIT,
exec_timeout_ms: DEFAULT_EXEC_TIMEOUT_MS,
}
}
}
impl LuaConfig {
pub fn parse_stdlib(&self) -> Result<mlua::StdLib> {
use mlua::StdLib;
let mut libs = StdLib::NONE;
for name in &self.stdlib {
libs |= match name.as_str() {
"coroutine" => StdLib::COROUTINE,
"table" => StdLib::TABLE,
"io" => StdLib::IO,
"os" => StdLib::OS,
"string" => StdLib::STRING,
"utf8" => StdLib::UTF8,
"math" => StdLib::MATH,
"package" => StdLib::PACKAGE,
"debug" => {
return Err(Error::Config(
"[lua] stdlib cannot include \"debug\": the Lua state is built with \
mlua's safe constructor, which refuses the debug library outright. \
It would also defeat the execution budget, since `debug.sethook` \
replaces the instruction-count hook that stops CPU-bound loops."
.into(),
));
}
_ => {
return Err(Error::Config(format!(
"unknown Lua standard library `{name}`"
)));
}
};
}
Ok(libs)
}
}