ombrac_client/
ffi.rs

1use std::ffi::{CStr, c_char};
2use std::sync::{Arc, Mutex};
3
4use figment::Figment;
5use figment::providers::{Format, Json, Serialized};
6use tokio::runtime::{Builder, Runtime};
7
8use ombrac_macros::{error, info};
9
10use crate::config::{ConfigFile, ServiceConfig};
11#[cfg(feature = "tracing")]
12use crate::logging::LogCallback;
13#[cfg(feature = "transport-quic")]
14use crate::service::QuicServiceBuilder;
15use crate::service::Service;
16
17// A global, thread-safe handle to the running service instance.
18static SERVICE_HANDLE: Mutex<Option<ServiceHandle>> = Mutex::new(None);
19
20// Encapsulates the service instance and its associated Tokio runtime.
21struct ServiceHandle {
22    #[cfg(feature = "transport-quic")]
23    service: Option<
24        Box<Service<ombrac_transport::quic::client::Client, ombrac_transport::quic::Connection>>,
25    >,
26    runtime: Runtime,
27}
28
29/// A helper function to safely convert a C string pointer to a Rust string slice.
30/// Returns an empty string if the pointer is null.
31unsafe fn c_str_to_str<'a>(s: *const c_char) -> &'a str {
32    if s.is_null() {
33        return "";
34    }
35    unsafe { CStr::from_ptr(s).to_str().unwrap_or("") }
36}
37
38/// Initializes the logging system to use a C-style callback for log messages.
39///
40/// This function must be called before `ombrac_client_service_startup` if you wish to
41/// receive logs in a C-compatible way. It sets up a global logger that will
42/// forward all log records to the provided callback function.
43///
44/// # Arguments
45///
46/// * `callback` - A function pointer of type `LogCallback`. See the definition of
47///   `LogCallback` for the expected signature and log level mappings.
48///
49/// # Safety
50///
51/// The provided `callback` function pointer must be valid and remain valid for
52/// the lifetime of the program. If a null pointer is passed, logging will be
53/// disabled.
54#[cfg(feature = "tracing")]
55#[unsafe(no_mangle)]
56pub unsafe extern "C" fn ombrac_client_set_log_callback(callback: *const LogCallback) {
57    let callback = if callback.is_null() {
58        None
59    } else {
60        Some(unsafe { *callback })
61    };
62    crate::logging::set_log_callback(callback);
63}
64
65/// Initializes and starts the service with a given JSON configuration.
66///
67/// This function sets up the asynchronous runtime, parses the configuration,
68/// and launches the main service. It must be called before any other service
69/// operations. The service must be shut down via `ombrac_client_service_shutdown` to ensure
70/// a clean exit.
71///
72/// # Arguments
73///
74/// * `config_json` - A pointer to a null-terminated UTF-8 string containing the
75///   service configuration in JSON format.
76///
77/// # Returns
78///
79/// * `0` on success.
80/// * `-1` on failure (e.g., invalid configuration, service already running, or
81///   runtime initialization failed).
82///
83/// # Safety
84///
85/// The caller must ensure that `config_json` is a valid pointer to a
86/// null-terminated C string. This function is not thread-safe and should not be
87/// called concurrently with `ombrac_client_service_shutdown`.
88#[unsafe(no_mangle)]
89pub unsafe extern "C" fn ombrac_client_service_startup(config_json: *const c_char) -> i32 {
90    let config_str = unsafe { c_str_to_str(config_json) };
91
92    let config_file: ConfigFile = match Figment::new()
93        .merge(Serialized::defaults(ConfigFile::default()))
94        .merge(Json::string(config_str))
95        .extract()
96    {
97        Ok(cfg) => cfg,
98        Err(_e) => {
99            error!("Failed to parse config JSON: {_e}");
100            return -1;
101        }
102    };
103
104    let service_config = match (config_file.secret, config_file.server) {
105        (Some(secret), Some(server)) => ServiceConfig {
106            secret,
107            server,
108            endpoint: config_file.endpoint,
109            #[cfg(feature = "transport-quic")]
110            transport: config_file.transport,
111            #[cfg(feature = "tracing")]
112            logging: config_file.logging,
113        },
114        (None, _) => {
115            error!("Configuration error: missing required field `secret` in JSON config");
116            return -1;
117        }
118        (_, None) => {
119            error!("Configuration error: missing required field `server` in JSON config");
120            return -1;
121        }
122    };
123
124    #[cfg(feature = "tracing")]
125    crate::logging::init_for_ffi(&service_config.logging);
126
127    let runtime = match Builder::new_multi_thread().enable_all().build() {
128        Ok(rt) => rt,
129        Err(_e) => {
130            error!("Failed to create Tokio runtime: {}", _e);
131            return -1;
132        }
133    };
134
135    let service = runtime.block_on(async {
136        #[cfg(feature = "transport-quic")]
137        Service::build::<QuicServiceBuilder>(Arc::new(service_config)).await
138    });
139
140    #[cfg(feature = "transport-quic")]
141    let service = match service {
142        Ok(s) => s,
143        Err(e) => {
144            error!("Failed to build service: {}", e);
145            return -1;
146        }
147    };
148
149    #[cfg(not(feature = "transport-quic"))]
150    {
151        error!("The application was compiled without a transport feature");
152        return -1;
153    }
154
155    let mut handle_guard = SERVICE_HANDLE.lock().unwrap();
156    if handle_guard.is_some() {
157        error!("Service is already running. Please shut down the existing service first.");
158        return -1;
159    }
160
161    *handle_guard = Some(ServiceHandle {
162        #[cfg(feature = "transport-quic")]
163        service: Some(Box::new(service)),
164        runtime,
165    });
166
167    info!("Service started successfully");
168
169    0
170}
171
172/// Triggers a network rebind on the underlying transport.
173///
174/// This is useful in scenarios where the network environment changes,
175/// to ensure the client can re-establish its connection through a new socket.
176///
177/// # Returns
178///
179/// * `0` on success.
180/// * `-1` if the service is not running or the rebind operation fails.
181///
182/// # Safety
183///
184/// This function is not thread-safe and should not be called concurrently with
185/// other service management functions.
186#[unsafe(no_mangle)]
187pub extern "C" fn ombrac_client_service_rebind() -> i32 {
188    let handle_guard = SERVICE_HANDLE.lock().unwrap();
189    if let Some(handle) = handle_guard.as_ref() {
190        #[cfg(feature = "transport-quic")]
191        if let Some(service) = &handle.service {
192            let result = handle.runtime.block_on(service.rebind());
193            if let Err(e) = result {
194                error!("Failed to rebind: {}", e);
195                return -1;
196            } else {
197                info!("Service rebind successful");
198                return 0;
199            }
200        }
201    }
202    -1
203}
204
205/// Shuts down the running service and releases all associated resources.
206///
207/// This function will gracefully stop the service and terminate the asynchronous
208/// runtime. It is safe to call even if the service was not started or has
209/// already been stopped.
210///
211/// # Returns
212///
213/// * `0` on completion.
214///
215/// # Safety
216///
217/// This function is not thread-safe and should not be called concurrently with
218/// `ombrac_client_service_startup`.
219#[unsafe(no_mangle)]
220pub extern "C" fn ombrac_client_service_shutdown() -> i32 {
221    let mut handle_guard = SERVICE_HANDLE.lock().unwrap();
222
223    if let Some(mut handle) = handle_guard.take() {
224        info!("Shutting down service");
225
226        #[cfg(feature = "transport-quic")]
227        if let Some(service) = handle.service.take() {
228            handle.runtime.block_on(async {
229                service.shutdown().await;
230            });
231        }
232
233        handle.runtime.shutdown_background();
234
235        info!("Service shut down complete.");
236    } else {
237        info!("Service was not running.");
238    }
239
240    0
241}
242
243/// Returns the version of the ombrac-client library.
244///
245/// The returned string is a null-terminated UTF-8 string. The memory for this
246/// string is managed by the library and should not be freed by the caller.
247#[unsafe(no_mangle)]
248pub extern "C" fn ombrac_client_get_version() -> *const c_char {
249    const VERSION_WITH_NULL: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
250    VERSION_WITH_NULL.as_ptr() as *const c_char
251}