refactor: drop internal bridge/ffi layers; exporter family lands

Single-lib cleanup: the per-crate src/bridge/ and src/ffi.rs layers are
gone (oakundo/oakcommon/oaknode/oaktimeline/oakcodec/oakaudio/
oakrender/oaktask/oakplugin/oakstorage); cross-crate calls are plain
Rust, CHandle marshalling shrinks to the oakengine boundary, and tests
call the Rust APIs directly (pure C-ABI wrapper tests removed where
the domain layer already covers the behavior).

exporter.h family implemented: oakengine_export_render (CLI contract),
oakengine_export_render_with_params (was a stub), last_error and
progress callback; synchronous path reuses task_create_export +
start_sync. Fixes on the way: oaktask video ticket self-deadlock,
audio params dropped on the export path, codec encoder AAC slicing and
H.264 time base. Real-mp4 tests cover both entry points, progress and
the illegal-argument matrix.

Also: oakstorage session maps null project handles to None (version-
info path), configstore test double literal 3.14 -> 3.15 (clippy PI
lint), oakaudio output callback scratch buffer + env-aware P1 test,
cli media round-trip test uses a generated 16-frame clip (no more
minute-long debug runs).
This commit is contained in:
2026-08-16 00:33:45 +08:00
parent 2248be8567
commit ab1a2e9c7b
293 changed files with 27826 additions and 90128 deletions
+3 -5
View File
@@ -28,8 +28,6 @@ sea-orm = { version = "2", features = ["sqlx-postgres", "sqlx-sqlite", "runtime-
tokio = { version = "1", features = ["rt", "macros"] }
[dev-dependencies]
# oakcodec's oakcore_*/oakrender_* host-mocks (test-stubs feature): the
# oakstorage test binary links the real oakcodec (via oaknode), whose
# ffmpeg unit references those cross-crate symbols that no Rust crate
# provides (same setup as oaknode's own dev-dependencies).
oakcodec = { path = "../oakcodec", features = ["test-stubs"] }
# oakcodec is also reachable through oaknode; the dev-dependency re-entry
# used to enable oakcodec's `test-stubs` host-mocks, which no longer exist
# (single-lib unification removed the oakcore_audioparams_* C ABI calls).
+1 -1
View File
@@ -66,7 +66,7 @@ use oaknode::sequence::SequenceBehavior;
use oaknode::track::{TrackBehavior, TrackListBehavior, TrackType};
use crate::backend::LoadResult;
use crate::bridge::node;
use crate::nodeutil as node;
use crate::error::{Error, Result};
use crate::uri::StorageUri;
+4 -4
View File
@@ -121,8 +121,8 @@ impl crate::backend::StorageBackend for OveXmlBackend {
Probe::Current | Probe::Old => {}
}
let project = crate::bridge::node::serializer_load(&xml)?;
let handle = crate::bridge::node::make_project_owned(project);
let project = crate::nodeutil::serializer_load(&xml)?;
let handle = crate::nodeutil::make_project_owned(project);
let version_info = if matches!(probe, Probe::Old) {
OAKSTORAGE_TOO_OLD
} else {
@@ -141,12 +141,12 @@ impl crate::backend::StorageBackend for OveXmlBackend {
.local_path()
.ok_or(Error::Invalid)?
.to_string();
let arc = unsafe { crate::bridge::node::project_arc(&project)? };
let arc = unsafe { crate::nodeutil::project_arc(&project)? };
let xml = {
let guard = arc
.lock()
.map_err(|_| Error::State)?;
crate::bridge::node::serializer_save(&guard)?
crate::nodeutil::serializer_save(&guard)?
};
std::fs::write(&path, xml).map_err(|e| Error::Io(e.to_string()))?;
Ok(())
-19
View File
@@ -1,19 +0,0 @@
// Oak Video Editor - Non-Linear Video Editor
// Copyright (C) 2026 Oak Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! C ABI imports from other oak modules.
pub mod node;
-430
View File
@@ -1,430 +0,0 @@
// Oak Video Editor - Non-Linear Video Editor
// Copyright (C) 2026 Oak Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! C ABI export layer: implements M10 §2.2/§2.3 verbatim
//! (`oakstorage_probe/open/save/project_free/project_take_project/
//! project_project/project_uri/last_error/debug_alive_count` and the
//! backend vtable registration pair).
//!
//! `oakstorage_open` returns a session handle (alive-counted). The
//! project inside is an `OakNodeProject*`-compatible handle boxed via
//! the shared `oakcore_rs::handle::CHandle`, so `take_project` hands
//! back something `oaknode_*` functions accept, and `save` accepts
//! handles produced by `oaknode_project_init`.
use std::cell::RefCell;
use std::ffi::{c_char, c_int, c_uint, CStr, CString};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Arc;
use crate::backend::StorageBackend;
use crate::bridge::node;
use crate::error::{Error, OAKSTORAGE_E_FAILED, OAKSTORAGE_OK, Result};
use crate::handle::CHandle;
use crate::session::Session;
use crate::uri::StorageUri;
/// Save options bitmask: compress the ove-xml container. Accepted but
/// not implemented by the built-in backends (the oaknode serializer
/// emits plain XML only); unknown bits are ignored (M10 §2.2).
pub const OAKSTORAGE_SAVE_COMPRESS: c_uint = 0x1;
/// Live session count (`oakstorage_debug_alive_count`).
static ALIVE: AtomicI32 = AtomicI32::new(0);
// Per-thread last-error detail (`oakstorage_last_error`).
thread_local! {
static LAST_ERROR: RefCell<String> = const { RefCell::new(String::new()) };
}
/// Record the thread's last error detail.
fn set_last_error(msg: &str) {
LAST_ERROR.with(|e| *e.borrow_mut() = msg.to_string());
}
/// Read the thread's last error detail.
fn take_last_error() -> String {
LAST_ERROR.with(|e| e.borrow().clone())
}
/// Release for session handles (alive-counted; the session's Drop
/// releases the held project handle).
unsafe extern "C" fn session_release(ctx: *mut std::ffi::c_void) {
unsafe {
let rb = ctx as *mut crate::handle::RefBox<Session>;
if (*rb).refs.fetch_sub(1, Ordering::AcqRel) == 1 {
drop(Box::from_raw(rb));
ALIVE.fetch_sub(1, Ordering::Relaxed);
}
}
}
/// `oakstorage_probe`: which backend claims this URI (two-stage
/// string; negative = E_NO_BACKEND).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_probe(
uri: *const c_char,
buf: *mut c_char,
buf_size: c_int,
) -> c_int {
let uri_str = unsafe { cstr(uri) }.map(str::to_string);
match catch_unwind(AssertUnwindSafe(|| {
let s = uri_str.as_deref().ok_or(Error::Invalid)?;
let parsed = StorageUri::parse(s)?;
let backend = crate::registry::Registry::global().resolve(&parsed)?;
Ok::<String, Error>(backend.name().to_string())
})) {
Ok(Ok(name)) => unsafe { node::copy_string_out(&name, buf, buf_size) },
Ok(Err(e)) => {
set_last_error(&e.to_string());
e.code()
}
Err(_) => {
set_last_error("storage: panic in oakstorage_probe");
OAKSTORAGE_E_FAILED
}
}
}
/// `oakstorage_open`: open a project session by URI (owned handle;
/// `result_code` receives an OAKSTORAGE_* code incl. the positive
/// version info codes).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_open(uri: *const c_char, result_code: *mut c_int) -> CHandle {
let uri_str = unsafe { cstr(uri) }.map(str::to_string);
match catch_unwind(AssertUnwindSafe(|| open_inner(uri_str.as_deref()))) {
Ok(Ok((handle, info))) => {
if !result_code.is_null() {
unsafe { *result_code = info };
}
handle
}
Ok(Err(e)) => {
set_last_error(&e.to_string());
if !result_code.is_null() {
unsafe { *result_code = e.code() };
}
CHandle::null()
}
Err(_) => {
set_last_error("storage: panic in oakstorage_open");
if !result_code.is_null() {
unsafe { *result_code = OAKSTORAGE_E_FAILED };
}
CHandle::null()
}
}
}
/// Open a session: parse + resolve + backend load, then wrap the
/// project in an alive-counted session handle. The returned info code
/// is the backend's version verdict (OK or a positive info code).
fn open_inner(uri: Option<&str>) -> Result<(CHandle, i32)> {
let s = uri.ok_or(Error::Invalid)?;
let parsed = StorageUri::parse(s)?;
let backend = crate::registry::Registry::global().resolve(&parsed)?;
let loaded = backend.load(&parsed)?;
let info = loaded.version_info;
if loaded.project.is_null() {
// Version probing declined to load (TOO_NEW / UNKNOWN_VERSION).
return Ok((CHandle::null(), info));
}
ALIVE.fetch_add(1, Ordering::Relaxed);
let session = Session::new(parsed, loaded.project);
Ok((crate::handle::make_owned_with(session, session_release), info))
}
/// `oakstorage_save`: save a project to a URI (options bitmask;
/// unknown bits ignored by backends).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_save(
project: CHandle,
uri: *const c_char,
options: c_uint,
) -> c_int {
let uri_str = unsafe { cstr(uri) }.map(str::to_string);
match catch_unwind(AssertUnwindSafe(|| {
let s = uri_str.as_deref().ok_or(Error::Invalid)?;
let parsed = StorageUri::parse(s)?;
let backend = crate::registry::Registry::global().resolve(&parsed)?;
backend.save(project, &parsed, options)
})) {
Ok(Ok(())) => OAKSTORAGE_OK,
Ok(Err(e)) => {
set_last_error(&e.to_string());
e.code()
}
Err(_) => {
set_last_error("storage: panic in oakstorage_save");
OAKSTORAGE_E_FAILED
}
}
}
/// `oakstorage_project_free` (NULL/empty no-op).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_project_free(session: *mut CHandle) {
crate::handle::guard_void(|| unsafe {
if session.is_null() || (*session).ctx.is_null() {
return;
}
let h = (*session).clone();
if let Some(f) = h.release {
f(h.ctx);
}
(*session).ctx = std::ptr::null_mut();
});
}
/// `oakstorage_project_take_project`: ownership transfer out of the
/// session (the session becomes an empty shell; still free it).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_project_take_project(session: CHandle) -> CHandle {
match catch_unwind(AssertUnwindSafe(|| unsafe { session_take(session) })) {
Ok(Ok(h)) => h,
Ok(Err(_)) | Err(_) => CHandle::null(),
}
}
/// Mutate the boxed session to take its project out (empty after an
/// earlier take — then an empty handle, not an error).
unsafe fn session_take(session: CHandle) -> Result<CHandle> {
let rb = session.ctx as *mut crate::handle::RefBox<Session>;
if rb.is_null() {
return Err(Error::Invalid);
}
Ok(unsafe { (*rb).value.take() }.unwrap_or_else(CHandle::null))
}
/// `oakstorage_project_project`: borrowed project handle (empty after
/// take). A fresh box over a clone of the project Arc, so releasing it
/// (or not) cannot disturb the session's own handle.
#[no_mangle]
pub unsafe extern "C" fn oakstorage_project_project(session: CHandle) -> CHandle {
match catch_unwind(AssertUnwindSafe(|| -> crate::error::Result<CHandle> {
unsafe {
let sess = crate::handle::get::<Session>(&session).ok_or(Error::Invalid)?;
let ph = sess.project().ok_or(Error::State)?;
let arc = oaknode::handle::get::<node::ProjectArc>(ph)
.ok_or(Error::Invalid)?
.clone();
Ok(oaknode::handle::make_owned(arc))
}
})) {
Ok(Ok(h)) => h,
Ok(Err(_)) | Err(_) => CHandle::null(),
}
}
/// `oakstorage_project_uri` (two-stage string).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_project_uri(
session: CHandle,
buf: *mut c_char,
buf_size: c_int,
) -> c_int {
let uri_str = match unsafe { crate::handle::get::<Session>(&session) } {
Some(s) => s.uri().to_uri_string(),
None => return crate::error::OAKSTORAGE_E_INVALID,
};
unsafe { node::copy_string_out(&uri_str, buf, buf_size) }
}
/// `oakstorage_last_error` (two-stage string; per-thread last error
/// detail).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_last_error(buf: *mut c_char, buf_size: c_int) -> c_int {
let msg = take_last_error();
unsafe { node::copy_string_out(&msg, buf, buf_size) }
}
/// `oakstorage_debug_alive_count` (leak assertions in tests).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_debug_alive_count() -> c_int {
ALIVE.load(Ordering::Relaxed)
}
// ---------------------------------------------------------------------
// Foreign (C-side) backend vtable registration — M10 §2.3
// ---------------------------------------------------------------------
/// C-side backend vtable (M10 §2.3; the layout is the C header's
/// struct — implementer copies it field-for-field).
#[repr(C)]
pub struct OakStorageBackendVtable {
/// Backend name (static string).
pub name: *const c_char,
/// URI scheme served (static string).
pub uri_scheme: *const c_char,
/// can_handle.
pub can_handle: Option<unsafe extern "C" fn(uri: *const c_char) -> c_int>,
/// load.
pub load: Option<
unsafe extern "C" fn(
uri: *const c_char,
result_code: *mut c_int,
err_buf: *mut c_char,
err_buf_size: c_int,
) -> CHandle,
>,
/// save.
pub save: Option<
unsafe extern "C" fn(
project: CHandle,
uri: *const c_char,
options: c_uint,
err_buf: *mut c_char,
err_buf_size: c_int,
) -> c_int,
>,
}
/// A backend registered from C: every call funnels through the vtable
/// function pointers (the vtable itself is not copied — the caller
/// guarantees it outlives unregistration).
struct ForeignBackend {
name: String,
uri_scheme: String,
can_handle: unsafe extern "C" fn(uri: *const c_char) -> c_int,
load: unsafe extern "C" fn(
uri: *const c_char,
result_code: *mut c_int,
err_buf: *mut c_char,
err_buf_size: c_int,
) -> CHandle,
save: unsafe extern "C" fn(
project: CHandle,
uri: *const c_char,
options: c_uint,
err_buf: *mut c_char,
err_buf_size: c_int,
) -> c_int,
}
impl StorageBackend for ForeignBackend {
fn name(&self) -> &str {
&self.name
}
fn uri_scheme(&self) -> &str {
&self.uri_scheme
}
fn can_handle(&self, uri: &StorageUri) -> bool {
let c = match CString::new(uri.to_uri_string()) {
Ok(c) => c,
Err(_) => return false,
};
let claimed = unsafe { (self.can_handle)(c.as_ptr()) };
claimed != 0
}
fn load(&self, uri: &StorageUri) -> Result<crate::backend::LoadResult> {
let c = CString::new(uri.to_uri_string()).map_err(|_| Error::Invalid)?;
let mut result_code: c_int = OAKSTORAGE_OK;
let handle = unsafe {
(self.load)(c.as_ptr(), &mut result_code, std::ptr::null_mut(), 0)
};
if !handle.is_null() {
Ok(crate::backend::LoadResult::with_info(handle, result_code))
} else if result_code > 0 {
// Version info code without a project.
Ok(crate::backend::LoadResult::info_only(result_code))
} else {
Err(code_to_error(result_code))
}
}
fn save(
&self,
project: CHandle,
uri: &StorageUri,
options: u32,
) -> Result<()> {
let c = CString::new(uri.to_uri_string()).map_err(|_| Error::Invalid)?;
let rc = unsafe { (self.save)(project, c.as_ptr(), options, std::ptr::null_mut(), 0) };
if rc == OAKSTORAGE_OK {
Ok(())
} else {
Err(code_to_error(rc))
}
}
}
/// Map a foreign backend's return code to the crate error.
fn code_to_error(code: c_int) -> Error {
match code {
crate::error::OAKSTORAGE_E_INVALID => Error::Invalid,
crate::error::OAKSTORAGE_E_STATE => Error::State,
crate::error::OAKSTORAGE_E_NOT_FOUND => Error::NotFound,
crate::error::OAKSTORAGE_E_FAILED => Error::Failed("foreign backend failed".to_string()),
crate::error::OAKSTORAGE_E_NO_BACKEND => Error::NoBackend,
crate::error::OAKSTORAGE_E_FORMAT => Error::Format("foreign backend format error".to_string()),
crate::error::OAKSTORAGE_E_IO => Error::Io("foreign backend I/O error".to_string()),
crate::error::OAKSTORAGE_E_NOMEM => Error::NoMem,
_ => Error::Failed(format!("foreign backend error code {code}")),
}
}
/// `oakstorage_backend_register`: register a foreign backend (the
/// vtable is not copied — the caller guarantees it outlives
/// unregistration).
#[no_mangle]
pub unsafe extern "C" fn oakstorage_backend_register(
backend: *const OakStorageBackendVtable,
) -> c_int {
crate::handle::guard(|| unsafe {
if backend.is_null() {
return Err(Error::Invalid);
}
let v = &*backend;
let name = cstr(v.name).ok_or(Error::Invalid)?.to_string();
let uri_scheme = cstr(v.uri_scheme).ok_or(Error::Invalid)?.to_string();
let can_handle = v.can_handle.ok_or(Error::Invalid)?;
let load = v.load.ok_or(Error::Invalid)?;
let save = v.save.ok_or(Error::Invalid)?;
let foreign = ForeignBackend {
name,
uri_scheme,
can_handle,
load,
save,
};
crate::registry::Registry::global().register(Arc::new(foreign))
})
}
/// `oakstorage_backend_unregister`.
#[no_mangle]
pub unsafe extern "C" fn oakstorage_backend_unregister(name: *const c_char) -> c_int {
crate::handle::guard(|| unsafe {
let name = cstr(name).ok_or(Error::Invalid)?;
crate::registry::Registry::global().unregister(name)
})
}
/// Safe read of a NUL-terminated C string argument.
///
/// # Safety
/// `p` must be a valid NUL-terminated C string for the returned
/// reference's lifetime.
unsafe fn cstr<'a>(p: *const c_char) -> Option<&'a str> {
if p.is_null() {
return None;
}
unsafe { CStr::from_ptr(p) }.to_str().ok()
}
+1 -2
View File
@@ -25,10 +25,9 @@
pub mod backend;
pub mod backends;
pub mod bridge;
pub mod error;
pub mod ffi;
pub mod handle;
pub mod nodeutil;
pub mod registry;
pub mod session;
pub mod uri;
@@ -14,23 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! oaknode calls — direct Rust calls into the oaknode crate (single-lib
//! unification, see `docs/zh/plans/riir/single-lib.md`).
//! oaknode project/serializer helpers (direct Rust calls into the
//! oaknode crate, single-lib unification; the former `bridge/node.rs`).
//!
//! The ove-xml backend needs oaknode's project + serializer families
//! (`oaknode_project_init` / `oaknode_serializer_save_to_file` /
//! `load_from_file` in the C++ world). With direct calls, graph
//! (de)serialization stays oaknode's own serializer (`load`/`save`),
//! and this bridge only boxes the resulting `Arc<Mutex<Project>>` into
//! the canonical `CHandle` form the public C API moves around.
//!
//! A project handle boxed here is layout-identical to one produced by
//! `oaknode_project_init`: both box `Arc<Mutex<Project>>` behind the
//! shared `oakcore_rs::handle::CHandle`, so `oakstorage_save` can
//! consume an oaknode-created handle and `oakstorage_project_take_*`
//! returns one the caller can hand back to oaknode functions.
//! The ove-xml/otio backends need oaknode's project + serializer
//! families. Graph (de)serialization stays oaknode's own serializer
//! (`load`/`save`); these helpers box the resulting `Arc<Mutex<Project>>`
//! into the canonical handle form the storage session API moves around.
use std::ffi::{c_char, c_int};
use std::sync::{Arc, Mutex};
use crate::error::Result;
@@ -39,24 +30,6 @@ use crate::handle::CHandle;
/// The project payload boxed by project handles.
pub type ProjectArc = Arc<Mutex<oaknode::project::Project>>;
/// New empty project, boxed as an owned handle (refcount 1). The
/// caller owns it (free with [`project_free`] / `oaknode_project_free`).
pub fn project_init() -> CHandle {
oaknode::handle::make_owned(oaknode::project::Project::new())
}
/// Free a project handle (`NULL`/empty no-op).
pub fn project_free(project: *mut CHandle) {
if project.is_null() || unsafe { (*project).ctx.is_null() } {
return;
}
let h = unsafe { (*project).clone() };
if let Some(f) = h.release {
unsafe { f(h.ctx) };
}
unsafe { (*project).ctx = std::ptr::null_mut() };
}
/// Box an existing project as an owned handle (refcount 1).
pub fn make_project_owned(project: ProjectArc) -> CHandle {
oaknode::handle::make_owned(project)
@@ -65,8 +38,8 @@ pub fn make_project_owned(project: ProjectArc) -> CHandle {
/// Read the boxed project of a project handle.
///
/// # Safety
/// The handle must box `Arc<Mutex<Project>>` (created by this bridge,
/// `oaknode_project_init`, or `oakstorage_project_take_project`).
/// The handle must box `Arc<Mutex<Project>>` (created by this module or
/// oaknode's project helpers).
pub unsafe fn project_arc(h: &CHandle) -> Result<ProjectArc> {
unsafe { oaknode::handle::get::<ProjectArc>(h) }
.cloned()
@@ -87,9 +60,9 @@ pub fn serializer_save(project: &oaknode::project::Project) -> Result<String> {
/// subtitle) in `graph`. Returns `(sequence_id, [video, audio,
/// subtitle] list ids)`.
///
/// Mirrors the private `append_default_track_lists` wiring of
/// `oaknode_sequence_create` (ffi.rs) so the otio backend can import
/// timelines into real projects; shared with tests through this bridge.
/// Mirrors the private `append_default_track_lists` wiring of the former
/// `oaknode_sequence_create` export so the otio backend can import
/// timelines into real projects.
pub fn create_sequence(
graph: &mut oaknode::graph::Graph,
) -> (oaknode::id::NodeId, Vec<oaknode::id::NodeId>) {
@@ -148,23 +121,3 @@ pub fn create_sequence(
}
(seq_id, lists)
}
/// Two-stage C string copy helper: returns the required size including
/// the NUL; writes up to `buf_size - 1` bytes plus NUL when
/// `buf_size > 0` (`// CPP-PARITY: src/node/c_api/valueconvert.h`
/// `copy_string`).
///
/// # Safety
/// `buf`/`buf_size` must describe a valid writable buffer (or `buf` may
/// be null).
pub unsafe fn copy_string_out(value: &str, buf: *mut c_char, buf_size: c_int) -> c_int {
let required = value.len() + 1;
if !buf.is_null() && buf_size > 0 {
let copy_len = value.len().min(buf_size as usize - 1);
unsafe {
std::ptr::copy_nonoverlapping(value.as_ptr() as *const c_char, buf, copy_len);
*buf.add(copy_len) = 0;
}
}
required as c_int
}
+4 -2
View File
@@ -30,11 +30,13 @@ pub struct Session {
}
impl Session {
/// Wrap a freshly loaded project.
/// Wrap a freshly loaded project. A null handle (the version-info
/// path: TOO_OLD/TOO_NEW/UNKNOWN_VERSION carries no project) maps to
/// `None`, not `Some(null)`.
pub fn new(uri: StorageUri, project: CHandle) -> Self {
Session {
uri,
project: Some(project),
project: (!project.is_null()).then_some(project),
}
}
+206 -295
View File
@@ -14,16 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! oakstorage contract tests (M10 §4 mapping).
//!
//! The oaknode serializer persists the node core surface (types,
//! values, keyframes, label/color, links, connections), settings, uuid,
//! AND the timeline structure (sequence track lists, track blocks,
//! block spans, clip footage references) — the .ove tests assert the
//! full surface; the otio/fcpxml interchange tests exercise the
//! oakotio model.
//! oakstorage contract tests (M10 §4 mapping), calling the public Rust
//! API: the backend registry, the `StorageBackend` trait, `StorageUri`
//! and the `Session` shell. The former `ffi.rs`/`bridge::node.rs` C ABI
//! is gone; save/load now go through `Registry::global().resolve(uri)`.
use std::ffi::{c_char, c_int, c_uint, CStr, CString};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
@@ -37,23 +32,22 @@ use oaknode::project::Project;
use oaknode::sequence::SequenceBehavior;
use oaknode::track::{TrackBehavior, TrackListBehavior, TrackType};
use oaknode::value::NodeValue;
use oakstorage::bridge::node;
use oakstorage::backend::{LoadResult, StorageBackend};
use oakstorage::error::{
OAKSTORAGE_E_FORMAT, OAKSTORAGE_E_INVALID, OAKSTORAGE_E_IO, OAKSTORAGE_E_NO_BACKEND,
OAKSTORAGE_E_STATE, OAKSTORAGE_OK, OAKSTORAGE_TOO_NEW, OAKSTORAGE_TOO_OLD,
OAKSTORAGE_UNKNOWN_VERSION,
};
use oakstorage::ffi;
use oakstorage::handle::CHandle;
use oakstorage::nodeutil::{make_project_owned, project_arc};
use oakstorage::registry::Registry;
use oakstorage::session::Session;
use oakstorage::uri::StorageUri;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn cs(s: &str) -> CString {
CString::new(s).unwrap()
}
fn file_uri(path: &Path) -> String {
format!("file://{}", path.display())
}
@@ -70,58 +64,48 @@ fn temp_dir(tag: &str) -> PathBuf {
dir
}
fn alive() -> i32 {
unsafe { ffi::oakstorage_debug_alive_count() }
}
fn last_error() -> String {
let needed = unsafe { ffi::oakstorage_last_error(std::ptr::null_mut(), 0) };
if needed <= 0 {
return String::new();
/// Release an owned handle (refcount 1).
fn release(h: CHandle) {
if let Some(release) = h.release {
unsafe { release(h.ctx) };
}
let mut buf = vec![0u8; needed as usize];
unsafe { ffi::oakstorage_last_error(buf.as_mut_ptr() as *mut c_char, needed) };
buf.pop(); // trailing NUL
String::from_utf8(buf).unwrap()
}
/// Probe for the backend name; `Err(code)` when no backend claims it.
fn probe_name(uri: &str) -> Result<String, c_int> {
let c = cs(uri);
let needed = unsafe { ffi::oakstorage_probe(c.as_ptr(), std::ptr::null_mut(), 0) };
if needed < 0 {
return Err(needed);
}
let mut buf = vec![0u8; needed as usize];
let rc = unsafe { ffi::oakstorage_probe(c.as_ptr(), buf.as_mut_ptr() as *mut c_char, needed) };
assert!(rc >= 0, "two-stage probe misbehaved");
buf.pop();
Ok(String::from_utf8(buf).unwrap())
/// The backend claiming `uri` (Err for none / invalid URI).
fn backend_for(uri: &str) -> Result<Arc<dyn StorageBackend>, oakstorage::error::Error> {
let parsed = StorageUri::parse(uri)?;
Registry::global().resolve(&parsed)
}
fn open(uri: &str) -> (CHandle, c_int) {
let c = cs(uri);
let mut rc = 0;
let session = unsafe { ffi::oakstorage_open(c.as_ptr(), &mut rc) };
(session, rc)
/// Save `handle` to `uri` with `options`.
fn save_handle(handle: CHandle, uri: &str, options: u32) -> oakstorage::error::Result<()> {
let parsed = StorageUri::parse(uri)?;
let backend = Registry::global().resolve(&parsed)?;
backend.save(handle, &parsed, options)
}
fn free_session(mut s: CHandle) {
unsafe { ffi::oakstorage_project_free(&mut s) };
/// Save an `Arc<Mutex<Project>>` to `uri`, releasing the wrapper handle.
fn save_project(
project: &Arc<Mutex<Project>>,
uri: &str,
options: u32,
) -> oakstorage::error::Result<()> {
let handle = make_project_owned(project.clone());
let result = save_handle(handle, uri, options);
release(handle);
result
}
fn free_project(mut h: CHandle) {
node::project_free(&mut h);
}
fn session_uri(s: &CHandle) -> String {
let needed = unsafe { ffi::oakstorage_project_uri(*s, std::ptr::null_mut(), 0) };
assert!(needed >= 0, "project_uri failed: {needed}");
let mut buf = vec![0u8; needed as usize];
let rc = unsafe { ffi::oakstorage_project_uri(*s, buf.as_mut_ptr() as *mut c_char, needed) };
assert!(rc >= 0);
buf.pop();
String::from_utf8(buf).unwrap()
/// Open `uri`: resolve the backend, load, wrap the result in a [`Session`].
/// `Err` is a hard failure (I/O, format, no backend, invalid URI); `Ok`
/// carries the session plus the version info code (TOO_OLD / TOO_NEW /
/// UNKNOWN_VERSION) the backend reported.
fn open(uri: &str) -> oakstorage::error::Result<(Session, i32)> {
let parsed = StorageUri::parse(uri)?;
let backend = Registry::global().resolve(&parsed)?;
let result = backend.load(&parsed)?;
let session = Session::new(parsed, result.project);
Ok((session, result.version_info))
}
fn r_to_f(r: Rational) -> f64 {
@@ -280,55 +264,45 @@ fn ove_xml_roundtrip_field_by_field() {
let uri = file_uri(&path);
let project = build_roundtrip_project();
let handle = node::make_project_owned(project.clone());
let rc = unsafe { ffi::oakstorage_save(handle, cs(&uri).as_ptr(), 0) };
assert_eq!(rc, OAKSTORAGE_OK, "save: {}", last_error());
free_project(handle);
save_project(&project, &uri, 0).unwrap();
// The file exists and is plain XML.
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.starts_with("<project version=\"1\">"), "{text}");
let (session, rc) = open(&uri);
assert!(!session.ctx.is_null(), "open failed rc={rc}: {}", last_error());
let (session, rc) = open(&uri).unwrap();
assert!(session.project().is_some(), "open failed rc={rc}");
assert_eq!(rc, OAKSTORAGE_OK);
assert_eq!(session_uri(&session), uri);
assert_eq!(session.uri().to_uri_string(), uri);
let proj_handle = unsafe { ffi::oakstorage_project_project(session) };
assert!(!proj_handle.ctx.is_null());
let loaded = unsafe { node::project_arc(&proj_handle) }.unwrap();
let proj_handle = session.project().cloned().unwrap();
let loaded = unsafe { project_arc(&proj_handle) }.unwrap();
{
let o = project.lock().unwrap();
let l = loaded.lock().unwrap();
assert_roundtrip_fields(&o, &l);
}
free_project(proj_handle);
free_session(session);
}
#[test]
fn ove_xml_compress_flag_still_round_trips() {
// OAKSTORAGE_SAVE_COMPRESS is accepted but not implemented (the
// OAKSTORAGE_SAVE_COMPRESS (bit 0) is accepted but not implemented (the
// oaknode serializer emits plain XML); the file still round-trips.
let dir = temp_dir("ove_compress");
let path = dir.join("compressed.ove");
let uri = file_uri(&path);
let project = build_roundtrip_project();
let handle = node::make_project_owned(project.clone());
let rc = unsafe { ffi::oakstorage_save(handle, cs(&uri).as_ptr(), ffi::OAKSTORAGE_SAVE_COMPRESS) };
assert_eq!(rc, OAKSTORAGE_OK, "save: {}", last_error());
free_project(handle);
save_project(&project, &uri, 1).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.starts_with("<project"), "compression must not corrupt the file");
let (session, rc) = open(&uri);
assert!(!session.ctx.is_null(), "open failed rc={rc}");
let (session, rc) = open(&uri).unwrap();
assert!(session.project().is_some(), "open failed rc={rc}");
assert_eq!(rc, OAKSTORAGE_OK);
let proj_handle = unsafe { ffi::oakstorage_project_project(session) };
let loaded = unsafe { node::project_arc(&proj_handle) }.unwrap();
let proj_handle = session.project().cloned().unwrap();
let loaded = unsafe { project_arc(&proj_handle) }.unwrap();
{
let o = project.lock().unwrap();
let l = loaded.lock().unwrap();
@@ -336,8 +310,6 @@ fn ove_xml_compress_flag_still_round_trips() {
assert_eq!(l.graph.node_count(), o.graph.node_count());
assert_eq!(l.settings, o.settings);
}
free_project(proj_handle);
free_session(session);
}
/// The .ove backend preserves the full timeline structure: the
@@ -356,16 +328,13 @@ fn ove_xml_timeline_roundtrip() {
let uri = file_uri(&path);
let project = build_timeline_project();
let handle = node::make_project_owned(project.clone());
let rc = unsafe { ffi::oakstorage_save(handle, cs(&uri).as_ptr(), 0) };
assert_eq!(rc, OAKSTORAGE_OK, "save: {}", last_error());
free_project(handle);
save_project(&project, &uri, 0).unwrap();
let (session, rc) = open(&uri);
assert!(!session.ctx.is_null(), "open failed rc={rc}: {}", last_error());
let (session, rc) = open(&uri).unwrap();
assert!(session.project().is_some(), "open failed rc={rc}");
assert_eq!(rc, OAKSTORAGE_OK);
let proj_handle = unsafe { ffi::oakstorage_project_project(session) };
let loaded = unsafe { node::project_arc(&proj_handle) }.unwrap();
let proj_handle = session.project().cloned().unwrap();
let loaded = unsafe { project_arc(&proj_handle) }.unwrap();
{
let l = loaded.lock().unwrap();
assert_imported_timeline(&l);
@@ -451,8 +420,6 @@ fn ove_xml_timeline_roundtrip() {
.unwrap();
assert_eq!(f2.filename, "/a/c.mp4");
}
free_project(proj_handle);
free_session(session);
}
// ---------------------------------------------------------------------------
@@ -461,19 +428,27 @@ fn ove_xml_timeline_roundtrip() {
#[test]
fn probe_dispatch() {
assert_eq!(probe_name("file:///tmp/x.ove").unwrap(), "ove-xml");
assert_eq!(probe_name("file:///tmp/x.OTIO").unwrap(), "otio", "case-insensitive");
assert_eq!(probe_name("file:///tmp/x.fcpxml").unwrap(), "otio");
assert_eq!(probe_name("/tmp/x.ove").unwrap(), "ove-xml", "bare path");
assert_eq!(backend_for("file:///tmp/x.ove").unwrap().name(), "ove-xml");
assert_eq!(
backend_for("file:///tmp/x.OTIO").unwrap().name(),
"otio",
"case-insensitive"
);
assert_eq!(backend_for("file:///tmp/x.fcpxml").unwrap().name(), "otio");
assert_eq!(backend_for("/tmp/x.ove").unwrap().name(), "ove-xml", "bare path");
// No backend claims these.
assert_eq!(probe_name("oakdb://user@host/db").unwrap_err(), OAKSTORAGE_E_NO_BACKEND);
assert_eq!(probe_name("file:///tmp/x.txt").unwrap_err(), OAKSTORAGE_E_NO_BACKEND);
assert_eq!(
backend_for("oakdb://user@host/db").err().unwrap().code(),
OAKSTORAGE_E_NO_BACKEND
);
assert_eq!(
backend_for("file:///tmp/x.txt").err().unwrap().code(),
OAKSTORAGE_E_NO_BACKEND
);
// NULL / empty URI -> E_INVALID.
let rc = unsafe { ffi::oakstorage_probe(std::ptr::null(), std::ptr::null_mut(), 0) };
assert_eq!(rc, OAKSTORAGE_E_INVALID);
assert_eq!(probe_name("").unwrap_err(), OAKSTORAGE_E_INVALID);
// Empty URI -> E_INVALID.
assert_eq!(backend_for("").err().unwrap().code(), OAKSTORAGE_E_INVALID);
}
// ---------------------------------------------------------------------------
@@ -482,39 +457,35 @@ fn probe_dispatch() {
#[test]
fn open_error_paths() {
// Nonexistent file: NULL + E_IO + a non-empty last_error.
let (session, rc) = open(&file_uri(&temp_dir("ove_missing").join("nope.ove")));
assert!(session.ctx.is_null());
assert_eq!(rc, OAKSTORAGE_E_IO);
assert!(!last_error().is_empty(), "last_error must be set");
// Nonexistent file: Err(Io).
let missing = file_uri(&temp_dir("ove_missing").join("nope.ove"));
assert_eq!(open(&missing).err().unwrap().code(), OAKSTORAGE_E_IO);
// Too-new version header -> TOO_NEW info code, no project.
let dir = temp_dir("ove_versions");
let future = dir.join("future.ove");
std::fs::write(&future, "<olive version=\"999999\"></olive>").unwrap();
let (session, rc) = open(&file_uri(&future));
assert!(session.ctx.is_null());
let (session, rc) = open(&file_uri(&future)).unwrap();
assert!(session.project().is_none());
assert_eq!(rc, OAKSTORAGE_TOO_NEW);
// Corrupt XML -> E_FORMAT.
let corrupt = dir.join("corrupt.ove");
std::fs::write(&corrupt, "<project><nodes><node></project>").unwrap();
let (session, rc) = open(&file_uri(&corrupt));
assert!(session.ctx.is_null());
assert_eq!(rc, OAKSTORAGE_E_FORMAT);
let err = open(&file_uri(&corrupt)).err().unwrap();
assert_eq!(err.code(), OAKSTORAGE_E_FORMAT);
// Unparseable garbage -> E_FORMAT (not a version info code).
let garbage = dir.join("garbage.ove");
std::fs::write(&garbage, "not xml at all").unwrap();
let (session, rc) = open(&file_uri(&garbage));
assert!(session.ctx.is_null());
assert_eq!(rc, OAKSTORAGE_E_FORMAT);
let err = open(&file_uri(&garbage)).err().unwrap();
assert_eq!(err.code(), OAKSTORAGE_E_FORMAT);
// Recognized olive root without a version -> UNKNOWN_VERSION.
let unversioned = dir.join("unversioned.ove");
std::fs::write(&unversioned, "<olive></olive>").unwrap();
let (session, rc) = open(&file_uri(&unversioned));
assert!(session.ctx.is_null());
let (session, rc) = open(&file_uri(&unversioned)).unwrap();
assert!(session.project().is_none());
assert_eq!(rc, OAKSTORAGE_UNKNOWN_VERSION);
// A known older version loads, reporting TOO_OLD.
@@ -524,115 +495,107 @@ fn open_error_paths() {
"<olive version=\"210528\"><project version=\"1\"><uuid>{old}</uuid><nodes></nodes><settings></settings></project></olive>",
)
.unwrap();
let (session, rc) = open(&file_uri(&old));
assert!(!session.ctx.is_null(), "old version must load");
let (session, rc) = open(&file_uri(&old)).unwrap();
assert!(session.project().is_some(), "old version must load");
assert_eq!(rc, OAKSTORAGE_TOO_OLD);
free_session(session);
// NULL URI -> E_INVALID.
let (session, rc) = unsafe {
let c = std::ptr::null();
let mut rc = 0;
(ffi::oakstorage_open(c, &mut rc), rc)
};
assert!(session.ctx.is_null());
assert_eq!(rc, OAKSTORAGE_E_INVALID);
// Empty URI -> E_INVALID.
assert_eq!(open("").err().unwrap().code(), OAKSTORAGE_E_INVALID);
}
// ---------------------------------------------------------------------------
// Backend vtable pluggability (the database-swap interface proof)
// Backend pluggability (the database-swap interface proof)
// ---------------------------------------------------------------------------
/// Record of the mock backend's save calls.
/// Record of the mock backend's calls.
static MOCK_SAVED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
unsafe extern "C" fn mock_can_handle(uri: *const c_char) -> c_int {
let s = unsafe { CStr::from_ptr(uri) }.to_str().unwrap_or("");
(s.starts_with("mem://")) as c_int
}
/// A mock backend claiming `mem://` (the Rust trait shape of the former
/// C vtable).
struct MemBackend;
unsafe extern "C" fn mock_load(
uri: *const c_char,
result_code: *mut c_int,
_err_buf: *mut c_char,
_err_buf_size: c_int,
) -> CHandle {
let s = unsafe { CStr::from_ptr(uri) }.to_str().unwrap_or("");
MOCK_SAVED.lock().unwrap().push(format!("load:{s}"));
if !result_code.is_null() {
unsafe { *result_code = OAKSTORAGE_OK };
impl StorageBackend for MemBackend {
fn name(&self) -> &'static str {
"mem-test"
}
// A real project handle is the "loaded project".
node::project_init()
}
unsafe extern "C" fn mock_save(
_project: CHandle,
uri: *const c_char,
options: c_uint,
_err_buf: *mut c_char,
_err_buf_size: c_int,
) -> c_int {
let s = unsafe { CStr::from_ptr(uri) }.to_str().unwrap_or("").to_string();
MOCK_SAVED.lock().unwrap().push(format!("save:{s}:options={options}"));
OAKSTORAGE_OK
fn uri_scheme(&self) -> &'static str {
"mem"
}
fn can_handle(&self, uri: &StorageUri) -> bool {
uri.scheme == "mem"
}
fn load(&self, uri: &StorageUri) -> oakstorage::error::Result<LoadResult> {
MOCK_SAVED
.lock()
.unwrap()
.push(format!("load:{}", uri.to_uri_string()));
// A real project handle is the "loaded project".
let project = Project::new();
Ok(LoadResult::success(make_project_owned(project)))
}
fn save(
&self,
_project: CHandle,
uri: &StorageUri,
options: u32,
) -> oakstorage::error::Result<()> {
MOCK_SAVED
.lock()
.unwrap()
.push(format!("save:{}:options={options}", uri.to_uri_string()));
Ok(())
}
}
#[test]
fn backend_vtable_pluggability() {
let name = cs("mem-test");
let scheme = cs("mem");
let vtable = ffi::OakStorageBackendVtable {
name: name.as_ptr(),
uri_scheme: scheme.as_ptr(),
can_handle: Some(mock_can_handle),
load: Some(mock_load),
save: Some(mock_save),
};
fn backend_pluggability() {
// The process-global registry already holds the built-ins; the mock
// is registered under its own name and unregistered at the end.
Registry::global().register(Arc::new(MemBackend)).unwrap();
assert_eq!(
unsafe { ffi::oakstorage_backend_register(&vtable) },
OAKSTORAGE_OK
);
// Probe routes through the registered backend.
assert_eq!(backend_for("mem://x").unwrap().name(), "mem-test");
// Probe routes through the foreign vtable.
assert_eq!(probe_name("mem://x").unwrap(), "mem-test");
// Open routes through the vtable's load.
let (session, rc) = open("mem://in");
assert!(!session.ctx.is_null(), "open failed rc={rc}");
// Open routes through the backend's load.
let (session, rc) = open("mem://in").unwrap();
assert!(session.project().is_some(), "open failed rc={rc}");
assert_eq!(rc, OAKSTORAGE_OK);
free_session(session);
assert!(session.uri().to_uri_string() == "mem://in");
// Save routes through the vtable's save, options passed through.
let project = node::project_init();
let rc = unsafe { ffi::oakstorage_save(project, cs("mem://out").as_ptr(), ffi::OAKSTORAGE_SAVE_COMPRESS) };
assert_eq!(rc, OAKSTORAGE_OK, "save: {}", last_error());
free_project(project);
// Save routes through the backend's save, options passed through.
let project = Project::new();
let handle = make_project_owned(project);
save_handle(handle, "mem://out", 1).unwrap();
release(handle);
{
let saved = MOCK_SAVED.lock().unwrap();
assert!(saved.iter().any(|s| s == "load:mem://in"), "{saved:?}");
assert!(
saved
.iter()
.any(|s| s == "save:mem://out:options=1"),
saved.iter().any(|s| s == "save:mem://out:options=1"),
"{saved:?}"
);
}
// Duplicate registration is rejected.
assert_eq!(
unsafe { ffi::oakstorage_backend_register(&vtable) },
Registry::global().register(Arc::new(MemBackend)).err().unwrap().code(),
OAKSTORAGE_E_STATE
);
// Unregister: probe reports E_NO_BACKEND again.
assert_eq!(unsafe { ffi::oakstorage_backend_unregister(name.as_ptr()) }, OAKSTORAGE_OK);
assert_eq!(probe_name("mem://x").unwrap_err(), OAKSTORAGE_E_NO_BACKEND);
assert!(Registry::global().unregister("mem-test").is_ok());
assert_eq!(
backend_for("mem://x").err().unwrap().code(),
OAKSTORAGE_E_NO_BACKEND
);
// Unregister of an unknown name -> E_NOT_FOUND.
assert_eq!(
unsafe { ffi::oakstorage_backend_unregister(cs("nope").as_ptr()) },
Registry::global().unregister("nope").err().unwrap().code(),
oakstorage::error::OAKSTORAGE_E_NOT_FOUND
);
}
@@ -648,7 +611,7 @@ fn build_timeline_project() -> Arc<Mutex<Project>> {
let mut p = project.lock().unwrap();
p.initialize().unwrap();
let (seq_id, lists) = node::create_sequence(&mut p.graph);
let (seq_id, lists) = oakstorage::nodeutil::create_sequence(&mut p.graph);
p.graph.get_mut(seq_id).unwrap().core.label = "My Seq".to_string();
let mut tb = TrackBehavior::new(TrackType::Video);
@@ -854,10 +817,7 @@ fn assert_interchange_roundtrip(ext: &str) {
let uri = file_uri(&path);
let project = build_timeline_project();
let handle = node::make_project_owned(project.clone());
let rc = unsafe { ffi::oakstorage_save(handle, cs(&uri).as_ptr(), 0) };
assert_eq!(rc, OAKSTORAGE_OK, "save: {}", last_error());
free_project(handle);
save_project(&project, &uri, 0).unwrap();
// The written file parses back through oakotio with clips/tracks.
match ext {
@@ -879,17 +839,15 @@ fn assert_interchange_roundtrip(ext: &str) {
}
// And imports back into an equivalent project.
let (session, rc) = open(&uri);
assert!(!session.ctx.is_null(), "open failed rc={rc}: {}", last_error());
let (session, rc) = open(&uri).unwrap();
assert!(session.project().is_some(), "open failed rc={rc}");
assert_eq!(rc, OAKSTORAGE_OK);
let proj_handle = unsafe { ffi::oakstorage_project_project(session) };
let loaded = unsafe { node::project_arc(&proj_handle) }.unwrap();
let proj_handle = session.project().cloned().unwrap();
let loaded = unsafe { project_arc(&proj_handle) }.unwrap();
{
let l = loaded.lock().unwrap();
assert_imported_timeline(&l);
}
free_project(proj_handle);
free_session(session);
}
#[test]
@@ -909,9 +867,8 @@ fn otio_bad_root_rejected() {
let dir = temp_dir("otio_badroot");
let path = dir.join("bad.otio");
std::fs::write(&path, "{\"OTIO_SCHEMA\": \"NotATimeline.1\", \"x\": 1}").unwrap();
let (session, rc) = open(&file_uri(&path));
assert!(session.ctx.is_null());
assert_eq!(rc, OAKSTORAGE_E_FORMAT);
let err = open(&file_uri(&path)).err().unwrap();
assert_eq!(err.code(), OAKSTORAGE_E_FORMAT);
}
// ---------------------------------------------------------------------------
@@ -920,115 +877,69 @@ fn otio_bad_root_rejected() {
#[test]
fn null_and_invalid_handles() {
// open with NULL / empty URI -> E_INVALID.
let mut rc = 0;
let session = unsafe { ffi::oakstorage_open(std::ptr::null(), &mut rc) };
assert!(session.ctx.is_null());
assert_eq!(rc, OAKSTORAGE_E_INVALID);
// open with an empty URI -> E_INVALID.
assert_eq!(open("").err().unwrap().code(), OAKSTORAGE_E_INVALID);
// save with a null project handle -> E_INVALID.
let rc = unsafe { ffi::oakstorage_save(CHandle::null(), cs("file:///tmp/x.ove").as_ptr(), 0) };
assert_eq!(rc, OAKSTORAGE_E_INVALID);
// save with a null project handle -> E_INVALID (the project cannot be
// read out of an empty handle).
let uri = "file:///tmp/x.ove";
let backend = backend_for(uri).unwrap();
let err = backend
.save(CHandle::null(), &StorageUri::parse(uri).unwrap(), 0)
.err().unwrap();
assert_eq!(err.code(), OAKSTORAGE_E_INVALID);
// save with a null URI -> E_INVALID.
let project = node::project_init();
let rc = unsafe { ffi::oakstorage_save(project, std::ptr::null(), 0) };
assert_eq!(rc, OAKSTORAGE_E_INVALID);
free_project(project);
// save to an unknown-scheme URI -> E_NO_BACKEND (never reaches a
// backend).
let project = Project::new();
let handle = make_project_owned(project);
let err = save_handle(handle, "oakdb://x", 0).err().unwrap();
assert_eq!(err.code(), OAKSTORAGE_E_NO_BACKEND);
release(handle);
// save to an unknown-scheme URI -> E_NO_BACKEND.
let project = node::project_init();
let rc = unsafe { ffi::oakstorage_save(project, cs("oakdb://x").as_ptr(), 0) };
assert_eq!(rc, OAKSTORAGE_E_NO_BACKEND);
free_project(project);
// project_free(NULL) is a no-op.
unsafe { ffi::oakstorage_project_free(std::ptr::null_mut()) };
// take_project / project_project on a null handle -> null.
let h = unsafe { ffi::oakstorage_project_take_project(CHandle::null()) };
assert!(h.ctx.is_null());
let h = unsafe { ffi::oakstorage_project_project(CHandle::null()) };
assert!(h.ctx.is_null());
// project_uri on a null handle -> E_INVALID.
let rc = unsafe { ffi::oakstorage_project_uri(CHandle::null(), std::ptr::null_mut(), 0) };
assert_eq!(rc, OAKSTORAGE_E_INVALID);
// Empty session shell: take twice yields null the second time.
// take transfers the project; the second take is empty.
let dir = temp_dir("null_matrix");
let path = dir.join("x.ove");
let uri = file_uri(&path);
let project = build_roundtrip_project();
let handle = node::make_project_owned(project);
assert_eq!(
unsafe { ffi::oakstorage_save(handle, cs(&uri).as_ptr(), 0) },
OAKSTORAGE_OK
);
free_project(handle);
save_project(&project, &uri, 0).unwrap();
let (session, _) = open(&uri);
let taken = unsafe { ffi::oakstorage_project_take_project(session) };
assert!(!taken.ctx.is_null(), "take transfers the project");
let again = unsafe { ffi::oakstorage_project_take_project(session) };
assert!(again.ctx.is_null(), "second take is empty");
let borrowed = unsafe { ffi::oakstorage_project_project(session) };
assert!(borrowed.ctx.is_null(), "borrowed is empty after take");
free_project(taken);
free_session(session);
// backend_register(NULL) / backend_unregister(NULL) -> E_INVALID.
assert_eq!(
unsafe { ffi::oakstorage_backend_register(std::ptr::null()) },
OAKSTORAGE_E_INVALID
);
assert_eq!(
unsafe { ffi::oakstorage_backend_unregister(std::ptr::null()) },
OAKSTORAGE_E_INVALID
);
let (mut session, _) = open(&uri).unwrap();
let taken = session.take().expect("take transfers the project");
assert!(!taken.ctx.is_null());
assert!(session.project().is_none(), "empty shell after take");
release(taken);
}
// ---------------------------------------------------------------------------
// Alive accounting
// Session shell lifecycle
// ---------------------------------------------------------------------------
/// open -> Session owns the project handle; take hands it out and the
/// shell stays usable (drop-safe).
#[test]
fn alive_count_accounting() {
let dir = temp_dir("alive");
fn session_take_transfers_project() {
let dir = temp_dir("session");
let path = dir.join("x.ove");
let uri = file_uri(&path);
let project = build_roundtrip_project();
let handle = node::make_project_owned(project);
assert_eq!(
unsafe { ffi::oakstorage_save(handle, cs(&uri).as_ptr(), 0) },
OAKSTORAGE_OK
);
free_project(handle);
save_project(&project, &uri, 0).unwrap();
let before = alive();
{
let (session, rc) = open(&uri);
assert_eq!(rc, OAKSTORAGE_OK);
assert_eq!(alive(), before + 1, "open counts one session");
let (mut session, rc) = open(&uri).unwrap();
assert_eq!(rc, OAKSTORAGE_OK);
assert!(session.project().is_some(), "open counts one project");
// Take transfers the project; the session shell stays alive.
let taken = unsafe { ffi::oakstorage_project_take_project(session) };
assert!(!taken.ctx.is_null());
assert_eq!(alive(), before + 1, "take keeps the session shell");
// Take transfers the project; the session shell stays empty.
let taken = session.take().unwrap();
assert!(!taken.ctx.is_null());
assert!(session.project().is_none(), "take empties the shell");
release(taken);
// Dropping the shell (with the project already taken) is a no-op.
drop(session);
free_project(taken);
free_session(session);
}
assert_eq!(alive(), before, "open/take/free pair leaves no leak");
// A second pairing through project_project (borrowed) as well.
let before = alive();
{
let (session, _) = open(&uri);
let borrowed = unsafe { ffi::oakstorage_project_project(session) };
assert!(!borrowed.ctx.is_null());
free_project(borrowed);
free_session(session);
}
assert_eq!(alive(), before, "borrowed view pairing leaves no leak");
// A second open/take pairing works the same.
let (mut session, _) = open(&uri).unwrap();
let taken = session.take().unwrap();
assert!(!taken.ctx.is_null());
release(taken);
}