返回 CodeWhale
actor.rs
根目录 / crates / telemetry / src / actor.rs
1 //! The background writer.
2 //!
3 //! One dedicated OS thread behind a bounded `mpsc`. `record()` is a
4 //! non-blocking `try_send` and a hard no-op when the process is not armed;
5 //! everything the thread does is wrapped in `catch_unwind`, so a panic inside
6 //! telemetry costs telemetry and nothing else.
7 //!
8 //! A plain thread rather than a `tokio` task, deliberately: `init` is called
9 //! from six subcommand dispatch points, several of which have no runtime yet,
10 //! and a telemetry subsystem that only works when someone remembered to be
11 //! inside an executor is a subsystem that silently collects nothing on half its
12 //! surfaces.
13
14 use std::panic::{AssertUnwindSafe, catch_unwind};
15 use std::path::PathBuf;
16 use std::sync::Arc;
17 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
18 use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
19 use std::time::{Duration, Instant};
20
21 use crate::buffer;
22 use crate::client::{self, SendOutcome};
23 use crate::decision::{self, TelemetryDecision};
24 use crate::envelope;
25 use crate::event::{Batch, Event, SCHEMA_VERSION, Surface};
26 use crate::spool::{self, SpoolContext};
27
28 /// Events per batch.
29 pub const BATCH_MAX_EVENTS: usize = 200;
30 /// Byte ceiling per batch body.
31 pub const BATCH_MAX_BYTES: usize = 64 * 1024;
32
33 pub(crate) enum Message {
34 Event(Box<Event>),
35 PersistLocal(SyncSender<FlushOutcome>),
36 Shutdown(SyncSender<FlushOutcome>),
37 }
38
39 /// What a flush attempt did.
40 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
41 pub enum FlushOutcome {
42 /// Nothing was buffered.
43 Empty,
44 /// Events remain in the local buffer for a later network flush.
45 Buffered,
46 /// A batch was written to the dry-run sink.
47 DryRun,
48 /// A batch was accepted by the endpoint.
49 Sent,
50 /// A batch was assembled and dropped — offline, refused, or contended.
51 Dropped,
52 /// Telemetry was off by the time the flush ran; nothing was sent.
53 Suppressed,
54 /// The actor did not answer inside the caller's deadline.
55 TimedOut,
56 }
57
58 /// Facts the writer thread needs, fixed at arming time.
59 #[derive(Debug, Clone)]
60 pub(crate) struct Context {
61 pub root: PathBuf,
62 pub endpoint: Option<String>,
63 pub surface: Surface,
64 pub config_path: Option<PathBuf>,
65 pub app_version: String,
66 pub git_sha: Option<String>,
67 pub tty: bool,
68 pub spool: PathBuf,
69 pub nonce: String,
70 }
71
72 impl Context {
73 fn header(&self) -> SpoolContext {
74 SpoolContext::new(
75 self.surface,
76 self.app_version.clone(),
77 self.git_sha.clone(),
78 self.tty,
79 )
80 }
81 }
82
83 /// A handle to the writer thread.
84 #[derive(Debug)]
85 pub(crate) struct Handle {
86 tx: SyncSender<Message>,
87 pending: Arc<AtomicUsize>,
88 closing: AtomicBool,
89 }
90
91 impl Handle {
92 /// Start the writer thread.
93 pub(crate) fn spawn(context: Context) -> Self {
94 let (tx, rx) = sync_channel::<Message>(buffer::MAX_EVENTS + 1);
95 let pending = Arc::new(AtomicUsize::new(0));
96 let worker_pending = pending.clone();
97 // A detached thread: nothing joins it, and the process exiting while it
98 // is mid-write is exactly the case the torn-line tolerance covers.
99 let _ = std::thread::Builder::new()
100 .name("codewhale-telemetry".to_string())
101 .spawn(move || run(&context, &rx, &worker_pending));
102 Self {
103 tx,
104 pending,
105 closing: AtomicBool::new(false),
106 }
107 }
108
109 /// Queue an event without blocking; drop it when full, closing or closed.
110 pub(crate) fn record(&self, event: Event) {
111 if self.closing.load(Ordering::Acquire) {
112 return;
113 }
114 let mut pending = self.pending.load(Ordering::Acquire);
115 loop {
116 if pending >= buffer::MAX_EVENTS {
117 return;
118 }
119 match self.pending.compare_exchange_weak(
120 pending,
121 pending + 1,
122 Ordering::AcqRel,
123 Ordering::Acquire,
124 ) {
125 Ok(_) => break,
126 Err(current) => pending = current,
127 }
128 }
129 if self.closing.load(Ordering::Acquire)
130 || self.tx.try_send(Message::Event(Box::new(event))).is_err()
131 {
132 self.pending.fetch_sub(1, Ordering::AcqRel);
133 }
134 }
135
136 /// Ask for a final flush and stop the thread.
137 pub(crate) fn shutdown(&self, deadline: Duration) -> FlushOutcome {
138 self.round_trip(deadline, Message::Shutdown)
139 }
140
141 /// Persist queued events locally and stop without making a network request.
142 ///
143 /// Unlike [`Handle::shutdown`], this waits without a deadline: the local
144 /// path performs only bounded disk work, and racing it against a clock is
145 /// what lost dry-run receipts on slow hosts (#6269). The writer always
146 /// acknowledges — even on panic — so the only way out without an outcome
147 /// is a writer that is already gone, which fails open as `TimedOut`.
148 pub(crate) fn persist_local(&self) -> FlushOutcome {
149 if self.closing.swap(true, Ordering::AcqRel) {
150 return FlushOutcome::TimedOut;
151 }
152 let (ack_tx, ack_rx) = sync_channel::<FlushOutcome>(1);
153 if self.tx.try_send(Message::PersistLocal(ack_tx)).is_err() {
154 return FlushOutcome::TimedOut;
155 }
156 ack_rx.recv().unwrap_or(FlushOutcome::TimedOut)
157 }
158
159 fn round_trip(
160 &self,
161 deadline: Duration,
162 build: impl FnOnce(SyncSender<FlushOutcome>) -> Message,
163 ) -> FlushOutcome {
164 let started = Instant::now();
165 if self.closing.swap(true, Ordering::AcqRel) {
166 return FlushOutcome::TimedOut;
167 }
168 let (ack_tx, ack_rx) = sync_channel::<FlushOutcome>(1);
169 if self.tx.try_send(build(ack_tx)).is_err() {
170 return FlushOutcome::TimedOut;
171 }
172 match ack_rx.recv_timeout(deadline.saturating_sub(started.elapsed())) {
173 Ok(outcome) => outcome,
174 Err(RecvTimeoutError::Timeout | RecvTimeoutError::Disconnected) => {
175 FlushOutcome::TimedOut
176 }
177 }
178 }
179 }
180
181 fn run(context: &Context, rx: &Receiver<Message>, pending: &AtomicUsize) {
182 while let Ok(message) = rx.recv() {
183 // Telemetry never takes the process with it. The hook has already been
184 // installed by the time this thread exists, so a panic here is caught,
185 // dropped, and the loop continues.
186 let result = catch_unwind(AssertUnwindSafe(|| match message {
187 Message::Event(event) => {
188 pending.fetch_sub(1, Ordering::AcqRel);
189 append(context, &event);
190 None
191 }
192 Message::PersistLocal(ack) => {
193 // The caller joins this without a deadline (#6269), so the
194 // acknowledgement must be unconditional: a panic here would
195 // otherwise hang a short CLI command at exit. The outer
196 // `catch_unwind` still guards the other arms.
197 let outcome = match catch_unwind(AssertUnwindSafe(|| persist_local(context))) {
198 Ok(outcome) => outcome,
199 Err(_) => {
200 tracing::debug!("telemetry local persist recovered from a panic");
201 FlushOutcome::Dropped
202 }
203 };
204 let _ = ack.send(outcome);
205 Some(())
206 }
207 Message::Shutdown(ack) => {
208 let _ = ack.send(flush(context));
209 Some(())
210 }
211 }));
212 match result {
213 Ok(Some(())) => return,
214 Ok(None) => {}
215 Err(_) => {
216 tracing::debug!("telemetry writer recovered from a panic");
217 }
218 }
219 }
220 }
221
222 fn append(context: &Context, event: &Event) {
223 let Ok(line) = serde_json::to_string(event) else {
224 return;
225 };
226 let _ = buffer::append_in_turn(&context.root, &context.spool, &line);
227 }
228
229 /// Seal every event queued before this message without reaching the network.
230 ///
231 /// The channel is FIFO, so all prior event appends have settled before this
232 /// runs. Re-deciding here preserves the same mid-session opt-out boundary as a
233 /// full flush. An explicitly empty endpoint is the local dry-run sink and can
234 /// therefore be finalized immediately; a configured endpoint leaves the
235 /// events in this process's spool for a later start to send.
236 fn persist_local(context: &Context) -> FlushOutcome {
237 match decision::re_decide(context.config_path.as_deref(), context.surface) {
238 TelemetryDecision::Enabled(_) => {}
239 TelemetryDecision::OptedOut | TelemetryDecision::ForcedOff => {
240 return FlushOutcome::Suppressed;
241 }
242 }
243 if buffer::tombstone_present(&context.root) {
244 return FlushOutcome::Suppressed;
245 }
246 if context.endpoint.is_none() {
247 return flush(context);
248 }
249 if buffer::read_lines(&context.spool)
250 .iter()
251 .all(|line| spool::is_header_line(line))
252 {
253 FlushOutcome::Empty
254 } else {
255 FlushOutcome::Buffered
256 }
257 }
258
259 /// Drain, re-check consent, and deliver.
260 ///
261 /// The re-check is the point: telemetry is resolved once at init, but the
262 /// documented mid-session opt-out is an external file write this process would
263 /// otherwise never observe. If the answer is now `OptedOut`, `decide` has
264 /// already wiped and left the tombstone, and the drained events go nowhere.
265 fn flush(context: &Context) -> FlushOutcome {
266 match decision::re_decide(context.config_path.as_deref(), context.surface) {
267 TelemetryDecision::Enabled(_) => {}
268 TelemetryDecision::OptedOut | TelemetryDecision::ForcedOff => {
269 return FlushOutcome::Suppressed;
270 }
271 }
272 if buffer::tombstone_present(&context.root) {
273 return FlushOutcome::Suppressed;
274 }
275
276 let lines = spool::take_own(&context.root, &context.spool);
277 if lines.is_empty() {
278 return FlushOutcome::Empty;
279 }
280 let events = parse_events(&lines);
281 if events.is_empty() {
282 return FlushOutcome::Empty;
283 }
284
285 let Ok(install) = envelope::read_or_create_install_id(&context.root) else {
286 return FlushOutcome::Dropped;
287 };
288
289 let mut state = envelope::read_state(&context.root);
290 state.schema_version = SCHEMA_VERSION;
291 state.last_flush = Some(envelope::now_rfc3339());
292 // Written on attempt, not on success, so a permanently offline machine
293 // attempts at most once per interval rather than on every launch.
294 let _ = envelope::write_state(&context.root, &state);
295
296 deliver(
297 &context.root,
298 context.endpoint.as_deref(),
299 &context.header(),
300 install.install_id,
301 events,
302 )
303 }
304
305 fn deliver(
306 root: &std::path::Path,
307 endpoint: Option<&str>,
308 header: &SpoolContext,
309 install_id: String,
310 events: Vec<Event>,
311 ) -> FlushOutcome {
312 let batch = Batch {
313 schema_version: header.schema_version,
314 notice_version: header.notice_version,
315 sent_at: envelope::now_rfc3339(),
316 install_id,
317 app_version: header.app_version.clone(),
318 git_sha: header.git_sha.clone(),
319 surface: header.surface,
320 os: envelope::current_os(),
321 arch: envelope::current_arch(),
322 libc: envelope::current_libc(),
323 tty: header.tty,
324 events,
325 };
326 match client::send(root, endpoint, &batch) {
327 SendOutcome::DryRun => FlushOutcome::DryRun,
328 SendOutcome::Accepted => FlushOutcome::Sent,
329 SendOutcome::Dropped => FlushOutcome::Dropped,
330 }
331 }
332
333 pub(crate) fn spawn_recovery(context: Context) {
334 if !matches!(
335 context.surface,
336 Surface::Tui | Surface::Exec | Surface::Serve
337 ) {
338 return;
339 }
340 let _ = std::thread::Builder::new()
341 .name("codewhale-telemetry-recover".to_string())
342 .spawn(move || {
343 let _ = catch_unwind(AssertUnwindSafe(|| recover(&context)));
344 });
345 }
346
347 pub(crate) fn recover(context: &Context) -> Vec<FlushOutcome> {
348 match decision::re_decide(context.config_path.as_deref(), context.surface) {
349 TelemetryDecision::Enabled(_) => {}
350 TelemetryDecision::OptedOut | TelemetryDecision::ForcedOff => return Vec::new(),
351 }
352 send_dead(context)
353 }
354
355 pub(crate) fn send_dead(context: &Context) -> Vec<FlushOutcome> {
356 if buffer::tombstone_present(&context.root) {
357 return Vec::new();
358 }
359 let Ok(install) = envelope::read_or_create_install_id(&context.root) else {
360 return Vec::new();
361 };
362 spool::take_dead(&context.root, &context.nonce, std::time::SystemTime::now())
363 .into_iter()
364 .filter_map(|recovered| {
365 let events = parse_events(&recovered.lines);
366 (!events.is_empty()).then(|| {
367 deliver(
368 &context.root,
369 context.endpoint.as_deref(),
370 &recovered.context,
371 install.install_id.clone(),
372 events,
373 )
374 })
375 })
376 .collect()
377 }
378
379 /// Parse drained lines into events, capped at [`BATCH_MAX_EVENTS`] and
380 /// [`BATCH_MAX_BYTES`], skipping anything that does not parse **or does not
381 /// satisfy its declared string bounds**.
382 ///
383 /// The bound re-check is the point. Everything upstream of here builds events
384 /// from closed enums, `u32`s, and two reducers — but this function is a
385 /// deserializer, and its input is a file on disk that any process running as
386 /// the user can append to. `Event::is_bounded` is what stops
387 /// `{"event":"panic","site":"<anything at all>"}` from becoming a first-party
388 /// POST under the user's install id.
389 pub(crate) fn parse_events(lines: &[String]) -> Vec<Event> {
390 let mut events = Vec::new();
391 let mut bytes = 0usize;
392 for line in lines {
393 if events.len() >= BATCH_MAX_EVENTS || bytes + line.len() > BATCH_MAX_BYTES {
394 break;
395 }
396 if let Ok(event) = serde_json::from_str::<Event>(line) {
397 if !event.is_bounded() {
398 tracing::debug!("telemetry dropped an out-of-bounds buffered event");
399 continue;
400 }
401 bytes += line.len();
402 events.push(event);
403 }
404 }
405 events
406 }
407
408 #[cfg(test)]
409 mod tests {
410 use super::*;
411
412 #[test]
413 fn local_persistence_joins_the_writer_without_a_deadline() {
414 // The caller blocks on a mock writer that answers on its own
415 // schedule: no sleep, no timing assertion, no race with the clock.
416 let (tx, rx) = sync_channel(buffer::MAX_EVENTS + 1);
417 let handle = Handle {
418 tx,
419 pending: Arc::new(AtomicUsize::new(0)),
420 closing: AtomicBool::new(false),
421 };
422 handle.record(Event::SessionStart {
423 source: crate::SessionSource::Unknown,
424 });
425 let waiter = std::thread::spawn(move || handle.persist_local());
426 assert!(matches!(rx.try_recv(), Ok(Message::Event(_))));
427 let Message::PersistLocal(ack) = rx.recv().expect("local persistence request") else {
428 panic!("short CLI persistence must not request a network shutdown flush");
429 };
430 ack.send(FlushOutcome::Buffered)
431 .expect("the caller is still joined");
432 assert_eq!(waiter.join().expect("waiter"), FlushOutcome::Buffered);
433 assert!(
434 rx.try_recv().is_err(),
435 "one persist request enqueues exactly one message"
436 );
437 }
438
439 #[test]
440 fn local_persistence_fails_open_when_the_writer_is_gone() {
441 // The writer thread exits after a persist or shutdown request; a
442 // second caller must fail open, not hang on a dead receiver. Send
443 // fails deterministically here, so no timing assertion is needed.
444 let (tx, rx) = sync_channel::<Message>(buffer::MAX_EVENTS + 1);
445 drop(rx);
446 let handle = Handle {
447 tx,
448 pending: Arc::new(AtomicUsize::new(0)),
449 closing: AtomicBool::new(false),
450 };
451 assert_eq!(handle.persist_local(), FlushOutcome::TimedOut);
452 }
453
454 #[test]
455 fn a_hung_writer_cannot_hold_a_termination_send_past_its_deadline() {
456 let (tx, rx) = sync_channel::<Message>(buffer::MAX_EVENTS + 1);
457 let handle = Handle {
458 tx,
459 pending: Arc::new(AtomicUsize::new(0)),
460 closing: AtomicBool::new(false),
461 };
462 let started = Instant::now();
463 let outcome = handle.shutdown(Duration::from_millis(50));
464 assert_eq!(outcome, FlushOutcome::TimedOut);
465 assert!(started.elapsed() < Duration::from_secs(5));
466 assert!(matches!(rx.try_recv(), Ok(Message::Shutdown(_))));
467 }
468
469 #[test]
470 fn a_second_termination_send_does_not_wait() {
471 let (tx, _rx) = sync_channel::<Message>(buffer::MAX_EVENTS + 1);
472 let handle = Handle {
473 tx,
474 pending: Arc::new(AtomicUsize::new(0)),
475 closing: AtomicBool::new(false),
476 };
477 assert_eq!(
478 handle.shutdown(Duration::from_millis(20)),
479 FlushOutcome::TimedOut
480 );
481 let started = Instant::now();
482 assert_eq!(
483 handle.shutdown(Duration::from_secs(30)),
484 FlushOutcome::TimedOut
485 );
486 assert!(started.elapsed() < Duration::from_secs(5));
487 }
488
489 #[test]
490 fn a_sibling_thread_holding_the_lock_delays_an_append_instead_of_dropping_it() {
491 let home = tempfile::tempdir().expect("temp home");
492 let root = home.path().join(crate::TELEMETRY_DIR);
493 buffer::ensure_dir(&root).expect("create root");
494 let context = Context {
495 root: root.clone(),
496 endpoint: None,
497 surface: Surface::Exec,
498 config_path: None,
499 app_version: "0.0.1".to_string(),
500 git_sha: None,
501 tty: false,
502 spool: root.join("own.jsonl"),
503 nonce: "0".repeat(32),
504 };
505 let held = Arc::new(std::sync::Barrier::new(2));
506 let holder = {
507 let root = root.clone();
508 let held = held.clone();
509 std::thread::spawn(move || {
510 buffer::with_lock(&root, || {
511 held.wait();
512 std::thread::sleep(Duration::from_millis(200));
513 Ok(())
514 })
515 })
516 };
517 held.wait();
518 append(
519 &context,
520 &Event::SessionStart {
521 source: crate::SessionSource::Unknown,
522 },
523 );
524 holder.join().expect("holder thread").expect("holder lock");
525 assert!(
526 buffer::read_lines(&context.spool)
527 .iter()
528 .any(|line| line.contains("\"event\":\"session_start\"")),
529 "a sibling thread's lock hold dropped this session's own event"
530 );
531 }
532 }
533
533 lines RUST