session_activity/
store.rs1use std::fs::{self, OpenOptions};
2use std::io::{Read, Write};
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use anyhow::{Context, Result, ensure};
8
9use crate::{Agent, FileEvent, SessionKey};
10
11pub(crate) const MAX_BATCH_BYTES: u64 = 16 * 1024 * 1024;
12
13#[derive(Debug, Default)]
14pub struct ReadReport {
15 pub events: Vec<FileEvent>,
16 pub warnings: Vec<BatchWarning>,
17}
18
19#[derive(Debug, Default)]
20pub struct SessionReport {
21 pub sessions: Vec<SessionKey>,
22 pub warnings: Vec<BatchWarning>,
23}
24
25#[derive(Debug)]
26pub struct BatchWarning {
27 pub path: PathBuf,
28 pub message: String,
29}
30
31static NEXT_BATCH: AtomicU64 = AtomicU64::new(0);
32
33#[derive(Clone, Debug)]
37pub struct Store {
38 root: PathBuf,
39}
40
41impl Store {
42 pub fn new(root: impl Into<PathBuf>) -> Self {
43 Self { root: root.into() }
44 }
45
46 pub(crate) fn directory(&self, session: &SessionKey) -> Result<PathBuf> {
47 session.validate()?;
48 Ok(self.root.join(session.agent.slug()).join(&session.session_id))
49 }
50
51 pub fn sessions(&self) -> SessionReport {
54 let mut report = SessionReport::default();
55 for agent in [Agent::Claude, Agent::Codex] {
56 let path = self.root.join(agent.slug());
57 let entries = (|| -> Result<Option<fs::ReadDir>> {
58 let metadata = match fs::symlink_metadata(&path) {
59 Ok(metadata) => metadata,
60 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
61 Err(e) => return Err(e.into()),
62 };
63 ensure!(metadata.is_dir(), "agent namespace must be a directory, not a symlink");
64 Ok(Some(fs::read_dir(&path)?))
65 })();
66 let entries = match entries {
67 Ok(Some(entries)) => entries,
68 Ok(None) => continue,
69 Err(error) => {
70 report.warnings.push(BatchWarning { path, message: format!("{error:#}") });
71 continue;
72 }
73 };
74 for entry in entries {
75 let entry = match entry {
76 Ok(entry) => entry,
77 Err(error) => {
78 report.warnings.push(BatchWarning { path: path.clone(), message: error.to_string() });
79 continue;
80 }
81 };
82 let result = (|| -> Result<Option<SessionKey>> {
83 let kind = entry.file_type()?;
84 ensure!(!kind.is_symlink(), "session directory symlinks are not followed");
85 if !kind.is_dir() {
86 return Ok(None);
87 }
88 let session_id = entry
89 .file_name()
90 .into_string()
91 .map_err(|_| anyhow::anyhow!("invalid session directory name"))?;
92 let key = SessionKey { agent, session_id };
93 key.validate()?;
94 Ok(Some(key))
95 })();
96 match result {
97 Ok(Some(key)) => report.sessions.push(key),
98 Ok(None) => {}
99 Err(error) => {
100 report.warnings.push(BatchWarning { path: entry.path(), message: format!("{error:#}") })
101 }
102 }
103 }
104 }
105 report
106 .sessions
107 .sort_by(|a, b| a.agent.slug().cmp(b.agent.slug()).then_with(|| a.session_id.cmp(&b.session_id)));
108 report
109 }
110
111 pub fn read_all(&self) -> ReadReport {
115 let sessions = self.sessions();
116 let mut report = ReadReport { events: Vec::new(), warnings: sessions.warnings };
117 for key in sessions.sessions {
118 match self.read(&key) {
119 Ok(mut read) => {
120 report.events.append(&mut read.events);
121 report.warnings.append(&mut read.warnings);
122 }
123 Err(error) => report.warnings.push(BatchWarning {
124 path: self.root.join(key.agent.slug()).join(&key.session_id),
125 message: format!("{error:#}"),
126 }),
127 }
128 }
129 report.events.sort_by_key(|e| e.timestamp);
130 report
131 }
132
133 pub fn append(&self, session: &SessionKey, events: &[FileEvent]) -> Result<()> {
134 let dir = self.directory(session)?;
135 if events.is_empty() {
136 return Ok(());
137 }
138 validate_batch(session, events)?;
139 let missing: Vec<_> =
140 dir.ancestors().take_while(|p| !p.as_os_str().is_empty() && !p.exists()).map(Path::to_path_buf).collect();
141 let mut builder = fs::DirBuilder::new();
142 builder.recursive(true);
143 #[cfg(unix)]
144 {
145 use std::os::unix::fs::DirBuilderExt;
146 builder.mode(0o700);
147 }
148 builder.create(&dir)?;
149 for path in missing {
151 sync_directory(&path)?;
152 if let Some(parent) = path.parent() {
153 sync_directory(if parent.as_os_str().is_empty() { Path::new(".") } else { parent })?;
154 }
155 }
156 let _lock = crate::lock::Lock::acquire(&dir, false)?;
157 let cutoff = crate::maintenance::retained_from(&dir)?;
158 let retained: Vec<_> = events.iter().filter(|e| cutoff.is_none_or(|at| e.timestamp >= at)).collect();
159 if retained.is_empty() {
160 return Ok(());
161 }
162 let bytes = serde_json::to_vec(&retained)?;
163 ensure!(bytes.len() as u64 <= MAX_BATCH_BYTES, "activity batch exceeds 16 MiB limit");
164 let nonce = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
165 let name = format!("{nonce:039}-{}-{}", std::process::id(), NEXT_BATCH.fetch_add(1, Ordering::Relaxed));
166 let temporary = dir.join(format!("{name}.tmp"));
167 let destination = dir.join(format!("{name}.json"));
168 let result = write_batch(&temporary, &bytes).and_then(|()| {
169 fs::rename(&temporary, destination).context("publishing activity batch")?;
170 sync_directory(&dir)
171 });
172 if result.is_err() {
173 let _ = fs::remove_file(&temporary);
174 }
175 result
176 }
177
178 pub fn events(&self, session: &SessionKey) -> Result<Vec<FileEvent>> {
180 let report = self.read(session)?;
181 ensure!(
182 report.warnings.is_empty(),
183 "incomplete activity history: {}",
184 report
185 .warnings
186 .iter()
187 .map(|w| format!("{}: {}", w.path.display(), w.message))
188 .collect::<Vec<_>>()
189 .join("; ")
190 );
191 Ok(report.events)
192 }
193
194 pub fn read(&self, session: &SessionKey) -> Result<ReadReport> {
197 let dir = self.directory(session)?;
198 if !dir.try_exists()? {
199 return Ok(ReadReport::default());
200 }
201 let _lock = crate::lock::Lock::acquire(&dir, false)?;
202 self.read_unlocked(session)
203 }
204
205 pub(crate) fn read_unlocked(&self, session: &SessionKey) -> Result<ReadReport> {
206 let dir = self.directory(session)?;
207 let paths = crate::maintenance::active_paths(&dir)?;
208 let mut report = ReadReport::default();
209 for path in paths {
210 match read_batch(&path, session) {
211 Ok(batch) => report.events.extend(batch),
212 Err(error) => report.warnings.push(BatchWarning { path, message: format!("{error:#}") }),
213 }
214 }
215 report.events.sort_by_key(|e| e.timestamp);
216 if let Some(cutoff) = crate::maintenance::retained_from(&dir)? {
217 report.events.retain(|event| event.timestamp >= cutoff);
218 }
219 Ok(report)
220 }
221}
222
223pub(crate) fn write_batch(path: &Path, bytes: &[u8]) -> Result<()> {
224 let mut options = OpenOptions::new();
225 options.write(true).create_new(true);
226 #[cfg(unix)]
227 {
228 use std::os::unix::fs::OpenOptionsExt;
229 options.mode(0o600);
230 }
231 let mut file = options.open(path)?;
232 file.write_all(bytes)?;
233 file.sync_all()?;
234 Ok(())
235}
236
237fn validate_batch(session: &SessionKey, events: &[FileEvent]) -> Result<()> {
238 for event in events {
239 ensure!(&event.session == session, "event belongs to a different session");
240 ensure!(event.schema_version == 1, "unsupported activity schema");
241 ensure!(event.path.is_absolute() && event.cwd.is_absolute(), "event paths must be absolute");
242 ensure!(event.previous_path.as_ref().is_none_or(|p| p.is_absolute()), "rename origin must be absolute");
243 ensure!(
244 (event.operation == crate::Operation::Rename) == event.previous_path.is_some(),
245 "rename operation and origin must agree"
246 );
247 }
248 Ok(())
249}
250
251fn read_batch(path: &Path, session: &SessionKey) -> Result<Vec<FileEvent>> {
252 ensure!(fs::symlink_metadata(path)?.file_type().is_file(), "batch must be a regular file");
253 let mut bytes = Vec::new();
254 fs::File::open(path)?.take(MAX_BATCH_BYTES + 1).read_to_end(&mut bytes)?;
255 ensure!(bytes.len() as u64 <= MAX_BATCH_BYTES, "activity batch exceeds 16 MiB limit");
256 let events = serde_json::from_slice::<Vec<FileEvent>>(&bytes)?;
257 validate_batch(session, &events)?;
258 Ok(events)
259}
260
261pub(crate) fn sync_directory(path: &Path) -> Result<()> {
262 #[cfg(unix)]
263 fs::File::open(path)?.sync_all().with_context(|| format!("syncing {}", path.display()))?;
264 #[cfg(not(unix))]
265 let _ = path;
266 Ok(())
267}