nodedb-client 0.6.1

Unified NodeDb trait and remote client for NodeDB Origin and Lite
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
// SPDX-License-Identifier: Apache-2.0

use nodedb_types::document::Document;
use nodedb_types::error::{NodeDbError, NodeDbResult};
use nodedb_types::filter::MetadataFilter;
use nodedb_types::result::SearchResult;

use super::super::trait_def::NodeDb;

pub(in crate::traits::core) async fn document_put_with_vector_default<T: NodeDb + ?Sized>(
    this: &T,
    doc_collection: &str,
    doc: Document,
    vector_collection: &str,
    id: &str,
    embedding: &[f32],
) -> NodeDbResult<()> {
    this.document_put(doc_collection, doc).await?;
    if !embedding.is_empty() {
        this.vector_insert(vector_collection, id, embedding, None)
            .await?;
    }
    Ok(())
}

pub(in crate::traits::core) fn document_get_as_of_default(
    collection: &str,
    id: &str,
    as_of_ms: Option<i64>,
    valid_time_ms: Option<i64>,
) -> NodeDbResult<Option<Document>> {
    let _ = (collection, id, as_of_ms, valid_time_ms);
    Err(NodeDbError::storage(
        "document_get_as_of is not implemented on this client",
    ))
}

pub(in crate::traits::core) fn document_put_with_valid_time_default(
    collection: &str,
    doc: Document,
    valid_from_ms: Option<i64>,
    valid_until_ms: Option<i64>,
) -> NodeDbResult<()> {
    let _ = (collection, doc, valid_from_ms, valid_until_ms);
    Err(NodeDbError::storage(
        "document_put_with_valid_time is not implemented on this client",
    ))
}

pub(in crate::traits::core) fn vector_insert_field_default(
    collection: &str,
    field_name: &str,
    id: &str,
    embedding: &[f32],
    metadata: Option<Document>,
) -> NodeDbResult<()> {
    let _ = (collection, id, embedding, metadata);
    Err(NodeDbError::storage(format!(
        "vector_insert_field is not implemented on this client; \
         field_name={field_name} would have been silently dropped"
    )))
}

pub(in crate::traits::core) fn vector_search_field_default(
    collection: &str,
    field_name: &str,
    query: &[f32],
    k: usize,
    filter: Option<&MetadataFilter>,
) -> NodeDbResult<Vec<SearchResult>> {
    let _ = (collection, query, k, filter);
    Err(NodeDbError::storage(format!(
        "vector_search_field is not implemented on this client; \
         field_name={field_name} would have been silently dropped"
    )))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capabilities::Capabilities;
    use async_trait::async_trait;
    use nodedb_types::document::Document;
    use nodedb_types::error::{NodeDbError, NodeDbResult};
    use nodedb_types::filter::{EdgeFilter, MetadataFilter};
    use nodedb_types::graph::GraphStats;
    use nodedb_types::id::{EdgeId, NodeId};
    use nodedb_types::result::{QueryResult, SearchResult, SubGraph};
    use nodedb_types::text_search::TextSearchParams;
    use nodedb_types::value::Value;
    use std::collections::{HashMap, HashSet};

    /// Mock implementation to verify the trait is object-safe and
    /// can be used as `Arc<dyn NodeDb>`.
    struct MockDb;

    #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
    #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
    impl NodeDb for MockDb {
        async fn vector_search(
            &self,
            _collection: &str,
            _query: &[f32],
            _k: usize,
            _filter: Option<&MetadataFilter>,
            _allowed_ids: Option<&HashSet<String>>,
        ) -> NodeDbResult<Vec<SearchResult>> {
            Ok(vec![SearchResult {
                id: "vec-1".into(),
                node_id: None,
                distance: 0.1,
                metadata: HashMap::new(),
            }])
        }

        async fn vector_insert(
            &self,
            _collection: &str,
            _id: &str,
            _embedding: &[f32],
            _metadata: Option<Document>,
        ) -> NodeDbResult<()> {
            Ok(())
        }

        async fn vector_delete(&self, _collection: &str, _id: &str) -> NodeDbResult<()> {
            Ok(())
        }

        async fn graph_traverse(
            &self,
            _collection: &str,
            _start: &NodeId,
            _depth: u8,
            _direction: nodedb_types::graph::Direction,
            _edge_filter: Option<&EdgeFilter>,
        ) -> NodeDbResult<SubGraph> {
            Ok(SubGraph::empty())
        }

        async fn graph_insert_edge(
            &self,
            _collection: &str,
            from: &NodeId,
            to: &NodeId,
            edge_type: &str,
            _properties: Option<Document>,
        ) -> NodeDbResult<EdgeId> {
            EdgeId::try_first(from.clone(), to.clone(), edge_type)
                .map_err(|e| NodeDbError::storage(format!("invalid edge label: {e}")))
        }

        async fn graph_delete_edge(
            &self,
            _collection: &str,
            _edge_id: &EdgeId,
        ) -> NodeDbResult<()> {
            Ok(())
        }

        async fn graph_stats(
            &self,
            collection: Option<&str>,
            _as_of: Option<i64>,
        ) -> NodeDbResult<Vec<GraphStats>> {
            Ok(vec![GraphStats::zero(collection.unwrap_or("mock"))])
        }

        async fn document_get(
            &self,
            _collection: &str,
            id: &str,
        ) -> NodeDbResult<Option<Document>> {
            let mut doc = Document::new(id);
            doc.set("title", Value::String("test".into()));
            Ok(Some(doc))
        }

        async fn document_put(&self, _collection: &str, _doc: Document) -> NodeDbResult<()> {
            Ok(())
        }

        async fn document_delete(&self, _collection: &str, _id: &str) -> NodeDbResult<()> {
            Ok(())
        }

        async fn list_insert(
            &self,
            _collection: &str,
            _document_id: &str,
            _list_path: &str,
            _index: usize,
            _fields: &Value,
        ) -> NodeDbResult<()> {
            Ok(())
        }

        async fn list_delete(
            &self,
            _collection: &str,
            _document_id: &str,
            _list_path: &str,
            _index: usize,
        ) -> NodeDbResult<()> {
            Ok(())
        }

        async fn list_move(
            &self,
            _collection: &str,
            _document_id: &str,
            _list_path: &str,
            _from_index: usize,
            _to_index: usize,
        ) -> NodeDbResult<()> {
            Ok(())
        }

        async fn text_search(
            &self,
            _collection: &str,
            _field: &str,
            _query: &str,
            _top_k: usize,
            _params: TextSearchParams,
            _allowed_ids: Option<&HashSet<String>>,
        ) -> NodeDbResult<Vec<SearchResult>> {
            Ok(Vec::new())
        }

        async fn execute_sql(&self, _query: &str, _params: &[Value]) -> NodeDbResult<QueryResult> {
            Ok(QueryResult::empty())
        }
    }

    #[test]
    fn trait_is_object_safe() {
        fn _accepts_dyn(_db: &dyn NodeDb) {}
        let db = MockDb;
        _accepts_dyn(&db);
    }

    #[test]
    fn trait_works_with_arc() {
        use std::sync::Arc;
        let db: Arc<dyn NodeDb> = Arc::new(MockDb);
        let _ = db;
    }

    #[tokio::test]
    async fn mock_vector_search() {
        let db = MockDb;
        let results = db
            .vector_search("embeddings", &[0.1, 0.2, 0.3], 5, None, None)
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].id, "vec-1");
        assert!(results[0].distance < 1.0);
    }

    #[tokio::test]
    async fn mock_vector_insert_and_delete() {
        let db = MockDb;
        db.vector_insert("coll", "v1", &[1.0, 2.0], None)
            .await
            .unwrap();
        db.vector_delete("coll", "v1").await.unwrap();
    }

    #[tokio::test]
    async fn mock_graph_stats_returns_zero() {
        let db = MockDb;
        let result = db.graph_stats(Some("social"), None).await.unwrap();
        assert_eq!(result.len(), 1);
        let stats = &result[0];
        assert_eq!(stats.collection, "social");
        assert_eq!(stats.node_count, 0);
        assert_eq!(stats.edge_count, 0);
        assert_eq!(stats.distinct_label_count, 0);
        assert!(stats.labels.is_empty());
    }

    #[tokio::test]
    async fn mock_graph_stats_tenant_wide_uses_mock_key() {
        let db = MockDb;
        let result = db.graph_stats(None, None).await.unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].collection, "mock");
    }

    #[tokio::test]
    async fn mock_graph_operations() {
        let db = MockDb;
        let start = NodeId::try_new("alice").expect("test fixture");
        let subgraph = db
            .graph_traverse(
                "social",
                &start,
                2,
                nodedb_types::graph::Direction::Out,
                None,
            )
            .await
            .unwrap();
        assert_eq!(subgraph.node_count(), 0);

        let from = NodeId::try_new("alice").expect("test fixture");
        let to = NodeId::try_new("bob").expect("test fixture");
        let edge_id = db
            .graph_insert_edge("social", &from, &to, "KNOWS", None)
            .await
            .unwrap();
        assert_eq!(edge_id.src.as_str(), "alice");
        assert_eq!(edge_id.dst.as_str(), "bob");
        assert_eq!(edge_id.label, "KNOWS");
        assert_eq!(edge_id.seq, 0);

        db.graph_delete_edge("social", &edge_id).await.unwrap();
    }

    #[tokio::test]
    async fn mock_document_operations() {
        let db = MockDb;
        let doc = db.document_get("notes", "n1").await.unwrap().unwrap();
        assert_eq!(doc.id, "n1");
        assert_eq!(doc.get_str("title"), Some("test"));

        let mut new_doc = Document::new("n2");
        new_doc.set("body", Value::String("hello".into()));
        db.document_put("notes", new_doc).await.unwrap();

        db.document_delete("notes", "n1").await.unwrap();
    }

    #[tokio::test]
    async fn mock_execute_sql() {
        let db = MockDb;
        let result = db.execute_sql("SELECT 1", &[]).await.unwrap();
        assert_eq!(result.row_count(), 0);
    }

    /// Verify the full "one API, any runtime" pattern: application
    /// code switches between `NodeDbLite` and `NodeDbRemote` only at
    /// the construction site.
    #[tokio::test]
    async fn unified_api_pattern() {
        use std::sync::Arc;

        let db: Arc<dyn NodeDb> = Arc::new(MockDb);

        let results = db
            .vector_search("knowledge_base", &[0.1, 0.2], 5, None, None)
            .await
            .unwrap();
        assert!(!results.is_empty());

        let start = NodeId::from_validated(results[0].id.clone());
        let _subgraph = db
            .graph_traverse(
                "knowledge_base",
                &start,
                2,
                nodedb_types::graph::Direction::Out,
                None,
            )
            .await
            .unwrap();

        let doc = Document::new("note-1");
        db.document_put("notes", doc).await.unwrap();
    }

    #[test]
    fn default_proto_version_is_zero() {
        let db = MockDb;
        assert_eq!(db.proto_version(), 0);
    }

    #[test]
    fn default_capabilities_is_zero() {
        let db = MockDb;
        assert_eq!(db.capabilities(), 0);
        let caps = Capabilities::from_raw(db.capabilities());
        assert!(!caps.supports_streaming());
        assert!(!caps.supports_graphrag());
    }

    #[test]
    fn default_server_version_is_empty() {
        let db = MockDb;
        assert!(db.server_version().is_empty());
    }

    #[test]
    fn default_limits_all_none() {
        let db = MockDb;
        let limits = db.limits();
        assert!(limits.max_vector_dim.is_none());
        assert!(limits.max_top_k.is_none());
        assert!(limits.max_scan_limit.is_none());
        assert!(limits.max_batch_size.is_none());
        assert!(limits.max_crdt_delta_bytes.is_none());
        assert!(limits.max_query_text_bytes.is_none());
        assert!(limits.max_graph_depth.is_none());
    }

    #[test]
    fn capabilities_newtype_smoke() {
        use nodedb_types::protocol::{CAP_FTS, CAP_STREAMING};
        let caps = Capabilities::from_raw(CAP_STREAMING | CAP_FTS);
        assert!(caps.supports_streaming());
        assert!(caps.supports_fts());
        assert!(!caps.supports_graphrag());
        assert!(!caps.supports_crdt());
    }
}