-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmod.rs
More file actions
2887 lines (2613 loc) · 105 KB
/
mod.rs
File metadata and controls
2887 lines (2613 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod event_writer;
mod runtime_context;
mod shared_state;
pub(crate) use runtime_context::RuntimeContext;
pub use runtime_context::current_worker_id;
pub(crate) use shared_state::SharedState;
use event_writer::EventWriter;
use runtime_context::{make_poll_end, make_poll_start, make_worker_park, make_worker_unpark};
use crate::metrics::{FlushMetrics, Operation, TlDrainMetrics};
use crate::primitives::sync::Arc;
use crate::primitives::sync::atomic::Ordering;
use crate::rate_limit::rate_limited;
use crate::telemetry::buffer;
use crate::telemetry::events::RawEvent;
use crate::telemetry::task_metadata::TaskId;
use crate::telemetry::writer::{RotatingWriter, TraceWriter};
use metrique::timers::Timer;
use metrique::unit::Microsecond;
use metrique::unit_of_work::metrics;
use metrique_timesource::time_source;
use std::cell::Cell;
use std::cell::RefCell;
use std::path::PathBuf;
use std::time::Duration;
crate::primitives::thread_local! {
/// Per-thread [`TelemetryHandle`], populated in `on_thread_start` and
/// cleared in `on_thread_stop`. Enables [`TelemetryHandle::current`].
static CURRENT_HANDLE: RefCell<Option<TelemetryHandle>> = const { RefCell::new(None) };
/// Set by `TelemetryHandle::spawn()` before calling `tokio::spawn()`,
/// so the `on_task_spawn` hook can distinguish instrumented from raw spawns.
static INSTRUMENTED_SPAWN: Cell<bool> = const { Cell::new(false) };
}
// ---------------------------------------------------------------------------
// Channel-based control for the flush thread
// ---------------------------------------------------------------------------
/// Commands sent to the flush thread from TelemetryHandle / TelemetryGuard.
pub(crate) enum ControlCommand {
/// Flush, finalize (seal segment), then exit the thread.
FinalizeAndStop(crate::primitives::sync::mpsc::SyncSender<()>),
}
/// Tracks the drain coordination state between the flush loop and the writer.
///
/// When the writer reports a drain is due (`should_drain()`), we can't act
/// immediately because thread-local buffers may still hold events that belong
/// in the current segment. Instead we bump the drain epoch (so threads
/// self-flush on their next `record_event`), wait one cycle (~5 ms) for that
/// to propagate, then perform the intrusive drain + flush + notify the writer
/// via `drained()`.
///
/// Without a state machine, the naïve check `if should_drain { schedule drain }`
/// fires every cycle (since we haven't drained yet), forever deferring the
/// actual drain.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DrainState {
/// Normal operation — poll `should_drain()` each cycle.
Idle,
/// The writer reported drain due and we bumped the drain epoch.
/// Next cycle: intrusive drain + flush + `drained()`.
EpochBumped,
}
/// Stats returned by flush for metrics publishing.
#[metrics(subfield, rename_all = "PascalCase")]
#[derive(Debug)]
pub(crate) struct FlushStats {
pub event_count: u64,
pub dropped_batches: u64,
#[metrics(unit = Microsecond)]
pub cpu_flush_duration: Duration,
}
/// Perform one flush cycle: drain CPU profilers, drain the collector, write
/// events to disk, and flush the writer. This is the only code path that
/// touches EventWriter, and it runs exclusively on the flush thread.
fn flush_once(
event_writer: &mut EventWriter,
shared: &SharedState,
drain_self: bool,
) -> FlushStats {
let events_before = event_writer.events_written();
let cpu_events_time = std::time::Instant::now();
#[cfg(feature = "cpu-profiling")]
{
if shared.is_enabled() {
event_writer.flush_cpu(shared);
}
}
let cpu_flush_duration = cpu_events_time.elapsed();
if drain_self {
// Periodically flush the flush thread's own TL buffer (queue samples + CPU events).
// We don't drain every cycle because each batch becomes its own trace segment;
// batching ~1s worth avoids writing tiny segments every 5ms.
buffer::drain_to_collector(&shared.collector);
}
let dropped = shared.collector.take_dropped_batches();
if dropped > 0 {
rate_limited!(Duration::from_secs(60), {
tracing::warn!(
dropped_batches = dropped,
"telemetry flush fell behind, dropped batches"
);
});
}
while let Some(batch) = shared.collector.next() {
if batch.event_count > 0
&& let Err(e) = event_writer.write_encoded_batch(&batch)
{
rate_limited!(Duration::from_secs(60), {
tracing::warn!("failed to transcode batch: {e}");
});
shared.enabled.store(false, Ordering::Relaxed);
return FlushStats {
event_count: event_writer.events_written() - events_before,
dropped_batches: dropped as u64,
cpu_flush_duration,
};
}
}
if let Err(e) = event_writer.flush() {
rate_limited!(Duration::from_secs(60), {
tracing::warn!("failed to flush trace data: {e}");
});
}
FlushStats {
event_count: event_writer.events_written() - events_before,
dropped_batches: dropped as u64,
cpu_flush_duration,
}
}
/// Register telemetry callbacks on a runtime builder.
/// Closures capture `Arc<RuntimeContext>` (runtime-specific) and `Arc<SharedState>` (recording core).
///
/// # Worker ID resolution
///
/// `WORKER_ID` TLS is populated lazily on the first `on_thread_unpark` / `on_before_task_poll`
/// call via [`resolve_worker_id`](runtime_context::resolve_worker_id), not in `on_thread_start`.
/// This is intentional: `on_thread_start` fires before `RuntimeMetrics` is available, so we
/// cannot yet call `metrics.worker_thread_id(i)` to determine which worker index we are.
/// By the time any waker calls `current_worker_id()`, at least one unpark or poll has occurred
/// and TLS is guaranteed to be populated.
fn register_hooks(
builder: &mut tokio::runtime::Builder,
ctx: &Arc<RuntimeContext>,
shared: &Arc<SharedState>,
control_tx: &crate::primitives::sync::mpsc::SyncSender<ControlCommand>,
task_tracking_enabled: bool,
) {
let c1 = ctx.clone();
let s1 = shared.clone();
let c2 = ctx.clone();
let s2 = shared.clone();
let c3 = ctx.clone();
let s3 = shared.clone();
let c4 = ctx.clone();
let s4 = shared.clone();
builder
.on_thread_park(move || {
s1.if_enabled(|buf| {
let event = make_worker_park(&c1, &s1);
buf.record_event(event);
});
})
.on_thread_unpark(move || {
s2.if_enabled(|buf| {
let event = make_worker_unpark(&c2, &s2);
buf.record_event(event);
});
})
.on_before_task_poll(move |meta| {
s3.if_enabled(|buf| {
let task_id = TaskId::from(meta.id());
let location = meta.spawned_at();
let event = make_poll_start(&c3, &s3, location, task_id);
buf.record_event(event);
});
})
.on_after_task_poll(move |_meta| {
s4.if_enabled(|buf| {
let event = make_poll_end(&c4, &s4);
buf.record_event(event);
});
});
if task_tracking_enabled {
let s5 = shared.clone();
builder.on_task_spawn(move |meta| {
s5.if_enabled(|buf| {
let task_id = TaskId::from(meta.id());
let location = meta.spawned_at();
let instrumented = INSTRUMENTED_SPAWN.with(|f| f.get());
buf.record_event(RawEvent::TaskSpawn {
timestamp_nanos: crate::telemetry::events::clock_monotonic_ns(),
task_id,
location,
instrumented,
});
});
});
let s6 = shared.clone();
builder.on_task_terminate(move |meta| {
s6.if_enabled(|buf| {
let task_id = TaskId::from(meta.id());
buf.record_event(RawEvent::TaskTerminate {
timestamp_nanos: crate::telemetry::events::clock_monotonic_ns(),
task_id,
});
});
});
}
// Unified on_thread_start / on_thread_stop. Tokio only stores one
// callback per hook, so any feature-gated work must live here rather
// than registering its own hook.
let handle_for_tl = TelemetryHandle::enabled(shared.clone(), control_tx.clone());
#[cfg(feature = "cpu-profiling")]
let s_start = shared.clone();
#[cfg(feature = "cpu-profiling")]
let s_stop = shared.clone();
builder
.on_thread_start(move || {
// Install this thread's TelemetryHandle so user code can call
// `TelemetryHandle::current()` from anywhere on this thread.
CURRENT_HANDLE.with(|cell| {
*cell.borrow_mut() = Some(handle_for_tl.clone());
});
#[cfg(feature = "cpu-profiling")]
{
// Register as Blocking initially; worker threads will
// overwrite this to Worker(i) in resolve_worker_id.
// NOTE: `tokio::runtime::worker_index()` will always return `None` at this point
// so we can't utilize that here.
let tid = crate::telemetry::events::current_tid();
s_start
.thread_roles
.lock()
.unwrap()
.insert(tid, crate::telemetry::events::ThreadRole::Blocking);
// Sched event sampling is deferred to register_tid_if_needed(),
// which runs only for worker threads on their first poll/park.
// This avoids opening perf fds for blocking pool threads.
// Registers the current thread for the CPU-profiling fallback (ctimer).
// No-op when perf is the active backend (perf uses inherit).
let _ = dial9_perf_self_profile::register_current_thread();
}
})
.on_thread_stop(move || {
CURRENT_HANDLE.with(|cell| {
*cell.borrow_mut() = None;
});
#[cfg(feature = "cpu-profiling")]
{
let tid = crate::telemetry::events::current_tid();
s_stop.thread_roles.lock().unwrap().remove(&tid);
if let Ok(mut prof) = s_stop.sched_profiler.lock()
&& let Some(ref mut p) = *prof
{
p.stop_tracking_current_thread();
}
dial9_perf_self_profile::unregister_current_thread();
}
});
}
/// Attach a runtime to an existing telemetry session: register hooks, build
/// the runtime, reserve worker IDs, and push the context.
fn attach_runtime(
shared: &Arc<SharedState>,
mut builder: tokio::runtime::Builder,
runtime_name: Option<String>,
control_tx: &crate::primitives::sync::mpsc::SyncSender<ControlCommand>,
task_tracking_enabled: bool,
) -> std::io::Result<tokio::runtime::Runtime> {
let ctx = Arc::new(RuntimeContext::new(runtime_name));
register_hooks(
&mut builder,
&ctx,
shared,
control_tx,
task_tracking_enabled,
);
let runtime = builder.build()?;
// Install the handle on the calling thread. For current_thread runtimes,
// this thread IS the worker (block_on runs here), so the tracing layer
// needs CURRENT_HANDLE to be set. Harmless for multi_thread runtimes.
CURRENT_HANDLE.with(|cell| {
*cell.borrow_mut() = Some(TelemetryHandle::enabled(shared.clone(), control_tx.clone()));
});
// Pre-reserve a contiguous block of worker IDs and set metrics atomically.
let metrics = runtime.handle().metrics();
let num_workers = metrics.num_workers() as u64;
let base = shared
.next_worker_id
.fetch_add(num_workers, Ordering::Relaxed);
ctx.metrics_and_base
.set((metrics, base))
.unwrap_or_else(|_| {
rate_limited!(Duration::from_secs(60), {
tracing::warn!(
"metrics_and_base already set for runtime context; ignoring duplicate attach"
);
});
});
// Eagerly populate worker_ids so segment metadata is complete from the
// first flush cycle, rather than waiting for each worker thread to lazily
// register on its first poll/park event.
{
let mut ids = ctx.worker_ids.write().unwrap();
for i in 0..num_workers {
ids.insert(i as usize, base + i);
}
}
shared.contexts.lock().unwrap().push(ctx);
Ok(runtime)
}
/// Cheap, cloneable handle for controlling telemetry from anywhere.
///
/// A handle may be in one of two modes:
///
/// - **Enabled** — backed by a real telemetry session; methods record
/// events, control recording, and wrap spawned futures with wake
/// tracking.
/// - **Disabled** — an inert sentinel returned by
/// [`TelemetryHandle::disabled`] and by [`TelemetryHandle::current`]
/// when called from a thread that is not owned by a dial9 runtime.
/// All methods are no-ops; [`spawn`](Self::spawn) falls back to
/// [`tokio::spawn`] without wake tracking.
///
/// Use [`is_enabled`](Self::is_enabled) to distinguish the two modes.
#[derive(Clone)]
pub struct TelemetryHandle {
inner: Option<HandleInner>,
}
#[derive(Clone)]
struct HandleInner {
shared: Arc<SharedState>,
control_tx: crate::primitives::sync::mpsc::SyncSender<ControlCommand>,
}
impl std::fmt::Debug for TelemetryHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TelemetryHandle")
.field("enabled", &self.is_enabled())
.finish_non_exhaustive()
}
}
impl TelemetryHandle {
pub(crate) fn enabled(
shared: Arc<SharedState>,
control_tx: crate::primitives::sync::mpsc::SyncSender<ControlCommand>,
) -> Self {
Self {
inner: Some(HandleInner { shared, control_tx }),
}
}
/// Return an inert handle that is not connected to any telemetry
/// session. All methods are no-ops; [`spawn`](Self::spawn) falls
/// back to [`tokio::spawn`] without wake tracking.
pub fn disabled() -> Self {
Self { inner: None }
}
/// Whether this handle is connected to a live telemetry session.
///
/// Returns `false` for handles obtained via
/// [`TelemetryHandle::disabled`], and for handles returned by
/// [`TelemetryHandle::current`] when called from a thread that is
/// not owned by a dial9 runtime.
pub fn is_enabled(&self) -> bool {
self.inner.is_some()
}
pub(crate) fn shared(&self) -> Option<&Arc<SharedState>> {
self.inner.as_ref().map(|i| &i.shared)
}
pub(crate) fn control_tx(
&self,
) -> Option<&crate::primitives::sync::mpsc::SyncSender<ControlCommand>> {
self.inner.as_ref().map(|i| &i.control_tx)
}
/// Return the [`TelemetryHandle`] for the current thread.
///
/// On threads owned by a dial9 runtime (workers and blocking
/// threads — installed via the runtime's `on_thread_start` hook,
/// cleared on `on_thread_stop`) this returns the live handle for
/// that runtime.
///
/// On any other thread (including the caller of
/// `runtime.block_on(...)` on a `current_thread` runtime, threads
/// outside any tokio context, and threads owned by a runtime built
/// with telemetry disabled) this returns an inert handle whose
/// methods are all no-ops — see [`TelemetryHandle::disabled`].
///
/// Use [`is_enabled`](Self::is_enabled) when you need to branch on
/// whether telemetry is actually live on the current thread.
pub fn current() -> Self {
CURRENT_HANDLE
.with(|cell| cell.borrow().clone())
.unwrap_or_else(Self::disabled)
}
/// Return the [`TelemetryHandle`] installed for the current thread,
/// or `None` if no dial9 runtime has claimed this thread.
///
/// Prefer [`current`](Self::current) instead.
pub fn try_current() -> Option<Self> {
CURRENT_HANDLE.with(|cell| cell.borrow().clone())
}
/// Enable telemetry recording. No-op on a disabled handle.
pub fn enable(&self) {
if let Some(inner) = &self.inner {
inner.shared.enabled.store(true, Ordering::Relaxed);
}
}
/// Disable telemetry recording. No-op on a disabled handle.
pub fn disable(&self) {
if let Some(inner) = &self.inner {
inner.shared.enabled.store(false, Ordering::Relaxed);
}
}
/// Get a [`TracedHandle`](crate::traced::TracedHandle) for wrapping
/// futures with wake tracking, or `None` on a disabled handle.
pub(crate) fn traced_handle(&self) -> Option<crate::traced::TracedHandle> {
self.inner.as_ref().map(|i| crate::traced::TracedHandle {
shared: i.shared.clone(),
})
}
/// Record a user-defined [`Encodable`](crate::telemetry::buffer::Encodable) event.
///
/// No-op on a disabled handle or when recording is paused.
pub(crate) fn record_encodable_event(&self, event: &dyn crate::telemetry::buffer::Encodable) {
if let Some(inner) = &self.inner {
inner
.shared
.if_enabled(|buf| buf.record_encodable_event(event));
}
}
/// Run a closure with direct access to the thread-local encoder.
///
/// The closure is only invoked if telemetry is enabled.
/// No-op on a disabled handle or when recording is paused.
// TODO(GH-XXX): consider making this public as an alternative to record_event
// for zero-copy dynamic schema encoding
pub(crate) fn with_encoder(
&self,
f: impl FnOnce(&mut crate::telemetry::buffer::ThreadLocalEncoder<'_>),
) {
if let Some(inner) = &self.inner {
inner.shared.if_enabled(|buf| buf.with_encoder(f));
}
}
/// Spawn a future on the ambient tokio runtime.
///
/// On an enabled handle, the future is wrapped with wake-event
/// tracking. On a disabled handle, this is a passthrough to
/// [`tokio::spawn`].
///
/// # Panics
///
/// Panics if called from outside a tokio runtime context (same
/// as [`tokio::spawn`]).
#[track_caller]
pub fn spawn<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
where
F: std::future::Future + Send + 'static,
F::Output: Send + 'static,
{
match self.traced_handle() {
Some(traced_handle) => {
let _guard = InstrumentedSpawnGuard::set();
tokio::spawn(async move {
let task_id = tokio::task::try_id().map(TaskId::from).unwrap_or_default();
crate::traced::Traced::new(future, traced_handle, task_id).await
})
}
None => tokio::spawn(future),
}
}
}
/// RAII guard that sets `INSTRUMENTED_SPAWN` to `true` on creation and
/// resets it to `false` on drop, even if `tokio::spawn` panics.
struct InstrumentedSpawnGuard;
impl InstrumentedSpawnGuard {
fn set() -> Self {
INSTRUMENTED_SPAWN.with(|c| c.set(true));
Self
}
}
impl Drop for InstrumentedSpawnGuard {
fn drop(&mut self) {
INSTRUMENTED_SPAWN.with(|c| c.set(false));
}
}
/// Handle for spawning wake-tracked futures on a specific runtime.
///
/// Returned by [`TraceRuntimeCoreBuilder::build`]. Unlike [`TelemetryHandle::spawn`]
/// which uses `tokio::spawn()` (requiring an ambient runtime context), this type
/// targets a specific runtime and works from any thread.
///
/// `Clone` is cheap — both inner handles are `Arc`-based.
#[derive(Clone, Debug)]
pub struct RuntimeTelemetryHandle {
runtime: tokio::runtime::Handle,
traced: Option<crate::traced::TracedHandle>,
}
impl RuntimeTelemetryHandle {
/// Spawn a future with wake-event tracking on this handle's runtime.
///
/// On a handle obtained from a disabled [`TelemetryGuard`], wake
/// tracking is skipped and the future is spawned plainly.
#[track_caller]
pub fn spawn<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
where
F: std::future::Future + Send + 'static,
F::Output: Send + 'static,
{
match &self.traced {
Some(traced) => {
let traced = traced.clone();
let _guard = InstrumentedSpawnGuard::set();
self.runtime.spawn(async move {
let task_id = tokio::task::try_id().map(TaskId::from).unwrap_or_default();
crate::traced::Traced::new(future, traced, task_id).await
})
}
None => self.runtime.spawn(future),
}
}
}
/// Holds the background worker thread and its stop signal.
pub(crate) struct WorkerHandle {
shutdown: Option<tokio::sync::oneshot::Sender<Duration>>,
thread: Option<crate::primitives::thread::JoinHandle<()>>,
}
/// RAII guard returned by [`TracedRuntimeBuilder::build`].
///
/// A guard is always present on a [`TracedRuntime`], regardless of
/// whether telemetry is enabled. When telemetry is disabled (because
/// the user opted out via `enabled(false)` or because a lenient config
/// path downgraded after a build failure), the guard is in an inert
/// mode: all methods are no-ops, [`handle`](Self::handle) returns an
/// inert [`TelemetryHandle`], and [`graceful_shutdown`](Self::graceful_shutdown)
/// is a successful no-op.
///
/// Use [`is_enabled`](Self::is_enabled) to distinguish the two modes.
pub struct TelemetryGuard {
inner: GuardInner,
}
enum GuardInner {
Enabled(EnabledGuard),
Disabled,
}
struct EnabledGuard {
handle: TelemetryHandle,
flush_thread: Option<crate::primitives::thread::JoinHandle<()>>,
worker: Option<WorkerHandle>,
}
impl std::fmt::Debug for TelemetryGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TelemetryGuard")
.field("enabled", &self.is_enabled())
.finish_non_exhaustive()
}
}
impl TelemetryGuard {
pub(crate) fn enabled(
handle: TelemetryHandle,
flush_thread: Option<crate::primitives::thread::JoinHandle<()>>,
worker: Option<WorkerHandle>,
) -> Self {
Self {
inner: GuardInner::Enabled(EnabledGuard {
handle,
flush_thread,
worker,
}),
}
}
pub(crate) fn disabled() -> Self {
Self {
inner: GuardInner::Disabled,
}
}
/// Whether this guard owns a live telemetry session.
///
/// Returns `false` for guards created by `enabled(false)` configs
/// or by lenient configs that downgraded after a build failure.
pub fn is_enabled(&self) -> bool {
matches!(self.inner, GuardInner::Enabled(_))
}
/// Get a cloneable handle for controlling telemetry.
///
/// On a disabled guard this returns an inert handle whose methods
/// are all no-ops — see [`TelemetryHandle::disabled`].
pub fn handle(&self) -> TelemetryHandle {
match &self.inner {
GuardInner::Enabled(eg) => eg.handle.clone(),
GuardInner::Disabled => TelemetryHandle::disabled(),
}
}
/// Monotonic start time of the telemetry session in nanoseconds, if
/// telemetry is enabled.
pub fn start_time(&self) -> Option<u64> {
self.shared().map(|s| s.start_time_ns)
}
/// Enable telemetry recording. No-op on a disabled guard.
pub fn enable(&self) {
if let GuardInner::Enabled(eg) = &self.inner {
eg.handle.enable();
}
}
/// Disable telemetry recording. No-op on a disabled guard.
pub fn disable(&self) {
if let GuardInner::Enabled(eg) = &self.inner {
eg.handle.disable();
}
}
/// Access the shared state for reuse by additional runtimes.
pub(crate) fn shared(&self) -> Option<&Arc<SharedState>> {
match &self.inner {
GuardInner::Enabled(eg) => eg.handle.shared(),
GuardInner::Disabled => None,
}
}
pub(crate) fn control_tx(
&self,
) -> Option<&crate::primitives::sync::mpsc::SyncSender<ControlCommand>> {
match &self.inner {
GuardInner::Enabled(eg) => eg.handle.control_tx(),
GuardInner::Disabled => None,
}
}
/// Attach a tokio runtime to this telemetry session.
///
/// Returns a builder that lets you configure per-runtime settings
/// (e.g. task tracking) before building the runtime.
///
/// On a disabled guard the resulting builder produces a plain tokio
/// runtime with no telemetry hooks installed.
///
/// ```rust,no_run
/// # use dial9_tokio_telemetry::telemetry::{NullWriter, TelemetryCore};
/// # fn main() -> std::io::Result<()> {
/// let guard = TelemetryCore::builder()
/// .writer(NullWriter)
/// .build()?;
/// guard.enable();
///
/// let mut builder = tokio::runtime::Builder::new_multi_thread();
/// builder.worker_threads(4).enable_all();
/// let (runtime, handle) = guard.trace_runtime("main").build(builder)?;
/// # Ok(())
/// # }
/// ```
pub fn trace_runtime(&self, name: impl Into<String>) -> TraceRuntimeCoreBuilder<'_> {
TraceRuntimeCoreBuilder {
guard: self,
name: name.into(),
task_tracking: false,
}
}
/// Send FinalizeAndStop to the flush thread, join it, then drain the
/// caller's thread-local buffer into the collector so the flush thread
/// picks up any stragglers. No-op when telemetry is disabled.
fn stop_flush_thread(&mut self) {
let GuardInner::Enabled(eg) = &mut self.inner else {
return;
};
// Drain the current thread's buffer (e.g. main thread in block_on)
// which may contain TaskSpawn events that were never flushed.
if let Some(shared) = eg.handle.shared() {
buffer::drain_to_collector(&shared.collector);
}
// Tell the flush thread to do a final flush + finalize, then exit.
let (ack_tx, ack_rx) = crate::primitives::sync::mpsc::sync_channel(0);
if let Some(tx) = eg.handle.control_tx()
&& tx.send(ControlCommand::FinalizeAndStop(ack_tx)).is_ok()
{
let _ = ack_rx.recv();
}
if let Some(t) = eg.flush_thread.take() {
let _ = t.join();
}
}
/// Flush remaining events, seal the final segment, and wait for the
/// background worker to drain (symbolize, compress, upload to S3).
///
/// **Call this after the runtime has been dropped** so that Tokio worker
/// threads have exited and their thread-local telemetry buffers have been
/// flushed to the central collector.
///
/// On a disabled guard this is a successful no-op — there is no
/// flush thread or background worker to drain.
///
/// ```rust,no_run
/// # use dial9_tokio_telemetry::telemetry::{RotatingWriter, TracedRuntime};
/// # use std::time::Duration;
/// # fn main() -> std::io::Result<()> {
/// # let writer = RotatingWriter::new("/tmp/t.bin", 1024, 4096)?;
/// # let builder = tokio::runtime::Builder::new_multi_thread();
/// let (runtime, guard) = TracedRuntime::build_and_start(builder, writer)?;
/// runtime.block_on(async { /* ... */ });
/// drop(runtime); // worker threads exit, flushing thread-local buffers
/// guard.graceful_shutdown(Duration::from_secs(5))?;
/// # Ok(())
/// # }
/// ```
///
/// Consumes the guard so `Drop` becomes a no-op.
pub fn graceful_shutdown(mut self, timeout: Duration) -> Result<(), std::io::Error> {
tracing::debug!(target: "dial9_telemetry", "graceful_shutdown starting");
// 1. Stop flush thread (flushes + finalizes the last segment).
// No-op when disabled.
self.stop_flush_thread();
tracing::debug!(target: "dial9_telemetry", "flush thread joined, segment sealed");
// 2. Signal worker to drain with the given timeout and wait
if let GuardInner::Enabled(eg) = &mut self.inner
&& let Some(ref mut w) = eg.worker
{
tracing::debug!(target: "dial9_telemetry", timeout_secs = timeout.as_secs(), "waiting for worker drain");
if let Some(tx) = w.shutdown.take() {
let _ = tx.send(timeout);
}
if let Some(t) = w.thread.take()
&& let Err(e) = t.join()
{
tracing::error!(target: "dial9_telemetry", panic = ?e, "worker thread panicked during shutdown");
}
tracing::debug!(target: "dial9_telemetry", "worker finished");
}
Ok(())
}
}
impl Drop for TelemetryGuard {
fn drop(&mut self) {
// 1. Stop the flush thread (flushes + finalizes). No-op when disabled.
self.stop_flush_thread();
// 2. Hard shutdown: drop the sender without sending — worker sees
// RecvError and exits without draining. No need to join the thread.
// For graceful drain, use graceful_shutdown() instead.
if let GuardInner::Enabled(eg) = &mut self.inner
&& let Some(ref mut w) = eg.worker
{
w.shutdown.take();
}
}
}
/// Marker: no trace path has been set yet.
#[derive(Debug)]
pub struct NoTracePath;
/// Marker: a trace path has been set.
#[derive(Debug)]
pub struct HasTracePath;
/// Builder for configuring a traced Tokio runtime.
pub struct TracedRuntimeBuilder<P = NoTracePath> {
enabled: bool,
task_tracking_enabled: bool,
trace_path: Option<PathBuf>,
runtime_name: Option<String>,
#[cfg(feature = "cpu-profiling")]
cpu_profiling_config: Option<crate::telemetry::cpu_profile::CpuProfilingConfig>,
#[cfg(feature = "cpu-profiling")]
sched_event_config: Option<crate::telemetry::cpu_profile::SchedEventConfig>,
#[cfg(feature = "worker-s3")]
s3_config: Option<crate::background_task::s3::S3Config>,
#[cfg(feature = "worker-s3")]
s3_client: Option<aws_sdk_s3::Client>,
worker_poll_interval: Option<Duration>,
worker_metrics_sink: Option<metrique_writer::BoxEntrySink>,
_marker: std::marker::PhantomData<P>,
}
impl<P> std::fmt::Debug for TracedRuntimeBuilder<P> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TracedRuntimeBuilder")
.finish_non_exhaustive()
}
}
// Methods available on both NoTracePath and HasTracePath.
impl<P> TracedRuntimeBuilder<P> {
/// Set to `false` to build a plain runtime with no telemetry
/// installed and a dummy [`TelemetryGuard`]. Defaults to `true`.
///
/// Unlike [`TelemetryGuard::enable`]/[`TelemetryGuard::disable`]
/// (which toggle recording at runtime), this controls whether
/// telemetry hooks and threads are installed at all.
pub fn install(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
/// Enable or disable task spawn/terminate tracking.
pub fn with_task_tracking(mut self, enabled: bool) -> Self {
self.task_tracking_enabled = enabled;
self
}
/// Set a human-readable name for this runtime. Used in segment metadata
/// to map runtime indices to names for the trace viewer.
pub fn with_runtime_name(mut self, name: impl Into<String>) -> Self {
self.runtime_name = Some(name.into());
self
}
/// Enable CPU profiling with the given configuration (Linux only).
#[cfg(feature = "cpu-profiling")]
pub fn with_cpu_profiling(
mut self,
config: crate::telemetry::cpu_profile::CpuProfilingConfig,
) -> Self {
self.cpu_profiling_config = Some(config);
self
}
/// Enable per-worker scheduler event capture (Linux only).
#[cfg(feature = "cpu-profiling")]
pub fn with_sched_events(
mut self,
config: crate::telemetry::cpu_profile::SchedEventConfig,
) -> Self {
self.sched_event_config = Some(config);
self
}
/// Configure S3 upload for sealed trace segments.
#[cfg(feature = "worker-s3")]
pub fn with_s3_uploader(mut self, config: crate::background_task::s3::S3Config) -> Self {
self.s3_config = Some(config);
self
}
/// Provide a pre-built S3 client (for custom credentials or endpoints).
#[cfg(feature = "worker-s3")]
pub fn with_s3_client(mut self, client: aws_sdk_s3::Client) -> Self {
self.s3_client = Some(client);
self
}
/// Set how often the background worker polls for sealed segments.
pub fn with_worker_poll_interval(mut self, interval: Duration) -> Self {
self.worker_poll_interval = Some(interval);
self
}
/// Set a metrics sink for the background worker.
pub fn with_worker_metrics_sink(mut self, sink: metrique_writer::BoxEntrySink) -> Self {
self.worker_metrics_sink = Some(sink);
self
}
/// Attach a new runtime to an existing telemetry session.
///
/// This reuses the `SharedState`, flush thread, writer, and CPU profiler
/// from the original `TelemetryGuard`. Only the tokio callbacks are
/// registered on the new builder. The new runtime's workers get a unique
/// runtime index so their `WorkerId`s don't collide with existing runtimes.
pub fn build_and_attach_to_telemetry(
self,
mut builder: tokio::runtime::Builder,
guard: &TelemetryGuard,
) -> std::io::Result<tokio::runtime::Runtime> {
let (Some(shared), Some(control_tx)) = (guard.shared(), guard.control_tx()) else {
// Disabled guard: produce a plain tokio runtime with no
// telemetry hooks so attaching still works gracefully.
return builder.build();
};
attach_runtime(
shared,
builder,
self.runtime_name,
control_tx,
self.task_tracking_enabled,
)
}
fn into_state<Q>(self) -> TracedRuntimeBuilder<Q> {
TracedRuntimeBuilder {
enabled: self.enabled,
task_tracking_enabled: self.task_tracking_enabled,
trace_path: self.trace_path,
runtime_name: self.runtime_name,
#[cfg(feature = "cpu-profiling")]
cpu_profiling_config: self.cpu_profiling_config,
#[cfg(feature = "cpu-profiling")]
sched_event_config: self.sched_event_config,
#[cfg(feature = "worker-s3")]
s3_config: self.s3_config,
#[cfg(feature = "worker-s3")]
s3_client: self.s3_client,
worker_poll_interval: self.worker_poll_interval,
worker_metrics_sink: self.worker_metrics_sink,
_marker: std::marker::PhantomData,
}
}
}
impl TracedRuntimeBuilder<NoTracePath> {
/// Set the trace output path. This transitions the builder to
/// `HasTracePath`, enabling `build()` and `build_and_start()`.
pub fn with_trace_path(
mut self,
path: impl Into<PathBuf>,
) -> TracedRuntimeBuilder<HasTracePath> {
self.trace_path = Some(path.into());
self.into_state()
}
/// Build with a custom writer (for tests or `NullWriter`).
/// No background worker is spawned.
pub fn build_with_writer(
self,
builder: tokio::runtime::Builder,
writer: impl TraceWriter + 'static,
) -> std::io::Result<(tokio::runtime::Runtime, TelemetryGuard)> {
self.into_state::<HasTracePath>()
.build_inner(builder, Box::new(writer))
}
/// Build with a custom writer and immediately enable recording.
pub fn build_and_start_with_writer(
self,
builder: tokio::runtime::Builder,
writer: impl TraceWriter + 'static,
) -> std::io::Result<(tokio::runtime::Runtime, TelemetryGuard)> {
let (runtime, guard) = self.build_with_writer(builder, writer)?;
guard.enable();
Ok((runtime, guard))
}
/// Build the traced runtime. No background worker is spawned
/// (use `with_trace_path()` first for worker support).
pub fn build(
self,
builder: tokio::runtime::Builder,