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, ombrac::protocol::Secret>(Arc::new(service_config))
137            .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/// Shuts down the running service and releases all associated resources.
173///
174/// This function will gracefully stop the service and terminate the asynchronous
175/// runtime. It is safe to call even if the service was not started or has
176/// already been stopped.
177///
178/// # Returns
179///
180/// * `0` on completion.
181///
182/// # Safety
183///
184/// This function is not thread-safe and should not be called concurrently with
185/// `ombrac_server_service_startup`.
186#[unsafe(no_mangle)]
187pub extern "C" fn ombrac_server_service_shutdown() -> i32 {
188    let mut handle_guard = SERVICE_HANDLE.lock().unwrap();
189
190    if let Some(mut handle) = handle_guard.take() {
191        info!("Shutting down service");
192
193        #[cfg(feature = "transport-quic")]
194        if let Some(service) = handle.service.take() {
195            handle.runtime.block_on(async {
196                service.shutdown().await;
197            });
198        }
199
200        handle.runtime.shutdown_background();
201
202        info!("Service shut down complete.");
203    } else {
204        info!("Service was not running.");
205    }
206
207    0
208}
209
210/// Returns the version of the ombrac-server library.
211///
212/// The returned string is a null-terminated UTF-8 string. The memory for this
213/// string is managed by the library and should not be freed by the caller.
214#[unsafe(no_mangle)]
215pub extern "C" fn ombrac_server_get_version() -> *const c_char {
216    const VERSION_WITH_NULL: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
217    VERSION_WITH_NULL.as_ptr() as *const c_char
218}