async-inspect 0.2.0

X-ray vision for async Rust - inspect and debug async state machines
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
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
//! Core inspection functionality
//!
//! This module provides the main `Inspector` type that manages task tracking
//! and event collection.

use crate::deadlock::DeadlockDetector;
use crate::task::{sort_tasks, SortDirection, TaskFilter, TaskId, TaskInfo, TaskSortBy, TaskState};
use crate::timeline::{Event, EventKind, Timeline};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;

/// Global inspector instance
static GLOBAL_INSPECTOR: once_cell::sync::Lazy<Inspector> =
    once_cell::sync::Lazy::new(Inspector::new);

/// Main inspector for tracking async execution
#[derive(Clone)]
pub struct Inspector {
    /// Shared state
    state: Arc<InspectorState>,
}

struct InspectorState {
    /// All tracked tasks
    tasks: RwLock<HashMap<TaskId, TaskInfo>>,

    /// Timeline of events
    timeline: RwLock<Timeline>,

    /// Deadlock detector
    deadlock_detector: DeadlockDetector,

    /// Event counter for unique IDs
    event_counter: AtomicU64,

    /// Whether the inspector is enabled
    enabled: RwLock<bool>,
}

impl Inspector {
    /// Create a new inspector
    #[must_use]
    pub fn new() -> Self {
        Self {
            state: Arc::new(InspectorState {
                tasks: RwLock::new(HashMap::new()),
                timeline: RwLock::new(Timeline::new()),
                deadlock_detector: DeadlockDetector::new(),
                event_counter: AtomicU64::new(1),
                enabled: RwLock::new(true),
            }),
        }
    }

    /// Get the global inspector instance
    #[must_use]
    pub fn global() -> &'static Self {
        &GLOBAL_INSPECTOR
    }

    /// Check if the inspector is enabled
    #[must_use]
    pub fn is_enabled(&self) -> bool {
        *self.state.enabled.read()
    }

    /// Enable the inspector
    pub fn enable(&self) {
        *self.state.enabled.write() = true;
    }

    /// Disable the inspector
    pub fn disable(&self) {
        *self.state.enabled.write() = false;
    }

    /// Register a new task
    #[must_use]
    pub fn register_task(&self, name: String) -> TaskId {
        if !self.is_enabled() {
            return TaskId::new();
        }

        let task = TaskInfo::new(name.clone());
        let task_id = task.id;

        // Add event
        self.add_event(
            task_id,
            EventKind::TaskSpawned {
                name,
                parent: None,
                location: None,
            },
        );

        // Store task
        self.state.tasks.write().insert(task_id, task);

        task_id
    }

    /// Register a child task with a parent
    #[must_use]
    pub fn register_child_task(&self, name: String, parent_id: TaskId) -> TaskId {
        if !self.is_enabled() {
            return TaskId::new();
        }

        let mut task = TaskInfo::new(name.clone());
        task.parent = Some(parent_id);
        let task_id = task.id;

        // Add event
        self.add_event(
            task_id,
            EventKind::TaskSpawned {
                name,
                parent: Some(parent_id),
                location: None,
            },
        );

        // Store task
        self.state.tasks.write().insert(task_id, task);

        task_id
    }

    /// Register a task with additional metadata
    #[must_use]
    pub fn register_task_with_info(&self, task: TaskInfo) -> TaskId {
        if !self.is_enabled() {
            return task.id;
        }

        let task_id = task.id;

        // Add event
        self.add_event(
            task_id,
            EventKind::TaskSpawned {
                name: task.name.clone(),
                parent: task.parent,
                location: task.location.clone(),
            },
        );

        // Store task
        self.state.tasks.write().insert(task_id, task);

        task_id
    }

    /// Update task state
    pub fn update_task_state(&self, task_id: TaskId, new_state: TaskState) {
        if !self.is_enabled() {
            return;
        }

        if let Some(task) = self.state.tasks.write().get_mut(&task_id) {
            let old_state = task.state.clone();
            task.update_state(new_state.clone());

            // Add event
            self.add_event(
                task_id,
                EventKind::StateChanged {
                    old_state,
                    new_state,
                },
            );
        }
    }

    /// Record a poll start
    pub fn poll_started(&self, task_id: TaskId) {
        if !self.is_enabled() {
            return;
        }

        self.update_task_state(task_id, TaskState::Running);
        self.add_event(task_id, EventKind::PollStarted);
    }

    /// Record a poll end
    pub fn poll_ended(&self, task_id: TaskId, duration: Duration) {
        if !self.is_enabled() {
            return;
        }

        if let Some(task) = self.state.tasks.write().get_mut(&task_id) {
            task.record_poll(duration);
        }

        self.add_event(task_id, EventKind::PollEnded { duration });
    }

    /// Record an await start
    pub fn await_started(&self, task_id: TaskId, await_point: String, location: Option<String>) {
        if !self.is_enabled() {
            return;
        }

        self.update_task_state(
            task_id,
            TaskState::Blocked {
                await_point: await_point.clone(),
            },
        );

        self.add_event(
            task_id,
            EventKind::AwaitStarted {
                await_point,
                location,
            },
        );
    }

    /// Record an await end
    pub fn await_ended(&self, task_id: TaskId, await_point: String, duration: Duration) {
        if !self.is_enabled() {
            return;
        }

        self.add_event(
            task_id,
            EventKind::AwaitEnded {
                await_point,
                duration,
            },
        );
    }

    /// Mark task as completed
    pub fn task_completed(&self, task_id: TaskId) {
        if !self.is_enabled() {
            return;
        }

        // Get duration while holding read lock, then release it
        let duration = {
            self.state
                .tasks
                .read()
                .get(&task_id)
                .map(super::task::TaskInfo::age)
        };

        if let Some(duration) = duration {
            self.update_task_state(task_id, TaskState::Completed);
            self.add_event(task_id, EventKind::TaskCompleted { duration });
        }
    }

    /// Mark task as failed
    pub fn task_failed(&self, task_id: TaskId, error: Option<String>) {
        if !self.is_enabled() {
            return;
        }

        self.update_task_state(task_id, TaskState::Failed);
        self.add_event(task_id, EventKind::TaskFailed { error });
    }

    /// Record an inspection point
    pub fn inspection_point(&self, task_id: TaskId, label: String, message: Option<String>) {
        if !self.is_enabled() {
            return;
        }

        self.add_event(task_id, EventKind::InspectionPoint { label, message });
    }

    /// Add an event to the timeline
    pub fn add_event(&self, task_id: TaskId, kind: EventKind) {
        let event_id = self.state.event_counter.fetch_add(1, Ordering::Relaxed);
        let event = Event::new(event_id, task_id, kind);
        self.state.timeline.write().add_event(event);
    }

    /// Get a task by ID
    #[must_use]
    pub fn get_task(&self, task_id: TaskId) -> Option<TaskInfo> {
        self.state.tasks.read().get(&task_id).cloned()
    }

    /// Get all tasks
    #[must_use]
    pub fn get_all_tasks(&self) -> Vec<TaskInfo> {
        self.state.tasks.read().values().cloned().collect()
    }

    /// Get tasks matching a filter
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_inspect::{Inspector, task::{TaskFilter, TaskState}};
    /// use std::time::Duration;
    ///
    /// let inspector = Inspector::new();
    ///
    /// // Find all running tasks with "fetch" in the name
    /// let filter = TaskFilter::new()
    ///     .with_state(TaskState::Running)
    ///     .with_name_pattern("fetch");
    ///
    /// let tasks = inspector.get_tasks_filtered(&filter);
    /// ```
    #[must_use]
    pub fn get_tasks_filtered(&self, filter: &TaskFilter) -> Vec<TaskInfo> {
        self.state
            .tasks
            .read()
            .values()
            .filter(|t| filter.matches(t))
            .cloned()
            .collect()
    }

    /// Get tasks matching a filter, sorted by the given criteria
    ///
    /// # Example
    ///
    /// ```rust
    /// use async_inspect::{Inspector, task::{TaskFilter, TaskState, TaskSortBy, SortDirection}};
    ///
    /// let inspector = Inspector::new();
    ///
    /// // Get blocked tasks sorted by age (oldest first)
    /// let filter = TaskFilter::new().with_state(TaskState::Blocked { await_point: String::new() });
    /// let tasks = inspector.get_tasks_sorted(&filter, TaskSortBy::Age, SortDirection::Descending);
    /// ```
    #[must_use]
    pub fn get_tasks_sorted(
        &self,
        filter: &TaskFilter,
        sort_by: TaskSortBy,
        direction: SortDirection,
    ) -> Vec<TaskInfo> {
        let mut tasks = self.get_tasks_filtered(filter);
        sort_tasks(&mut tasks, sort_by, direction);
        tasks
    }

    /// Get running tasks
    #[must_use]
    pub fn get_running_tasks(&self) -> Vec<TaskInfo> {
        self.get_tasks_filtered(&TaskFilter::new().with_state(TaskState::Running))
    }

    /// Get blocked tasks
    #[must_use]
    pub fn get_blocked_tasks(&self) -> Vec<TaskInfo> {
        self.get_tasks_filtered(&TaskFilter::new().with_state(TaskState::Blocked {
            await_point: String::new(),
        }))
    }

    /// Get long-running tasks (older than the specified duration)
    #[must_use]
    pub fn get_long_running_tasks(&self, min_duration: Duration) -> Vec<TaskInfo> {
        self.get_tasks_filtered(&TaskFilter::new().with_min_duration(min_duration))
    }

    /// Get root tasks (tasks without a parent)
    #[must_use]
    pub fn get_root_tasks(&self) -> Vec<TaskInfo> {
        self.get_tasks_filtered(&TaskFilter::new().root_only())
    }

    /// Get child tasks of a specific parent
    #[must_use]
    pub fn get_child_tasks(&self, parent_id: TaskId) -> Vec<TaskInfo> {
        self.get_tasks_filtered(&TaskFilter::new().with_parent(parent_id))
    }

    /// Get all events
    #[must_use]
    pub fn get_events(&self) -> Vec<Event> {
        self.state.timeline.read().events().to_vec()
    }

    /// Get events for a specific task
    #[must_use]
    pub fn get_task_events(&self, task_id: TaskId) -> Vec<Event> {
        self.state
            .timeline
            .read()
            .events_for_task(task_id)
            .into_iter()
            .cloned()
            .collect()
    }

    /// Build a performance profiler from collected data
    #[must_use]
    pub fn build_profiler(&self) -> crate::profile::Profiler {
        use crate::profile::{Profiler, TaskMetrics};
        use crate::timeline::EventKind;

        let mut profiler = Profiler::new();
        let tasks = self.state.tasks.read();
        let timeline = self.state.timeline.read();

        for task in tasks.values() {
            let mut metrics = TaskMetrics::new(task.id, task.name.clone());

            // Calculate durations
            metrics.total_duration = task.age();
            metrics.running_time = task.total_run_time;
            metrics.blocked_time = if metrics.total_duration > task.total_run_time {
                metrics.total_duration - task.total_run_time
            } else {
                Duration::ZERO
            };

            // Set poll count
            metrics.poll_count = task.poll_count;

            // Calculate average poll duration
            if task.poll_count > 0 {
                metrics.avg_poll_duration = task.total_run_time / task.poll_count as u32;
            }

            // Check if completed
            metrics.completed = matches!(task.state, TaskState::Completed);

            // Collect await durations from events
            let task_events: Vec<&Event> = timeline
                .events()
                .iter()
                .filter(|e| e.task_id == task.id)
                .collect();

            let mut await_start_times: HashMap<String, std::time::Instant> = HashMap::new();

            for event in task_events {
                match &event.kind {
                    EventKind::AwaitStarted { await_point, .. } => {
                        await_start_times.insert(await_point.clone(), event.timestamp);
                    }
                    EventKind::AwaitEnded { await_point, .. } => {
                        if let Some(start_time) = await_start_times.remove(&await_point.clone()) {
                            let duration = event.timestamp.duration_since(start_time);
                            metrics.await_durations.push(duration);
                            metrics.await_count += 1;
                        }
                    }
                    _ => {}
                }
            }

            profiler.record_task(metrics);
        }

        profiler
    }

    /// Get statistics
    #[must_use]
    pub fn stats(&self) -> InspectorStats {
        let tasks = self.state.tasks.read();
        let timeline = self.state.timeline.read();

        let total = tasks.len();
        let pending = tasks
            .values()
            .filter(|t| matches!(t.state, TaskState::Pending))
            .count();
        let running = tasks
            .values()
            .filter(|t| matches!(t.state, TaskState::Running))
            .count();
        let blocked = tasks
            .values()
            .filter(|t| matches!(t.state, TaskState::Blocked { .. }))
            .count();
        let completed = tasks
            .values()
            .filter(|t| matches!(t.state, TaskState::Completed))
            .count();
        let failed = tasks
            .values()
            .filter(|t| matches!(t.state, TaskState::Failed))
            .count();

        InspectorStats {
            total_tasks: total,
            pending_tasks: pending,
            running_tasks: running,
            blocked_tasks: blocked,
            completed_tasks: completed,
            failed_tasks: failed,
            total_events: timeline.len(),
            timeline_duration: timeline.duration(),
        }
    }

    /// Clear all data
    pub fn clear(&self) {
        self.state.tasks.write().clear();
        self.state.timeline.write().clear();
        self.state.event_counter.store(1, Ordering::Relaxed);
    }

    /// Reset the inspector
    pub fn reset(&self) {
        self.clear();
        self.enable();
    }

    /// Get the deadlock detector
    ///
    /// Returns a reference to the integrated deadlock detector for resource
    /// tracking and deadlock analysis.
    #[must_use]
    pub fn deadlock_detector(&self) -> &DeadlockDetector {
        &self.state.deadlock_detector
    }
}

impl Default for Inspector {
    fn default() -> Self {
        Self::new()
    }
}

/// Inspector statistics
#[derive(Debug, Clone)]
pub struct InspectorStats {
    /// Total number of tasks
    pub total_tasks: usize,
    /// Tasks in pending state
    pub pending_tasks: usize,
    /// Tasks in running state
    pub running_tasks: usize,
    /// Tasks in blocked state
    pub blocked_tasks: usize,
    /// Completed tasks
    pub completed_tasks: usize,
    /// Failed tasks
    pub failed_tasks: usize,
    /// Total number of events
    pub total_events: usize,
    /// Total timeline duration
    pub timeline_duration: Duration,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_inspector_creation() {
        let inspector = Inspector::new();
        assert!(inspector.is_enabled());
    }

    #[test]
    fn test_register_task() {
        let inspector = Inspector::new();
        let task_id = inspector.register_task("test_task".to_string());
        let task = inspector.get_task(task_id).unwrap();
        assert_eq!(task.name, "test_task");
    }

    #[test]
    fn test_task_lifecycle() {
        let inspector = Inspector::new();
        let task_id = inspector.register_task("test".to_string());

        inspector.poll_started(task_id);
        inspector.poll_ended(task_id, Duration::from_millis(10));
        inspector.task_completed(task_id);

        let task = inspector.get_task(task_id).unwrap();
        assert_eq!(task.state, TaskState::Completed);
        assert_eq!(task.poll_count, 1);
    }

    #[test]
    fn test_stats() {
        let inspector = Inspector::new();
        inspector.register_task("task1".to_string());
        inspector.register_task("task2".to_string());

        let stats = inspector.stats();
        assert_eq!(stats.total_tasks, 2);
    }
}