Cotton code
263 lines · 8.4 KB · RustRaw
//! Handles and callback contexts are registry IDs, never JVM-supplied pointers.//! Removing a callback prevents new deliveries; an already-running callback//! owns an Arc, so unsubscribe and close cannot free its JVM reference early.use crate::native::{Core, Error, OwnedString, Result};use cotton_ffi::{cotton_subscribe, cotton_version};use jni::errors::ThrowRuntimeExAndDefault;use jni::objects::{JObject, JString, JValue};use jni::refs::Global;use jni::strings::JNIString;use jni::{jni_sig, jni_str, Env, EnvUnowned, JavaVM};use std::cell::Cell;use std::collections::HashMap;use std::ffi::{c_char, c_void, CStr};use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex, OnceLock, RwLock};thread_local! {    static IN_CALLBACK: Cell<bool> = const { Cell::new(false) };}struct CallbackFrame(bool);impl Drop for CallbackFrame {    fn drop(&mut self) {        IN_CALLBACK.set(self.0);    }}fn refuse_reentrant_call() -> Result<()> {    if IN_CALLBACK.get() {        Err(Error::Invalid("an event callback must enqueue work before calling the core".into()))    } else {        Ok(())    }}struct Callback {    vm: JavaVM,    sink: Global<JObject<'static>>,    failed: AtomicBool,}struct Session {    core: Core,    callback: Option<(usize, Arc<Callback>)>,}impl Session {    fn unsubscribe(&mut self) -> Result<()> {        unsafe { cotton_subscribe(self.core.0, std::ptr::null_mut(), None) };        if let Some((id, _)) = self.callback.take() {            callbacks().lock().map_err(lock_error)?.remove(&id);        }        Ok(())    }}type Sessions = Mutex<HashMap<usize, Arc<RwLock<Option<Session>>>>>;fn sessions() -> &'static Sessions {    static SESSIONS: OnceLock<Sessions> = OnceLock::new();    SESSIONS.get_or_init(Mutex::default)}fn callbacks() -> &'static Mutex<HashMap<usize, Arc<Callback>>> {    static CALLBACKS: OnceLock<Mutex<HashMap<usize, Arc<Callback>>>> = OnceLock::new();    CALLBACKS.get_or_init(Mutex::default)}fn lock_error<T>(_: T) -> Error {    Error::Invalid("the native core lifetime lock failed".into())}fn next_id() -> Result<usize> {    static NEXT: AtomicUsize = AtomicUsize::new(1);    NEXT.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {        // Both JNI jlong and a 32-bit Android context pointer must hold it.        (value < isize::MAX as usize).then_some(value + 1)    })    .map_err(|_| Error::Invalid("native handle IDs are exhausted".into()))}fn session(id: i64) -> Result<Arc<RwLock<Option<Session>>>> {    let id = usize::try_from(id).map_err(|_| Error::Invalid("invalid native handle".into()))?;    sessions()        .lock()        .map_err(lock_error)?        .get(&id)        .cloned()        .ok_or_else(|| Error::Invalid("the Cotton core is closed".into()))}extern "C" fn on_event(context: *mut c_void, line: *const c_char) {    // No Rust panic may cross a callback into the C ABI.    let _ = std::panic::catch_unwind(|| {        let callback = callbacks()            .lock()            .ok()            .and_then(|entries| entries.get(&(context as usize)).cloned());        let Some(callback) = callback else { return };        if line.is_null() {            callback.failed.store(true, Ordering::Release);            return;        }        // This is BORROWED by cotton_subscribe. Copy before returning; never free.        let text = unsafe { CStr::from_ptr(line) }            .to_string_lossy()            .into_owned();        let _frame = CallbackFrame(IN_CALLBACK.replace(true));        let delivered = callback            .vm            .attach_current_thread(|env| -> jni::errors::Result<()> {                let text = JString::from_str(env, text)?;                env.call_method(                    &callback.sink,                    jni_str!("onEvent"),                    jni_sig!("(Ljava/lang/String;)V"),                    &[JValue::Object(text.as_ref())],                )?;                Ok(())            });        if delivered.is_err() {            // Report on the next native call; a callback failure must not leave            // the UI silently believing it has a working event subscription.            callback.failed.store(true, Ordering::Release);        }    });}fn open(env: &mut Env<'_>, config: &str) -> Result<i64> {    refuse_reentrant_call()?;    let core = match Core::open(config) {        Ok(core) => core,        Err(Error::Open(error)) => {            env.throw_new(                jni_str!("com/cottondb/android/core/NativeOpenException"),                JNIString::new(error),            )?;            return Err(jni::errors::Error::JavaException.into());        }        Err(error) => return Err(error),    };    let id = next_id()?;    sessions().lock().map_err(lock_error)?.insert(        id,        Arc::new(RwLock::new(Some(Session {            core,            callback: None,        }))),    );    Ok(id as i64)}#[no_mangle]pub extern "system" fn Java_com_cottondb_android_core_NativeBindings_open<'local>(    mut env: EnvUnowned<'local>,    _this: JObject<'local>,    config: JString<'local>,) -> i64 {    env.with_env(|env| open(env, &config.to_string()))        .resolve::<ThrowRuntimeExAndDefault>()}#[no_mangle]pub extern "system" fn Java_com_cottondb_android_core_NativeBindings_call<'local>(    mut env: EnvUnowned<'local>,    _this: JObject<'local>,    id: i64,    method: JString<'local>,    request: JString<'local>,) -> JString<'local> {    env.with_env(|env| -> Result<_> {        refuse_reentrant_call()?;        let owner = session(id)?;        let guard = owner.read().map_err(lock_error)?;        let session = guard            .as_ref()            .ok_or_else(|| Error::Invalid("the Cotton core is closed".into()))?;        if session            .callback            .as_ref()            .is_some_and(|(_, callback)| callback.failed.load(Ordering::Acquire))        {            return Err(Error::Invalid("native event delivery failed".into()));        }        let answer = session            .core            .call(&method.to_string(), &request.to_string())?;        Ok(JString::from_str(env, answer)?)    })    .resolve::<ThrowRuntimeExAndDefault>()}#[no_mangle]pub extern "system" fn Java_com_cottondb_android_core_NativeBindings_subscribe<'local>(    mut env: EnvUnowned<'local>,    _this: JObject<'local>,    id: i64,    sink: JObject<'local>,) {    env.with_env(|env| -> Result<()> {        refuse_reentrant_call()?;        let owner = session(id)?;        let mut guard = owner.write().map_err(lock_error)?;        let session = guard            .as_mut()            .ok_or_else(|| Error::Invalid("the Cotton core is closed".into()))?;        session.unsubscribe()?;        if sink.is_null() {            return Ok(());        }        let callback = Arc::new(Callback {            vm: env.get_java_vm()?,            sink: env.new_global_ref(sink)?,            failed: AtomicBool::new(false),        });        let token = next_id()?;        callbacks()            .lock()            .map_err(lock_error)?            .insert(token, callback.clone());        session.callback = Some((token, callback));        unsafe { cotton_subscribe(session.core.0, token as *mut c_void, Some(on_event)) };        Ok(())    })    .resolve::<ThrowRuntimeExAndDefault>()}#[no_mangle]pub extern "system" fn Java_com_cottondb_android_core_NativeBindings_close<'local>(    mut env: EnvUnowned<'local>,    _this: JObject<'local>,    id: i64,) {    env.with_env(|_| -> Result<()> {        refuse_reentrant_call()?;        let id = usize::try_from(id).map_err(|_| Error::Invalid("invalid native handle".into()))?;        let owner = sessions().lock().map_err(lock_error)?.remove(&id);        if let Some(owner) = owner {            // Removing the ID first prevents new calls; the write lock waits            // for every existing call before dropping the C handle.            if let Some(mut session) = owner.write().map_err(lock_error)?.take() {                session.unsubscribe()?;            }        }        Ok(())    })    .resolve::<ThrowRuntimeExAndDefault>()}#[no_mangle]pub extern "system" fn Java_com_cottondb_android_core_NativeBindings_version<'local>(    mut env: EnvUnowned<'local>,    _this: JObject<'local>,) -> JString<'local> {    env.with_env(|env| -> Result<_> {        Ok(JString::from_str(            env,            OwnedString(cotton_version()).take()?,        )?)    })    .resolve::<ThrowRuntimeExAndDefault>()}