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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! C API Transaction Management Module
//!
//! Provides transaction management functionality, including transaction start, commit, rollback, and savepoints

use crate::api_core::types::TransactionHandle;
use crate::embedded::c_api::error::{
    error_code_from_core_error, linkrs_error_code_t, set_last_error_message,
};
use crate::embedded::c_api::result::LinkrsResultHandle;
use crate::embedded::c_api::session::LinkrsSessionHandle;
use crate::embedded::c_api::types::{linkrs_result_t, linkrs_session_t, linkrs_txn_t};
use std::ffi::{c_char, c_int, CStr};
use std::ptr;

/// Internal structure of transaction 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 transaction completes.
pub struct LinkrsTxnHandle {
    pub(crate) session: *mut LinkrsSessionHandle,
    pub(crate) txn_handle: Option<TransactionHandle>,
    pub(crate) committed: bool,
    pub(crate) rolled_back: bool,
}

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

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

impl Drop for LinkrsTxnHandle {
    fn drop(&mut self) {
        if !self.committed && !self.rolled_back {
            if let Some(txn_handle) = self.txn_handle.take() {
                // Try to rollback the transaction if not committed/rolled back
                if let Some(session) = self.get_session() {
                    let _ = session.inner.rollback_transaction(txn_handle);
                }
            }
        }
    }
}

/// Begin a transaction
///
/// # Parameters
/// - `session`: session handle
/// - `txn`: output parameter, transaction handle
///
/// # Return
/// Success: LINKRS_OK
/// Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `txn` must be a valid pointer to store the transaction handle
/// - The session must not have been closed
/// - The caller is responsible for freeing the transaction using `linkrs_txn_free` when done
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_begin(
    session: *mut linkrs_session_t,
    txn: *mut *mut linkrs_txn_t,
) -> c_int {
    if session.is_null() || txn.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &*(session as *mut LinkrsSessionHandle);

    // Use embedded session API instead of direct TransactionManager access
    match handle.inner.begin_transaction() {
        Ok(transaction) => {
            let txn_handle = transaction.txn_handle();
            let txn_handle_box = Box::new(LinkrsTxnHandle {
                session: session as *mut LinkrsSessionHandle,
                txn_handle: Some(txn_handle),
                committed: false,
                rolled_back: false,
            });
            // Leak the transaction to prevent Drop from being called
            // The transaction lifecycle is now managed by LinkrsTxnHandle
            std::mem::forget(transaction);
            *txn = Box::into_raw(txn_handle_box) as *mut linkrs_txn_t;
            linkrs_error_code_t::LINKRS_OK as c_int
        }
        Err(e) => {
            let error_code = linkrs_error_code_t::LINKRS_ABORT as c_int;
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            *txn = ptr::null_mut();
            error_code
        }
    }
}

/// Starting a read-only transaction
///
/// # Parameters
/// - `session`: Session handle
/// - `txn`: Output parameter, transaction handle
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `txn` must be a valid pointer to store the transaction handle
/// - The session must not have been closed
/// - The caller is responsible for freeing the transaction using `linkrs_txn_free` when done
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_begin_readonly(
    session: *mut linkrs_session_t,
    txn: *mut *mut linkrs_txn_t,
) -> c_int {
    if session.is_null() || txn.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &*(session as *mut LinkrsSessionHandle);

    // Use embedded session API with read-only config
    let config = crate::embedded::TransactionConfig::new().read_only();
    match handle.inner.begin_transaction_with_config(config) {
        Ok(transaction) => {
            let txn_handle = transaction.txn_handle();
            let txn_handle_box = Box::new(LinkrsTxnHandle {
                session: session as *mut LinkrsSessionHandle,
                txn_handle: Some(txn_handle),
                committed: false,
                rolled_back: false,
            });
            std::mem::forget(transaction);
            *txn = Box::into_raw(txn_handle_box) as *mut linkrs_txn_t;
            linkrs_error_code_t::LINKRS_OK as c_int
        }
        Err(e) => {
            let error_code = linkrs_error_code_t::LINKRS_ABORT as c_int;
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            *txn = ptr::null_mut();
            error_code
        }
    }
}

/// Executing queries in a transaction
///
/// # Parameters
/// - `txn`: Transaction handle
/// - `query`: Query statement (UTF-8 encoding)
/// - `result`: Output parameter, result set handle
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `txn` must be a valid transaction handle created by `linkrs_txn_begin` or `linkrs_txn_begin_readonly`
/// - `query` must be a valid pointer to a null-terminated UTF-8 string
/// - `result` must be a valid pointer to store the result handle
/// - The transaction must not have been committed or rolled back
/// - The caller is responsible for freeing the result using `linkrs_result_free` when done
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_execute(
    txn: *mut linkrs_txn_t,
    query: *const c_char,
    result: *mut *mut linkrs_result_t,
) -> c_int {
    if txn.is_null() || query.is_null() || result.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let query_str = match CStr::from_ptr(query).to_str() {
        Ok(s) => s,
        Err(_) => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    let handle = &mut *(txn as *mut LinkrsTxnHandle);

    if handle.committed || handle.rolled_back {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // Checking session validity
    let session = match handle.get_session() {
        Some(s) => s,
        None => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    let txn_handle = match handle.txn_handle.as_ref() {
        Some(h) => h,
        None => return linkrs_error_code_t::LINKRS_INTERNAL as c_int,
    };

    let ctx = crate::api_core::QueryRequest {
        space_id: session.inner.space_id(),
        space_name: session.inner.space_name().map(|s| s.to_string()),
        auto_commit: false,
        transaction_id: Some(txn_handle.0),
        parameters: None,
        session_variables: None,
        query_id: None,
        isolation_level: None,
        parsed_statement: None,
        consistency: Default::default(),
    };

    let mut query_api = session.inner.query_api_mut();
    match query_api.execute(query_str, ctx) {
        Ok(core_result) => {
            let query_result = crate::embedded::result::QueryResult::from_core(core_result);
            let result_handle = Box::new(LinkrsResultHandle {
                inner: query_result,
            });
            *result = Box::into_raw(result_handle) as *mut linkrs_result_t;
            linkrs_error_code_t::LINKRS_OK as c_int
        }
        Err(e) => {
            let (error_code, _) = error_code_from_core_error(&e);
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            *result = ptr::null_mut();
            error_code
        }
    }
}

/// Commit transactions
///
/// # Parameters
/// - `txn`: Transaction handle
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `txn` must be a valid transaction handle created by `linkrs_txn_begin` or `linkrs_txn_begin_readonly`
/// - The transaction must not have been committed or rolled back already
/// - The associated session must still be valid
/// - After calling this function, the transaction handle should be freed using `linkrs_txn_free`
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_commit(txn: *mut linkrs_txn_t) -> c_int {
    if txn.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(txn as *mut LinkrsTxnHandle);

    if handle.committed || handle.rolled_back {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // Check session validity first (only check pointer, don't borrow)
    if !handle.is_session_valid() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // Get session pointer for later use
    let session_ptr = handle.session;

    // NOTE: the C commit hook is bridged into the transaction manager's
    // veto registry at `linkrs_commit_hook` time, so evaluation happens
    // inside `commit_transaction` below (shared point with Rust
    // `register_commit_veto` hooks). No direct invocation here.

    // Use embedded session API instead of direct TransactionManager access
    let session = &*session_ptr;

    // Commit transaction (synchronous, no longer async). A veto fails with
    // `CommitVetoed` and leaves the transaction active; roll it back
    // through the standard path so the rollback hook fires, exactly like
    // the historical pre-commit veto behavior.
    let txn_id = match handle.txn_handle.as_ref() {
        Some(h) => h.0,
        None => return linkrs_error_code_t::LINKRS_INTERNAL as c_int,
    };
    let result = session.inner.txn_manager().commit_transaction(txn_id);
    match result {
        Ok(_) => {
            handle.txn_handle.take();
            handle.committed = true;
            linkrs_error_code_t::LINKRS_OK as c_int
        }
        Err(e) if e.kind() == linkrs_transaction::TransactionErrorKind::CommitVetoed => {
            linkrs_txn_rollback(txn)
        }
        Err(e) => {
            handle.txn_handle.take();
            let error_code = linkrs_error_code_t::LINKRS_ABORT as c_int;
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            error_code
        }
    }
}

/// Rolling back transactions
///
/// # Parameters
/// - `txn`: Transaction handle
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `txn` must be a valid transaction handle created by `linkrs_txn_begin` or `linkrs_txn_begin_readonly`
/// - The transaction must not have been committed or rolled back already
/// - The associated session must still be valid
/// - After calling this function, the transaction handle should be freed using `linkrs_txn_free`
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_rollback(txn: *mut linkrs_txn_t) -> c_int {
    if txn.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(txn as *mut LinkrsTxnHandle);

    if handle.committed || handle.rolled_back {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // Check session validity first (only check pointer, don't borrow)
    if !handle.is_session_valid() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // Get session pointer for later use
    let session_ptr = handle.session;

    // Execute rollback hook if present, with panic isolation so a broken
    // observer can never block the rollback itself.
    {
        let session = &*session_ptr;
        if let Some(callback) = session.rollback_hook {
            let user_data = session.rollback_hook_user_data;
            if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                callback(user_data);
            }))
            .is_err()
            {
                log::error!("rollback hook panicked; continuing rollback");
            }
        }
    }

    let txn_handle = match handle.txn_handle.take() {
        Some(h) => h,
        None => return linkrs_error_code_t::LINKRS_INTERNAL as c_int,
    };

    // Use embedded session API instead of direct TransactionManager access
    let session = &*session_ptr;
    match session.inner.rollback_transaction(txn_handle) {
        Ok(_) => {
            handle.rolled_back = true;
            linkrs_error_code_t::LINKRS_OK as c_int
        }
        Err(e) => {
            let error_code = linkrs_error_code_t::LINKRS_ABORT as c_int;
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            error_code
        }
    }
}

/// Creating a savepoint
///
/// # Parameters
/// - `txn`: Transaction handle
/// - `name`: Name of the savepoint (UTF-8 encoding)
///
/// # Returns
/// - Success: Savepoint ID
/// - Failure: -1
///
/// # Safety
/// - `txn` must be a valid transaction handle created by `linkrs_txn_begin` or `linkrs_txn_begin_readonly`
/// - `name` must be a valid pointer to a null-terminated UTF-8 string
/// - The transaction must not have been committed or rolled back
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_savepoint(txn: *mut linkrs_txn_t, name: *const c_char) -> i64 {
    if txn.is_null() || name.is_null() {
        return -1;
    }

    let name_str = match CStr::from_ptr(name).to_str() {
        Ok(s) => s,
        Err(_) => return -1,
    };

    let handle = &mut *(txn as *mut LinkrsTxnHandle);

    if handle.committed || handle.rolled_back {
        return -1;
    }

    let session = match handle.get_session() {
        Some(s) => s,
        None => return -1,
    };

    let txn_handle = match handle.txn_handle.as_ref() {
        Some(h) => h,
        None => return -1,
    };

    // Use embedded session API instead of direct TransactionManager access
    match session.inner.create_savepoint(txn_handle, name_str) {
        Ok(id) => id.0 as i64,
        Err(_) => -1,
    }
}

/// Release the savepoint.
///
/// # Parameters
/// - `txn`: Transaction handle
/// - `savepoint_id`: ID of the savepoint
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `txn` must be a valid transaction handle created by `linkrs_txn_begin` or `linkrs_txn_begin_readonly`
/// - `savepoint_id` must be a valid savepoint ID returned by `linkrs_txn_savepoint`
/// - The transaction must not have been committed or rolled back
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_release_savepoint(
    txn: *mut linkrs_txn_t,
    savepoint_id: i64,
) -> c_int {
    if txn.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(txn as *mut LinkrsTxnHandle);

    if handle.committed || handle.rolled_back {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let session = match handle.get_session() {
        Some(s) => s,
        None => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    let txn_handle = match handle.txn_handle.as_ref() {
        Some(h) => h,
        None => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    let savepoint = crate::api_core::types::SavepointId(savepoint_id as u64);

    // Use embedded session API instead of direct TransactionManager access
    match session.inner.release_savepoint(txn_handle, savepoint) {
        Ok(_) => linkrs_error_code_t::LINKRS_OK as c_int,
        Err(e) => {
            let core_error = crate::api_core::error::CoreError::TransactionFailed(format!("{}", e));
            let (error_code, _) = error_code_from_core_error(&core_error);
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            error_code
        }
    }
}

/// Roll back to the savepoint.
///
/// # Parameters
/// - `txn`: Transaction handle
/// - `savepoint_id`: Savepoint ID
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `txn` must be a valid transaction handle created by `linkrs_txn_begin` or `linkrs_txn_begin_readonly`
/// - `savepoint_id` must be a valid savepoint ID returned by `linkrs_txn_savepoint`
/// - The transaction must not have been committed or rolled back
#[no_mangle]
pub unsafe extern "C" fn linkrs_txn_rollback_to_savepoint(
    txn: *mut linkrs_txn_t,
    savepoint_id: i64,
) -> c_int {
    if txn.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let handle = &mut *(txn as *mut LinkrsTxnHandle);

    if handle.committed || handle.rolled_back {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    let session = match handle.get_session() {
        Some(s) => s,
        None => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
    };

    let txn_handle = match handle.txn_handle.as_ref() {
        Some(h) => h,
        None => return linkrs_error_code_t::LINKRS_INTERNAL as c_int,
    };

    let savepoint = crate::api_core::types::SavepointId(savepoint_id as u64);

    // Use embedded session API instead of direct TransactionManager access
    match session.inner.rollback_to_savepoint(txn_handle, savepoint) {
        Ok(_) => linkrs_error_code_t::LINKRS_OK as c_int,
        Err(e) => {
            let core_error = crate::api_core::error::CoreError::TransactionFailed(format!("{}", e));
            let (error_code, _) = error_code_from_core_error(&core_error);
            let error_msg = format!("{}", e);
            set_last_error_message(error_msg);
            error_code
        }
    }
}

/// Free the transaction handle
///
/// # Parameters
/// - `txn`: Transaction handle
///
/// # Safety
/// - `txn` must be a valid transaction handle created by `linkrs_txn_begin` or `linkrs_txn_begin_readonly`
/// - `txn` 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_txn_free(txn: *mut linkrs_txn_t) {
    if !txn.is_null() {
        let _ = Box::from_raw(txn as *mut LinkrsTxnHandle);
    }
}

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

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

    #[test]
    fn test_txn_free_null() {
        // Should not panic
        unsafe { linkrs_txn_free(ptr::null_mut()) };
    }

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

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