ombrac_server/
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::server::Server, 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_server_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_server_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_server_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_server_service_shutdown`.
88#[unsafe(no_mangle)]
89pub unsafe extern "C" fn ombrac_server_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.listen) {
105        (Some(secret), Some(listen)) => ServiceConfig {
106            secret,
107            listen,
108            #[cfg(feature = "transport-quic")]
109            transport: config_file.transport,
110            #[cfg(feature = "tracing")]
111            logging: config_file.logging,
112        },
113        (None, _) => {
114            error!("Configuration error: missing required field `secret` in JSON config");
115            return -1;
116        }
117        (_, None) => {
118            error!("Configuration error: missing required field `listen` in JSON config");
119            return -1;
120        }
121    };
122
123    #[cfg(feature = "tracing")]
124    crate::logging::init_for_ffi(&service_config.logging);
125
126    let runtime = match Builder::new_multi_thread().enable_all().build() {
127        Ok(rt) => rt,
128        Err(_e) => {
129            error!("Failed to create Tokio runtime: {_e}");
130            return -1;
131        }
132    };
133
134    let service = runtime.block_on(async {
135        #[cfg(feature = "transport-quic")]
136        Service::build::<QuicServiceBuilder>(Arc::new(service_config)).await
137    });
138
139    #[cfg(feature = "transport-quic")]
140    let service = match service {
141        Ok(s) => s,
142        Err(e) => {
143            error!("Failed to build service: {}", e);
144            return -1;
145        }
146    };
147
148    #[cfg(not(feature = "transport-quic"))]
149    {
150        error!("The application was compiled without a transport feature");
151        return -1;
152    }
153
154    let mut handle_guard = SERVICE_HANDLE.lock().unwrap();
155    if handle_guard.is_some() {
156        error!("Service is already running. Please shut down the existing service first.");
157        return -1;
158    }
159
160    *handle_guard = Some(ServiceHandle {
161        #[cfg(feature = "transport-quic")]
162        service: Some(Box::new(service)),
163        runtime,
164    });
165
166    info!("Service started successfully");
167
168    0
169}
170
171/// Shuts down the running service and releases all associated resources.
172///
173/// This function will gracefully stop the service and terminate the asynchronous
174/// runtime. It is safe to call even if the service was not started or has
175/// already been stopped.
176///
177/// # Returns
178///
179/// * `0` on completion.
180///
181/// # Safety
182///
183/// This function is not thread-safe and should not be called concurrently with
184/// `ombrac_server_service_startup`.
185#[unsafe(no_mangle)]
186pub extern "C" fn ombrac_server_service_shutdown() -> i32 {
187    let mut handle_guard = SERVICE_HANDLE.lock().unwrap();
188
189    if let Some(mut handle) = handle_guard.take() {
190        info!("Shutting down service");
191
192        #[cfg(feature = "transport-quic")]
193        if let Some(service) = handle.service.take() {
194            handle.runtime.block_on(async {
195                service.shutdown().await;
196            });
197        }
198
199        handle.runtime.shutdown_background();
200
201        info!("Service shut down complete.");
202    } else {
203        info!("Service was not running.");
204    }
205
206    0
207}
208
209/// Returns the version of the ombrac-server library.
210///
211/// The returned string is a null-terminated UTF-8 string. The memory for this
212/// string is managed by the library and should not be freed by the caller.
213#[unsafe(no_mangle)]
214pub extern "C" fn ombrac_server_get_version() -> *const c_char {
215    const VERSION_WITH_NULL: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
216    VERSION_WITH_NULL.as_ptr() as *const c_char
217}