kql-language-tools 0.1.0

Rust bindings to Kusto.Language for KQL validation and language services
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
//! Dynamic library loading for the native KQL validator
//!
//! This module handles finding and loading the .NET AOT native library
//! across different platforms.

use crate::error::Error;
use crate::ffi::{
    symbols, KqlCleanupFn, KqlGetClassificationsFn, KqlGetCompletionsFn, KqlGetLastErrorFn,
    KqlInitFn, KqlValidateSyntaxFn, KqlValidateWithSchemaFn,
};
use libloading::Library;
use once_cell::sync::OnceCell;
use std::path::PathBuf;

/// Environment variable for specifying library path
pub const LIB_PATH_ENV: &str = "KQL_LANGUAGE_TOOLS_PATH";

/// Platform-specific library name (DNNE-generated native export library)
#[cfg(target_os = "macos")]
pub const LIB_NAME: &str = "KqlLanguageFfiNE.dylib";

#[cfg(target_os = "linux")]
pub const LIB_NAME: &str = "KqlLanguageFfiNE.so";

#[cfg(target_os = "windows")]
pub const LIB_NAME: &str = "KqlLanguageFfiNE.dll";

/// Get the runtime identifier for the current platform
pub fn current_rid() -> &'static str {
    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    return "osx-arm64";

    #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
    return "osx-x64";

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    return "linux-x64";

    #[cfg(all(target_os = "linux", target_arch = "aarch64"))]
    return "linux-arm64";

    #[cfg(all(target_os = "windows", target_arch = "x86_64"))]
    return "win-x64";

    #[cfg(all(target_os = "windows", target_arch = "aarch64"))]
    return "win-arm64";
}

/// Find the native library path
///
/// Search order:
/// 1. `kql_language_tools_PATH` environment variable
/// 2. Same directory as the current executable
/// 3. `native/{rid}/` relative to the crate root
/// 4. Current working directory
pub fn find_library_path() -> Option<PathBuf> {
    // 1. Check environment variable
    if let Ok(path) = std::env::var(LIB_PATH_ENV) {
        let path = PathBuf::from(path);
        // If it's a file, use it directly
        if path.is_file() {
            log::debug!("Found library via {LIB_PATH_ENV}: {}", path.display());
            return Some(path);
        }
        // If it's a directory, look for the library file in it
        if path.is_dir() {
            let lib_path = path.join(LIB_NAME);
            if lib_path.exists() {
                log::debug!(
                    "Found library in {LIB_PATH_ENV} directory: {}",
                    lib_path.display()
                );
                return Some(lib_path);
            }
        }
    }

    // 2. Same directory as executable
    if let Ok(exe_path) = std::env::current_exe() {
        if let Some(exe_dir) = exe_path.parent() {
            let lib_path = exe_dir.join(LIB_NAME);
            if lib_path.exists() {
                log::debug!("Found library next to executable: {}", lib_path.display());
                return Some(lib_path);
            }
        }
    }

    // 3. Native directory relative to crate (for development)
    let native_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("dotnet")
        .join("native")
        .join(current_rid());
    let lib_path = native_dir.join(LIB_NAME);
    if lib_path.exists() {
        log::debug!("Found library in native directory: {}", lib_path.display());
        return Some(lib_path);
    }

    // 4. Current working directory
    let cwd_path = PathBuf::from(LIB_NAME);
    if cwd_path.exists() {
        log::debug!("Found library in current directory: {}", cwd_path.display());
        return Some(cwd_path);
    }

    log::debug!("Native library not found");
    None
}

/// Get the list of paths that were searched
pub fn searched_paths() -> Vec<PathBuf> {
    let mut paths = Vec::new();

    // Environment variable
    if let Ok(path) = std::env::var(LIB_PATH_ENV) {
        paths.push(PathBuf::from(&path));
        paths.push(PathBuf::from(path).join(LIB_NAME));
    }

    // Executable directory
    if let Ok(exe_path) = std::env::current_exe() {
        if let Some(exe_dir) = exe_path.parent() {
            paths.push(exe_dir.join(LIB_NAME));
        }
    }

    // Native directory
    let native_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("dotnet")
        .join("native")
        .join(current_rid());
    paths.push(native_dir.join(LIB_NAME));

    // Current directory
    paths.push(PathBuf::from(LIB_NAME));

    paths
}

/// Loaded library instance (singleton)
static LIBRARY: OnceCell<LoadedLibrary> = OnceCell::new();

/// Container for loaded library and function pointers
pub struct LoadedLibrary {
    /// The loaded library handle
    #[allow(dead_code)]
    library: Library,

    /// Initialize function
    pub init: KqlInitFn,

    /// Cleanup function (for future use)
    #[allow(dead_code)]
    pub cleanup: KqlCleanupFn,

    /// Validate syntax function
    pub validate_syntax: KqlValidateSyntaxFn,

    /// Get last error function
    pub get_last_error: KqlGetLastErrorFn,

    /// Validate with schema function (optional)
    pub validate_with_schema: Option<KqlValidateWithSchemaFn>,

    /// Get completions function (optional, Phase 2)
    pub get_completions: Option<KqlGetCompletionsFn>,

    /// Get classifications function (optional, Phase 3)
    pub get_classifications: Option<KqlGetClassificationsFn>,
}

// SAFETY: `LoadedLibrary` can be safely sent between threads because:
// 1. The `Library` handle from libloading is Send (it's just a handle/pointer)
// 2. All function pointers are plain data (Copy) with no interior mutability
// 3. The underlying .NET runtime (DNNE) initializes thread-safe state
// 4. We load the library exactly once via OnceLock, ensuring single initialization
unsafe impl Send for LoadedLibrary {}

// SAFETY: `LoadedLibrary` can be safely shared between threads because:
// 1. All methods take `&self` and only read the function pointers
// 2. The FFI functions are stateless from the caller's perspective
//    (any internal state in .NET runtime is managed thread-safely)
// 3. Multiple threads can safely call the same FFI functions concurrently
// 4. The Library handle itself is read-only after initialization
unsafe impl Sync for LoadedLibrary {}

impl LoadedLibrary {
    /// Load the library from the given path
    fn load_from(path: &PathBuf) -> Result<Self, Error> {
        log::info!("Loading KQL language library from {}", path.display());

        // SAFETY: Library::new loads a dynamic library from the filesystem.
        // This is safe because:
        // 1. The path has been validated to exist by find_library_path()
        // 2. We trust the library at this path (it's either user-provided or we built it)
        // 3. libloading handles the platform-specific loading correctly
        let library =
            unsafe { Library::new(path) }.map_err(|e| Error::library_load_failed(path, e))?;

        // SAFETY for all symbol loads below:
        // 1. The symbol names are compile-time constants matching the C ABI exports
        // 2. The function pointer types match the signatures in the .NET library
        // 3. libloading returns a reference that we dereference to get the fn pointer
        // 4. The library remains loaded for the lifetime of LoadedLibrary

        // Load required symbols
        let init: KqlInitFn = unsafe {
            *library
                .get(symbols::KQL_INIT.as_bytes())
                .map_err(|_| Error::SymbolNotFound {
                    symbol: symbols::KQL_INIT.to_string(),
                })?
        };

        let cleanup: KqlCleanupFn = unsafe {
            *library
                .get(symbols::KQL_CLEANUP.as_bytes())
                .map_err(|_| Error::SymbolNotFound {
                    symbol: symbols::KQL_CLEANUP.to_string(),
                })?
        };

        let validate_syntax: KqlValidateSyntaxFn = unsafe {
            *library
                .get(symbols::KQL_VALIDATE_SYNTAX.as_bytes())
                .map_err(|_| Error::SymbolNotFound {
                    symbol: symbols::KQL_VALIDATE_SYNTAX.to_string(),
                })?
        };

        let get_last_error: KqlGetLastErrorFn = unsafe {
            *library
                .get(symbols::KQL_GET_LAST_ERROR.as_bytes())
                .map_err(|_| Error::SymbolNotFound {
                    symbol: symbols::KQL_GET_LAST_ERROR.to_string(),
                })?
        };

        // Load optional symbols (don't fail if not present)
        let validate_with_schema: Option<KqlValidateWithSchemaFn> = unsafe {
            library
                .get(symbols::KQL_VALIDATE_WITH_SCHEMA.as_bytes())
                .ok()
                .map(|s| *s)
        };

        let get_completions: Option<KqlGetCompletionsFn> = unsafe {
            library
                .get(symbols::KQL_GET_COMPLETIONS.as_bytes())
                .ok()
                .map(|s| *s)
        };

        let get_classifications: Option<KqlGetClassificationsFn> = unsafe {
            library
                .get(symbols::KQL_GET_CLASSIFICATIONS.as_bytes())
                .ok()
                .map(|s| *s)
        };

        log::debug!(
            "Loaded symbols: validate_with_schema={}, get_completions={}, get_classifications={}",
            validate_with_schema.is_some(),
            get_completions.is_some(),
            get_classifications.is_some()
        );

        Ok(Self {
            library,
            init,
            cleanup,
            validate_syntax,
            get_last_error,
            validate_with_schema,
            get_completions,
            get_classifications,
        })
    }

    /// Check if schema validation is supported
    pub fn supports_schema_validation(&self) -> bool {
        self.validate_with_schema.is_some()
    }

    /// Check if completion is supported
    pub fn supports_completion(&self) -> bool {
        self.get_completions.is_some()
    }

    /// Check if classification is supported
    pub fn supports_classification(&self) -> bool {
        self.get_classifications.is_some()
    }
}

impl Drop for LoadedLibrary {
    fn drop(&mut self) {
        // SAFETY: cleanup is a valid function pointer loaded from the library.
        // It takes no arguments and has no preconditions.
        // We call it exactly once when the library is being unloaded.
        log::debug!("Calling kql_cleanup before unloading library");
        unsafe { (self.cleanup)() };
    }
}

/// Ensure `DOTNET_ROOT` is set for the .NET runtime
///
/// DNNE-based libraries require the .NET runtime, which needs `DOTNET_ROOT`
/// to be set on some systems (especially macOS with Homebrew).
fn ensure_dotnet_root() {
    // Skip if already set
    if std::env::var("DOTNET_ROOT").is_ok() {
        return;
    }

    // Try to find dotnet and derive DOTNET_ROOT
    if let Some(dotnet_root) = find_dotnet_root() {
        log::debug!("Auto-detected DOTNET_ROOT: {}", dotnet_root.display());
        std::env::set_var("DOTNET_ROOT", &dotnet_root);
    }
}

/// Try to find the .NET runtime root directory
fn find_dotnet_root() -> Option<PathBuf> {
    // Common locations to check
    let candidates = [
        // Homebrew on Apple Silicon
        "/opt/homebrew/Cellar/dotnet",
        // Homebrew on Intel Mac
        "/usr/local/Cellar/dotnet",
        // Standard Linux/macOS locations
        "/usr/share/dotnet",
        "/usr/local/share/dotnet",
        // Windows default
        "C:\\Program Files\\dotnet",
    ];

    // First, try to find via `dotnet --info` output
    if let Ok(output) = std::process::Command::new("dotnet")
        .args(["--info"])
        .output()
    {
        if output.status.success() {
            let info = String::from_utf8_lossy(&output.stdout);
            // Look for "Base Path:" line which contains the SDK path
            // e.g., "Base Path:   /opt/homebrew/Cellar/dotnet/9.0.8/libexec/sdk/9.0.109/"
            for line in info.lines() {
                if line.trim().starts_with("Base Path:") {
                    if let Some(path_str) = line.split(':').nth(1) {
                        let path = PathBuf::from(path_str.trim());
                        // Navigate up to find libexec (the actual runtime root)
                        // Path is like: .../libexec/sdk/X.Y.Z/ -> we want .../libexec
                        if let Some(libexec) = path.ancestors().find(|p| p.ends_with("libexec")) {
                            return Some(libexec.to_path_buf());
                        }
                        // Or try to find the dotnet root another way
                        if let Some(dotnet_dir) = path
                            .ancestors()
                            .find(|p| p.join("dotnet").exists() || p.join("shared").exists())
                        {
                            return Some(dotnet_dir.to_path_buf());
                        }
                    }
                }
            }
        }
    }

    // Fall back to checking known locations
    for candidate in candidates {
        let path = PathBuf::from(candidate);
        if path.exists() {
            // For Homebrew, we need to find the version directory with libexec
            if candidate.contains("Cellar") {
                if let Ok(entries) = std::fs::read_dir(&path) {
                    // Find the latest version directory
                    let mut versions: Vec<_> = entries
                        .filter_map(std::result::Result::ok)
                        .filter(|e| e.path().is_dir())
                        .collect();
                    versions.sort_by_key(|b| std::cmp::Reverse(b.path()));

                    if let Some(version_dir) = versions.first() {
                        let libexec = version_dir.path().join("libexec");
                        if libexec.exists() {
                            return Some(libexec);
                        }
                    }
                }
            } else if path.join("shared").exists() {
                return Some(path);
            }
        }
    }

    None
}

/// Load the library (or get cached instance)
pub fn load_library() -> Result<&'static LoadedLibrary, Error> {
    LIBRARY.get_or_try_init(|| {
        // Ensure DOTNET_ROOT is set for DNNE libraries
        ensure_dotnet_root();

        let path = find_library_path().ok_or_else(|| Error::LibraryNotFound {
            searched_paths: searched_paths(),
        })?;

        let lib = LoadedLibrary::load_from(&path)?;

        // Initialize the library
        let result = unsafe { (lib.init)() };
        if result != 0 {
            // Get error message
            let mut error_buf = vec![0u8; 1024];
            #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
            let error_len =
                unsafe { (lib.get_last_error)(error_buf.as_mut_ptr(), error_buf.len() as i32) };
            let message = if error_len > 0 {
                #[allow(clippy::cast_sign_loss)]
                let len = error_len as usize;
                String::from_utf8_lossy(&error_buf[..len]).to_string()
            } else {
                format!("Initialization returned error code: {result}")
            };
            return Err(Error::InitializationFailed { message });
        }

        log::info!("KQL language library initialized successfully");
        Ok(lib)
    })
}

/// Check if the library is loaded
#[allow(dead_code)]
pub fn is_loaded() -> bool {
    LIBRARY.get().is_some()
}

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

    #[test]
    fn test_current_rid() {
        let rid = current_rid();
        assert!(!rid.is_empty());
        #[cfg(target_os = "macos")]
        assert!(rid.starts_with("osx-"));
        #[cfg(target_os = "linux")]
        assert!(rid.starts_with("linux-"));
        #[cfg(target_os = "windows")]
        assert!(rid.starts_with("win-"));
    }

    #[test]
    fn test_searched_paths_not_empty() {
        let paths = searched_paths();
        assert!(!paths.is_empty());
    }
}