1use std::{collections::BTreeMap, io::Write, path::Path, time::Duration};
14
15use serde::{Deserialize, Serialize};
16
17use crate::config::{Backend, Field};
18#[cfg(test)]
19mod backend_tests;
20
21pub const FILE: &str = "limits.json";
22const MAX_BYTES: u64 = 64 * 1024;
24const MAX_SLOTS: u32 = 100_000;
27pub const SESSIONS_MAX_BYTES: u64 = 1024 * 1024 * 1024;
29pub const SESSIONS_TARGET_BYTES: u64 = 768 * 1024 * 1024;
31const SESSION_TARGET_NUMERATOR: u64 = 3;
34const SESSION_TARGET_DENOMINATOR: u64 = 4;
35pub const SIGNOFF_IDLE_GRACE: Duration = Duration::from_secs(120);
38pub const MAX_SIGNOFF_IDLE_GRACE: Duration = Duration::from_secs(24 * 60 * 60);
40const GRACE_FIELD: &str = "signoffIdleGraceSeconds";
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
46#[serde(rename_all = "camelCase")]
47pub struct Limits {
48 backends: BTreeMap<Backend, u32>,
49 agent_sessions: AgentSessions,
50 #[serde(rename = "signoffIdleGraceSeconds", serialize_with = "seconds")]
51 signoff_idle_grace: Duration,
52}
53
54fn seconds<S: serde::Serializer>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
55 serializer.serialize_u64(duration.as_secs())
56}
57
58impl Default for Limits {
59 fn default() -> Self {
60 Self {
61 backends: BTreeMap::new(),
62 agent_sessions: AgentSessions::default(),
63 signoff_idle_grace: SIGNOFF_IDLE_GRACE,
64 }
65 }
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
71#[serde(rename_all = "camelCase")]
72pub struct AgentSessions {
73 enabled: bool,
74 max_bytes: u64,
75 target_bytes: u64,
76}
77
78impl AgentSessions {
79 pub fn new(enabled: bool, max_bytes: u64, target_bytes: u64) -> Result<Self, String> {
80 if max_bytes == 0 {
81 return Err("agentSessions.maxBytes must be at least 1.".into());
82 }
83 if target_bytes >= max_bytes {
84 return Err(format!(
85 "agentSessions.targetBytes ({target_bytes}) must be lower than maxBytes ({max_bytes})."
86 ));
87 }
88 Ok(Self {
89 enabled,
90 max_bytes,
91 target_bytes,
92 })
93 }
94
95 pub fn enabled(&self) -> bool {
96 self.enabled
97 }
98
99 pub fn max_bytes(&self) -> u64 {
100 self.max_bytes
101 }
102
103 pub fn target_bytes(&self) -> u64 {
104 self.target_bytes
105 }
106}
107
108impl Default for AgentSessions {
109 fn default() -> Self {
110 Self::new(true, SESSIONS_MAX_BYTES, SESSIONS_TARGET_BYTES)
111 .expect("valid default session bounds")
112 }
113}
114
115#[derive(Default, Deserialize, Serialize)]
116#[serde(rename_all = "camelCase", deny_unknown_fields)]
117struct Declared {
118 #[serde(
119 default,
120 deserialize_with = "backend_limits",
121 skip_serializing_if = "Option::is_none"
122 )]
123 backends: Option<BTreeMap<Backend, u32>>,
124 #[serde(default, skip_serializing_if = "Field::missing")]
125 agent_sessions: Field<DeclaredSessions>,
126 #[serde(default, skip_serializing_if = "Field::missing")]
127 signoff_idle_grace_seconds: Field<u64>,
128}
129
130impl Declared {
131 fn resolve(&mut self, override_grace: Option<Duration>) -> Result<Limits, String> {
134 let agent_sessions = self
135 .agent_sessions
136 .value()
137 .map(DeclaredSessions::resolve)
138 .transpose()?
139 .unwrap_or_default();
140 let original_grace = self
141 .signoff_idle_grace_seconds
142 .value()
143 .copied()
144 .map(grace)
145 .transpose()?;
146 let signoff_idle_grace = match override_grace {
147 Some(grace) => {
148 self.signoff_idle_grace_seconds = Field::Value(grace.as_secs());
149 grace
150 }
151 None => original_grace.unwrap_or(SIGNOFF_IDLE_GRACE),
152 };
153 Ok(Limits {
154 backends: self.backends.clone().unwrap_or_default(),
155 agent_sessions,
156 signoff_idle_grace,
157 })
158 }
159}
160
161fn grace(seconds: u64) -> Result<Duration, String> {
163 let grace = Duration::from_secs(seconds);
164 if grace > MAX_SIGNOFF_IDLE_GRACE {
165 return Err(format!(
166 "{GRACE_FIELD} must be at most {}.",
167 MAX_SIGNOFF_IDLE_GRACE.as_secs()
168 ));
169 }
170 Ok(grace)
171}
172
173fn backend_limits<'de, D: serde::Deserializer<'de>>(
174 deserializer: D,
175) -> Result<Option<BTreeMap<Backend, u32>>, D::Error> {
176 let names = BTreeMap::<String, u32>::deserialize(deserializer)?;
179 names
180 .into_iter()
181 .map(|(name, limit)| {
182 let backend = name
183 .parse()
184 .map_err(|error| serde::de::Error::custom(format!("backends: {error}")))?;
185 if !(1..=MAX_SLOTS).contains(&limit) {
186 return Err(serde::de::Error::custom(format!(
187 "backends.{name} must be between 1 and {MAX_SLOTS}."
188 )));
189 }
190 Ok((backend, limit))
191 })
192 .collect::<Result<_, _>>()
193 .map(Some)
194}
195
196#[derive(Deserialize, Serialize)]
197#[serde(rename_all = "camelCase", deny_unknown_fields)]
198struct DeclaredSessions {
199 #[serde(default, skip_serializing_if = "Field::missing")]
200 enabled: Field<bool>,
201 #[serde(default, skip_serializing_if = "Field::missing")]
202 max_bytes: Field<u64>,
203 #[serde(default, skip_serializing_if = "Field::missing")]
204 target_bytes: Field<u64>,
205}
206
207impl DeclaredSessions {
208 fn resolve(&self) -> Result<AgentSessions, String> {
211 let max_bytes = self
212 .max_bytes
213 .value()
214 .copied()
215 .unwrap_or(SESSIONS_MAX_BYTES);
216 let target_bytes = self.target_bytes.value().copied().unwrap_or_else(|| {
217 if SESSIONS_TARGET_BYTES < max_bytes {
218 SESSIONS_TARGET_BYTES
219 } else {
220 max_bytes / SESSION_TARGET_DENOMINATOR * SESSION_TARGET_NUMERATOR
221 }
222 });
223 AgentSessions::new(
224 self.enabled.value().copied().unwrap_or(true),
225 max_bytes,
226 target_bytes,
227 )
228 }
229}
230
231fn location(path: &Path, message: impl std::fmt::Display) -> String {
232 format!("{}: {message}", crate::platform::path_text(path))
233}
234
235fn read_declared(path: &Path) -> Result<Declared, String> {
236 let too_large = || {
237 location(
238 path,
239 "limits.json must be a regular file no larger than 64 KiB.",
240 )
241 };
242 let file = match crate::platform::open_regular(path) {
243 Ok(file) => file,
244 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
245 return Ok(Declared::default());
246 }
247 Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {
248 return Err(too_large());
249 }
250 Err(error) => return Err(location(path, error)),
251 };
252 let mut text = String::new();
253 std::io::Read::read_to_string(&mut std::io::Read::take(&file, MAX_BYTES + 1), &mut text)
254 .map_err(|error| location(path, error))?;
255 if text.len() as u64 > MAX_BYTES {
256 return Err(too_large());
257 }
258 serde_json::from_str(&text).map_err(|error| {
259 let message = error.to_string();
260 let message = if message.starts_with("backends:") || message.starts_with("backends.") {
263 message
264 .strip_suffix(&format!(
265 " at line {} column {}",
266 error.line(),
267 error.column()
268 ))
269 .unwrap_or(&message)
270 } else {
271 &message
272 };
273 location(path, message)
274 })
275}
276
277impl Limits {
278 pub fn read(state: &Path) -> Result<Self, String> {
282 let path = state.join(FILE);
283 read_declared(&path)?
284 .resolve(None)
285 .map_err(|error| location(&path, error))
286 }
287
288 pub fn set_signoff_idle_grace(state: &Path, grace: Duration) -> Result<Self, String> {
292 if grace > MAX_SIGNOFF_IDLE_GRACE || grace.subsec_nanos() != 0 {
293 return Err(format!(
294 "The sign-off idle grace must be whole seconds, at most {}.",
295 MAX_SIGNOFF_IDLE_GRACE.as_secs()
296 ));
297 }
298 let path = state.join(FILE);
299 let mut declared = read_declared(&path)?;
300 let limits = declared
301 .resolve(Some(grace))
302 .map_err(|error| location(&path, error))?;
303 let mut text =
304 serde_json::to_vec_pretty(&declared).map_err(|error| location(&path, error))?;
305 text.push(b'\n');
306 if text.len() as u64 > MAX_BYTES {
307 return Err(location(
308 &path,
309 "limits.json must be no larger than 64 KiB.",
310 ));
311 }
312 crate::platform::create_private_dir_all(state).map_err(|error| location(&path, error))?;
313 let mut file =
314 tempfile::NamedTempFile::new_in(state).map_err(|error| location(&path, error))?;
315 file.write_all(&text)
316 .map_err(|error| location(&path, error))?;
317 crate::platform::paths::replace_open_file(file, &path)
318 .map_err(|error| location(&path, error))?;
319 Ok(limits)
320 }
321
322 pub fn limit(&self, backend: &Backend) -> Option<u32> {
324 self.backends.get(backend).copied()
325 }
326
327 pub fn backends(&self) -> &BTreeMap<Backend, u32> {
328 &self.backends
329 }
330
331 pub fn agent_sessions(&self) -> AgentSessions {
332 self.agent_sessions
333 }
334
335 pub fn signoff_idle_grace(&self) -> Duration {
337 self.signoff_idle_grace
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344 use std::fs;
345
346 fn read(text: &str) -> Result<Limits, String> {
347 let directory = crate::test_os::tempdir();
348 fs::write(directory.path().join(FILE), text).unwrap();
349 Limits::read(directory.path())
350 }
351
352 #[test]
353 fn agent_sessions_default_and_validate() {
354 assert_eq!(
355 read("{}").unwrap().agent_sessions(),
356 AgentSessions {
357 enabled: true,
358 max_bytes: 1_073_741_824,
359 target_bytes: 805_306_368,
360 }
361 );
362 assert_eq!(
363 read(r#"{"agentSessions":{"enabled":false}}"#)
364 .unwrap()
365 .agent_sessions(),
366 AgentSessions {
367 enabled: false,
368 max_bytes: 1_073_741_824,
369 target_bytes: 805_306_368,
370 }
371 );
372 assert_eq!(
373 read(r#"{"agentSessions":{"maxBytes":4000,"targetBytes":1000}}"#)
374 .unwrap()
375 .agent_sessions(),
376 AgentSessions {
377 enabled: true,
378 max_bytes: 4000,
379 target_bytes: 1000
380 }
381 );
382 assert_eq!(
384 read(r#"{"agentSessions":{"maxBytes":4000}}"#)
385 .unwrap()
386 .agent_sessions()
387 .target_bytes,
388 3000
389 );
390 for (max_bytes, target_bytes) in [(1, 0), (3, 0), (5, 3), (7, 3), (8, 6), (11, 6)] {
392 assert_eq!(
393 read(&format!(
394 r#"{{"agentSessions":{{"maxBytes":{max_bytes}}}}}"#
395 ))
396 .unwrap()
397 .agent_sessions()
398 .target_bytes,
399 target_bytes
400 );
401 }
402 assert_eq!(
403 read(r#"{"agentSessions":{"maxBytes":18446744073709551615}}"#)
404 .unwrap()
405 .agent_sessions()
406 .target_bytes,
407 805306368
408 );
409 for (text, error) in [
410 (
411 r#"{"agentSessions":{"maxBytes":100,"targetBytes":100}}"#,
412 "agentSessions.targetBytes (100) must be lower than maxBytes (100).",
413 ),
414 (
415 r#"{"agentSessions":{"targetBytes":2147483648}}"#,
416 "must be lower than maxBytes (1073741824)",
417 ),
418 (
419 r#"{"agentSessions":{"maxBytes":0}}"#,
420 "agentSessions.maxBytes must be at least 1.",
421 ),
422 (r#"{"agentSessions":{"maxbytes":10}}"#, "unknown field"),
423 (r#"{"agentSessions":{"maxBytes":-1}}"#, "invalid value"),
424 (r#"{"agentSessions":{"enabled":"no"}}"#, "invalid type"),
425 (r#"{"agentSessions":true}"#, "invalid type"),
426 ] {
427 let message = read(text).unwrap_err();
428 assert!(message.contains(error), "{text}: {message}");
429 assert!(message.contains(FILE), "{message}");
430 }
431 }
432
433 #[test]
434 fn signoff_idle_grace_defaults_validates_and_saves_beside_other_limits() {
435 assert_eq!(
436 read("{}").unwrap().signoff_idle_grace(),
437 Duration::from_secs(120)
438 );
439 assert_eq!(
440 read(r#"{"signoffIdleGraceSeconds":0}"#)
441 .unwrap()
442 .signoff_idle_grace(),
443 Duration::ZERO
444 );
445 for (text, error) in [
446 (
447 r#"{"signoffIdleGraceSeconds":86401}"#,
448 "must be at most 86400",
449 ),
450 (r#"{"signoffIdleGraceSeconds":-1}"#, "invalid value"),
451 (r#"{"signoffIdleGraceSeconds":"2m"}"#, "invalid type"),
452 ] {
453 let message = read(text).unwrap_err();
454 assert!(message.contains(error), "{text}: {message}");
455 }
456
457 let directory = crate::test_os::tempdir();
458 let state = directory.path().join("state");
459 let saved = Limits::set_signoff_idle_grace(&state, Duration::from_secs(300)).unwrap();
460 assert_eq!(saved.signoff_idle_grace(), Duration::from_secs(300));
461 fs::write(
462 state.join(FILE),
463 r#"{"backends":{"codex":4},"agentSessions":{"maxBytes":4000,"enabled":null}}"#,
464 )
465 .unwrap();
466 let saved = Limits::set_signoff_idle_grace(&state, Duration::ZERO).unwrap();
467 assert_eq!(saved.signoff_idle_grace(), Duration::ZERO);
468 assert_eq!(saved.limit(&crate::config::Provider::Codex.into()), Some(4));
469 assert_eq!(saved.agent_sessions().max_bytes, 4000);
470 assert_eq!(saved.agent_sessions().target_bytes, 3000);
471 assert_eq!(Limits::read(&state).unwrap(), saved);
472 let declared: serde_json::Value =
473 serde_json::from_slice(&fs::read(state.join(FILE)).unwrap()).unwrap();
474 assert_eq!(
475 declared,
476 serde_json::json!({
477 "backends": {"codex": 4}, "agentSessions": {"maxBytes": 4000, "enabled": null},
478 "signoffIdleGraceSeconds": 0,
479 })
480 );
481 assert!(
482 Limits::set_signoff_idle_grace(&state, Duration::from_secs(86401))
483 .unwrap_err()
484 .contains("at most 86400")
485 );
486 for invalid in [r#"{"unknown":1}"#, r#"{"signoffIdleGraceSeconds":86401}"#] {
487 fs::write(state.join(FILE), invalid).unwrap();
488 assert!(Limits::set_signoff_idle_grace(&state, Duration::ZERO).is_err());
489 assert_eq!(fs::read_to_string(state.join(FILE)).unwrap(), invalid);
490 }
491 }
492}