linkrs-api 0.1.0

Transport-independent core API for Linkrs
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! C API Batch Operation Module
//!
//! Provides batch operation functions, supporting batch insert, batch update, and batch delete

use crate::embedded::c_api::error::{linkrs_error_code_t, set_last_error_message};
use crate::embedded::c_api::session::LinkrsSessionHandle;
use crate::embedded::c_api::types::{linkrs_batch_t, linkrs_session_t, linkrs_value_t};
use linkrs_core::types::VertexId;
use linkrs_core::vertex_edge_path::Tag;
use linkrs_core::{Edge, Vertex};
use std::collections::HashMap;
use std::ffi::{c_char, c_int, CStr};

// Batch action item type
enum BatchItem {
    Vertex(Vertex),
    Edge(Edge),
}

/// Internal Structure of Batch Operation Handles
///
/// Note: This structure holds the session pointer, but does not own the session.
/// The caller must ensure that the session is not closed until the batch operation handle is released.
pub struct LinkrsBatchHandle {
    /// Associated session pointer (used to verify session validity)
    session_ptr: *mut LinkrsSessionHandle,
    /// Batch size
    batch_size: usize,
    /// Buffer
    buffer: Vec<BatchItem>,
    /// Number of inserted vertices
    vertices_inserted: usize,
    /// Number of inserted edges
    edges_inserted: usize,
    /// Error messages
    errors: Vec<String>,
}

impl LinkrsBatchHandle {
    /// Check if the session is still active
    fn is_session_valid(&self) -> bool {
        !self.session_ptr.is_null()
    }

    /// Get session reference (if valid)
    fn get_session(&self) -> Option<&LinkrsSessionHandle> {
        if self.is_session_valid() {
            Some(unsafe { &*self.session_ptr })
        } else {
            None
        }
    }

    /// Flush vertex buffer - using embedded session API instead of direct storage access
    fn flush_vertices(&mut self) -> Result<(), String> {
        // Separate vertices and edges
        let mut vertices = Vec::new();
        let mut remaining = Vec::new();

        for item in self.buffer.drain(..) {
            match item {
                BatchItem::Vertex(v) => vertices.push(v),
                _ => remaining.push(item),
            }
        }

        // Put the edge back into the buffer
        self.buffer.extend(remaining);

        if vertices.is_empty() {
            return Ok(());
        }

        let vertex_count = vertices.len();

        // Use embedded session API instead of direct storage access
        let result = {
            let session = self
                .get_session()
                .ok_or_else(|| "Session invalid or closed".to_string())?;

            session.inner.batch_insert_vertices(vertices)
        };

        match result {
            Ok(_) => {
                self.vertices_inserted += vertex_count;
                Ok(())
            }
            Err(e) => {
                let err_msg = format!("Batch insert vertices failed: {}", e);
                self.errors.push(err_msg.clone());
                Err(err_msg)
            }
        }
    }

    /// Flush edge buffer - using embedded session API instead of direct storage access
    fn flush_edges(&mut self) -> Result<(), String> {
        // Separate edges and vertices
        let mut edges = Vec::new();
        let mut remaining = Vec::new();

        for item in self.buffer.drain(..) {
            match item {
                BatchItem::Edge(e) => edges.push(e),
                _ => remaining.push(item),
            }
        }

        // Put vertices back into the buffer
        self.buffer.extend(remaining);

        if edges.is_empty() {
            return Ok(());
        }

        let edge_count = edges.len();

        // Use embedded session API instead of direct storage access
        let result = {
            let session = self
                .get_session()
                .ok_or_else(|| "Session invalid or closed".to_string())?;

            session.inner.batch_insert_edges(edges)
        };

        match result {
            Ok(_) => {
                self.edges_inserted += edge_count;
                Ok(())
            }
            Err(e) => {
                let err_msg = format!("Batch insert edges failed: {}", e);
                self.errors.push(err_msg.clone());
                Err(err_msg)
            }
        }
    }

    /// Performs a batch insert, flushing all buffered data
    fn execute(&mut self) -> Result<(), String> {
        // Flush vertices first.
        self.flush_vertices()?;

        // Flush edges
        self.flush_edges()?;

        Ok(())
    }
}

/// Create a batch inserter
///
/// # Parameters
/// - `session`: session handle
/// - `batch_size`: batch size
/// - `batch`: output parameter, batch operation handle
///
/// # Returns
/// Success: LINKRS_OK
/// Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `batch_size` must be a positive integer (if <= 0, defaults to 100)
/// - `batch` must be a valid pointer to store the batch handle
/// - The created batch handle holds a session pointer but does not own the session
/// - The caller must ensure the session is not closed before the batch handle is freed
/// - The caller is responsible for freeing the batch handle using `linkrs_batch_free` when done
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_inserter_create(
    session: *mut linkrs_session_t,
    batch_size: c_int,
    batch: *mut *mut linkrs_batch_t,
) -> c_int {
    if session.is_null() || batch.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let size = if batch_size <= 0 {
        100
    } else {
        batch_size as usize
    };

    let handle = Box::new(LinkrsBatchHandle {
        session_ptr: session as *mut LinkrsSessionHandle,
        batch_size: size,
        buffer: Vec::new(),
        vertices_inserted: 0,
        edges_inserted: 0,
        errors: Vec::new(),
    });

    *batch = Box::into_raw(handle) as *mut linkrs_batch_t;
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Free batch operation handle
///
/// # Parameters
/// - `batch`: batch operation handle
///
/// # Safety
/// - `batch` must be a valid batch handle created by `linkrs_batch_inserter_create`
/// - `batch` can be null (in which case this function does nothing)
/// - After calling this function, the handle is invalid and must not be used again
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_free(batch: *mut linkrs_batch_t) -> c_int {
    if batch.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }
    let _ = Box::from_raw(batch as *mut LinkrsBatchHandle);
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Add a vertex to the batch
///
/// # Parameters
/// - `batch`: batch operation handle
/// - `vid`: vertex ID
/// - `tags`: single tag name (exactly one label is required)
///
/// # Returns
/// Success: LINKRS_OK
/// Failure: Error code
///
/// # Safety
/// - `batch` must be a valid batch handle
/// - `vid` must be a valid pointer to a linkrs_value_t
/// - `tags` must be a non-null single tag name (null, empty, or
///   multi-tag comma-separated values are rejected)
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_add_vertex(
    batch: *mut linkrs_batch_t,
    vid: *const linkrs_value_t,
    tags: *const c_char,
) -> c_int {
    if batch.is_null() || vid.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(batch as *mut LinkrsBatchHandle);

    // Check if session is valid
    if !handle.is_session_valid() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // Convert C value to core Value
    let vid_value = unsafe { super::value::linkrs_value_to_core(vid) };
    let vid_id = match value_to_vertex_id(&vid_value) {
        Some(id) => id,
        None => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    // Parse the single tag: exactly one non-empty label is required.
    if tags.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }
    let tags_str = match unsafe { CStr::from_ptr(tags).to_str() } {
        Ok(s) => s,
        Err(_) => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };
    let mut tag_names = tags_str
        .split(',')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty());
    let single_tag = match (tag_names.next(), tag_names.next()) {
        (Some(name), None) => name.to_string(),
        _ => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    // Create vertex
    let vertex = Vertex::new(vid_id, Tag::new(single_tag, HashMap::new()));
    handle.buffer.push(BatchItem::Vertex(vertex));

    // Auto-flush if buffer is full
    if handle.buffer.len() >= handle.batch_size {
        if let Err(e) = handle.execute() {
            set_last_error_message(e);
            return linkrs_error_code_t::LINKRS_ERROR as c_int;
        }
    }

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Add an edge to the batch
///
/// # Parameters
/// - `batch`: batch operation handle
/// - `src_vid`: source vertex ID
/// - `dst_vid`: destination vertex ID
/// - `edge_type`: edge type
///
/// # Returns
/// Success: LINKRS_OK
/// Failure: Error code
///
/// # Safety
/// - `batch` must be a valid batch handle
/// - `src_vid` and `dst_vid` must be valid pointers to linkrs_value_t
/// - `edge_type` must be a valid null-terminated UTF-8 string
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_add_edge(
    batch: *mut linkrs_batch_t,
    src_vid: *const linkrs_value_t,
    dst_vid: *const linkrs_value_t,
    edge_type: *const c_char,
) -> c_int {
    if batch.is_null() || src_vid.is_null() || dst_vid.is_null() || edge_type.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(batch as *mut LinkrsBatchHandle);

    // Check if session is valid
    if !handle.is_session_valid() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // Convert C values to core Values
    let src_value = unsafe { super::value::linkrs_value_to_core(src_vid) };
    let dst_value = unsafe { super::value::linkrs_value_to_core(dst_vid) };
    let src_id = match value_to_vertex_id(&src_value) {
        Some(id) => id,
        None => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };
    let dst_id = match value_to_vertex_id(&dst_value) {
        Some(id) => id,
        None => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    // Get edge type
    let edge_type_str = match CStr::from_ptr(edge_type).to_str() {
        Ok(s) => s.to_string(),
        Err(_) => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    // Create edge
    let edge = Edge::new(src_id, dst_id, edge_type_str, 0, HashMap::new());
    handle.buffer.push(BatchItem::Edge(edge));

    // Auto-flush if buffer is full
    if handle.buffer.len() >= handle.batch_size {
        if let Err(e) = handle.execute() {
            set_last_error_message(e);
            return linkrs_error_code_t::LINKRS_ERROR as c_int;
        }
    }

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Execute batch operation (flush all buffered data)
///
/// # Parameters
/// - `batch`: batch operation handle
///
/// # Returns
/// Success: LINKRS_OK
/// Failure: Error code
///
/// # Safety
/// - `batch` must be a valid batch handle
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_execute(batch: *mut linkrs_batch_t) -> c_int {
    if batch.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(batch as *mut LinkrsBatchHandle);

    // Check if session is valid
    if !handle.is_session_valid() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    if let Err(e) = handle.execute() {
        set_last_error_message(e);
        return linkrs_error_code_t::LINKRS_ERROR as c_int;
    }

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Get the number of vertices inserted
///
/// # Parameters
/// - `batch`: batch operation handle
/// - `count`: output parameter
///
/// # Returns
/// Success: LINKRS_OK
/// Failure: Error code
///
/// # Safety
/// - `batch` must be a valid batch handle
/// - `count` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_vertices_inserted(
    batch: *mut linkrs_batch_t,
    count: *mut c_int,
) -> c_int {
    if batch.is_null() || count.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &*(batch as *mut LinkrsBatchHandle);
    *count = handle.vertices_inserted as c_int;

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Get the number of edges inserted
///
/// # Parameters
/// - `batch`: batch operation handle
/// - `count`: output parameter
///
/// # Returns
/// Success: LINKRS_OK
/// Failure: Error code
///
/// # Safety
/// - `batch` must be a valid batch handle
/// - `count` must be a valid pointer
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_edges_inserted(
    batch: *mut linkrs_batch_t,
    count: *mut c_int,
) -> c_int {
    if batch.is_null() || count.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &*(batch as *mut LinkrsBatchHandle);
    *count = handle.edges_inserted as c_int;

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Get the number of buffered vertices
///
/// # Safety
/// - `batch` must be a valid batch handle or null
///
/// # Returns
/// - Number of buffered vertices, or -1 if batch is null
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_buffered_vertices(batch: *mut linkrs_batch_t) -> c_int {
    if batch.is_null() {
        return -1;
    }

    let handle = &*(batch as *mut LinkrsBatchHandle);
    handle
        .buffer
        .iter()
        .filter(|item| matches!(item, BatchItem::Vertex(_)))
        .count() as c_int
}

/// Get the number of buffered edges
///
/// # Safety
/// - `batch` must be a valid batch handle or null
///
/// # Returns
/// - Number of buffered edges, or -1 if batch is null
#[no_mangle]
pub unsafe extern "C" fn linkrs_batch_buffered_edges(batch: *mut linkrs_batch_t) -> c_int {
    if batch.is_null() {
        return -1;
    }

    let handle = &*(batch as *mut LinkrsBatchHandle);
    handle
        .buffer
        .iter()
        .filter(|item| matches!(item, BatchItem::Edge(_)))
        .count() as c_int
}

fn value_to_vertex_id(value: &linkrs_core::Value) -> Option<VertexId> {
    use linkrs_core::Value;
    match value {
        Value::Int(i) => VertexId::try_from_int64(*i as i64).ok(),
        Value::BigInt(i) => VertexId::try_from_int64(*i).ok(),
        Value::String(s) => VertexId::try_from_string(s.as_str()).ok(),
        _ => None,
    }
}

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

    #[test]
    fn test_batch_inserter_create_null_params() {
        let result = unsafe {
            linkrs_batch_inserter_create(std::ptr::null_mut(), 100, std::ptr::null_mut())
        };
        assert_eq!(result, linkrs_error_code_t::LINKRS_MISUSE as c_int);
    }

    #[test]
    fn test_batch_free_null() {
        // Should not panic
        unsafe { linkrs_batch_free(std::ptr::null_mut()) };
    }
}