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
//! C API Custom Function Module
//!
//! Provide a registration function for custom scalar functions and aggregate functions.

use crate::embedded::c_api::error::linkrs_error_code_t;
use crate::embedded::c_api::session::LinkrsSessionHandle;
use crate::embedded::c_api::types::{linkrs_session_t, linkrs_value_t, linkrs_value_type_t};
use linkrs_query::executor::expression::functions::{
    AggregateFinalCallback, AggregateStepCallback, CFunctionContext, CustomFunction,
    ScalarFunctionCallback,
};
use log::error;
use std::ffi::{c_char, c_int, c_void, CStr};

/// Scalar function callback type
#[allow(non_camel_case_types)]
pub type linkrs_scalar_function_callback =
    Option<extern "C" fn(context: *mut linkrs_context_t, argc: c_int, argv: *mut linkrs_value_t)>;

/// Aggregation function step callback type
#[allow(non_camel_case_types)]
pub type linkrs_aggregate_step_callback =
    Option<extern "C" fn(context: *mut linkrs_context_t, argc: c_int, argv: *mut linkrs_value_t)>;

/// The final callback type of the aggregate function
#[allow(non_camel_case_types)]
pub type linkrs_aggregate_final_callback = Option<extern "C" fn(context: *mut linkrs_context_t)>;

/// Function destruction callback type
#[allow(non_camel_case_types)]
pub type linkrs_function_destroy_callback = Option<extern "C" fn(user_data: *mut c_void)>;

/// Function execution context (opaque pointer).
///
/// The context is passed to registered callbacks as a borrowed pointer to the
/// query engine's `CFunctionContext`; all access goes through the
/// `linkrs_context_*` functions below, so the layout stays private to C.
#[repr(C)]
pub struct linkrs_context_t {
    _dummy: u8,
}

/// Create a custom scalar function
///
/// # Arguments
/// - `session`: Session handle
/// - `name`: Function name
/// - `argc`: Number of arguments, -1 for variable arguments
/// - `user_data`: User data pointer
/// - `x_func`: Scalar function callback
/// - `x_destroy`: Destructor callback, can be NULL
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Example
/// ```c
/// extern void my_function(linkrs_context_t* ctx, int argc, linkrs_value_t* argv) {
///     // Implement function logic
/// }
///
/// linkrs_create_function(session, "my_func", 2, NULL, my_function, NULL);
/// ```
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `name` must be a valid pointer to a null-terminated UTF-8 string
/// - `x_func` must be a valid function pointer
/// - `user_data` is passed to the callback and must remain valid for the lifetime of the function
#[no_mangle]
pub unsafe extern "C" fn linkrs_create_function(
    session: *mut linkrs_session_t,
    name: *const c_char,
    argc: c_int,
    user_data: *mut c_void,
    x_func: linkrs_scalar_function_callback,
    _x_destroy: linkrs_function_destroy_callback,
) -> c_int {
    if session.is_null() || name.is_null() || x_func.is_none() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

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

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

        // Convert the C callback to a Rust callback type.
        let callback: ScalarFunctionCallback = std::mem::transmute(x_func);

        // Create a custom function
        let func = CustomFunction::new_c(
            name_str,
            argc as usize,
            argc < 0,
            format!("C function: {}", name_str),
            callback,
            user_data,
        );

        // Register for the session.
        if let Err(e) = handle.inner.register_custom_function(func) {
            error!("Registration function failed: {:?}", e);
            return linkrs_error_code_t::LINKRS_ERROR as c_int;
        }
    }

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Creating custom aggregate functions
///
/// # Arguments
/// - `session`: Session handle
/// - `name`: Function name
/// - `argc`: Number of arguments, -1 for variable arguments
/// - `user_data`: User data pointer
/// - `x_step`: Aggregate step callback
/// - `x_final`: Aggregate final callback
/// - `x_destroy`: Destructor callback, can be NULL
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `name` must be a valid pointer to a null-terminated UTF-8 string
/// - `x_step` and `x_final` must be valid function pointers
/// - `user_data` is passed to the callbacks and must remain valid for the lifetime of the function
#[no_mangle]
pub unsafe extern "C" fn linkrs_create_aggregate(
    session: *mut linkrs_session_t,
    name: *const c_char,
    argc: c_int,
    user_data: *mut c_void,
    x_step: linkrs_aggregate_step_callback,
    x_final: linkrs_aggregate_final_callback,
    _x_destroy: linkrs_function_destroy_callback,
) -> c_int {
    if session.is_null() || name.is_null() || x_step.is_none() || x_final.is_none() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

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

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

        // Convert the C callback to a Rust callback type.
        let step_callback: AggregateStepCallback = std::mem::transmute(x_step);
        let final_callback: AggregateFinalCallback = std::mem::transmute(x_final);

        // Create an aggregate function
        let func = CustomFunction::new_c_aggregate(
            name_str,
            argc as usize,
            argc < 0,
            format!("C aggregate function: {}", name_str),
            step_callback,
            final_callback,
            user_data,
        );

        // Register for the session.
        if let Err(e) = handle.inner.register_custom_function(func) {
            error!("Registration of the aggregate function failed: {:?}", e);
            return linkrs_error_code_t::LINKRS_ERROR as c_int;
        }
    }

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Delete the custom function.
///
/// # Arguments
/// - `session`: Session handle
/// - `name`: Function name
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `name` must be a valid pointer to a null-terminated UTF-8 string
#[no_mangle]
pub unsafe extern "C" fn linkrs_delete_function(
    session: *mut linkrs_session_t,
    name: *const c_char,
) -> c_int {
    if session.is_null() || name.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    // The function needs to be deleted from the registry.
    // The current return was successful (the function will automatically clean up at the end of the session).
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Setting the return value of a function
///
/// # Arguments
/// - `context`: Function execution context
/// - `value`: Return value
///
/// # Description
/// Call this function in the scalar function or aggregate function's xFinal callback to set the return value
///
/// # Safety
/// - `context` must be a valid function context pointer passed to the callback
/// - `value` must be a valid pointer to a value structure, or NULL to set a null result
/// - This function should only be called from within a registered function callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_context_set_result(
    context: *mut linkrs_context_t,
    value: *const linkrs_value_t,
) -> c_int {
    if context.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    unsafe {
        let ctx = &mut *(context as *mut CFunctionContext);
        if value.is_null() {
            ctx.set_result(linkrs_core::Value::Null(linkrs_core::NullType::Null));
        } else {
            let val = crate::embedded::c_api::value::linkrs_value_to_core(value);
            ctx.set_result(val);
        }
    }

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Obtaining the type of the value returned by a function
///
/// # Arguments
/// - `context`: Function execution context
///
/// # Returns
/// - Value type
///
/// # Safety
/// - `context` must be a valid function context pointer passed to the callback
/// - This function should only be called from within a registered function callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_context_result_type(
    context: *mut linkrs_context_t,
) -> linkrs_value_type_t {
    if context.is_null() {
        return linkrs_value_type_t::LINKRS_NULL;
    }

    unsafe {
        let ctx = &*(context as *const CFunctionContext);
        match &ctx.result {
            Some(val) => linkrs_core::value_conversion::core_value_to_linkrs_type(val),
            None => linkrs_value_type_t::LINKRS_NULL,
        }
    }
}

/// Setting error messages
///
/// # Arguments
/// - `context`: Function execution context
/// - `error_msg`: Error message
///
/// # Description
/// Call this function to set an error message when the function execution fails
///
/// # Safety
/// - `context` must be a valid function context pointer passed to the callback
/// - `error_msg` must be a valid pointer to a null-terminated UTF-8 string
/// - This function should only be called from within a registered function callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_context_set_error(
    context: *mut linkrs_context_t,
    error_msg: *const c_char,
) -> c_int {
    if context.is_null() || error_msg.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }

    unsafe {
        let ctx = &mut *(context as *mut CFunctionContext);
        let msg = CStr::from_ptr(error_msg).to_string_lossy().into_owned();
        ctx.set_error(msg);
    }

    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Obtain parameter values from the context (auxiliary function)
///
/// # Arguments
/// - `context`: Function execution context
/// - `index`: Argument index
///
/// # Returns
/// - Argument value pointer, returns NULL if index is out of bounds
///
/// # Safety
/// - `context` must be a valid function context pointer passed to the callback
/// - `index` must be a valid argument index (0 <= index < argc)
/// - The returned pointer is only valid for the duration of the callback
/// - This function should only be called from within a registered function callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_context_get_arg(
    context: *mut linkrs_context_t,
    index: c_int,
) -> *const linkrs_value_t {
    if context.is_null() {
        return std::ptr::null();
    }
    let ctx = &*(context as *const CFunctionContext);
    if index < 0 || index as usize >= ctx.argc {
        return std::ptr::null();
    }
    ctx.argv.as_ptr().add(index as usize)
}

/// Get the number of parameters
///
/// # Arguments
/// - `context`: Function execution context
///
/// # Returns
/// - Number of arguments
///
/// # Safety
/// - `context` must be a valid function context pointer passed to the callback
/// - This function should only be called from within a registered function callback
#[no_mangle]
pub unsafe extern "C" fn linkrs_context_arg_count(context: *mut linkrs_context_t) -> c_int {
    if context.is_null() {
        return 0;
    }
    (*(context as *const CFunctionContext)).argc as c_int
}

/// Load a UDF dynamic library and register the exported function.
///
/// # Arguments
/// - `session`: Session handle
/// - `path`: Null-terminated UTF-8 path to the `.so` / `.dylib` / `.dll` file
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `path` must be a valid pointer to a null-terminated UTF-8 string
#[no_mangle]
pub unsafe extern "C" fn linkrs_load_extension(
    session: *mut linkrs_session_t,
    path: *const c_char,
) -> c_int {
    if session.is_null() || path.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }
    let path_str = unsafe {
        match CStr::from_ptr(path).to_str() {
            Ok(s) => s,
            Err(_) => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
        }
    };
    unsafe {
        let handle = &*(session as *mut LinkrsSessionHandle);
        if let Err(e) = handle.inner.load_extension(std::path::Path::new(path_str)) {
            error!("Load extension failed: {:?}", e);
            return linkrs_error_code_t::LINKRS_ERROR as c_int;
        }
    }
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Unload a previously loaded dynamic UDF by function name.
///
/// # Arguments
/// - `session`: Session handle
/// - `name`: Null-terminated UTF-8 function name
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `name` must be a valid pointer to a null-terminated UTF-8 string
#[no_mangle]
pub unsafe extern "C" fn linkrs_unload_extension(
    session: *mut linkrs_session_t,
    name: *const c_char,
) -> c_int {
    if session.is_null() || name.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }
    let name_str = unsafe {
        match CStr::from_ptr(name).to_str() {
            Ok(s) => s,
            Err(_) => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
        }
    };
    unsafe {
        let handle = &*(session as *mut LinkrsSessionHandle);
        if let Err(e) = handle.inner.unload_extension(name_str) {
            error!("Unload extension failed: {:?}", e);
            return linkrs_error_code_t::LINKRS_ERROR as c_int;
        }
    }
    linkrs_error_code_t::LINKRS_OK as c_int
}

/// Reload a dynamic UDF from its original library path.
///
/// # Arguments
/// - `session`: Session handle
/// - `name`: Null-terminated UTF-8 function name
/// - `reloaded`: Out-parameter set to 1 when the library was reloaded,
///   0 when the file is unchanged and reloading was skipped
///
/// # Returns
/// - Success: LINKRS_OK
/// - Failure: Error code
///
/// # Safety
/// - `session` must be a valid session handle created by `linkrs_session_create`
/// - `name` must be a valid pointer to a null-terminated UTF-8 string
/// - `reloaded` must be a valid writable pointer (may be NULL to ignore)
#[no_mangle]
pub unsafe extern "C" fn linkrs_reload_extension(
    session: *mut linkrs_session_t,
    name: *const c_char,
    reloaded: *mut c_int,
) -> c_int {
    if session.is_null() || name.is_null() {
        return linkrs_error_code_t::LINKRS_MISUSE as c_int;
    }
    let name_str = unsafe {
        match CStr::from_ptr(name).to_str() {
            Ok(s) => s,
            Err(_) => return linkrs_error_code_t::LINKRS_MISUSE as c_int,
        }
    };
    unsafe {
        let handle = &*(session as *mut LinkrsSessionHandle);
        match handle.inner.reload_extension(name_str) {
            Ok(did_reload) => {
                if !reloaded.is_null() {
                    *reloaded = i32::from(did_reload);
                }
            }
            Err(e) => {
                error!("Reload extension failed: {:?}", e);
                return linkrs_error_code_t::LINKRS_ERROR as c_int;
            }
        }
    }
    linkrs_error_code_t::LINKRS_OK as c_int
}