1use std::{collections::BTreeMap, io::Write, path::Path, time::Duration};
14
15use serde::{Deserialize, Serialize};
16
17use crate::config::{Backend, Field};
18#[cfg(test)]
19#[path = "limits/tests/backend.rs"]
20mod backend_tests;
21
22pub const FILE: &str = "limits.json";
23const MAX_BYTES: u64 = 64 * 1024;
25const MAX_SLOTS: u32 = 100_000;
28pub const SESSIONS_MAX_BYTES: u64 = 1024 * 1024 * 1024;
30pub const SESSIONS_TARGET_BYTES: u64 = 768 * 1024 * 1024;
32const SESSION_TARGET_NUMERATOR: u64 = 3;
35const SESSION_TARGET_DENOMINATOR: u64 = 4;
36pub const SIGNOFF_IDLE_GRACE: Duration = Duration::from_secs(120);
39pub const MAX_SIGNOFF_IDLE_GRACE: Duration = Duration::from_secs(24 * 60 * 60);
41const GRACE_FIELD: &str = "signoffIdleGraceSeconds";
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
47#[serde(rename_all = "camelCase")]
48pub struct Limits {
49 backends: BTreeMap<Backend, u32>,
50 agent_sessions: AgentSessions,
51 #[serde(rename = "signoffIdleGraceSeconds", serialize_with = "seconds")]
52 signoff_idle_grace: Duration,
53}
54
55fn seconds<S: serde::Serializer>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
56 serializer.serialize_u64(duration.as_secs())
57}
58
59impl Default for Limits {
60 fn default() -> Self {
61 Self {
62 backends: BTreeMap::new(),
63 agent_sessions: AgentSessions::default(),
64 signoff_idle_grace: SIGNOFF_IDLE_GRACE,
65 }
66 }
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
72#[serde(rename_all = "camelCase")]
73pub struct AgentSessions {
74 enabled: bool,
75 max_bytes: u64,
76 target_bytes: u64,
77}
78
79impl AgentSessions {
80 pub fn new(enabled: bool, max_bytes: u64, target_bytes: u64) -> Result<Self, String> {
81 if max_bytes == 0 {
82 return Err("agentSessions.maxBytes must be at least 1.".into());
83 }
84 if target_bytes >= max_bytes {
85 return Err(format!(
86 "agentSessions.targetBytes ({target_bytes}) must be lower than maxBytes ({max_bytes})."
87 ));
88 }
89 Ok(Self {
90 enabled,
91 max_bytes,
92 target_bytes,
93 })
94 }
95
96 pub fn enabled(&self) -> bool {
97 self.enabled
98 }
99
100 pub fn max_bytes(&self) -> u64 {
101 self.max_bytes
102 }
103
104 pub fn target_bytes(&self) -> u64 {
105 self.target_bytes
106 }
107}
108
109impl Default for AgentSessions {
110 fn default() -> Self {
111 Self::new(true, SESSIONS_MAX_BYTES, SESSIONS_TARGET_BYTES)
112 .expect("valid default session bounds")
113 }
114}
115
116#[derive(Default, Deserialize, Serialize)]
117#[serde(rename_all = "camelCase", deny_unknown_fields)]
118struct Declared {
119 #[serde(
120 default,
121 deserialize_with = "backend_limits",
122 skip_serializing_if = "Option::is_none"
123 )]
124 backends: Option<BTreeMap<Backend, u32>>,
125 #[serde(default, skip_serializing_if = "Field::missing")]
126 agent_sessions: Field<DeclaredSessions>,
127 #[serde(default, skip_serializing_if = "Field::missing")]
128 signoff_idle_grace_seconds: Field<u64>,
129}
130
131impl Declared {
132 fn resolve(&mut self, override_grace: Option<Duration>) -> Result<Limits, String> {
135 let agent_sessions = self
136 .agent_sessions
137 .value()
138 .map(DeclaredSessions::resolve)
139 .transpose()?
140 .unwrap_or_default();
141 let original_grace = self
142 .signoff_idle_grace_seconds
143 .value()
144 .copied()
145 .map(grace)
146 .transpose()?;
147 let signoff_idle_grace = match override_grace {
148 Some(grace) => {
149 self.signoff_idle_grace_seconds = Field::Value(grace.as_secs());
150 grace
151 }
152 None => original_grace.unwrap_or(SIGNOFF_IDLE_GRACE),
153 };
154 Ok(Limits {
155 backends: self.backends.clone().unwrap_or_default(),
156 agent_sessions,
157 signoff_idle_grace,
158 })
159 }
160}
161
162fn grace(seconds: u64) -> Result<Duration, String> {
164 let grace = Duration::from_secs(seconds);
165 if grace > MAX_SIGNOFF_IDLE_GRACE {
166 return Err(format!(
167 "{GRACE_FIELD} must be at most {}.",
168 MAX_SIGNOFF_IDLE_GRACE.as_secs()
169 ));
170 }
171 Ok(grace)
172}
173
174fn backend_limits<'de, D: serde::Deserializer<'de>>(
175 deserializer: D,
176) -> Result<Option<BTreeMap<Backend, u32>>, D::Error> {
177 let names = BTreeMap::<String, u32>::deserialize(deserializer)?;
180 names
181 .into_iter()
182 .map(|(name, limit)| {
183 let backend = name
184 .parse()
185 .map_err(|error| serde::de::Error::custom(format!("backends: {error}")))?;
186 if !(1..=MAX_SLOTS).contains(&limit) {
187 return Err(serde::de::Error::custom(format!(
188 "backends.{name} must be between 1 and {MAX_SLOTS}."
189 )));
190 }
191 Ok((backend, limit))
192 })
193 .collect::<Result<_, _>>()
194 .map(Some)
195}
196
197#[derive(Deserialize, Serialize)]
198#[serde(rename_all = "camelCase", deny_unknown_fields)]
199struct DeclaredSessions {
200 #[serde(default, skip_serializing_if = "Field::missing")]
201 enabled: Field<bool>,
202 #[serde(default, skip_serializing_if = "Field::missing")]
203 max_bytes: Field<u64>,
204 #[serde(default, skip_serializing_if = "Field::missing")]
205 target_bytes: Field<u64>,
206}
207
208impl DeclaredSessions {
209 fn resolve(&self) -> Result<AgentSessions, String> {
212 let max_bytes = self
213 .max_bytes
214 .value()
215 .copied()
216 .unwrap_or(SESSIONS_MAX_BYTES);
217 let target_bytes = self.target_bytes.value().copied().unwrap_or_else(|| {
218 if SESSIONS_TARGET_BYTES < max_bytes {
219 SESSIONS_TARGET_BYTES
220 } else {
221 max_bytes / SESSION_TARGET_DENOMINATOR * SESSION_TARGET_NUMERATOR
222 }
223 });
224 AgentSessions::new(
225 self.enabled.value().copied().unwrap_or(true),
226 max_bytes,
227 target_bytes,
228 )
229 }
230}
231
232fn location(path: &Path, message: impl std::fmt::Display) -> String {
233 format!("{}: {message}", crate::platform::path_text(path))
234}
235
236fn read_declared(path: &Path) -> Result<Declared, String> {
237 let too_large = || {
238 location(
239 path,
240 "limits.json must be a regular file no larger than 64 KiB.",
241 )
242 };
243 let file = match crate::platform::open_regular(path) {
244 Ok(file) => file,
245 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
246 return Ok(Declared::default());
247 }
248 Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {
249 return Err(too_large());
250 }
251 Err(error) => return Err(location(path, error)),
252 };
253 let mut text = String::new();
254 std::io::Read::read_to_string(&mut std::io::Read::take(&file, MAX_BYTES + 1), &mut text)
255 .map_err(|error| location(path, error))?;
256 if text.len() as u64 > MAX_BYTES {
257 return Err(too_large());
258 }
259 serde_json::from_str(&text).map_err(|error| {
260 let message = error.to_string();
261 let message = if message.starts_with("backends:") || message.starts_with("backends.") {
264 message
265 .strip_suffix(&format!(
266 " at line {} column {}",
267 error.line(),
268 error.column()
269 ))
270 .unwrap_or(&message)
271 } else {
272 &message
273 };
274 location(path, message)
275 })
276}
277
278impl Limits {
279 pub fn read(state: &Path) -> Result<Self, String> {
283 let path = state.join(FILE);
284 read_declared(&path)?
285 .resolve(None)
286 .map_err(|error| location(&path, error))
287 }
288
289 pub fn set_signoff_idle_grace(state: &Path, grace: Duration) -> Result<Self, String> {
293 if grace > MAX_SIGNOFF_IDLE_GRACE || grace.subsec_nanos() != 0 {
294 return Err(format!(
295 "The sign-off idle grace must be whole seconds, at most {}.",
296 MAX_SIGNOFF_IDLE_GRACE.as_secs()
297 ));
298 }
299 let path = state.join(FILE);
300 let mut declared = read_declared(&path)?;
301 let limits = declared
302 .resolve(Some(grace))
303 .map_err(|error| location(&path, error))?;
304 let mut text =
305 serde_json::to_vec_pretty(&declared).map_err(|error| location(&path, error))?;
306 text.push(b'\n');
307 if text.len() as u64 > MAX_BYTES {
308 return Err(location(
309 &path,
310 "limits.json must be no larger than 64 KiB.",
311 ));
312 }
313 crate::platform::create_private_dir_all(state).map_err(|error| location(&path, error))?;
314 let mut file =
315 tempfile::NamedTempFile::new_in(state).map_err(|error| location(&path, error))?;
316 file.write_all(&text)
317 .map_err(|error| location(&path, error))?;
318 crate::platform::paths::replace_open_file(file, &path)
319 .map_err(|error| location(&path, error))?;
320 Ok(limits)
321 }
322
323 pub fn limit(&self, backend: &Backend) -> Option<u32> {
325 self.backends.get(backend).copied()
326 }
327
328 pub fn backends(&self) -> &BTreeMap<Backend, u32> {
329 &self.backends
330 }
331
332 pub fn agent_sessions(&self) -> AgentSessions {
333 self.agent_sessions
334 }
335
336 pub fn signoff_idle_grace(&self) -> Duration {
338 self.signoff_idle_grace
339 }
340}
341
342#[cfg(test)]
343mod tests;