nitr_http/config/sections/runtime.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Sections shaping the Lua runtime: `[lua]`, `[std]`, `[env]`,
7//! `[testing]`.
8
9use std::path::PathBuf;
10
11use serde::{Deserialize, Serialize};
12
13use nitr_core::{Error, Result};
14
15/// Default per-state Lua memory limit in bytes.
16const DEFAULT_MEMORY_LIMIT: usize = 8 * 1024 * 1024; // 8 MiB
17
18/// Default wall-clock budget per handler invocation, in milliseconds.
19const DEFAULT_EXEC_TIMEOUT_MS: u64 = 30_000;
20
21/// Standard library selection (`[std]` section): which built-in `nitr.*`
22/// modules are exposed to scripts.
23///
24/// The standard library provides building blocks — scripts opt into the
25/// features they need (or replace them with their own modules). Without an
26/// explicit list only the minimal set is enabled to keep the footprint
27/// small.
28#[derive(Debug, Clone, Default, Deserialize, Serialize)]
29#[serde(default, deny_unknown_fields)]
30pub struct StdConfig {
31 /// Enabled standard library features. Valid names: `"dbg"`, `"fetch"`,
32 /// `"template"`, `"json"`, `"db"`, `"http"`, `"log"`, `"crypto"`,
33 /// `"cache"`, `"time"`, `"validate"`, `"base64"`, `"path"`, `"url"`,
34 /// `"env"`.
35 /// `None` enables the minimal default set (`json`, `http`, `log`,
36 /// `time`, `validate`, `base64`, `path`, `url`); an explicit list is
37 /// strict —
38 /// unknown names or a listed feature missing its required setting
39 /// (e.g. `db` without `database`) fail at startup.
40 pub features: Option<Vec<String>>,
41}
42
43/// Test runner settings (`[testing]` section).
44#[derive(Debug, Clone, Deserialize, Serialize)]
45#[serde(default, deny_unknown_fields)]
46pub struct TestingConfig {
47 /// Directory `nitr test` discovers `*.lua` test files in.
48 pub dir: PathBuf,
49 /// The SQLite file tests run against when a `[database]` is
50 /// configured. Unset means a fresh private file per run, with the
51 /// migrations applied — never `[database] path`: a test's
52 /// `before_each` is typically a `DELETE FROM ...`, and `nitr test`
53 /// on a host whose `nitr.toml` names the live database must not
54 /// empty it. A named file is recreated at the start of every run and
55 /// kept afterwards for inspection; naming `[database] path` here is
56 /// refused.
57 pub database: Option<PathBuf>,
58 /// A SQL file applied to the test database after the migrations and
59 /// before the snapshot `nitr.test.db.reset()` restores.
60 pub seed: Option<PathBuf>,
61 /// Whether log lines are captured per test and printed only under a
62 /// failed one (`--nocapture` streams them instead).
63 pub capture: bool,
64 /// Tests slower than this many milliseconds are marked `slow`.
65 pub slow_ms: u64,
66}
67
68impl Default for TestingConfig {
69 fn default() -> Self {
70 Self {
71 dir: PathBuf::from("tests"),
72 database: None,
73 seed: None,
74 capture: true,
75 slow_ms: 1000,
76 }
77 }
78}
79
80/// Environment handling (`[env]` section): the env file loaded at
81/// startup, and the read policy for the opt-in `nitr.env` builtin
82/// (`[std] features = ["env", ...]`).
83#[derive(Debug, Clone, Default, Deserialize, Serialize)]
84#[serde(default, deny_unknown_fields)]
85pub struct EnvConfig {
86 /// Dotenv-style file loaded at startup, resolved relative to the
87 /// config file. Unset loads `.env` next to `nitr.toml` when present;
88 /// an explicitly named file must exist. Values never override the
89 /// real process environment.
90 pub file: Option<PathBuf>,
91 /// Names `nitr.env` may read: exact names, or prefixes written with a
92 /// trailing `_` (`"APP_"`). Unset lets an enabled `env` builtin read
93 /// any variable. `NITR_*` internals are hidden from scripts either way.
94 pub allow: Option<Vec<String>>,
95}
96
97/// Lua runtime settings (`[lua]` section).
98#[derive(Debug, Clone, Deserialize, Serialize)]
99#[serde(default, deny_unknown_fields)]
100pub struct LuaConfig {
101 /// Lua standard libraries loaded into every state.
102 ///
103 /// `"io"` and `"os"` give scripts ambient filesystem/process access and
104 /// are excluded by default; adding `"io"` also restores `dofile` and
105 /// `loadfile`, which read and execute any file the process can reach.
106 ///
107 /// `"debug"` is **refused**: mlua's safe constructor cannot load it, and
108 /// it would defeat the execution budget anyway, since `debug.sethook`
109 /// replaces the instruction-count hook that stops CPU-bound loops.
110 pub stdlib: Vec<String>,
111 /// Per-state Lua memory limit in bytes.
112 pub memory_limit: usize,
113 /// Wall-clock budget per handler invocation, in milliseconds; `0`
114 /// disables the limit. Enforced by an instruction-count hook (CPU-bound
115 /// loops) and an outer async timeout (slow I/O).
116 pub exec_timeout_ms: u64,
117}
118
119impl Default for LuaConfig {
120 fn default() -> Self {
121 Self {
122 // `io` and `os` are deliberately excluded: they give scripts
123 // ambient filesystem/process access. Opt in via `[lua] stdlib`.
124 stdlib: ["math", "table", "string", "utf8", "coroutine", "package"]
125 .map(String::from)
126 .to_vec(),
127 memory_limit: DEFAULT_MEMORY_LIMIT,
128 exec_timeout_ms: DEFAULT_EXEC_TIMEOUT_MS,
129 }
130 }
131}
132
133impl LuaConfig {
134 /// Parses the stdlib names into [`mlua::StdLib`] flags.
135 pub fn parse_stdlib(&self) -> Result<mlua::StdLib> {
136 use mlua::StdLib;
137 let mut libs = StdLib::NONE;
138 for name in &self.stdlib {
139 libs |= match name.as_str() {
140 "coroutine" => StdLib::COROUTINE,
141 "table" => StdLib::TABLE,
142 "io" => StdLib::IO,
143 "os" => StdLib::OS,
144 "string" => StdLib::STRING,
145 "utf8" => StdLib::UTF8,
146 "math" => StdLib::MATH,
147 "package" => StdLib::PACKAGE,
148 // Refused here, where the names are mapped, rather than
149 // passed through: mlua would reject `StdLib::DEBUG` at boot
150 // anyway, but naming an internal Rust constructor instead of
151 // the `nitr.toml` setting. The full rationale is the error
152 // below.
153 "debug" => {
154 return Err(Error::Config(
155 "[lua] stdlib cannot include \"debug\": the Lua state is built with \
156 mlua's safe constructor, which refuses the debug library outright. \
157 It would also defeat the execution budget, since `debug.sethook` \
158 replaces the instruction-count hook that stops CPU-bound loops."
159 .into(),
160 ));
161 }
162 _ => {
163 return Err(Error::Config(format!(
164 "unknown Lua standard library `{name}`"
165 )));
166 }
167 };
168 }
169 Ok(libs)
170 }
171}