tauri-plugin-velesdb 1.8.0

Tauri plugin for VelesDB - Vector search in desktop apps
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
// Tauri plugin - pedantic/nursery lints relaxed
#![allow(clippy::pedantic)]
#![allow(clippy::nursery)]

//! # tauri-plugin-velesdb
//!
//! A Tauri plugin for `VelesDB` - Vector search in desktop applications.
//!
//! This plugin provides seamless integration of `VelesDB`'s vector database
//! capabilities into Tauri desktop applications.
//!
//! ## Features
//!
//! - **Collection Management**: Create, list, and delete vector collections
//! - **Vector Operations**: Insert, update, and delete vectors with payloads
//! - **Vector Search**: Fast similarity search with multiple distance metrics
//! - **Text Search**: BM25 full-text search across payloads
//! - **Hybrid Search**: Combined vector + text search with RRF fusion
//! - **`VelesQL`**: SQL-like query language for advanced searches
//!
//! ## Usage
//!
//! ### Rust (Plugin Registration)
//!
//! ```rust,ignore
//! fn main() {
//!     tauri::Builder::default()
//!         .plugin(tauri_plugin_velesdb::init("./data"))
//!         .run(tauri::generate_context!())
//!         .expect("error while running tauri application");
//! }
//! ```
//!
//! ### JavaScript (Frontend)
//!
//! ```javascript
//! import { invoke } from '@tauri-apps/api/core';
//!
//! // Create a collection
//! await invoke('plugin:velesdb|create_collection', {
//!   request: { name: 'documents', dimension: 768, metric: 'cosine' }
//! });
//!
//! // Insert vectors
//! await invoke('plugin:velesdb|upsert', {
//!   request: {
//!     collection: 'documents',
//!     points: [{ id: 1, vector: [...], payload: { title: 'Doc' } }]
//!   }
//! });
//!
//! // Search
//! const results = await invoke('plugin:velesdb|search', {
//!   request: { collection: 'documents', vector: [...], topK: 10 }
//! });
//! ```

#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]

use std::path::Path;

use tauri::{
    plugin::{Builder, TauriPlugin},
    Manager, Runtime,
};

pub mod commands;
pub mod commands_graph;
pub mod error;
pub mod events;
pub mod helpers;
pub mod state;
pub mod types;

pub use error::{CommandError, Error, Result};
pub use state::VelesDbState;

// ============================================================================
// Simple In-Memory Index for Demo (VelesDbExt trait)
// ============================================================================

use std::collections::HashMap;
use std::sync::Arc;

use parking_lot::RwLock;

// Use DistanceMetric from velesdb_core
use velesdb_core::DistanceMetric;

/// Simple in-memory vector index for demo/prototyping purposes.
///
/// **WARNING:** O(n) brute-force search — not suitable beyond 10,000 vectors.
/// No persistence, no HNSW acceleration. For production workloads, use the
/// full plugin commands backed by `VelesDbState` which provides persistent
/// HNSW-indexed collections.
pub(crate) struct SimpleVectorIndex {
    vectors: HashMap<u64, Vec<f32>>,
    dimension: usize,
    metric: DistanceMetric,
}

impl SimpleVectorIndex {
    /// Creates a new empty index with the given dimension.
    #[must_use]
    pub fn new(dimension: usize) -> Self {
        Self {
            vectors: HashMap::new(),
            dimension,
            metric: DistanceMetric::Cosine, // Default metric
        }
    }

    /// Inserts a vector with the given ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the vector dimension doesn't match the index dimension.
    pub fn insert(&mut self, id: u64, vector: &[f32]) -> Result<()> {
        if vector.len() != self.dimension {
            return Err(Error::InvalidConfig(format!(
                "Vector dimension mismatch: expected {}, got {}",
                self.dimension,
                vector.len()
            )));
        }
        self.vectors.insert(id, vector.to_vec());
        Ok(())
    }

    /// Searches for the k most similar vectors.
    ///
    /// # Errors
    ///
    /// Returns an error if the query dimension doesn't match the index dimension.
    pub fn search(&self, query: &[f32], k: usize) -> Result<Vec<(u64, f32)>> {
        if query.len() != self.dimension {
            return Err(Error::InvalidConfig(format!(
                "Query dimension mismatch: expected {}, got {}",
                self.dimension,
                query.len()
            )));
        }

        let mut scores: Vec<(u64, f32)> = self
            .vectors
            .iter()
            .map(|(id, vec)| {
                let score = self.metric.calculate(query, vec);
                (*id, score)
            })
            .collect();

        // Sort by score according to metric ordering
        self.metric.sort_results(&mut scores);
        scores.truncate(k);
        Ok(scores)
    }

    /// Returns the number of vectors in the index.
    #[must_use]
    pub fn len(&self) -> usize {
        self.vectors.len()
    }

    /// Returns true if the index is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.vectors.is_empty()
    }

    /// Returns the dimension of vectors in this index.
    #[must_use]
    pub fn dimension(&self) -> usize {
        self.dimension
    }

    /// Clears all vectors from the index.
    pub fn clear(&mut self) {
        self.vectors.clear();
    }
}

/// State for the simple vector index (used by `VelesDbExt`).
pub(crate) struct SimpleIndexState(pub(crate) Arc<RwLock<SimpleVectorIndex>>);

/// Extension trait for easy access to `VelesDB` from Tauri `AppHandle`.
pub trait VelesDbExt<R: Runtime> {
    /// Returns a handle to the simple vector index, or `None` if not initialized.
    ///
    /// Returns `None` when `init()` has not been called before this method.
    fn velesdb(&self) -> Option<SimpleIndexHandle>;
}

impl<R: Runtime, T: Manager<R>> VelesDbExt<R> for T {
    fn velesdb(&self) -> Option<SimpleIndexHandle> {
        self.try_state::<SimpleIndexState>()
            .map(|state| SimpleIndexHandle(Arc::clone(&state.0)))
    }
}

/// Handle to interact with the simple vector index.
pub struct SimpleIndexHandle(Arc<RwLock<SimpleVectorIndex>>);

impl SimpleIndexHandle {
    /// Inserts a vector with the given ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the vector dimension doesn't match the index dimension.
    ///
    pub fn insert(&self, id: u64, vector: &[f32]) -> Result<()> {
        self.0.write().insert(id, vector)
    }

    /// Searches for the k most similar vectors.
    ///
    /// # Errors
    ///
    /// Returns an error if the query dimension doesn't match the index dimension.
    ///
    pub fn search(&self, query: &[f32], k: usize) -> Result<Vec<(u64, f32)>> {
        self.0.read().search(query, k)
    }

    /// Returns the number of vectors in the index.
    ///
    /// Returns `0` and logs an error if the index state is unavailable.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.read().len()
    }

    /// Returns true if the index is empty.
    ///
    /// Returns `true` and logs an error if the index state is unavailable.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.read().is_empty()
    }

    /// Returns the dimension of vectors in this index.
    ///
    /// Returns `0` and logs an error if the index state is unavailable.
    #[must_use]
    pub fn dimension(&self) -> usize {
        self.0.read().dimension()
    }

    /// Clears all vectors from the index.
    pub fn clear(&self) {
        self.0.write().clear();
    }
}

/// Initializes the `VelesDB` plugin with the default settings.
///
/// Uses `./velesdb_data` as the default path for persistence.
/// This is the simplest way to get started.
///
/// # Example
///
/// ```rust,ignore
/// tauri::Builder::default()
///     .plugin(tauri_plugin_velesdb::init())
///     .run(tauri::generate_context!())
///     .expect("error while running tauri application");
/// ```
#[must_use]
pub fn init<R: Runtime>() -> TauriPlugin<R> {
    init_with_path("./velesdb_data")
}

/// Initializes the `VelesDB` plugin with a custom data directory.
///
/// # Arguments
///
/// * `path` - Path to the database directory
///
/// # Example
///
/// ```rust,ignore
/// tauri::Builder::default()
///     .plugin(tauri_plugin_velesdb::init_with_path("./my_data"))
///     .run(tauri::generate_context!())
///     .expect("error while running tauri application");
/// ```
#[must_use]
pub fn init_with_path<R: Runtime, P: AsRef<Path>>(path: P) -> TauriPlugin<R> {
    let db_path = path.as_ref().to_path_buf();

    #[cfg(feature = "persistence")]
    let builder = Builder::new("velesdb").invoke_handler(tauri::generate_handler![
        commands::create_collection,
        commands::create_metadata_collection,
        commands::delete_collection,
        commands::list_collections,
        commands::get_collection,
        commands::upsert,
        commands::upsert_metadata,
        commands::get_points,
        commands::delete_points,
        commands::search,
        commands::batch_search,
        commands::text_search,
        commands::hybrid_search,
        commands::multi_query_search,
        commands::query,
        commands::is_empty,
        commands::flush,
        // Sparse vector commands
        commands::sparse_search,
        commands::hybrid_sparse_search,
        commands::sparse_upsert,
        // PQ training command
        commands::train_pq,
        // Streaming insert command (requires persistence)
        commands::stream_insert,
        // AgentMemory commands (EPIC-016 US-003)
        commands::semantic_store,
        commands::semantic_query,
        // Knowledge Graph commands (EPIC-015 US-001)
        commands_graph::add_edge,
        commands_graph::get_edges,
        commands_graph::traverse_graph,
        commands_graph::get_node_degree,
    ]);
    #[cfg(not(feature = "persistence"))]
    let builder = Builder::new("velesdb").invoke_handler(tauri::generate_handler![
        commands::create_collection,
        commands::create_metadata_collection,
        commands::delete_collection,
        commands::list_collections,
        commands::get_collection,
        commands::upsert,
        commands::upsert_metadata,
        commands::get_points,
        commands::delete_points,
        commands::search,
        commands::batch_search,
        commands::text_search,
        commands::hybrid_search,
        commands::multi_query_search,
        commands::query,
        commands::is_empty,
        commands::flush,
        // Sparse vector commands
        commands::sparse_search,
        commands::hybrid_sparse_search,
        commands::sparse_upsert,
        // PQ training command
        commands::train_pq,
        // AgentMemory commands (EPIC-016 US-003)
        commands::semantic_store,
        commands::semantic_query,
        // Knowledge Graph commands (EPIC-015 US-001)
        commands_graph::add_edge,
        commands_graph::get_edges,
        commands_graph::traverse_graph,
        commands_graph::get_node_degree,
    ]);
    builder
        .setup(move |app, _api| {
            let state = VelesDbState::new(db_path.clone());
            app.manage(state);
            // Initialize simple in-memory index for VelesDbExt trait (384 dimensions for AllMiniLML6V2)
            let simple_index = SimpleIndexState(Arc::new(RwLock::new(SimpleVectorIndex::new(384))));
            app.manage(simple_index);
            tracing::info!("VelesDB plugin initialized with path: {:?}", db_path);
            Ok(())
        })
        .build()
}

/// Alias for `init()` for backward compatibility.
#[must_use]
pub fn init_default<R: Runtime>() -> TauriPlugin<R> {
    init()
}

/// Initializes the `VelesDB` plugin using the platform's app data directory.
///
/// This is the recommended way to initialize the plugin for production apps.
/// Data is stored in the standard location for each platform:
/// - **Windows**: `%APPDATA%\<app_name>\velesdb\`
/// - **macOS**: `~/Library/Application Support/<app_name>/velesdb/`
/// - **Linux**: `~/.local/share/<app_name>/velesdb/`
///
/// # Arguments
///
/// * `app_name` - Your application's name (used in the path)
///
/// # Errors
///
/// Returns an error if the platform's app data directory cannot be determined.
///
/// # Example
///
/// ```rust,ignore
/// tauri::Builder::default()
///     .plugin(tauri_plugin_velesdb::init_with_app_data("my-app")?)
///     .run(tauri::generate_context!())
///     .expect("error while running tauri application");
/// ```
pub fn init_with_app_data<R: Runtime>(app_name: &str) -> Result<TauriPlugin<R>> {
    let app_data_dir = get_app_data_dir(app_name)?;
    Ok(init_with_path(app_data_dir))
}

/// Returns the platform-specific app data directory for `VelesDB`.
///
/// # Arguments
///
/// * `app_name` - Your application's name
///
/// # Returns
///
/// Path to `<app_data>/<app_name>/velesdb/`, or an error if the platform
/// data directory cannot be determined.
///
/// # Errors
///
/// Returns `Error::InvalidConfig` if the platform data directory cannot be resolved.
pub fn get_app_data_dir(app_name: &str) -> Result<std::path::PathBuf> {
    let base_dir = dirs::data_dir().or_else(dirs::config_dir).ok_or_else(|| {
        Error::InvalidConfig("Could not determine app data directory for this platform".to_string())
    })?;

    Ok(base_dir.join(app_name).join("velesdb"))
}

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

    #[test]
    fn test_velesdb_state_creation() {
        // Arrange
        let path = std::path::PathBuf::from("/tmp/test");

        // Act
        let state = VelesDbState::new(path.clone());

        // Assert
        assert_eq!(state.path(), &path);
    }

    #[test]
    fn test_get_app_data_dir_structure() {
        // Act
        let path = get_app_data_dir("test-app").unwrap();

        // Assert - path should end with test-app/velesdb
        assert!(path.ends_with("test-app/velesdb") || path.ends_with("test-app\\velesdb"));
        assert!(path.to_string_lossy().contains("test-app"));
    }

    #[test]
    fn test_get_app_data_dir_different_apps() {
        // Act
        let path1 = get_app_data_dir("app1").unwrap();
        let path2 = get_app_data_dir("app2").unwrap();

        // Assert - different apps should have different paths
        assert_ne!(path1, path2);
    }
}