artifactize_core/agent/session/
gc.rs1use std::{collections::BTreeSet, fs::File, path::Path, time::SystemTime};
6
7use rusqlite::OpenFlags;
8use serde::Serialize;
9
10use super::directory;
11use crate::{limits::AgentSessions, store::DATABASE, types::SessionId};
12
13#[derive(Debug, Default, Clone, Serialize)]
15#[serde(rename_all = "camelCase")]
16pub struct Collection {
17 pub bytes: u64,
19 pub remaining: u64,
21 pub removed: Vec<SessionId>,
23}
24
25#[derive(Debug, Default, Clone, Copy, Serialize)]
27pub struct Usage {
28 pub sessions: usize,
29 pub bytes: u64,
30}
31
32struct Entry {
33 id: SessionId,
34 bytes: u64,
35 written: SystemTime,
36}
37
38fn entries(state: &Path) -> Result<Vec<Entry>, String> {
40 let directory = directory(state);
41 let handle = match crate::platform::open_no_follow(File::options().read(true), &directory) {
42 Ok(handle) => handle,
43 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
44 Err(error) => {
45 return Err(format!(
46 "{}: {error}",
47 crate::platform::path_text(&directory)
48 ));
49 }
50 };
51 let listing = crate::platform::read_dir(&handle).map_err(|e| e.to_string())?;
52 let mut entries = Vec::new();
53 for entry in listing {
54 let entry = entry.map_err(|e| e.to_string())?;
55 let name = entry.file_name();
56 let Some(id) = crate::platform::os_text(&name).and_then(|name| name.strip_suffix(".jsonl"))
57 else {
58 continue;
59 };
60 let Ok(id) = id.parse::<SessionId>() else {
61 continue;
63 };
64 if crate::platform::entry_kind(&handle, &name).map_err(|e| e.to_string())?
65 != crate::platform::FileKind::File
66 {
67 continue;
68 }
69 let name = crate::platform::EntryName::new(&name).ok_or("Invalid session entry name.")?;
70 let file = crate::platform::open_entry(&handle, &name).map_err(|e| e.to_string())?;
71 let metadata = file.metadata().map_err(|e| e.to_string())?;
72 if !metadata.is_file() {
73 continue;
74 }
75 let written = metadata.modified().map_err(|e| e.to_string())?;
76 #[cfg(test)]
78 let written = tests::written(state, &id).unwrap_or(written);
79 entries.push(Entry {
80 id,
81 bytes: metadata.len(),
82 written,
83 });
84 }
85 Ok(entries)
86}
87
88fn order(entries: &mut [Entry]) {
90 entries.sort_by(|a, b| a.written.cmp(&b.written).then_with(|| a.id.cmp(&b.id)));
91}
92
93pub fn usage(state: &Path) -> Result<Usage, String> {
95 let entries = entries(state)?;
96 Ok(Usage {
97 sessions: entries.len(),
98 bytes: entries.iter().map(|entry| entry.bytes).sum(),
99 })
100}
101
102fn running(state: &Path) -> Result<BTreeSet<SessionId>, String> {
104 crate::store::check_probe_files(state)?;
105 let database = state.join(DATABASE);
106 if !crate::platform::paths::target_exists(&database).map_err(|e| e.to_string())? {
107 return Ok(BTreeSet::new());
108 }
109 let read = || -> Result<BTreeSet<SessionId>, rusqlite::Error> {
110 let db =
111 rusqlite::Connection::open_with_flags(&database, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
112 crate::store::wait_when_busy(&db)?;
113 let initialized: bool = db.query_row(
114 "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='requests')",
115 [],
116 |row| row.get(0),
117 )?;
118 if !initialized {
119 return Ok(BTreeSet::new());
120 }
121 let mut statement = db.prepare(
122 "SELECT json_extract(data,'$.sessionId') FROM requests WHERE status='RUNNING' AND json_extract(data,'$.sessionId') IS NOT NULL",
123 )?;
124 statement
125 .query_map([], |row| row.get::<_, SessionId>(0))?
126 .collect()
127 };
128 read().map_err(|e| format!("Cannot read running Agent reviews: {e}"))
129}
130
131pub fn collect(state: &Path, bounds: AgentSessions, dry_run: bool) -> Result<Collection, String> {
135 let publisher = if dry_run {
136 crate::changes::Publisher::default()
137 } else {
138 crate::changes::Publisher::new(state)
139 };
140 let mut entries = entries(state)?;
141 let bytes = entries.iter().map(|entry| entry.bytes).sum();
142 let mut collection = Collection {
143 bytes,
144 remaining: bytes,
145 removed: Vec::new(),
146 };
147 if bytes <= bounds.max_bytes() {
148 return Ok(collection);
149 }
150 let running = running(state)?;
151 order(&mut entries);
152 let directory = directory(state);
153 for entry in entries {
154 if collection.remaining <= bounds.target_bytes() {
155 break;
156 }
157 if running.contains(&entry.id) {
158 continue;
159 }
160 if !dry_run {
161 let lock = directory.join(format!("{}.lock", entry.id));
162 let held = match crate::platform::open_no_follow(
164 File::options().read(true).write(true),
165 &lock,
166 ) {
167 Ok(file) => match crate::platform::paths::try_lock(&file) {
168 Ok(()) => Some(file),
169 Err(std::fs::TryLockError::WouldBlock) => continue,
170 Err(std::fs::TryLockError::Error(error)) => return Err(error.to_string()),
171 },
172 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
173 Err(error) => return Err(error.to_string()),
174 };
175 match crate::platform::paths::remove_open_file(
176 &directory.join(format!("{}.jsonl", entry.id)),
177 ) {
178 Ok(()) => {
179 publisher.notify(crate::changes::Change::SessionInvalidated(entry.id.clone()))
180 }
181 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
182 Err(error) => {
183 return Err(format!("Cannot remove Agent session {}: {error}", entry.id));
184 }
185 }
186 if held.is_some() {
187 let _ = crate::platform::paths::remove_open_file(&lock);
188 }
189 }
190 collection.remaining = collection.remaining.saturating_sub(entry.bytes);
191 collection.removed.push(entry.id);
192 }
193 Ok(collection)
194}
195
196#[cfg(test)]
197mod tests;