dial9 0.5.0

Low-overhead async runtime telemetry: event recording, Tokio integration, CPU/memory profiling, and a trace viewer CLI
Documentation
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
use std::path::PathBuf;

fn tmp_base_path() -> PathBuf {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("trace.bin");
    std::mem::forget(dir);
    path
}

// ===========================================================================
// Recorder builder API — `recorder(DiskBuffer::builder()...)` + `attach_tokio_runtime`
// ===========================================================================
mod fluent_builder {
    use std::io;
    use std::panic::{AssertUnwindSafe, catch_unwind};

    use dial9::{AttachedRuntime, Dial9HandleTokioExt, DiskBuffer, Recorder, TokioAttachOptions};

    use super::tmp_base_path;

    /// Attach a default multi-thread runtime to `recorder` and hand both to the
    /// macro.
    fn with_runtime(recorder: Recorder, worker_threads: usize) -> io::Result<AttachedRuntime> {
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        builder.enable_all().worker_threads(worker_threads);
        let runtime = recorder
            .handle()
            .attach_tokio_runtime(builder, TokioAttachOptions::default())?;
        Ok((recorder, runtime))
    }

    fn test_config() -> io::Result<AttachedRuntime> {
        let writer = DiskBuffer::builder()
            .base_path(tmp_base_path())
            .max_file_size(1024 * 1024)
            .max_total_size(4 * 1024 * 1024)
            .build()
            .expect("writer build failed");
        with_runtime(dial9::recorder(writer).build(), 2)
    }

    fn disabled_config() -> io::Result<AttachedRuntime> {
        with_runtime(dial9::recorder_disabled(), 2)
    }

    #[dial9::main(config = test_config)]
    async fn runs_async_body() {
        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }

    #[test]
    fn macro_runs_async_body() {
        runs_async_body();
    }

    #[dial9::main(config = || {
        let writer = DiskBuffer::builder()
            .base_path(tmp_base_path())
            .max_file_size(1024 * 1024)
            .max_total_size(4 * 1024 * 1024)
            .build()
            .expect("writer build failed");
        with_runtime(dial9::recorder(writer).build(), 2)
    })]
    async fn runs_with_inline_closure() {
        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }

    #[test]
    fn macro_runs_with_inline_closure() {
        runs_with_inline_closure();
    }

    #[dial9::main(config = move || {
        let writer = DiskBuffer::builder()
            .base_path(tmp_base_path())
            .max_file_size(1024 * 1024)
            .max_total_size(4 * 1024 * 1024)
            .build()
            .expect("writer build failed");
        with_runtime(dial9::recorder(writer).build(), 2)
    })]
    async fn runs_with_move_closure() {
        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }

    #[test]
    fn macro_runs_with_move_closure() {
        runs_with_move_closure();
    }

    #[dial9::main(config = test_config)]
    async fn with_return_type() -> Result<i32, Box<dyn std::error::Error + Send + Sync>> {
        let val = tokio::spawn(async { 42 }).await?;
        Ok(val)
    }

    #[test]
    fn macro_preserves_return_type() {
        let result = with_return_type();
        assert_eq!(result.unwrap(), 42);
    }

    #[dial9::main(config = test_config)]
    async fn with_nested_spawn() -> i32 {
        // `Dial9TokioHandle::current()` is populated by `on_thread_start` on
        // every runtime-owned thread — use it to spawn instrumented sub-tasks.
        let handle = dial9::Dial9TokioHandle::current();
        let sub = handle.spawn(async { 7 + 3 });
        sub.await.unwrap()
    }

    #[test]
    fn macro_exposes_handle_for_nested_spawn() {
        let result = with_nested_spawn();
        assert_eq!(result, 10);
    }

    // --- Error propagation ---

    #[dial9::main(config = test_config)]
    async fn body_returns_err() -> Result<(), String> {
        Err("something went wrong".into())
    }

    #[test]
    fn macro_propagates_err_variant() {
        let result = body_returns_err();
        assert_eq!(result.unwrap_err(), "something went wrong");
    }

    #[dial9::main(config = test_config)]
    async fn body_returns_custom_err() -> Result<i32, std::io::Error> {
        Err(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"))
    }

    #[test]
    fn macro_propagates_io_error() {
        let result = body_returns_custom_err();
        let err = result.unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
        assert_eq!(err.to_string(), "missing");
    }

    // --- Panic propagation ---

    #[dial9::main(config = test_config)]
    async fn body_panics_with_str() {
        panic!("boom");
    }

    #[test]
    fn macro_propagates_panic_payload() {
        let result = catch_unwind(AssertUnwindSafe(body_panics_with_str));
        let payload = result.expect_err("should have panicked");
        let msg = payload
            .downcast_ref::<&str>()
            .expect("payload should be &str");
        assert_eq!(*msg, "boom");
    }

    #[dial9::main(config = test_config)]
    #[allow(clippy::unnecessary_literal_unwrap)]
    async fn body_panics_with_format() {
        let x: Option<i32> = None;
        x.unwrap();
    }

    #[test]
    fn macro_propagates_unwrap_panic() {
        let result = catch_unwind(AssertUnwindSafe(body_panics_with_format));
        let payload = result.expect_err("should have panicked");
        let msg = payload
            .downcast_ref::<&str>()
            .map(|s| s.to_string())
            .or_else(|| payload.downcast_ref::<String>().cloned())
            .expect("payload should be &str or String");
        assert!(msg.contains("None"), "expected unwrap message, got: {msg}");
    }

    // --- Disabled telemetry ---

    fn disabled_config_default() -> io::Result<AttachedRuntime> {
        let recorder = dial9::recorder_disabled();
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        builder.enable_all();
        let runtime = recorder
            .handle()
            .attach_tokio_runtime(builder, TokioAttachOptions::default())?;
        Ok((recorder, runtime))
    }

    #[dial9::main(config = disabled_config)]
    async fn runs_without_telemetry() -> i32 {
        tokio::spawn(async { 123 }).await.unwrap()
    }

    #[test]
    fn macro_runs_with_disabled_config() {
        let result = runs_without_telemetry();
        assert_eq!(result, 123);
    }

    #[dial9::main(config = disabled_config_default)]
    async fn disabled_default_runs() -> i32 {
        tokio::spawn(async { 99 }).await.unwrap()
    }

    #[test]
    fn macro_runs_with_disabled_default() {
        assert_eq!(disabled_default_runs(), 99);
    }

    #[dial9::main(config = disabled_config)]
    async fn disabled_with_return_type() -> Result<i32, Box<dyn std::error::Error + Send + Sync>> {
        let val = tokio::spawn(async { 42 }).await?;
        Ok(val)
    }

    #[test]
    fn macro_disabled_preserves_return_type() {
        assert_eq!(disabled_with_return_type().unwrap(), 42);
    }

    #[dial9::main(config = disabled_config)]
    async fn disabled_no_telemetry_handle() -> bool {
        // The current handle should be inert when telemetry is disabled.
        !dial9::Dial9Handle::current().is_enabled()
    }

    #[test]
    fn macro_disabled_has_no_telemetry_handle() {
        assert!(disabled_no_telemetry_handle());
    }

    #[dial9::main(config = disabled_config)]
    async fn disabled_timers_work() {
        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
    }

    #[test]
    fn macro_disabled_timers_work() {
        disabled_timers_work();
    }

    #[dial9::main(config = disabled_config)]
    async fn disabled_nested_spawn() -> i32 {
        let inner = tokio::spawn(async { tokio::spawn(async { 7 + 3 }).await.unwrap() });
        inner.await.unwrap()
    }

    #[test]
    fn macro_disabled_nested_spawn() {
        assert_eq!(disabled_nested_spawn(), 10);
    }
}

// In-memory writer via `recorder(MemoryBuffer::builder()...)`.
mod in_memory {
    use std::future::Future;
    use std::io;
    use std::pin::Pin;

    use dial9::Dial9Handle;
    use dial9::Dial9TokioHandle;
    use dial9::core::pipeline::{ProcessError, SegmentData, SegmentProcessor};
    use dial9::{
        AttachedRuntime, Dial9HandleTokioExt, MemoryBuffer, RecorderPipelineExt, TokioAttachOptions,
    };

    /// Stand-in delivery processor: forwards each segment unchanged.
    #[derive(Debug, Default)]
    struct NoopProcessor;

    impl SegmentProcessor for NoopProcessor {
        fn name(&self) -> &'static str {
            "Noop"
        }

        fn process(
            &mut self,
            data: SegmentData,
        ) -> Pin<Box<dyn Future<Output = Result<SegmentData, ProcessError>> + Send + '_>> {
            Box::pin(async move { Ok(data) })
        }
    }

    fn memory_config() -> io::Result<AttachedRuntime> {
        let writer = MemoryBuffer::builder()
            .max_total_size(16 * 1024 * 1024)
            .build()
            .expect("in-memory writer build failed");
        let recorder = dial9::recorder(writer)
            .with_custom_pipeline(|p| p.pipe(NoopProcessor))
            .build();
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        builder.enable_all();
        let runtime = recorder
            .handle()
            .attach_tokio_runtime(builder, TokioAttachOptions::default())?;
        Ok((recorder, runtime))
    }

    #[dial9::main(config = memory_config)]
    async fn runs_with_memory_writer() -> bool {
        let sub = Dial9TokioHandle::current().spawn(async { 7 + 3 });
        assert_eq!(sub.await.unwrap(), 10);
        Dial9Handle::current().is_enabled()
    }

    #[test]
    fn macro_runs_with_memory_writer() {
        assert!(
            runs_with_memory_writer(),
            "in-memory config should keep telemetry enabled through the macro"
        );
    }
}

// ===========================================================================
// Lenient downgrade path: on a writer-I/O failure `recorder_or_disabled` falls
// back to a disabled recorder (a plain tokio runtime with no telemetry).
// Exercises the macro through that downgrade.
// ===========================================================================
mod fluent_builder_fallback {
    use std::io;
    use std::path::PathBuf;

    use dial9::Dial9Handle;
    use dial9::{AttachedRuntime, Dial9HandleTokioExt, DiskBuffer, TokioAttachOptions};

    use super::tmp_base_path;

    /// Build a disk-backed recorder, or fall back to a disabled recorder (a
    /// plain tokio runtime) when the writer cannot be created.
    fn disk_recorder_or_disabled(base_path: PathBuf) -> io::Result<AttachedRuntime> {
        let writer = DiskBuffer::builder()
            .base_path(base_path)
            .max_file_size(1024 * 1024)
            .max_total_size(4 * 1024 * 1024)
            .build();
        let recorder = dial9::recorder_or_disabled(writer).build();
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        builder.enable_all();
        let runtime = recorder
            .handle()
            .attach_tokio_runtime(builder, TokioAttachOptions::default())?;
        Ok((recorder, runtime))
    }

    fn fallback_config() -> io::Result<AttachedRuntime> {
        disk_recorder_or_disabled(tmp_base_path())
    }

    fn unwritable_base_path() -> PathBuf {
        PathBuf::from("/this/dir/does/not/exist/dial9_macro_fallback_trace.bin")
    }

    fn cascading_fallback_config() -> io::Result<AttachedRuntime> {
        disk_recorder_or_disabled(unwritable_base_path())
    }

    #[dial9::main(config = fallback_config)]
    async fn fallback_runs_async_body() -> bool {
        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
        Dial9Handle::current().is_enabled()
    }

    #[test]
    fn fallback_config_runs_async_body() {
        let telemetry_active = fallback_runs_async_body();
        assert!(
            telemetry_active,
            "writable base_path should keep telemetry enabled through the macro"
        );
    }

    #[dial9::main(config = cascading_fallback_config)]
    async fn cascade_runs_async_body() -> bool {
        let result = tokio::spawn(async { 21 + 21 }).await.unwrap();
        assert_eq!(result, 42);
        !Dial9Handle::current().is_enabled()
    }

    #[test]
    fn fallback_cascade_runs_without_telemetry() {
        let telemetry_disabled = cascade_runs_async_body();
        assert!(
            telemetry_disabled,
            "unwritable base_path must downgrade to a plain tokio runtime with no telemetry"
        );
    }
}

/// `Dial9HandleTokioExt::attach_tokio_runtime` builds an instrumented runtime
/// from a recorder's handle.
mod attach_tokio_runtime {
    use dial9::{AttachedRuntime, Dial9HandleTokioExt, MemoryBuffer, TokioAttachOptions};

    #[test]
    fn builds_an_instrumented_runtime() {
        let recorder = dial9::recorder(MemoryBuffer::new(4 * 1024 * 1024).unwrap()).build();
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        builder.enable_all().worker_threads(2);
        let runtime = recorder
            .handle()
            .attach_tokio_runtime(
                builder,
                TokioAttachOptions::builder().runtime_name("main").build(),
            )
            .expect("build tokio runtime");

        let enabled = runtime.block_on(async { dial9::Dial9Handle::current().is_enabled() });
        assert!(enabled, "the runtime should be instrumented");

        drop(runtime);
        recorder.graceful_shutdown(std::time::Duration::from_secs(1));
    }

    /// A disabled recorder still yields a usable runtime, just an untraced one.
    #[test]
    fn disabled_recorder_gives_a_plain_runtime() {
        let recorder = dial9::recorder_disabled();
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        builder.enable_all();
        let runtime = recorder
            .handle()
            .attach_tokio_runtime(builder, TokioAttachOptions::default())
            .expect("build tokio runtime");

        assert_eq!(runtime.block_on(async { 42 }), 42);
        assert!(!recorder.handle().is_enabled());
    }

    /// An inline `config` closure that attaches a runtime and hands
    /// `#[dial9::main]` the recorder and runtime it expects.
    #[dial9::main(config = || -> std::io::Result<AttachedRuntime> {
        let recorder = dial9::recorder_disabled();
        let mut builder = tokio::runtime::Builder::new_multi_thread();
        builder.enable_all().worker_threads(2);
        let runtime = recorder
            .handle()
            .attach_tokio_runtime(builder, TokioAttachOptions::default())?;
        Ok((recorder, runtime))
    })]
    async fn runs_from_an_attach_runtime_config() -> u32 {
        dial9::spawn(async { 21 + 21 }).await.unwrap()
    }

    #[test]
    fn attach_runtime_result_feeds_the_macro() {
        assert_eq!(runs_from_an_attach_runtime_config(), 42);
    }
}