| 1 | //! The on-disk ring buffer, the tombstone, and the wipe. |
| 2 | //! |
| 3 | //! Everything lives under `$CODEWHALE_HOME/telemetry/`, created `0700`, with |
| 4 | //! every file `0600`: |
| 5 | //! |
| 6 | //! | file | role | |
| 7 | //! |---|---| |
| 8 | //! | `spool/<nonce>.jsonl` | one process's header line, then one JSON event per line, awaiting its flush | |
| 9 | //! | `spool/<nonce>.lock` | held exclusively by that process while it lives | |
| 10 | //! | `buffer.jsonl` | the pre-spool sink, only ever truncated now | |
| 11 | //! | `buffer.jsonl.lock` | the **privacy** lock, a sibling file; never a data file | |
| 12 | //! | `dryrun.jsonl` | the sink when the endpoint resolves empty, same ring policy | |
| 13 | //! | `state.json` | last version seen and last flush attempt | |
| 14 | //! | `install_id.json` | the random install id | |
| 15 | //! | `disabled` | the tombstone: present ⇒ nothing is appended, drained, or sent | |
| 16 | //! |
| 17 | //! Appends, compaction, delivery, identity/state writes, startup arming, and |
| 18 | //! wipe share one sibling lock. Threads of one process take turns on it; |
| 19 | //! between processes, runtime and exit paths take it with `try_write()`, and on |
| 20 | //! contention the event or batch is dropped. The panic hook and signal path |
| 21 | //! never wait, not even for a sibling thread. Only startup arming and the |
| 22 | //! user-requested wipe may wait for another process. That keeps the panic hook |
| 23 | //! and SIGINT path non-blocking while also making opt-out an ordering boundary — |
| 24 | //! after wipe returns, no pre-wipe writer or sender can still publish data. |
| 25 | //! |
| 26 | //! Appenders re-open per append, so a compaction rewrite cannot leave anyone |
| 27 | //! writing to a stale inode. |
| 28 | |
| 29 | use std::collections::HashMap; |
| 30 | use std::fs::{self, DirBuilder, File, OpenOptions}; |
| 31 | use std::io::{Read as _, Seek as _, SeekFrom, Write as _}; |
| 32 | use std::path::{Path, PathBuf}; |
| 33 | use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, TryLockError}; |
| 34 | use std::time::{Duration, Instant}; |
| 35 | |
| 36 | use anyhow::{Context, Result}; |
| 37 | |
| 38 | /// Newest events retained in either sink. |
| 39 | pub const MAX_EVENTS: usize = 512; |
| 40 | /// Byte ceiling for either sink. |
| 41 | pub const MAX_BYTES: u64 = 256 * 1024; |
| 42 | /// A single append must fit in one atomic `write(2)`. |
| 43 | pub const MAX_LINE_BYTES: usize = 4096; |
| 44 | |
| 45 | const PRIVACY_LOCK_BUDGET: Duration = Duration::from_secs(3); |
| 46 | const LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(25); |
| 47 | |
| 48 | /// Exact contents of the opt-out tombstone observed by a consent decision. |
| 49 | /// |
| 50 | /// A fresh nonce is written when a machine transitions into an opted-out |
| 51 | /// period. Arming may clear only the exact generation its decision observed, |
| 52 | /// so an older consent token cannot erase a newer opt-out. |
| 53 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 54 | pub(crate) struct TombstoneGeneration(Vec<u8>); |
| 55 | |
| 56 | const MAX_TOMBSTONE_BYTES: u64 = 128; |
| 57 | |
| 58 | /// Below this size a sink cannot possibly hold [`MAX_EVENTS`] lines, so an |
| 59 | /// append skips the count probe entirely. The shortest serializable event line |
| 60 | /// is well over 8 bytes, and `512 * 9 > 4096`, so this bound is safe by |
| 61 | /// construction — `probe_threshold_cannot_hide_an_over_cap_buffer` pins it. |
| 62 | const PROBE_BYTES: u64 = 4096; |
| 63 | |
| 64 | /// `buffer.jsonl` — the pending-event sink. |
| 65 | #[must_use] |
| 66 | pub fn buffer_path(root: &Path) -> PathBuf { |
| 67 | root.join("buffer.jsonl") |
| 68 | } |
| 69 | |
| 70 | /// `dryrun.jsonl` — where batches go when the endpoint resolves to `None`. |
| 71 | /// |
| 72 | /// Reached by configuring `telemetry_endpoint` empty; an unconfigured endpoint |
| 73 | /// resolves to `codewhale_config::DEFAULT_TELEMETRY_ENDPOINT` instead. |
| 74 | #[must_use] |
| 75 | pub fn dryrun_path(root: &Path) -> PathBuf { |
| 76 | root.join("dryrun.jsonl") |
| 77 | } |
| 78 | |
| 79 | /// `buffer.jsonl.lock` — the sibling lock file. Never the data file, and never |
| 80 | /// unlinked: replacing it would leave appenders and compactors holding |
| 81 | /// different inodes and serialising against nothing. |
| 82 | #[must_use] |
| 83 | pub fn lock_path(root: &Path) -> PathBuf { |
| 84 | root.join("buffer.jsonl.lock") |
| 85 | } |
| 86 | |
| 87 | /// `disabled` — the tombstone. |
| 88 | #[must_use] |
| 89 | pub fn tombstone_path(root: &Path) -> PathBuf { |
| 90 | root.join("disabled") |
| 91 | } |
| 92 | |
| 93 | /// `install_id.json`. |
| 94 | #[must_use] |
| 95 | pub fn install_id_path(root: &Path) -> PathBuf { |
| 96 | root.join("install_id.json") |
| 97 | } |
| 98 | |
| 99 | /// `state.json`. |
| 100 | #[must_use] |
| 101 | pub fn state_path(root: &Path) -> PathBuf { |
| 102 | root.join("state.json") |
| 103 | } |
| 104 | |
| 105 | /// Whether the tombstone is present. |
| 106 | /// |
| 107 | /// Re-checked on **every** append and immediately before **every** send. This is |
| 108 | /// what makes `codewhale config set telemetry false` — an external write by |
| 109 | /// another process — observable to a session that is already running. |
| 110 | #[must_use] |
| 111 | pub fn tombstone_present(root: &Path) -> bool { |
| 112 | tombstone_path(root).exists() |
| 113 | } |
| 114 | |
| 115 | /// Read the exact tombstone generation, or `None` when collection has never |
| 116 | /// been disabled in this home. |
| 117 | pub(crate) fn tombstone_generation(root: &Path) -> Result<Option<TombstoneGeneration>> { |
| 118 | let path = tombstone_path(root); |
| 119 | let file = match File::open(&path) { |
| 120 | Ok(file) => file, |
| 121 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 122 | Err(error) => { |
| 123 | return Err( |
| 124 | anyhow::Error::new(error).context(format!("failed to open {}", path.display())) |
| 125 | ); |
| 126 | } |
| 127 | }; |
| 128 | let mut bytes = Vec::new(); |
| 129 | file.take(MAX_TOMBSTONE_BYTES + 1) |
| 130 | .read_to_end(&mut bytes) |
| 131 | .with_context(|| format!("failed to read {}", path.display()))?; |
| 132 | if bytes.len() as u64 > MAX_TOMBSTONE_BYTES { |
| 133 | anyhow::bail!("{} exceeds the tombstone size limit", path.display()); |
| 134 | } |
| 135 | Ok(Some(TombstoneGeneration(bytes))) |
| 136 | } |
| 137 | |
| 138 | /// Create the telemetry directory `0700`, if it is missing. |
| 139 | pub fn ensure_dir(root: &Path) -> Result<()> { |
| 140 | if root.is_dir() { |
| 141 | return Ok(()); |
| 142 | } |
| 143 | let mut builder = DirBuilder::new(); |
| 144 | builder.recursive(true); |
| 145 | #[cfg(unix)] |
| 146 | { |
| 147 | use std::os::unix::fs::DirBuilderExt as _; |
| 148 | builder.mode(0o700); |
| 149 | } |
| 150 | builder |
| 151 | .create(root) |
| 152 | .with_context(|| format!("failed to create {}", root.display())) |
| 153 | } |
| 154 | |
| 155 | #[cfg(unix)] |
| 156 | fn secure(file: &File) -> Result<()> { |
| 157 | use std::os::unix::fs::PermissionsExt as _; |
| 158 | file.set_permissions(fs::Permissions::from_mode(0o600)) |
| 159 | .context("failed to restrict telemetry file permissions") |
| 160 | } |
| 161 | |
| 162 | #[cfg(not(unix))] |
| 163 | fn secure(_file: &File) -> Result<()> { |
| 164 | Ok(()) |
| 165 | } |
| 166 | |
| 167 | /// Append one serialized event or batch to `path`. |
| 168 | /// |
| 169 | /// Returns `None` — never an error — when the tombstone is present, the privacy |
| 170 | /// lock is held, the line would not fit in one atomic write, or any filesystem |
| 171 | /// step fails. The lock acquisition is non-blocking, including on the panic and |
| 172 | /// signal paths. |
| 173 | pub fn append(root: &Path, path: &Path, line: &str) -> Option<()> { |
| 174 | append_with_limit(root, path, line, MAX_LINE_BYTES, Turn::Never) |
| 175 | } |
| 176 | |
| 177 | pub(crate) fn append_in_turn(root: &Path, path: &Path, line: &str) -> Option<()> { |
| 178 | append_with_limit(root, path, line, MAX_LINE_BYTES, Turn::Wait) |
| 179 | } |
| 180 | |
| 181 | /// Append a line that is too large for one atomic `write(2)`, serialising |
| 182 | /// against other writers with the compaction lock instead. |
| 183 | /// |
| 184 | /// Only the dry-run sink uses this: a whole batch does not fit under |
| 185 | /// `PIPE_BUF`, and the flush path is neither the panic hook nor the signal |
| 186 | /// handler, so it may wait for a sibling thread. Another process holding the |
| 187 | /// lock still drops the batch, which is the same fail-open behavior as a failed |
| 188 | /// POST. |
| 189 | pub fn append_locked(root: &Path, path: &Path, line: &str) -> Option<()> { |
| 190 | append_with_limit(root, path, line, MAX_BYTES as usize, Turn::Wait) |
| 191 | } |
| 192 | |
| 193 | fn append_with_limit(root: &Path, path: &Path, line: &str, limit: usize, turn: Turn) -> Option<()> { |
| 194 | let bytes = line.as_bytes(); |
| 195 | if bytes.is_empty() || bytes.len() + 1 > limit { |
| 196 | return None; |
| 197 | } |
| 198 | |
| 199 | let mut buf = Vec::with_capacity(bytes.len() + 1); |
| 200 | buf.extend_from_slice(bytes); |
| 201 | buf.push(b'\n'); |
| 202 | |
| 203 | let operation = || append_under_lock(root, path, &buf); |
| 204 | let attempt = match turn { |
| 205 | Turn::Never => try_with_lock(root, operation), |
| 206 | Turn::Wait => try_with_lock_in_turn(root, operation), |
| 207 | }; |
| 208 | let wrote = attempt.ok().flatten().unwrap_or(false); |
| 209 | if !wrote { |
| 210 | return None; |
| 211 | } |
| 212 | |
| 213 | enforce_ring(root, path); |
| 214 | Some(()) |
| 215 | } |
| 216 | |
| 217 | /// Append bytes while the caller holds the sibling privacy lock. |
| 218 | fn append_under_lock(root: &Path, path: &Path, buf: &[u8]) -> Result<bool> { |
| 219 | if tombstone_present(root) { |
| 220 | return Ok(false); |
| 221 | } |
| 222 | let file = OpenOptions::new() |
| 223 | .create(true) |
| 224 | .append(true) |
| 225 | .open(path) |
| 226 | .with_context(|| format!("failed to open {}", path.display()))?; |
| 227 | secure(&file)?; |
| 228 | // One `write(2)`, not `write_fmt` and not two calls: a split write is what |
| 229 | // a concurrent appender would interleave with. |
| 230 | (&file) |
| 231 | .write_all(buf) |
| 232 | .with_context(|| format!("failed to append to {}", path.display()))?; |
| 233 | file.sync_data() |
| 234 | .with_context(|| format!("failed to sync {}", path.display()))?; |
| 235 | Ok(true) |
| 236 | } |
| 237 | |
| 238 | pub(crate) fn append_header(root: &Path, path: &Path, line: &str) -> Result<bool> { |
| 239 | let mut buf = Vec::with_capacity(line.len() + 1); |
| 240 | buf.extend_from_slice(line.as_bytes()); |
| 241 | buf.push(b'\n'); |
| 242 | append_under_lock(root, path, &buf) |
| 243 | } |
| 244 | |
| 245 | fn keep_spool_header(path: &Path, mut lines: Vec<String>) -> Vec<String> { |
| 246 | use std::io::BufRead as _; |
| 247 | let Ok(file) = File::open(path) else { |
| 248 | return lines; |
| 249 | }; |
| 250 | let mut first = String::new(); |
| 251 | if std::io::BufReader::new(file.take(MAX_LINE_BYTES as u64 + 2)) |
| 252 | .read_line(&mut first) |
| 253 | .is_err() |
| 254 | { |
| 255 | return lines; |
| 256 | } |
| 257 | let first = first.trim_end().to_string(); |
| 258 | if first.is_empty() || !crate::spool::is_header_line(&first) || lines.first() == Some(&first) { |
| 259 | return lines; |
| 260 | } |
| 261 | lines.insert(0, first); |
| 262 | let size = |lines: &[String]| lines.iter().map(|l| l.len() as u64 + 1).sum::<u64>(); |
| 263 | while lines.len() > 1 && (lines.len() > MAX_EVENTS || size(&lines) > MAX_BYTES) { |
| 264 | lines.remove(1); |
| 265 | } |
| 266 | lines |
| 267 | } |
| 268 | |
| 269 | /// Keep the newest [`MAX_EVENTS`] lines and at most [`MAX_BYTES`], under the |
| 270 | /// compaction lock. On lock contention this cycle is skipped: the next append |
| 271 | /// tries again, and the cap is a ceiling on disk footprint, not an invariant |
| 272 | /// that must hold at every instant. |
| 273 | fn enforce_ring(root: &Path, path: &Path) { |
| 274 | let Ok(meta) = fs::metadata(path) else { |
| 275 | return; |
| 276 | }; |
| 277 | let len = meta.len(); |
| 278 | if len < PROBE_BYTES { |
| 279 | return; |
| 280 | } |
| 281 | let _ = try_with_lock(root, || { |
| 282 | // Re-read under the same lock as wipe. Reusing a snapshot captured |
| 283 | // before a concurrent wipe would resurrect the records it truncated. |
| 284 | if tombstone_present(root) { |
| 285 | return Ok(()); |
| 286 | } |
| 287 | let Ok(meta) = fs::metadata(path) else { |
| 288 | return Ok(()); |
| 289 | }; |
| 290 | let len = meta.len(); |
| 291 | if len < PROBE_BYTES { |
| 292 | return Ok(()); |
| 293 | } |
| 294 | let lines = keep_spool_header(path, read_ring_tail(path)?); |
| 295 | let mut body = lines.join("\n"); |
| 296 | if !body.is_empty() { |
| 297 | body.push('\n'); |
| 298 | } |
| 299 | if body.len() as u64 == len { |
| 300 | return Ok(()); |
| 301 | } |
| 302 | rewrite(path, body.as_bytes()) |
| 303 | }); |
| 304 | } |
| 305 | |
| 306 | fn read_ring_tail(path: &Path) -> Result<Vec<String>> { |
| 307 | let mut file = |
| 308 | File::open(path).with_context(|| format!("failed to open {}", path.display()))?; |
| 309 | let metadata = file |
| 310 | .metadata() |
| 311 | .with_context(|| format!("failed to inspect {}", path.display()))?; |
| 312 | anyhow::ensure!( |
| 313 | metadata.is_file(), |
| 314 | "{} is not a regular telemetry sink", |
| 315 | path.display() |
| 316 | ); |
| 317 | let start = metadata.len().saturating_sub(MAX_BYTES); |
| 318 | let mut partial = false; |
| 319 | if start > 0 { |
| 320 | file.seek(SeekFrom::Start(start - 1))?; |
| 321 | let mut previous = [0]; |
| 322 | file.read_exact(&mut previous)?; |
| 323 | partial = previous[0] != b'\n'; |
| 324 | } |
| 325 | let mut bytes = Vec::with_capacity(metadata.len().min(MAX_BYTES) as usize); |
| 326 | (&mut file).take(MAX_BYTES).read_to_end(&mut bytes)?; |
| 327 | let contents = if partial { |
| 328 | bytes |
| 329 | .iter() |
| 330 | .position(|byte| *byte == b'\n') |
| 331 | .map_or(&[][..], |index| &bytes[index + 1..]) |
| 332 | } else { |
| 333 | &bytes |
| 334 | }; |
| 335 | let mut lines = Vec::new(); |
| 336 | let mut retained = 0; |
| 337 | for line in contents.split(|byte| *byte == b'\n').rev() { |
| 338 | let Ok(line) = std::str::from_utf8(line) else { |
| 339 | continue; |
| 340 | }; |
| 341 | let line = line.strip_suffix('\r').unwrap_or(line); |
| 342 | if line.trim().is_empty() { |
| 343 | continue; |
| 344 | } |
| 345 | let size = line.len() as u64 + 1; |
| 346 | if lines.len() == MAX_EVENTS || retained + size > MAX_BYTES { |
| 347 | break; |
| 348 | } |
| 349 | retained += size; |
| 350 | lines.push(line.to_string()); |
| 351 | } |
| 352 | lines.reverse(); |
| 353 | Ok(lines) |
| 354 | } |
| 355 | |
| 356 | fn sync_directory(dir: &Path) -> std::io::Result<()> { |
| 357 | #[cfg(unix)] |
| 358 | { |
| 359 | File::open(dir)?.sync_all()?; |
| 360 | } |
| 361 | #[cfg(not(unix))] |
| 362 | { |
| 363 | let _ = dir; |
| 364 | } |
| 365 | Ok(()) |
| 366 | } |
| 367 | |
| 368 | fn persist_atomic_with_sync( |
| 369 | path: &Path, |
| 370 | bytes: &[u8], |
| 371 | sync_file: impl FnOnce(&File) -> std::io::Result<()>, |
| 372 | sync_dir: impl FnOnce(&Path) -> std::io::Result<()>, |
| 373 | ) -> Result<()> { |
| 374 | let dir = path |
| 375 | .parent() |
| 376 | .filter(|parent| !parent.as_os_str().is_empty()) |
| 377 | .unwrap_or_else(|| Path::new(".")); |
| 378 | let mut tmp = tempfile::NamedTempFile::new_in(dir) |
| 379 | .with_context(|| format!("failed to stage {}", path.display()))?; |
| 380 | secure(tmp.as_file())?; |
| 381 | tmp.write_all(bytes) |
| 382 | .with_context(|| format!("failed to write {}", path.display()))?; |
| 383 | sync_file(tmp.as_file()).with_context(|| format!("failed to sync {}", path.display()))?; |
| 384 | tmp.persist(path) |
| 385 | .map_err(|error| error.error) |
| 386 | .with_context(|| format!("failed to persist {}", path.display()))?; |
| 387 | sync_dir(dir).with_context(|| format!("failed to sync directory {}", dir.display()))?; |
| 388 | Ok(()) |
| 389 | } |
| 390 | |
| 391 | fn persist_atomic(path: &Path, bytes: &[u8]) -> Result<()> { |
| 392 | persist_atomic_with_sync(path, bytes, File::sync_all, sync_directory) |
| 393 | } |
| 394 | |
| 395 | /// Replace `path` atomically through a sibling temp file in the same directory. |
| 396 | fn rewrite(path: &Path, bytes: &[u8]) -> Result<()> { |
| 397 | persist_atomic(path, bytes) |
| 398 | } |
| 399 | |
| 400 | /// Open (creating if needed) the sibling lock file. |
| 401 | fn open_lock(root: &Path) -> Result<File> { |
| 402 | ensure_dir(root)?; |
| 403 | let path = lock_path(root); |
| 404 | let file = OpenOptions::new() |
| 405 | .create(true) |
| 406 | .read(true) |
| 407 | .write(true) |
| 408 | // The file is only a lock handle; its contents are never read and |
| 409 | // truncating it would race other holders for no benefit. |
| 410 | .truncate(false) |
| 411 | .open(&path) |
| 412 | .with_context(|| format!("failed to open {}", path.display()))?; |
| 413 | secure(&file)?; |
| 414 | Ok(file) |
| 415 | } |
| 416 | |
| 417 | #[derive(Clone, Copy)] |
| 418 | enum Turn { |
| 419 | Never, |
| 420 | Wait, |
| 421 | } |
| 422 | |
| 423 | fn process_gate(root: &Path) -> Arc<Mutex<()>> { |
| 424 | static GATES: OnceLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> = OnceLock::new(); |
| 425 | GATES |
| 426 | .get_or_init(Mutex::default) |
| 427 | .lock() |
| 428 | .unwrap_or_else(PoisonError::into_inner) |
| 429 | .entry(root.to_path_buf()) |
| 430 | .or_default() |
| 431 | .clone() |
| 432 | } |
| 433 | |
| 434 | fn wait_turn(gate: &Mutex<()>) -> MutexGuard<'_, ()> { |
| 435 | gate.lock().unwrap_or_else(PoisonError::into_inner) |
| 436 | } |
| 437 | |
| 438 | fn try_flock<T>(root: &Path, operation: impl FnOnce() -> Result<T>) -> Result<Option<T>> { |
| 439 | let file = open_lock(root)?; |
| 440 | let mut lock = fd_lock::RwLock::new(file); |
| 441 | match lock.try_write() { |
| 442 | Ok(_guard) => operation().map(Some), |
| 443 | Err(_) => Ok(None), |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | fn with_flock<T>( |
| 448 | root: &Path, |
| 449 | timeout: Option<Duration>, |
| 450 | operation: impl FnOnce() -> Result<T>, |
| 451 | ) -> Result<T> { |
| 452 | let mut lock = fd_lock::RwLock::new(open_lock(root)?); |
| 453 | let Some(timeout) = timeout else { |
| 454 | let _guard = lock |
| 455 | .write() |
| 456 | .context("failed to acquire the telemetry privacy lock")?; |
| 457 | return operation(); |
| 458 | }; |
| 459 | let deadline = Instant::now() + timeout; |
| 460 | loop { |
| 461 | match lock.try_write() { |
| 462 | Ok(_guard) => return operation(), |
| 463 | Err(_) if Instant::now() < deadline => std::thread::sleep(LOCK_RETRY_INTERVAL), |
| 464 | Err(_) => anyhow::bail!("the telemetry compaction lock stayed busy"), |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | /// Run `operation` holding the exclusive compaction lock. |
| 470 | /// |
| 471 | /// Startup arming, the opt-out wipe, and the spool header write use this. |
| 472 | /// `flock` has no timeout of its own, so a suspended process holding the lock |
| 473 | /// would wedge every launch behind it; the wait is bounded by |
| 474 | /// `PRIVACY_LOCK_BUDGET` and a still-busy lock returns an error, which every |
| 475 | /// caller treats as skip-and-continue rather than fatal. |
| 476 | pub fn with_lock<T>(root: &Path, operation: impl FnOnce() -> Result<T>) -> Result<T> { |
| 477 | let gate = process_gate(root); |
| 478 | let _turn = wait_turn(&gate); |
| 479 | with_flock(root, Some(PRIVACY_LOCK_BUDGET), operation) |
| 480 | } |
| 481 | |
| 482 | /// Run `operation` holding the exclusive compaction lock if it is free. |
| 483 | /// |
| 484 | /// Returns `Ok(None)` when the lock is held elsewhere, by this process or |
| 485 | /// another. Never blocks. |
| 486 | pub fn try_with_lock<T>(root: &Path, operation: impl FnOnce() -> Result<T>) -> Result<Option<T>> { |
| 487 | let gate = process_gate(root); |
| 488 | let _turn = match gate.try_lock() { |
| 489 | Ok(turn) => turn, |
| 490 | Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), |
| 491 | Err(TryLockError::WouldBlock) => return Ok(None), |
| 492 | }; |
| 493 | try_flock(root, operation) |
| 494 | } |
| 495 | |
| 496 | pub(crate) fn try_with_lock_in_turn<T>( |
| 497 | root: &Path, |
| 498 | operation: impl FnOnce() -> Result<T>, |
| 499 | ) -> Result<Option<T>> { |
| 500 | let gate = process_gate(root); |
| 501 | let _turn = wait_turn(&gate); |
| 502 | try_flock(root, operation) |
| 503 | } |
| 504 | |
| 505 | /// Read the newest bounded tail from `path`, skipping invalid UTF-8 lines. |
| 506 | /// |
| 507 | /// `std::process::exit` on the signal path can truncate a concurrent write, so |
| 508 | /// the last line may be a partial JSON document. Skipping unparseable lines is |
| 509 | /// the whole tolerance: a drain must never fail because one record was cut. |
| 510 | #[must_use] |
| 511 | pub fn read_lines(path: &Path) -> Vec<String> { |
| 512 | read_ring_tail(path).unwrap_or_default() |
| 513 | } |
| 514 | |
| 515 | /// Truncate a file to zero length, leaving the inode in place. A missing file |
| 516 | /// is not an error. |
| 517 | pub fn truncate(path: &Path) -> Result<()> { |
| 518 | if !path.exists() { |
| 519 | return Ok(()); |
| 520 | } |
| 521 | let file = OpenOptions::new() |
| 522 | .write(true) |
| 523 | .truncate(true) |
| 524 | .open(path) |
| 525 | .with_context(|| format!("failed to truncate {}", path.display()))?; |
| 526 | secure(&file)?; |
| 527 | Ok(()) |
| 528 | } |
| 529 | |
| 530 | /// Wipe every trace of collection, leaving a permanent tombstone. |
| 531 | /// |
| 532 | /// Order matters and is the whole of the guarantee: |
| 533 | /// |
| 534 | /// 1. wait for an outstanding delivery to release the privacy lock; |
| 535 | /// 2. write the tombstone and keep it for the rest of this opted-out period; |
| 536 | /// 3. truncate `buffer.jsonl` and `dryrun.jsonl` — do **not** unlink them, and |
| 537 | /// never unlink the privacy lock file — and delete every spool; |
| 538 | /// 4. remove `install_id.json` and `state.json`. |
| 539 | /// |
| 540 | /// If any step after the tombstone fails, the error is returned and the caller |
| 541 | /// logs it — but the tombstone alone already makes the buffer permanently |
| 542 | /// undrainable, so a failed wipe fails **closed**. |
| 543 | pub fn wipe(root: &Path) -> Result<()> { |
| 544 | wipe_with_timeout(root, None) |
| 545 | } |
| 546 | |
| 547 | pub(crate) fn wipe_on_startup(root: &Path) -> Result<()> { |
| 548 | wipe_with_timeout(root, Some(PRIVACY_LOCK_BUDGET)) |
| 549 | } |
| 550 | |
| 551 | fn wipe_with_timeout(root: &Path, timeout: Option<Duration>) -> Result<()> { |
| 552 | let gate = process_gate(root); |
| 553 | let _turn = wait_turn(&gate); |
| 554 | match with_flock(root, timeout, || { |
| 555 | write_tombstone(root)?; |
| 556 | |
| 557 | let mut failure: Option<anyhow::Error> = None; |
| 558 | for path in [buffer_path(root), dryrun_path(root)] { |
| 559 | if let Err(error) = truncate(&path) { |
| 560 | failure.get_or_insert(error); |
| 561 | } |
| 562 | } |
| 563 | for path in [install_id_path(root), state_path(root)] { |
| 564 | if path.exists() |
| 565 | && let Err(error) = fs::remove_file(&path) |
| 566 | { |
| 567 | failure.get_or_insert( |
| 568 | anyhow::Error::new(error) |
| 569 | .context(format!("failed to remove {}", path.display())), |
| 570 | ); |
| 571 | } |
| 572 | } |
| 573 | if let Err(error) = fs::remove_dir_all(crate::spool::dir(root)) |
| 574 | && error.kind() != std::io::ErrorKind::NotFound |
| 575 | { |
| 576 | failure.get_or_insert(anyhow::Error::new(error).context("failed to remove the spools")); |
| 577 | } |
| 578 | match failure { |
| 579 | Some(error) => Err(error), |
| 580 | None => Ok(()), |
| 581 | } |
| 582 | }) { |
| 583 | Ok(()) => Ok(()), |
| 584 | Err(error) => { |
| 585 | write_tombstone(root)?; |
| 586 | Err(error) |
| 587 | } |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | fn write_tombstone(root: &Path) -> Result<()> { |
| 592 | let tombstone = tombstone_path(root); |
| 593 | // A tombstone generation identifies one durable opted-out period. Keep |
| 594 | // it stable across later launches that re-observe the same persistent |
| 595 | // choice; re-enable removes the file, so the next real opt-out creates |
| 596 | // a naturally distinct generation. An unreadable or oversized file is |
| 597 | // repaired in the fail-closed direction by replacing it here; legacy |
| 598 | // empty tombstones remain valid stable generations. |
| 599 | if tombstone_generation(root).ok().flatten().is_some() { |
| 600 | return Ok(()); |
| 601 | } |
| 602 | let generation = uuid::Uuid::new_v4().to_string(); |
| 603 | persist_atomic(&tombstone, generation.as_bytes()) |
| 604 | } |
| 605 | |
| 606 | /// Clear the tombstone, deleting every spool when there was one, and truncate |
| 607 | /// the pre-spool buffer. |
| 608 | /// |
| 609 | /// Called by `init` on every arming. Both the exact tombstone generation and a |
| 610 | /// fresh durable permission check must still match while the wipe lock is held. |
| 611 | /// A stale buffer left by an earlier run or by a bug cannot enter the new |
| 612 | /// process's batch. |
| 613 | pub(crate) fn arm( |
| 614 | root: &Path, |
| 615 | observed_generation: Option<&TombstoneGeneration>, |
| 616 | permission_still_enabled: impl Fn() -> bool, |
| 617 | ) -> Result<()> { |
| 618 | ensure_dir(root)?; |
| 619 | with_lock(root, || { |
| 620 | let current_generation = tombstone_generation(root)?; |
| 621 | if current_generation.as_ref() != observed_generation { |
| 622 | anyhow::bail!("telemetry permission changed before arming"); |
| 623 | } |
| 624 | if !permission_still_enabled() { |
| 625 | anyhow::bail!("telemetry permission is no longer enabled"); |
| 626 | } |
| 627 | let tombstone = tombstone_path(root); |
| 628 | if observed_generation.is_some() && tombstone.exists() { |
| 629 | if tombstone_generation(root)?.as_ref() != observed_generation { |
| 630 | anyhow::bail!("telemetry permission changed before arming"); |
| 631 | } |
| 632 | let _ = fs::remove_dir_all(crate::spool::dir(root)); |
| 633 | fs::remove_file(&tombstone) |
| 634 | .with_context(|| format!("failed to remove {}", tombstone.display()))?; |
| 635 | if !permission_still_enabled() { |
| 636 | let _ = write_tombstone(root); |
| 637 | anyhow::bail!("telemetry permission is no longer enabled"); |
| 638 | } |
| 639 | } |
| 640 | if tombstone.exists() { |
| 641 | anyhow::bail!("telemetry permission changed before arming"); |
| 642 | } |
| 643 | truncate(&buffer_path(root)) |
| 644 | }) |
| 645 | } |
| 646 | |
| 647 | #[cfg(test)] |
| 648 | mod tests { |
| 649 | use super::*; |
| 650 | |
| 651 | #[test] |
| 652 | fn persist_atomic_syncs_file_before_rename_and_parent_dir_after() { |
| 653 | let dir = tempfile::tempdir().unwrap(); |
| 654 | let target = dir.path().join("buffer.jsonl"); |
| 655 | fs::write(&target, b"old\n").unwrap(); |
| 656 | |
| 657 | let events = std::cell::RefCell::new(Vec::new()); |
| 658 | persist_atomic_with_sync( |
| 659 | &target, |
| 660 | b"new\n", |
| 661 | |file| { |
| 662 | assert_eq!(fs::read(&target).unwrap(), b"old\n"); |
| 663 | file.sync_all()?; |
| 664 | events.borrow_mut().push("file_sync"); |
| 665 | Ok(()) |
| 666 | }, |
| 667 | |parent| { |
| 668 | assert_eq!(parent, dir.path()); |
| 669 | assert_eq!(fs::read(&target).unwrap(), b"new\n"); |
| 670 | sync_directory(parent)?; |
| 671 | events.borrow_mut().push("dir_sync"); |
| 672 | Ok(()) |
| 673 | }, |
| 674 | ) |
| 675 | .unwrap(); |
| 676 | assert_eq!(events.into_inner(), vec!["file_sync", "dir_sync"]); |
| 677 | } |
| 678 | |
| 679 | #[test] |
| 680 | fn persist_atomic_preserves_existing_file_on_file_sync_error_and_reports_dir_sync_error() { |
| 681 | let dir = tempfile::tempdir().unwrap(); |
| 682 | let target = dir.path().join("buffer.jsonl"); |
| 683 | fs::write(&target, b"original\n").unwrap(); |
| 684 | |
| 685 | let err = persist_atomic_with_sync( |
| 686 | &target, |
| 687 | b"replacement\n", |
| 688 | |_| Err(std::io::Error::other("injected file sync failure")), |
| 689 | |_| Ok(()), |
| 690 | ) |
| 691 | .unwrap_err(); |
| 692 | assert!(err.to_string().contains("failed to sync")); |
| 693 | assert_eq!(fs::read(&target).unwrap(), b"original\n"); |
| 694 | |
| 695 | let err = persist_atomic_with_sync(&target, b"replacement\n", File::sync_all, |_| { |
| 696 | Err(std::io::Error::other("injected dir sync failure")) |
| 697 | }) |
| 698 | .unwrap_err(); |
| 699 | assert!(err.to_string().contains("failed to sync directory")); |
| 700 | } |
| 701 | |
| 702 | #[test] |
| 703 | fn rewrite_and_write_tombstone_persist_durably_with_restricted_mode() { |
| 704 | let dir = tempfile::tempdir().unwrap(); |
| 705 | let root = dir.path(); |
| 706 | ensure_dir(root).unwrap(); |
| 707 | |
| 708 | let buf = buffer_path(root); |
| 709 | rewrite(&buf, b"{\"ok\":true}\n").unwrap(); |
| 710 | assert_eq!(fs::read(&buf).unwrap(), b"{\"ok\":true}\n"); |
| 711 | |
| 712 | write_tombstone(root).unwrap(); |
| 713 | let generation = tombstone_generation(root) |
| 714 | .unwrap() |
| 715 | .expect("tombstone present"); |
| 716 | assert!(!generation.0.is_empty()); |
| 717 | #[cfg(unix)] |
| 718 | { |
| 719 | use std::os::unix::fs::PermissionsExt as _; |
| 720 | assert_eq!( |
| 721 | fs::metadata(&buf).unwrap().permissions().mode() & 0o777, |
| 722 | 0o600 |
| 723 | ); |
| 724 | assert_eq!( |
| 725 | fs::metadata(tombstone_path(root)) |
| 726 | .unwrap() |
| 727 | .permissions() |
| 728 | .mode() |
| 729 | & 0o777, |
| 730 | 0o600 |
| 731 | ); |
| 732 | } |
| 733 | } |
| 734 | } |
| 735 |