Skip to main content

acta_ffi/
lib.rs

1//! C ABI for acta (ABI version 2).
2//!
3//! Every function returns an `acta_ffi_status`; strings are passed as
4//! pointer/length pairs. Logger handles are opaque 64-bit tokens backed by
5//! magic-guarded allocations — no global registry, so calls cost one
6//! pointer dereference. On failure, `acta_last_error()` returns the detail
7//! message for the most recent failed call on the calling thread.
8//!
9//! `include/acta_ffi.h` is generated from this crate by cbindgen at build
10//! time and must not be edited by hand.
11
12#![allow(unsafe_code)]
13
14use std::{slice, str};
15
16use acta_abi as abi;
17
18/// Opaque logger handle, created by `acta_logger_create`.
19#[allow(non_camel_case_types)]
20pub type acta_ffi_handle = u64;
21
22/// Log level values for `acta_logger_log`.
23#[allow(non_camel_case_types)]
24#[repr(u32)]
25pub enum acta_ffi_level {
26    Error = 0,
27    Warn = 1,
28    Info = 2,
29    Debug = 3,
30    Trace = 4,
31}
32
33/// Status codes returned by every acta function.
34#[allow(non_camel_case_types)]
35#[repr(i32)]
36pub enum acta_ffi_status {
37    Ok = 0,
38    InvalidArgument = 1,
39    InvalidHandle = 2,
40    LoggerError = 3,
41    InternalError = 4,
42}
43
44/// Bytes stored at the start of every live logger allocation; a stale or
45/// forged handle fails with `InvalidHandle` instead of crashing in the
46/// common cases.
47const HANDLE_MAGIC: u64 = u64::from_be_bytes(*b"ACTALOG2");
48
49struct LoggerBox {
50    magic: u64,
51    logger: abi::Logger,
52}
53
54thread_local! {
55    static LAST_ERROR: std::cell::RefCell<Option<std::ffi::CString>> =
56        const { std::cell::RefCell::new(None) };
57}
58
59fn fail(error: &abi::Error) -> acta_ffi_status {
60    LAST_ERROR.with(|slot| {
61        *slot.borrow_mut() = std::ffi::CString::new(error.message.as_str()).ok();
62    });
63    match error.status {
64        abi::STATUS_INVALID_ARGUMENT => acta_ffi_status::InvalidArgument,
65        abi::STATUS_INVALID_HANDLE => acta_ffi_status::InvalidHandle,
66        abi::STATUS_LOGGER_ERROR => acta_ffi_status::LoggerError,
67        _ => acta_ffi_status::InternalError,
68    }
69}
70
71fn reject(message: &str) -> acta_ffi_status {
72    fail(&abi::Error::new(abi::STATUS_INVALID_ARGUMENT, message))
73}
74
75/// Maps a binding operation to a status code, recording failures for
76/// `acta_last_error`.
77fn finish<T>(result: abi::Result<T>, commit: impl FnOnce(T)) -> acta_ffi_status {
78    match result {
79        Ok(value) => {
80            commit(value);
81            acta_ffi_status::Ok
82        }
83        Err(error) => fail(&error),
84    }
85}
86
87/// # Safety
88/// `handle` must be a token returned by `acta_logger_create` that has not
89/// been destroyed, or 0.
90unsafe fn logger(handle: acta_ffi_handle) -> abi::Result<&'static abi::Logger> {
91    if handle == 0 {
92        return Err(abi::Error::new(
93            abi::STATUS_INVALID_HANDLE,
94            "logger handle is null",
95        ));
96    }
97    // SAFETY: per the caller contract `handle` is a live token; the magic
98    // check rejects most stale or forged values before any field is used.
99    let boxed = unsafe { &*(handle as *const LoggerBox) };
100    if boxed.magic != HANDLE_MAGIC {
101        return Err(abi::Error::new(
102            abi::STATUS_INVALID_HANDLE,
103            "logger handle is invalid or already destroyed",
104        ));
105    }
106    Ok(&boxed.logger)
107}
108
109/// # Safety
110/// When `length > 0`, `pointer` must point to `length` readable bytes.
111unsafe fn read_str<'a>(pointer: *const u8, length: usize) -> abi::Result<&'a str> {
112    if length == 0 {
113        return Ok("");
114    }
115    if pointer.is_null() || length > isize::MAX as usize {
116        return Err(abi::Error::new(
117            abi::STATUS_INVALID_ARGUMENT,
118            "string pointer is null",
119        ));
120    }
121    // SAFETY: caller contract checked above.
122    let bytes = unsafe { slice::from_raw_parts(pointer, length) };
123    str::from_utf8(bytes).map_err(|error| {
124        abi::Error::new(
125            abi::STATUS_INVALID_ARGUMENT,
126            format!("input is not valid UTF-8: {error}"),
127        )
128    })
129}
130
131/// Returns the ABI version of this library.
132#[unsafe(no_mangle)]
133pub extern "C" fn acta_abi_version() -> u32 {
134    abi::ABI_VERSION
135}
136
137/// Returns the acta version as a NUL-terminated static string.
138#[unsafe(no_mangle)]
139pub extern "C" fn acta_version() -> *const std::ffi::c_char {
140    concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr().cast()
141}
142
143/// Returns the message of the most recent failed call on this thread, or
144/// null. The pointer is valid until the next failing call on the thread.
145#[unsafe(no_mangle)]
146pub extern "C" fn acta_last_error() -> *const std::ffi::c_char {
147    LAST_ERROR.with(|slot| {
148        slot.borrow()
149            .as_ref()
150            .map_or(std::ptr::null(), |error| error.as_ptr())
151    })
152}
153
154/// Creates a logger from a JSON config, writing a handle to `out_handle`.
155///
156/// # Safety
157/// `config_json`/`config_json_len` follow `read_str`; `out_handle` must
158/// point to writable memory.
159#[unsafe(no_mangle)]
160pub unsafe extern "C" fn acta_logger_create(
161    config_json: *const u8,
162    config_json_len: usize,
163    capacity: usize,
164    out_handle: *mut acta_ffi_handle,
165) -> acta_ffi_status {
166    if out_handle.is_null() {
167        return reject("out_handle pointer is null");
168    }
169    // SAFETY: out pointer is non-null.
170    unsafe { out_handle.write(0) };
171    finish(
172        unsafe { read_str(config_json, config_json_len) }
173            .and_then(|config_json| abi::Logger::from_config_json(config_json, capacity))
174            .map(|logger| {
175                Box::into_raw(Box::new(LoggerBox {
176                    magic: HANDLE_MAGIC,
177                    logger,
178                })) as acta_ffi_handle
179            }),
180        |handle| {
181            // SAFETY: out pointer is non-null.
182            unsafe { out_handle.write(handle) };
183        },
184    )
185}
186
187/// # Safety
188/// `message`/`message_len` follow `read_str`; `handle` follows `logger`.
189#[unsafe(no_mangle)]
190pub unsafe extern "C" fn acta_logger_log(
191    handle: acta_ffi_handle,
192    level: acta_ffi_level,
193    message: *const u8,
194    message_len: usize,
195) -> acta_ffi_status {
196    finish(
197        unsafe { logger(handle) }.and_then(|logger| {
198            let message = unsafe { read_str(message, message_len) }?;
199            logger.log(level as u32, message)
200        }),
201        |_| {},
202    )
203}
204
205/// # Safety
206/// `event_json`/`event_json_len` follow `read_str`; `handle` follows `logger`.
207#[unsafe(no_mangle)]
208pub unsafe extern "C" fn acta_logger_event(
209    handle: acta_ffi_handle,
210    event_json: *const u8,
211    event_json_len: usize,
212) -> acta_ffi_status {
213    finish(
214        unsafe { logger(handle) }.and_then(|logger| {
215            let event_json = unsafe { read_str(event_json, event_json_len) }?;
216            logger.event_json(event_json)
217        }),
218        |_| {},
219    )
220}
221
222/// Opens a span, writing its id to `out_id`.
223///
224/// # Safety
225/// `event_json`/`event_json_len` follow `read_str`; `handle` follows
226/// `logger`; `out_id` must point to writable memory.
227#[unsafe(no_mangle)]
228pub unsafe extern "C" fn acta_logger_create_span(
229    handle: acta_ffi_handle,
230    event_json: *const u8,
231    event_json_len: usize,
232    out_id: *mut u32,
233) -> acta_ffi_status {
234    if out_id.is_null() {
235        return reject("out_id pointer is null");
236    }
237    // SAFETY: out pointer is non-null.
238    unsafe { out_id.write(0) };
239    finish(
240        unsafe { logger(handle) }.and_then(|logger| {
241            let event_json = unsafe { read_str(event_json, event_json_len) }?;
242            logger.create_span_json(event_json)
243        }),
244        |id| {
245            // SAFETY: out pointer is non-null.
246            unsafe { out_id.write(id) };
247        },
248    )
249}
250
251/// # Safety
252/// `fields_json`/`fields_json_len` follow `read_str`; `handle` follows `logger`.
253#[unsafe(no_mangle)]
254pub unsafe extern "C" fn acta_logger_record_span(
255    handle: acta_ffi_handle,
256    id: u32,
257    fields_json: *const u8,
258    fields_json_len: usize,
259) -> acta_ffi_status {
260    finish(
261        unsafe { logger(handle) }.and_then(|logger| {
262            let fields_json = unsafe { read_str(fields_json, fields_json_len) }?;
263            logger.record_span_json(id, fields_json)
264        }),
265        |_| {},
266    )
267}
268
269/// # Safety
270/// `handle` follows `logger`.
271#[unsafe(no_mangle)]
272pub extern "C" fn acta_logger_close_span(handle: acta_ffi_handle, id: u32) -> acta_ffi_status {
273    finish(
274        unsafe { logger(handle) }.and_then(|logger| logger.close_span(id)),
275        |_| {},
276    )
277}
278
279/// Drains up to `output_capacity` buffered bytes into `output` and reports
280/// the cumulative dropped-byte count via `out_dropped`.
281///
282/// # Safety
283/// `output` must point to `output_capacity` writable bytes when the capacity
284/// is non-zero; `out_written` and `out_dropped` must point to writable memory;
285/// `handle` follows `logger`.
286#[unsafe(no_mangle)]
287pub unsafe extern "C" fn acta_logger_drain(
288    handle: acta_ffi_handle,
289    output: *mut u8,
290    output_capacity: usize,
291    out_written: *mut usize,
292    out_dropped: *mut u64,
293) -> acta_ffi_status {
294    if out_written.is_null()
295        || out_dropped.is_null()
296        || output_capacity > isize::MAX as usize
297        || (output_capacity > 0 && output.is_null())
298    {
299        return reject("output pointers are invalid");
300    }
301    // SAFETY: out pointers are non-null.
302    unsafe {
303        out_written.write(0);
304        out_dropped.write(0);
305    }
306    finish(
307        unsafe { logger(handle) }.map(|logger| {
308            let bytes = logger.drain(output_capacity);
309            if !bytes.is_empty() {
310                // SAFETY: drain returns at most `output_capacity` bytes and
311                // `output` is valid for that many.
312                unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), output, bytes.len()) };
313            }
314            // SAFETY: out pointers are non-null.
315            unsafe {
316                out_written.write(bytes.len());
317                out_dropped.write(logger.dropped());
318            }
319        }),
320        |_| {},
321    )
322}
323
324/// # Safety
325/// `filter`/`filter_len` follow `read_str`; `handle` follows `logger`.
326#[unsafe(no_mangle)]
327pub unsafe extern "C" fn acta_logger_set_filter(
328    handle: acta_ffi_handle,
329    filter: *const u8,
330    filter_len: usize,
331) -> acta_ffi_status {
332    finish(
333        unsafe { logger(handle) }.and_then(|logger| {
334            let filter = unsafe { read_str(filter, filter_len) }?;
335            logger.set_filter(filter)
336        }),
337        |_| {},
338    )
339}
340
341/// Destroys a logger. The handle must not be used again.
342///
343/// # Safety
344/// `handle` must be a token returned by `acta_logger_create` that has not
345/// been destroyed, or 0.
346#[unsafe(no_mangle)]
347pub unsafe extern "C" fn acta_logger_destroy(handle: acta_ffi_handle) -> acta_ffi_status {
348    match unsafe { logger(handle) } {
349        Err(error) => fail(&error),
350        // SAFETY: the magic check in `logger` passed; reclaim the allocation.
351        Ok(_) => {
352            drop(unsafe { Box::from_raw(handle as *mut LoggerBox) });
353            acta_ffi_status::Ok
354        }
355    }
356}