返回 CodeWhale
spool.rs
根目录 / crates / telemetry / src / spool.rs
1 //! Per-process spool files and the once-only recovery of dead processes' spools.
2 //!
3 //! Known limitation: a spool is only as trustworthy as the user account, like
4 //! every other file here. Recovery therefore re-validates the header and every
5 //! event as untrusted input instead of inheriting any bound.
6
7 use std::collections::BTreeSet;
8 use std::fs::{self, File, OpenOptions};
9 use std::path::{Path, PathBuf};
10 use std::time::{Duration, SystemTime};
11
12 use serde::{Deserialize, Serialize};
13
14 use crate::buffer;
15 use crate::event::{NOTICE_VERSION, SCHEMA_VERSION, Surface, is_release_version_string};
16
17 /// Dead spools sent at one start. Older or surplus ones are deleted unsent.
18 pub const MAX_RECOVERED: usize = 4;
19 /// A dead spool older than this is deleted unsent.
20 pub const MAX_AGE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
21
22 const HEADER_VERSION: u32 = 1;
23 const MAX_VERSION_BYTES: usize = 64;
24
25 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26 #[serde(deny_unknown_fields)]
27 pub(crate) struct SpoolContext {
28 spool: u32,
29 pub schema_version: u32,
30 pub notice_version: u32,
31 pub app_version: String,
32 pub git_sha: Option<String>,
33 pub surface: Surface,
34 pub tty: bool,
35 }
36
37 impl SpoolContext {
38 pub(crate) fn new(
39 surface: Surface,
40 app_version: String,
41 git_sha: Option<String>,
42 tty: bool,
43 ) -> Self {
44 Self {
45 spool: HEADER_VERSION,
46 schema_version: SCHEMA_VERSION,
47 notice_version: NOTICE_VERSION,
48 app_version,
49 git_sha,
50 surface,
51 tty,
52 }
53 }
54
55 pub(crate) fn is_sendable(&self) -> bool {
56 self.spool == HEADER_VERSION
57 && self.schema_version == SCHEMA_VERSION
58 && self.notice_version == NOTICE_VERSION
59 && self.app_version.len() <= MAX_VERSION_BYTES
60 && is_release_version_string(&self.app_version)
61 && self.git_sha.as_deref().is_none_or(|sha| {
62 sha.len() == 12 && sha.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
63 })
64 }
65 }
66
67 pub(crate) fn is_header_line(line: &str) -> bool {
68 serde_json::from_str::<SpoolContext>(line).is_ok()
69 }
70
71 /// `$CODEWHALE_HOME/telemetry/spool`.
72 #[must_use]
73 pub fn dir(root: &Path) -> PathBuf {
74 root.join("spool")
75 }
76
77 /// Every spool data file under `root`, for tests and diagnostics.
78 #[must_use]
79 pub fn data_files(root: &Path) -> Vec<PathBuf> {
80 let Ok(entries) = fs::read_dir(dir(root)) else {
81 return Vec::new();
82 };
83 let mut files: Vec<PathBuf> = entries
84 .filter_map(Result::ok)
85 .map(|entry| entry.path())
86 .filter(|path| path.extension().is_some_and(|ext| ext == "jsonl"))
87 .collect();
88 files.sort();
89 files
90 }
91
92 fn data_path(root: &Path, nonce: &str) -> PathBuf {
93 dir(root).join(format!("{nonce}.jsonl"))
94 }
95
96 fn lock_file_path(root: &Path, nonce: &str) -> PathBuf {
97 dir(root).join(format!("{nonce}.lock"))
98 }
99
100 fn is_nonce(value: &str) -> bool {
101 value.len() == 32
102 && value
103 .bytes()
104 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
105 }
106
107 fn open_lock_file(path: &Path) -> Option<File> {
108 OpenOptions::new()
109 .create(true)
110 .read(true)
111 .write(true)
112 .truncate(false)
113 .open(path)
114 .ok()
115 }
116
117 fn hold_lock(path: &Path) -> bool {
118 let Some(file) = open_lock_file(path) else {
119 return false;
120 };
121 let lock = Box::leak(Box::new(fd_lock::RwLock::new(file)));
122 match lock.try_write() {
123 Ok(guard) => {
124 std::mem::forget(guard);
125 true
126 }
127 Err(_) => false,
128 }
129 }
130
131 pub(crate) fn open(root: &Path, context: &SpoolContext) -> (PathBuf, String) {
132 let nonce = uuid::Uuid::new_v4().simple().to_string();
133 let path = data_path(root, &nonce);
134 if buffer::ensure_dir(&dir(root)).is_ok()
135 && hold_lock(&lock_file_path(root, &nonce))
136 && let Ok(header) = serde_json::to_string(context)
137 {
138 let _ = buffer::with_lock(root, || buffer::append_header(root, &path, &header));
139 }
140 (path, nonce)
141 }
142
143 #[must_use]
144 pub(crate) fn take_own(root: &Path, path: &Path) -> Vec<String> {
145 if buffer::tombstone_present(root) {
146 return Vec::new();
147 }
148 buffer::try_with_lock_in_turn(root, || {
149 if buffer::tombstone_present(root) {
150 return Ok(Vec::new());
151 }
152 let lines = buffer::read_lines(path);
153 if lines.is_empty() {
154 return Ok(lines);
155 }
156 if remove_or_truncate(path) {
157 Ok(lines)
158 } else {
159 Ok(Vec::new())
160 }
161 })
162 .ok()
163 .flatten()
164 .unwrap_or_default()
165 }
166
167 fn remove_or_truncate(path: &Path) -> bool {
168 fs::remove_file(path).is_ok() || buffer::truncate(path).is_ok_and(|()| !path.exists())
169 }
170
171 #[derive(Debug)]
172 pub(crate) struct Recovered {
173 pub context: SpoolContext,
174 pub lines: Vec<String>,
175 }
176
177 pub(crate) fn take_dead(root: &Path, own_nonce: &str, now: SystemTime) -> Vec<Recovered> {
178 let Ok(entries) = fs::read_dir(dir(root)) else {
179 return Vec::new();
180 };
181 let mut stems = BTreeSet::new();
182 for entry in entries.filter_map(Result::ok) {
183 let name = entry.file_name();
184 let Some(name) = name.to_str() else { continue };
185 if let Some((stem, ext)) = name.rsplit_once('.')
186 && matches!(ext, "jsonl" | "lock")
187 && is_nonce(stem)
188 && stem != own_nonce
189 {
190 stems.insert(stem.to_string());
191 }
192 }
193 let mut ranked: Vec<(SystemTime, String)> = stems
194 .into_iter()
195 .map(|stem| {
196 let modified = [data_path(root, &stem), lock_file_path(root, &stem)]
197 .iter()
198 .find_map(|path| fs::symlink_metadata(path).and_then(|m| m.modified()).ok())
199 .unwrap_or(SystemTime::UNIX_EPOCH);
200 (modified, stem)
201 })
202 .collect();
203 ranked.sort_by(|a, b| b.cmp(a));
204
205 let mut recovered = Vec::new();
206 for (modified, stem) in ranked {
207 if buffer::tombstone_present(root) {
208 break;
209 }
210 let data = data_path(root, &stem);
211 let lock_path = lock_file_path(root, &stem);
212 let eligible = recovered.len() < MAX_RECOVERED
213 && now.duration_since(modified).is_ok_and(|age| age <= MAX_AGE);
214 let claimed = with_dead_lock(&lock_path, || {
215 let claimed = if eligible { claim(&data) } else { None };
216 if claimed.is_none() {
217 let _ = fs::remove_file(&data);
218 }
219 let _ = fs::remove_file(&lock_path);
220 claimed
221 });
222 if let Some(Some(claimed)) = claimed {
223 recovered.push(claimed);
224 }
225 }
226 recovered
227 }
228
229 fn with_dead_lock<T>(lock_path: &Path, operation: impl FnOnce() -> T) -> Option<T> {
230 let file = open_lock_file(lock_path)?;
231 let mut lock = fd_lock::RwLock::new(file);
232 let _guard = lock.try_write().ok()?;
233 Some(operation())
234 }
235
236 fn claim(data: &Path) -> Option<Recovered> {
237 let meta = fs::symlink_metadata(data).ok()?;
238 if !meta.is_file() {
239 return None;
240 }
241 let lines = buffer::read_lines(data);
242 let (header, events) = lines.split_first()?;
243 let context = serde_json::from_str::<SpoolContext>(header).ok()?;
244 if !context.is_sendable() || events.is_empty() || !remove_or_truncate(data) {
245 return None;
246 }
247 Some(Recovered {
248 context,
249 lines: events.to_vec(),
250 })
251 }
252
252 lines RUST