no-block-pls 0.1.0

Instrument async Rust code to surface blocking work between await points
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
pub mod transformer;

#[cfg(test)]
mod loop_test;

use anyhow::Result;
use std::fs;
use std::path::Path;
use syn::{ExprAsync, File, ImplItemFn, Item, ItemFn, parse_file, parse_quote, visit::Visit};
use transformer::AsyncInstrumenter;

/// Visitor to check if a file contains any async code
struct AsyncDetector {
    has_async: bool,
}

impl AsyncDetector {
    fn new() -> Self {
        Self { has_async: false }
    }

    fn check(file: &File) -> bool {
        let mut detector = Self::new();
        detector.visit_file(file);
        detector.has_async
    }
}

impl<'ast> Visit<'ast> for AsyncDetector {
    fn visit_expr_async(&mut self, _: &'ast ExprAsync) {
        self.has_async = true;
    }

    fn visit_impl_item_fn(&mut self, func: &'ast ImplItemFn) {
        if func.sig.asyncness.is_some() {
            self.has_async = true;
            return;
        }
        syn::visit::visit_impl_item_fn(self, func);
    }

    fn visit_item_fn(&mut self, func: &'ast ItemFn) {
        if func.sig.asyncness.is_some() {
            self.has_async = true;
            return;
        }
        syn::visit::visit_item_fn(self, func);
    }
}

#[derive(Default)]
struct InstrumentationDetector {
    already_instrumented: bool,
}

impl InstrumentationDetector {
    fn check(file: &File) -> bool {
        let mut detector = Self::default();
        detector.visit_file(file);
        detector.already_instrumented
    }
}

impl<'ast> Visit<'ast> for InstrumentationDetector {
    fn visit_item_mod(&mut self, module: &'ast syn::ItemMod) {
        if module.ident == "__async_profile_guard__" {
            self.already_instrumented = true;
            return;
        }
        syn::visit::visit_item_mod(self, module);
    }

    fn visit_path(&mut self, path: &'ast syn::Path) {
        if self.already_instrumented {
            return;
        }

        let segments: Vec<_> = path.segments.iter().map(|s| s.ident.to_string()).collect();

        if segments.windows(3).any(|window| {
            window[0] == "__async_profile_guard__" && window[1] == "Guard" && window[2] == "new"
        }) {
            self.already_instrumented = true;
            return;
        }

        syn::visit::visit_path(self, path);
    }
}

/// Generate the guard module code with the specified threshold
fn generate_guard_module(threshold_ms: u64) -> Item {
    parse_quote! {
        #[doc(hidden)]
        #[allow(dead_code)]
        mod __async_profile_guard__ {
            use std::time::{Duration, Instant};

            const THRESHOLD_MS: u64 = #threshold_ms;

            pub struct Guard {
                name: &'static str,
                file: &'static str,
                from_line: u32,
                current_start: Option<Instant>,
                consecutive_hits: u32,
            }

            impl Guard {
                pub fn new(name: &'static str, file: &'static str, line: u32) -> Self {
                    Guard {
                        name,
                        file,
                        from_line: line,
                        current_start: Some(Instant::now()),
                        consecutive_hits: 0,
                    }
                }

                pub fn checkpoint(&mut self, new_line: u32) {
                    if let Some(start) = self.current_start.take() {
                        let elapsed = start.elapsed();
                        if elapsed > Duration::from_millis(THRESHOLD_MS) {
                            self.consecutive_hits = self.consecutive_hits.saturating_add(1);
                            let span = format!("{file}:{from}-{to}", file = self.file, from = self.from_line, to = new_line);
                            let wraparound = new_line < self.from_line;
                            if wraparound {
                                tracing::warn!(
                                    elapsed_ms = elapsed.as_millis(),
                                    name = %self.name,
                                    span = %span,
                                    hits = self.consecutive_hits,
                                    wraparound = wraparound,
                                    "long poll (iteration tail wraparound)"
                                );
                            } else {
                                tracing::warn!(
                                    elapsed_ms = elapsed.as_millis(),
                                    name = %self.name,
                                    span = %span,
                                    hits = self.consecutive_hits,
                                    wraparound = wraparound,
                                    "long poll (iteration tail)"
                                );
                            }
                        } else {
                            self.consecutive_hits = 0;
                        }
                    }
                    self.from_line = new_line;
                    self.current_start = Some(Instant::now());
                }

                pub fn end_section(&mut self, to_line: u32) {
                    if let Some(start) = self.current_start.take() {
                        let elapsed = start.elapsed();
                        if elapsed > Duration::from_millis(THRESHOLD_MS) {
                            self.consecutive_hits = self.consecutive_hits.saturating_add(1);
                            let span = format!("{file}:{from}-{to}", file = self.file, from = self.from_line, to = to_line);
                            let wraparound = to_line < self.from_line;
                            if wraparound {
                                tracing::warn!(
                                    elapsed_ms = elapsed.as_millis(),
                                    name = %self.name,
                                    span = %span,
                                    hits = self.consecutive_hits,
                                    wraparound = wraparound,
                                    "long poll (loop wraparound)"
                                );
                            } else {
                                tracing::warn!(
                                    elapsed_ms = elapsed.as_millis(),
                                    name = %self.name,
                                    span = %span,
                                    hits = self.consecutive_hits,
                                    wraparound = wraparound,
                                    "long poll"
                                );
                            }
                        } else {
                            self.consecutive_hits = 0;
                        }
                    }
                }

                pub fn start_section(&mut self, new_line: u32) {
                    self.from_line = new_line;
                    self.current_start = Some(Instant::now());
                }
            }

            impl Drop for Guard {
                fn drop(&mut self) {
                    // Check final section if still timing
                    if let Some(start) = self.current_start {
                        let elapsed = start.elapsed();
                        if elapsed > Duration::from_millis(THRESHOLD_MS) {
                            self.consecutive_hits = self.consecutive_hits.saturating_add(1);
                            let span =
                                format!("{file}:{line}-{line}", file = self.file, line = self.from_line);
                            tracing::warn!(
                                elapsed_ms = elapsed.as_millis(),
                                name = %self.name,
                                span = %span,
                                hits = self.consecutive_hits,
                                wraparound = false,
                                "long poll"
                            );
                        }
                    }
                }
            }
        }
    }
}

/// Inject the guard module into a root file (lib.rs or main.rs)
/// This should only be called once per crate
pub fn inject_guard_module(source: &str, threshold_ms: u64) -> Result<String> {
    let mut syntax_tree = parse_file(source)?;

    if InstrumentationDetector::check(&syntax_tree) {
        return Ok(source.to_owned());
    }

    // Insert guard module at the beginning
    let guard_module = generate_guard_module(threshold_ms);
    syntax_tree.items.insert(0, guard_module);

    // Also instrument any async functions in this file
    let mut instrumenter = AsyncInstrumenter::new(threshold_ms);
    instrumenter.instrument_file(&mut syntax_tree);

    let formatted = prettyplease::unparse(&syntax_tree);
    Ok(formatted)
}

/// Instrument async functions without injecting the guard module
/// Use this for all non-root files (assumes guard module exists in crate root)
/// Returns None if the file has no async code
pub fn instrument_async_only(source: &str) -> Result<Option<String>> {
    let mut syntax_tree = parse_file(source)?;

    if InstrumentationDetector::check(&syntax_tree) {
        return Ok(None);
    }

    // Check if file has any async code
    if !AsyncDetector::check(&syntax_tree) {
        return Ok(None);
    }

    // Only instrument async functions, don't inject guard module
    let mut instrumenter = AsyncInstrumenter::new(10);
    instrumenter.instrument_file(&mut syntax_tree);

    let formatted = prettyplease::unparse(&syntax_tree);
    Ok(Some(formatted))
}

/// Process a single Rust source file and return the instrumented code with default threshold
/// This injects the guard module AND instruments async functions (backward compatibility)
pub fn instrument_code(source: &str) -> Result<String> {
    instrument_code_with_threshold(source, 10)
}

/// Process a single Rust source file and return the instrumented code with specified threshold
/// This injects the guard module AND instruments async functions (backward compatibility)
pub fn instrument_code_with_threshold(source: &str, threshold_ms: u64) -> Result<String> {
    inject_guard_module(source, threshold_ms)
}

/// Process a file at the given path and return the instrumented code with default threshold
pub fn instrument_file(path: &Path) -> Result<String> {
    let content = fs::read_to_string(path)?;
    instrument_code(&content)
}

/// Process a file at the given path and return the instrumented code with specified threshold
pub fn instrument_file_with_threshold(path: &Path, threshold_ms: u64) -> Result<String> {
    let content = fs::read_to_string(path)?;
    instrument_code_with_threshold(&content, threshold_ms)
}

/// Process a file and write the instrumented version back (with backup)
pub fn instrument_file_in_place(path: &Path) -> Result<()> {
    let instrumented = instrument_file(path)?;

    // Create backup
    let backup_path = path.with_extension("rs.bak");
    fs::copy(path, &backup_path)?;

    // Write instrumented version
    fs::write(path, instrumented)?;

    Ok(())
}

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

    #[test]
    fn test_inject_guard_module() {
        let source = r#"
async fn fetch_data() {
    let response = client.get().await;
    let parsed = parse(response);
    store(parsed).await;
}
"#;

        let result = inject_guard_module(source, 10).unwrap();
        assert!(result.contains("mod __async_profile_guard__"));
        assert!(result.contains("__guard"));
        assert!(result.contains("__guard.end_section("));
        assert!(result.contains("__guard.start_section("));
        assert!(!result.contains("line!()"));
    }

    #[test]
    fn test_instrument_async_only() {
        let source = r#"
async fn fetch_data() {
    let response = client.get().await;
    let parsed = parse(response);
    store(parsed).await;
}
"#;

        let result = instrument_async_only(source).unwrap();
        assert!(result.is_some(), "Should instrument async functions");
        let instrumented = result.unwrap();
        // Should NOT contain the module definition
        assert!(!instrumented.contains("mod __async_profile_guard__"));
        // But should contain references to it
        assert!(instrumented.contains("crate::__async_profile_guard__::Guard::new"));
        assert!(instrumented.contains("__guard.end_section("));
        assert!(instrumented.contains("__guard.start_section("));
        assert!(!instrumented.contains("line!()"));
    }

    #[test]
    fn test_instrument_async_only_idempotent() {
        let source = r#"
async fn fetch_data() {
    let response = client.get().await;
    store(response).await;
}
"#;

        let first = instrument_async_only(source).unwrap().unwrap();
        assert!(instrument_async_only(&first).unwrap().is_none());
    }

    #[test]
    fn test_inject_guard_module_idempotent() {
        let source = r#"
async fn action() {
    do_it().await;
}
"#;

        let first = inject_guard_module(source, 10).unwrap();
        let second = inject_guard_module(&first, 10).unwrap();
        assert_eq!(first, second);
    }

    #[test]
    fn test_skip_non_async_file() {
        let source = r#"
fn regular_function() {
    println!("No async here");
}

struct MyStruct {
    field: String,
}

impl MyStruct {
    fn new() -> Self {
        Self { field: String::new() }
    }
}
"#;

        let result = instrument_async_only(source).unwrap();
        assert!(result.is_none(), "Should skip files without async code");
    }

    #[test]
    fn test_detect_async_in_impl() {
        let source = r#"
struct Service;

impl Service {
    async fn handle_request(&self) {
        tokio::time::sleep(Duration::from_millis(100)).await;
    }
}
"#;

        let result = instrument_async_only(source).unwrap();
        assert!(
            result.is_some(),
            "Should detect async methods in impl blocks"
        );
    }

    #[test]
    fn test_detect_async_block() {
        let source = r#"
fn spawn_task() {
    tokio::spawn(async {
        println!("In async block");
    });
}
"#;

        let result = instrument_async_only(source).unwrap();
        assert!(result.is_some(), "Should detect async blocks");
    }

    #[test]
    fn test_instrument_code() {
        let source = r#"
async fn fetch_data() {
    let response = client.get().await;
    let parsed = parse(response);
    store(parsed).await;
}
"#;

        let result = instrument_code(source).unwrap();
        assert!(result.contains("__guard"));
        assert!(result.contains("__guard.end_section("));
        assert!(result.contains("__guard.start_section("));
        assert!(!result.contains("line!()"));
    }

    #[test]
    fn test_no_instrument_sync() {
        let source = r#"
fn sync_function() {
    let x = 42;
    println!("{}", x);
}
"#;

        let result = instrument_code(source).unwrap();
        assert!(!result.contains("__guard"));
    }
}