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
//! Language Server Protocol (LSP) integration for async-inspect
//!
//! This module provides a Language Server Protocol server that enables async-inspect
//! functionality in any LSP-compatible editor (vim, emacs, Sublime Text, etc.).
//!
//! # Features
//!
//! - **Code Actions**: Quick-fix suggestions for adding async-inspect instrumentation
//! - **Diagnostics**: Warnings for potential async issues and performance problems
//! - **Hover Information**: Display task statistics and performance metrics
//! - **Completion**: Auto-complete for async-inspect methods
//!
//! # Example
//!
//! ```no_run
//! use async_inspect::lsp::AsyncInspectLanguageServer;
//!
//! #[tokio::main]
//! async fn main() {
//!     let (service, socket) = tower_lsp::LspService::new(|client| {
//!         AsyncInspectLanguageServer::new(client)
//!     });
//!
//!     tower_lsp::Server::new(tokio::io::stdin(), tokio::io::stdout(), socket)
//!         .serve(service)
//!         .await;
//! }
//! ```

#[cfg(feature = "lsp")]
use crate::inspector::Inspector;

#[cfg(feature = "lsp")]
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};

#[cfg(feature = "lsp")]
use tower_lsp::jsonrpc::Result;

#[cfg(feature = "lsp")]
use tower_lsp::lsp_types::{
    ClientCapabilities, CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams,
    CodeActionProviderCapability, CodeActionResponse, CompletionItem, CompletionItemKind,
    CompletionOptions, CompletionParams, CompletionResponse, Diagnostic, DiagnosticSeverity,
    DidChangeTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams,
    Documentation, Hover, HoverContents, HoverParams, HoverProviderCapability, InitializeParams,
    InitializeResult, InitializedParams, InsertTextFormat, MarkupContent, MarkupKind, MessageType,
    NumberOrString, Position, Range, ServerCapabilities, ServerInfo, TextDocumentSyncCapability,
    TextDocumentSyncKind, TextEdit, Url, WorkspaceEdit,
};

#[cfg(feature = "lsp")]
use tower_lsp::{Client, LanguageServer};

#[cfg(feature = "lsp")]
use std::sync::Arc;

#[cfg(feature = "lsp")]
use parking_lot::RwLock;

/// Language server for async-inspect
#[cfg(feature = "lsp")]
pub struct AsyncInspectLanguageServer {
    /// LSP client for sending notifications
    client: Client,

    /// Inspector instance
    inspector: &'static Inspector,

    /// Server state
    state: Arc<RwLock<ServerState>>,
}

#[cfg(feature = "lsp")]
struct ServerState {
    /// Workspace root URI
    workspace_root: Option<Url>,

    /// Client capabilities
    client_capabilities: Option<ClientCapabilities>,
}

#[cfg(feature = "lsp")]
impl AsyncInspectLanguageServer {
    /// Create a new language server instance
    #[must_use]
    pub fn new(client: Client) -> Self {
        Self {
            client,
            inspector: Inspector::global(),
            state: Arc::new(RwLock::new(ServerState {
                workspace_root: None,
                client_capabilities: None,
            })),
        }
    }

    /// Analyze document and provide diagnostics
    async fn analyze_document(&self, _uri: Url, text: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Check for untracked async tasks
        if text.contains("tokio::spawn") && !text.contains("spawn_tracked") {
            // Find all tokio::spawn occurrences
            for (line_num, line) in text.lines().enumerate() {
                if line.contains("tokio::spawn") && !line.contains("spawn_tracked") {
                    let col = line.find("tokio::spawn").unwrap_or(0);

                    diagnostics.push(Diagnostic {
                        range: Range {
                            start: Position {
                                line: line_num as u32,
                                character: col as u32,
                            },
                            end: Position {
                                line: line_num as u32,
                                character: (col + "tokio::spawn".len()) as u32,
                            },
                        },
                        severity: Some(DiagnosticSeverity::HINT),
                        code: Some(NumberOrString::String("async-inspect-001".to_string())),
                        source: Some("async-inspect".to_string()),
                        message: "Consider using spawn_tracked for better async debugging"
                            .to_string(),
                        related_information: None,
                        tags: None,
                        code_description: None,
                        data: None,
                    });
                }
            }
        }

        // Check for missing .inspect() on awaits
        if text.contains(".await") && text.contains("async fn") {
            for (line_num, line) in text.lines().enumerate() {
                if line.contains(".await") && !line.contains(".inspect(") {
                    let col = line.find(".await").unwrap_or(0);

                    diagnostics.push(Diagnostic {
                        range: Range {
                            start: Position {
                                line: line_num as u32,
                                character: col as u32,
                            },
                            end: Position {
                                line: line_num as u32,
                                character: (col + ".await".len()) as u32,
                            },
                        },
                        severity: Some(DiagnosticSeverity::INFORMATION),
                        code: Some(NumberOrString::String("async-inspect-002".to_string())),
                        source: Some("async-inspect".to_string()),
                        message: "Add .inspect() to track this await point".to_string(),
                        related_information: None,
                        tags: None,
                        code_description: None,
                        data: None,
                    });
                }
            }
        }

        diagnostics
    }

    /// Provide code actions for diagnostics
    fn provide_code_actions(&self, params: &CodeActionParams) -> Vec<CodeActionOrCommand> {
        let mut actions = Vec::new();

        for diagnostic in &params.context.diagnostics {
            if let Some(NumberOrString::String(code)) = &diagnostic.code {
                match code.as_str() {
                    "async-inspect-001" => {
                        // Convert tokio::spawn to spawn_tracked
                        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
                            title: "Use spawn_tracked instead".to_string(),
                            kind: Some(CodeActionKind::QUICKFIX),
                            diagnostics: Some(vec![diagnostic.clone()]),
                            edit: Some(WorkspaceEdit {
                                changes: Some(
                                    [(
                                        params.text_document.uri.clone(),
                                        vec![TextEdit {
                                            range: diagnostic.range,
                                            new_text: "spawn_tracked".to_string(),
                                        }],
                                    )]
                                    .iter()
                                    .cloned()
                                    .collect(),
                                ),
                                document_changes: None,
                                change_annotations: None,
                            }),
                            command: None,
                            is_preferred: Some(true),
                            disabled: None,
                            data: None,
                        }));
                    }
                    "async-inspect-002" => {
                        // Add .inspect() before .await
                        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
                            title: "Add .inspect() tracking".to_string(),
                            kind: Some(CodeActionKind::QUICKFIX),
                            diagnostics: Some(vec![diagnostic.clone()]),
                            edit: Some(WorkspaceEdit {
                                changes: Some(
                                    [(
                                        params.text_document.uri.clone(),
                                        vec![TextEdit {
                                            range: Range {
                                                start: diagnostic.range.start,
                                                end: diagnostic.range.start,
                                            },
                                            new_text: ".inspect(\"await_point\")".to_string(),
                                        }],
                                    )]
                                    .iter()
                                    .cloned()
                                    .collect(),
                                ),
                                document_changes: None,
                                change_annotations: None,
                            }),
                            command: None,
                            is_preferred: Some(true),
                            disabled: None,
                            data: None,
                        }));
                    }
                    _ => {}
                }
            }
        }

        actions
    }

    /// Provide hover information
    fn provide_hover(&self, _params: &HoverParams) -> Option<Hover> {
        let stats = self.inspector.stats();

        let markdown = format!(
            "## Async Inspect Statistics\n\n\
            - **Total Tasks:** {}\n\
            - **Running Tasks:** {}\n\
            - **Completed Tasks:** {}\n\
            - **Failed Tasks:** {}\n\
            - **Blocked Tasks:** {}\n\n\
            [Open Dashboard](http://localhost:8080)",
            stats.total_tasks,
            stats.running_tasks,
            stats.completed_tasks,
            stats.failed_tasks,
            stats.blocked_tasks
        );

        Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: markdown,
            }),
            range: None,
        })
    }
}

#[cfg(feature = "lsp")]
#[tower_lsp::async_trait]
impl LanguageServer for AsyncInspectLanguageServer {
    async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
        {
            let mut state = self.state.write();
            state.workspace_root = params.root_uri;
            state.client_capabilities = Some(params.capabilities);
        } // Drop the lock before await

        self.client
            .log_message(MessageType::INFO, "async-inspect LSP server initialized")
            .await;

        Ok(InitializeResult {
            server_info: Some(ServerInfo {
                name: "async-inspect-lsp".to_string(),
                version: Some(env!("CARGO_PKG_VERSION").to_string()),
            }),
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncCapability::Kind(
                    TextDocumentSyncKind::FULL,
                )),
                hover_provider: Some(HoverProviderCapability::Simple(true)),
                code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
                completion_provider: Some(CompletionOptions {
                    resolve_provider: Some(false),
                    trigger_characters: Some(vec![".".to_string()]),
                    work_done_progress_options: Default::default(),
                    all_commit_characters: None,
                    completion_item: None,
                }),
                ..Default::default()
            },
        })
    }

    async fn initialized(&self, _: InitializedParams) {
        self.client
            .log_message(MessageType::INFO, "async-inspect LSP server ready")
            .await;
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let uri = params.text_document.uri;
        let text = params.text_document.text;

        let diagnostics = self.analyze_document(uri.clone(), &text).await;

        self.client
            .publish_diagnostics(uri, diagnostics, Some(params.text_document.version))
            .await;
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        let uri = params.text_document.uri;
        let text = &params.content_changes[0].text;

        let diagnostics = self.analyze_document(uri.clone(), text).await;

        self.client
            .publish_diagnostics(uri, diagnostics, Some(params.text_document.version))
            .await;
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        if let Some(text) = params.text {
            let diagnostics = self
                .analyze_document(params.text_document.uri.clone(), &text)
                .await;

            self.client
                .publish_diagnostics(params.text_document.uri, diagnostics, None)
                .await;
        }
    }

    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
        Ok(self.provide_hover(&params))
    }

    async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
        let actions = self.provide_code_actions(&params);

        if actions.is_empty() {
            Ok(None)
        } else {
            Ok(Some(actions))
        }
    }

    async fn completion(&self, _params: CompletionParams) -> Result<Option<CompletionResponse>> {
        let items = vec![
            CompletionItem {
                label: "spawn_tracked".to_string(),
                kind: Some(CompletionItemKind::FUNCTION),
                detail: Some("Spawn a tracked async task".to_string()),
                documentation: Some(Documentation::MarkupContent(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: "Spawns an async task with automatic tracking by async-inspect.\n\n\
                            ```rust\n\
                            spawn_tracked(\"task_name\", async { /* ... */ });\n\
                            ```"
                    .to_string(),
                })),
                insert_text: Some("spawn_tracked(\"${1:task_name}\", ${2:future})".to_string()),
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                ..Default::default()
            },
            CompletionItem {
                label: "inspect".to_string(),
                kind: Some(CompletionItemKind::METHOD),
                detail: Some("Track an await point".to_string()),
                documentation: Some(Documentation::MarkupContent(MarkupContent {
                    kind: MarkupKind::Markdown,
                    value: "Track an await point with a label.\n\n\
                            ```rust\n\
                            future.inspect(\"await_label\").await\n\
                            ```"
                    .to_string(),
                })),
                insert_text: Some("inspect(\"${1:label}\")".to_string()),
                insert_text_format: Some(InsertTextFormat::SNIPPET),
                ..Default::default()
            },
        ];

        Ok(Some(CompletionResponse::Array(items)))
    }
}

#[cfg(not(feature = "lsp"))]
compile_error!("The lsp module requires the 'lsp' feature to be enabled");