lemma/limits.rs
1use crate::error::Error;
2use crate::parsing::source::Source;
3
4pub const MAX_SPEC_NAME_LENGTH: usize = 128;
5pub const MAX_FACT_NAME_LENGTH: usize = 256;
6pub const MAX_RULE_NAME_LENGTH: usize = 256;
7pub const MAX_TYPE_NAME_LENGTH: usize = 256;
8
9/// Maximum significant digits in a number string. rust_decimal supports at most 28;
10/// more can panic or overflow in parse or arithmetic.
11pub const MAX_NUMBER_DIGITS: usize = 28;
12
13/// Maximum character length for a text value (fact/runtime input).
14pub const MAX_TEXT_VALUE_LENGTH: usize = 1024;
15
16/// Validate that a name does not exceed the given character limit.
17/// `kind` is a human-readable noun like "spec", "fact", "rule", or "type".
18pub fn check_max_length(
19 name: &str,
20 limit: usize,
21 kind: &str,
22 source: Option<Source>,
23) -> Result<(), Error> {
24 if name.len() > limit {
25 return Err(Error::resource_limit_exceeded(
26 format!("max_{kind}_name_length"),
27 format!("{limit} characters"),
28 format!("{} characters", name.len()),
29 format!("Shorten the {kind} name to at most {limit} characters"),
30 source,
31 None,
32 None,
33 ));
34 }
35 Ok(())
36}
37
38/// Limits to prevent abuse and enable predictable resource usage
39///
40/// These limits protect against malicious inputs while being generous enough
41/// for all legitimate use cases.
42#[derive(Debug, Clone)]
43pub struct ResourceLimits {
44 /// Maximum file size in bytes
45 /// Real usage: ~5KB, Limit: 5MB (1000x)
46 pub max_file_size_bytes: usize,
47
48 /// Maximum expression nesting depth
49 /// Real usage: ~3 levels, Limit: 7. Deeper logic via rule composition.
50 pub max_expression_depth: usize,
51
52 /// Maximum expression nodes per file (parser-level)
53 /// Quick-reject for pathological single files.
54 pub max_expression_count: usize,
55
56 /// Maximum total expression nodes across all files (engine-level)
57 /// The real capacity ceiling. pi (~3.1M) — generous for national-scale
58 /// regulatory systems while bounding total engine workload.
59 pub max_total_expression_count: usize,
60
61 /// Maximum size of a single fact value in bytes
62 /// Real usage: ~100 bytes, Limit: 1KB (10x)
63 /// Enables server pre-allocation for zero-allocation evaluation
64 pub max_fact_value_bytes: usize,
65
66 /// Maximum total bytes to read in a single load_from_paths call (and/or in-memory size of loaded specs)
67 pub max_loaded_bytes: usize,
68
69 /// Maximum number of .lemma files to load in a single load_from_paths call
70 pub max_files: usize,
71}
72
73impl Default for ResourceLimits {
74 fn default() -> Self {
75 Self {
76 max_file_size_bytes: 5 * 1024 * 1024, // 5 MB
77 max_expression_depth: 7,
78 max_expression_count: 4096,
79 max_total_expression_count: 3_141_592,
80 max_fact_value_bytes: 1024, // 1 KB
81 max_loaded_bytes: 50 * 1024 * 1024, // 50 MB
82 max_files: 4096,
83 }
84 }
85}