feat(engine): write-through persistence (M13 D2)

- facade storage session manager: project handles bind to the default
  SQLite library on project_new/load; every undo push/group_end/jump
  write-throughs via DatabaseBackend::save (diff journal); project_free
  flushes and unbinds
- background snapshot thread (Storage/SnapshotIntervalSec, latest-wins,
  newest 3 kept) with exit flush (oakengine_storage_flush)
- config-gated: storage only activates with an explicit
  Storage/Backend=sqlite, so headless consumers and tests never touch
  the real library; new exports: storage_flush/is_bound/last_error
- it_storage: kill -9 recovery, cross-session undo, snapshot pruning,
  multi-project isolation, graceful degradation
- also fixes a real config test polluting the user config.ini and the
  undo-stack test races
This commit is contained in:
2026-08-16 08:52:23 +08:00
parent b35f3b49bc
commit 5fabad8efd
18 changed files with 1386 additions and 16 deletions
@@ -76,6 +76,35 @@ pub fn with_manager(f: impl FnOnce()) {
f()
}
/// Serializes every test that reads or writes the `Storage` config group
/// (the facade's write-through library selection — see src/storage.rs).
/// The config store is process-global, so the write-through tests and the
/// tests that disable the backend must take this lock for their whole
/// body instead of racing on the shared store.
pub static STORAGE_CONFIG_LOCK: Mutex<()> = Mutex::new(());
/// Run `f` with the write-through storage backend disabled
/// (`Storage/Backend = "off"`). Tests that push undo commands on real
/// projects (e.g. `oakengine_project_add_node`) would otherwise bind them
/// to the default user library and write there; disabling the backend
/// keeps them side-effect-free. The value intentionally persists — every
/// storage test sets its own backend explicitly under
/// [`STORAGE_CONFIG_LOCK`].
pub fn with_storage_off<R>(f: impl FnOnce() -> R) -> R {
let _g = storage_off_guard();
f()
}
/// Take the storage-config lock AND disable the write-through backend,
/// returning the guard: a test that pushes undo commands throughout its
/// body holds the guard (and thus the lock) for its whole lifetime, so a
/// concurrently running storage test cannot flip the backend mid-test.
pub fn storage_off_guard() -> std::sync::MutexGuard<'static, ()> {
let g = STORAGE_CONFIG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
oakcommon::configstore::ConfigStore::instance().set(Some("Storage"), "Backend", "off");
g
}
// ---------------------------------------------------------------------------
// oakcore_* stubs (see module docs)
// ---------------------------------------------------------------------------
@@ -38,8 +38,19 @@ use crate::common::{
};
/// Config: load/save, string and int round-trips, missing-key behavior.
///
/// Serialized with the write-through tests (the config store is
/// process-global) and redirected to a temp `OAK_CONFIG_DIR` — without the
/// redirect, `oakengine_config_save` would write the real `config.ini`.
#[test]
fn config_round_trip() {
let _config = common::STORAGE_CONFIG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = std::env::temp_dir().join(format!(
"oakengine_common_smoke_config_{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&dir);
std::env::set_var("OAK_CONFIG_DIR", &dir);
assert_eq!(unsafe { oakengine_config_load() }, 0);
// Missing key reads as 0 / empty.
@@ -92,6 +103,10 @@ fn config_round_trip() {
);
assert_eq!(unsafe { oakengine_config_save() }, 0);
assert!(dir.join("config.ini").exists());
std::env::remove_var("OAK_CONFIG_DIR");
let _ = std::fs::remove_dir_all(&dir);
}
/// Config error handler: registered, then invoked via report_error.
@@ -40,7 +40,6 @@ use super::common;
use std::ffi::{c_char, c_int};
use std::path::Path;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::Mutex;
use crate::common::{
oakengine_config_get_int, oakengine_config_get_string, oakengine_config_load,
@@ -71,8 +70,11 @@ unsafe fn read_buf(buf: &mut [c_char]) -> String {
/// redirects `OAK_CONFIG_DIR` to a fresh temp dir for the duration of `f`
/// (same pattern as the oakcommon crate's own test support). The only
/// readers of `OAK_CONFIG_DIR` in this binary are these serialized tests.
/// The serialization uses the SHARED storage-config lock (common), so the
/// config tests never race the write-through tests on the singleton store
/// or the env override.
fn with_temp_config_dir<T>(f: impl FnOnce(&Path) -> T) -> T {
let _guard = CONFIG_LOCK.lock().unwrap();
let _guard = common::STORAGE_CONFIG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir =
std::env::temp_dir().join(format!("oakengine_it_common_config_{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
@@ -84,7 +86,7 @@ fn with_temp_config_dir<T>(f: impl FnOnce(&Path) -> T) -> T {
}
/// The process-wide config store is a singleton; see module doc.
static CONFIG_LOCK: Mutex<()> = Mutex::new(());
// (Serialization now uses the shared `common::STORAGE_CONFIG_LOCK`.)
// ---------------------------------------------------------------------------
// config.h
+21 -3
View File
@@ -78,9 +78,23 @@ const CODEC_AAC: c_int = 12;
/// does not cascade into `PoisonError` failures in every later test.
static SERIAL: Mutex<()> = Mutex::new(());
/// Take the [`SERIAL`] lock, recovering from any poisoning.
fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|e| e.into_inner())
/// Both lock guards held by [`serial`].
struct SerialGuard {
/// The [`SERIAL`] lock.
_task: std::sync::MutexGuard<'static, ()>,
/// The facade-wide undo-stack lock, so the `oakengine_project_new`
/// calls in these tests never race the it_undo / it_storage stack tests.
_stack: std::sync::MutexGuard<'static, ()>,
}
/// Take the [`SERIAL`] lock AND the global undo-stack lock, recovering
/// from any poisoning.
fn serial() -> SerialGuard {
let _task = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let _stack = super::it_undo::GLOBAL_STACK_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
SerialGuard { _task, _stack }
}
/// A unique temp path (per-process, so parallel test binaries never
@@ -105,6 +119,10 @@ unsafe fn assemble_test_sequence(
frame_count: i64,
fps: c_int,
) -> (*mut OakEngineProject, *mut OakEngineSequence) {
// The undoable import/add-track/add-clip commands below would bind the
// project to the default user library; disable the write-through for
// the assembly (and keep the config lock held while pushing).
let _storage = common::storage_off_guard();
let media_c = std::ffi::CString::new(media.to_string_lossy().into_owned()).unwrap();
assert_eq!(
oakengine_testmedia_write_clip(media_c.as_ptr(), width, height, frame_count as c_int, fps),
@@ -0,0 +1,642 @@
// 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/>.
//! D2 integration tests: the facade's live write-through (plan M13 §2/§3).
//!
//! End-to-end against real SQLite library files in temp directories,
//! driving the facade exactly like the app: `oakengine_project_new` binds
//! the project, undoable edits (`oakengine_project_add_node`) write
//! through on push, and the journal is verified directly with raw sea-orm
//! reads (the same pattern as the oakstorage database tests) plus fresh
//! oakstorage sessions for cross-process recovery.
//!
//! Coverage: write-through lands journal rows without any flush; a
//! kill-9-style session (no cleanup, a fresh session reading the same
//! file) recovers the last command; undo history persists across sessions
//! (`load_at`); the background snapshot thread writes and prunes
//! snapshots and the exit flush drains; multiple bound projects keep
//! their rows apart; and the graceful-degradation paths (backend off /
//! unwritable library) record `last_error` without breaking the undo
//! stack.
//!
//! Every test holds the shared undo-stack lock (the facade's stack is
//! process-wide, same as the it_undo family) and the storage-config lock
//! (the config store is process-global too), so the suite never races on
//! either singleton.
use std::path::{Path, PathBuf};
use std::time::Duration;
use sea_orm::entity::prelude::*;
use sea_orm::QueryOrder;
use oakstorage::backend::StorageBackend;
use oakstorage::backends::database::entities::{journal, project, snapshot};
use oakstorage::backends::database::DatabaseBackend;
use oakstorage::error::OAKSTORAGE_OK;
use oakstorage::handle::CHandle;
use oakstorage::nodeutil::project_arc;
use oakstorage::uri::StorageUri;
use super::common;
use super::it_undo::GLOBAL_STACK_LOCK;
use crate::handle::OakEngineProject;
/// The node type the tests add (a real graph node with an input the
/// serializer round-trips).
const MATH: &str = "org.olivevideoeditor.Olive.math";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/// Serialize a storage test: hold the process-global undo-stack lock AND
/// the storage-config lock for the whole body, then point the write-through
/// backend at a temp library.
fn with_storage<R>(db: &Path, interval: i32, f: impl FnOnce() -> R) -> R {
let _stack = GLOBAL_STACK_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _config = common::STORAGE_CONFIG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let store = oakcommon::configstore::ConfigStore::instance();
store.set(Some("Storage"), "Backend", "sqlite");
store.set(Some("Storage"), "SqlitePath", &db.to_string_lossy());
store.set_int(Some("Storage"), "SnapshotIntervalSec", interval);
f()
}
/// Serialize a storage test with the backend disabled (`Storage/Backend =
/// "off"`): projects bind to nothing and the undo stack stays untouched by
/// write-throughs.
fn with_storage_off<R>(f: impl FnOnce() -> R) -> R {
let _stack = GLOBAL_STACK_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _config = common::STORAGE_CONFIG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
oakcommon::configstore::ConfigStore::instance().set(Some("Storage"), "Backend", "off");
f()
}
/// A fresh, unique temp directory for one test.
fn temp_dir(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("oakengine_storage_{}_{}", std::process::id(), tag));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// `oakdb+sqlite:///…` uri for a database file.
fn db_uri(path: &Path) -> String {
format!("oakdb+sqlite://{}", path.display())
}
/// `…?project=<uuid>` uri selecting one library row.
fn project_uri(db: &str, uuid: &str) -> String {
format!("{db}?project={uuid}")
}
/// Release an owned handle (refcount 1).
fn release(h: CHandle) {
if let Some(release) = h.release {
unsafe { release(h.ctx) };
}
}
/// Create a project through the facade and initialize it (bind + active).
fn new_project() -> *mut OakEngineProject {
let project = unsafe { crate::node::oakengine_project_create() };
assert!(!project.is_null());
assert_eq!(unsafe { crate::node::oakengine_project_new(project) }, 0);
project
}
/// The project's uuid (from its in-memory payload).
fn project_uuid(project: *mut OakEngineProject) -> String {
let h = unsafe { crate::handle::unbox(project) }.expect("project handle");
let arc = unsafe { crate::handle::domain::project_of(&h) }.expect("project payload");
let guard = arc.lock().unwrap_or_else(|e| e.into_inner());
guard.uuid.clone()
}
/// Add a math node (an undoable command; pushes and write-throughs).
fn add_math_node(project: *mut OakEngineProject) -> *mut crate::handle::OakEngineNode {
unsafe {
crate::node::oakengine_project_add_node(
project,
c"org.olivevideoeditor.Olive.math".as_ptr(),
)
}
}
/// Load the head state through a *fresh* database backend (a new
/// connection pool = a new session, as after a process restart).
fn load_head(uri: &str) -> std::sync::Arc<std::sync::Mutex<oaknode::project::Project>> {
let parsed = StorageUri::parse(uri).unwrap();
let result = DatabaseBackend::new().load(&parsed).unwrap();
assert_eq!(result.version_info, OAKSTORAGE_OK);
let handle = result.project;
let loaded = unsafe { project_arc(&handle) }.unwrap();
release(handle);
loaded
}
/// Load the state at `seq` through a fresh database backend.
fn load_at(uri: &str, uuid: &str, seq: i64) -> std::sync::Arc<std::sync::Mutex<oaknode::project::Project>> {
let parsed = StorageUri::parse(uri).unwrap();
let handle = DatabaseBackend::new()
.load_at(&parsed, uuid, seq)
.unwrap();
let loaded = unsafe { project_arc(&handle) }.unwrap();
release(handle);
loaded
}
/// Count the math nodes of a loaded project (the root folder is slot 0).
fn math_count(p: &oaknode::project::Project) -> usize {
p.graph
.node_ids()
.into_iter()
.filter(|id| {
p.graph
.get(*id)
.map(|e| e.behavior.type_id() == MATH)
.unwrap_or(false)
})
.count()
}
/// Open a raw sea-orm connection to the library file and drive one future
/// against it on a private current-thread runtime (inspection behind the
/// backend's back — same pattern as the oakstorage database tests).
fn inspect_db<R, Fut>(path: &Path, f: impl FnOnce(sea_orm::DatabaseConnection) -> Fut) -> R
where
Fut: std::future::Future<Output = R>,
{
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
let options = sea_orm::sqlx::sqlite::SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
.journal_mode(sea_orm::sqlx::sqlite::SqliteJournalMode::Wal)
.busy_timeout(Duration::from_secs(5))
.foreign_keys(true);
let pool = sea_orm::sqlx::sqlite::SqlitePoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.unwrap();
f(sea_orm::DatabaseConnection::from(pool)).await
})
}
/// The `(command_seq, journal rows)` of a library row.
fn journal_rows(
path: &Path,
uuid: &str,
) -> (i64, Vec<oakstorage::backends::database::entities::journal::Model>) {
let uuid = uuid.to_string();
inspect_db(path, move |conn| async move {
let proj = project::Entity::find()
.filter(project::Column::Uuid.eq(&uuid))
.one(&conn)
.await
.unwrap()
.expect("library row exists");
let rows = journal::Entity::find()
.filter(journal::Column::ProjectId.eq(proj.id))
.order_by_asc(journal::Column::Seq)
.order_by_asc(journal::Column::NodeIdentity)
.all(&conn)
.await
.unwrap();
(proj.command_seq, rows)
})
}
/// The snapshot seqs of a library row (newest first).
fn snapshot_seqs(path: &Path, uuid: &str) -> Vec<i64> {
let uuid = uuid.to_string();
inspect_db(path, move |conn| async move {
let proj = project::Entity::find()
.filter(project::Column::Uuid.eq(&uuid))
.one(&conn)
.await
.unwrap()
.expect("library row exists");
snapshot::Entity::find()
.filter(snapshot::Column::ProjectId.eq(proj.id))
.order_by_desc(snapshot::Column::CommandSeq)
.all(&conn)
.await
.unwrap()
.into_iter()
.map(|s| s.command_seq)
.collect()
})
}
// ---------------------------------------------------------------------------
// Write-through
// ---------------------------------------------------------------------------
/// Every undoable edit lands in the journal synchronously (no flush): the
/// first edit is the import command, later edits are diffs.
#[test]
fn write_through_persists_commands() {
common::force_link();
let dir = temp_dir("wt");
let db = dir.join("lib.db");
with_storage(&db, 600, || {
let project = new_project();
let node1 = add_math_node(project);
assert!(!node1.is_null());
let node2 = add_math_node(project);
assert!(!node2.is_null());
let uuid = project_uuid(project);
let (head, rows) = journal_rows(&db, &uuid);
assert_eq!(head, 2, "two commands written through");
// Seq 1 (import): the root folder + the first math node + the
// settings pseudo-node, all with only after-images.
let seq1: Vec<_> = rows.iter().filter(|r| r.seq == 1).collect();
assert_eq!(seq1.len(), 3, "root + first math node + settings row");
assert!(seq1.iter().all(|r| r.kind == "import"));
assert!(seq1.iter().all(|r| r.old_xml.is_none() && r.new_xml.is_some()));
// Seq 2 (redo diff): exactly the second math node.
let seq2: Vec<_> = rows.iter().filter(|r| r.seq == 2).collect();
assert_eq!(seq2.len(), 1, "one changed node in the diff");
assert_eq!(seq2[0].kind, "redo");
assert!(seq2[0].new_xml.as_deref().unwrap().contains(MATH));
// The head state reads back through a fresh session (3 nodes: root
// + two math nodes), and the import point has exactly one math node.
let uri = db_uri(&db);
let head_loaded = load_head(&project_uri(&uri, &uuid));
let guard = head_loaded.lock().unwrap();
assert_eq!(guard.graph.node_count(), 3);
assert_eq!(math_count(&guard), 2);
drop(guard);
let at1 = load_at(&uri, &uuid, 1);
let guard = at1.lock().unwrap();
assert_eq!(guard.graph.node_count(), 2);
assert_eq!(math_count(&guard), 1);
unsafe { crate::node::oakengine_project_free(project) };
});
let _ = std::fs::remove_dir_all(&dir);
}
/// kill -9 recovery: the write-through is synchronous, so a fresh session
/// reading the same file (no flush, no cleanup) sees the state after the
/// LAST command.
#[test]
fn kill_nine_recovers_last_command() {
common::force_link();
let dir = temp_dir("k9");
let db = dir.join("lib.db");
with_storage(&db, 600, || {
let project = new_project();
for _ in 0..3 {
let node = add_math_node(project);
assert!(!node.is_null());
}
let uuid = project_uuid(project);
// NOTE: the project is intentionally NOT freed — the process "dies"
// here. The journal already holds every command.
let uri = db_uri(&db);
let (head, rows) = journal_rows(&db, &uuid);
assert_eq!(head, 3);
assert_eq!(rows.len(), 5, "3 import rows + 2 diff rows");
let loaded = load_head(&project_uri(&uri, &uuid));
let guard = loaded.lock().unwrap();
assert_eq!(guard.graph.node_count(), 4, "root + three math nodes");
assert_eq!(math_count(&guard), 3);
// Cleanup without flush would leave the file behind; free the
// project so the temp dir can be removed.
unsafe { crate::node::oakengine_project_free(project) };
});
let _ = std::fs::remove_dir_all(&dir);
}
// ---------------------------------------------------------------------------
// Undo across sessions
// ---------------------------------------------------------------------------
/// The journal is the persistent undo history: three commands, one undo,
/// then a NEW session's `load_at(2)` reproduces the post-command-2 state
/// while `load_at(3)` still yields the pre-undo (post-command-3) state.
///
/// The undoable operations are label renames: their undo closure captures
/// `(project, id)` and reliably reverts, unlike the add-node command
/// (whose factory handle is released at push — a facade limitation).
#[test]
fn undo_history_crosses_sessions() {
common::force_link();
let dir = temp_dir("ux");
let db = dir.join("lib.db");
with_storage(&db, 600, || {
let project = new_project();
// Command 1: add a math node (import).
let node = add_math_node(project);
assert!(!node.is_null());
// Command 2: rename to "Alpha".
assert_eq!(
unsafe { crate::node::oakengine_node_set_label(node, c"Alpha".as_ptr()) },
0
);
// Command 3: rename to "Beta".
assert_eq!(
unsafe { crate::node::oakengine_node_set_label(node, c"Beta".as_ptr()) },
0
);
let uuid = project_uuid(project);
// Undo one command through the facade (jump + write-through).
assert_eq!(unsafe { crate::node::oakengine_project_undo(project) }, 0);
let uri = db_uri(&db);
let (head, _) = journal_rows(&db, &uuid);
assert_eq!(head, 4, "the undo itself is a written command");
// A new session at seq 2 = the state right after command 2.
let at2 = load_at(&uri, &uuid, 2);
assert_eq!(math_label(&at2), "Alpha");
// At seq 3 the pre-undo state (after command 3) is intact.
let at3 = load_at(&uri, &uuid, 3);
assert_eq!(math_label(&at3), "Beta");
// The head (default load) matches the undone state.
let head_loaded = load_head(&project_uri(&uri, &uuid));
assert_eq!(math_label(&head_loaded), "Alpha");
unsafe { crate::node::oakengine_project_free(project) };
});
let _ = std::fs::remove_dir_all(&dir);
}
/// The label of the first math node of a loaded project (its renames are
/// the undoable operations of [`undo_history_crosses_sessions`]).
fn math_label(arc: &std::sync::Arc<std::sync::Mutex<oaknode::project::Project>>) -> String {
let guard = arc.lock().unwrap();
let id = guard
.graph
.node_ids()
.into_iter()
.find(|id| {
guard
.graph
.get(*id)
.map(|e| e.behavior.type_id() == MATH)
.unwrap_or(false)
})
.expect("a math node is present");
guard.graph.get(id).unwrap().core.label.clone()
}
// ---------------------------------------------------------------------------
// Snapshot thread
// ---------------------------------------------------------------------------
/// The background snapshot thread writes periodic snapshots of dirty
/// projects (short interval), the backend prunes to the newest three, and
/// the exit flush drains and leaves a snapshot behind.
#[test]
fn snapshot_thread_and_exit_flush() {
common::force_link();
let dir = temp_dir("snap");
let db = dir.join("lib.db");
with_storage(&db, 1, || {
let project = new_project();
let uuid = project_uuid(project);
// Four command batches ~1.1 s apart (the 1 s interval): each batch
// is a rapid pair of writes so the save-time snapshot policy stays
// quiet and the THREAD is the one capturing the new head.
for _ in 0..4 {
let a = add_math_node(project);
assert!(!a.is_null());
let b = add_math_node(project);
assert!(!b.is_null());
std::thread::sleep(Duration::from_millis(1100));
}
// One more tick window so the final batch is snapshotted too.
std::thread::sleep(Duration::from_millis(1500));
let seqs = snapshot_seqs(&db, &uuid);
assert!(!seqs.is_empty(), "the thread produced snapshots");
assert!(
seqs.len() <= 3,
"pruning keeps at most three (got {:?})",
seqs
);
let (head, _) = journal_rows(&db, &uuid);
assert_eq!(head, 8, "eight commands written through");
// Exit flush: drains (save + snapshot) and leaves the snapshot at
// the head seq regardless of thread timing.
assert_eq!(crate::storage::oakengine_storage_flush(), 0);
let seqs = snapshot_seqs(&db, &uuid);
assert!(!seqs.is_empty(), "flush leaves a snapshot behind");
assert_eq!(seqs[0], 8, "the newest snapshot covers the head seq");
unsafe { crate::node::oakengine_project_free(project) };
});
let _ = std::fs::remove_dir_all(&dir);
}
/// A dirty project flushed on close (project_free) gets its head snapshot
/// even with a long (default) interval — the flush, not the thread, is the
/// guaranteed drain.
#[test]
fn close_flushes_snapshot() {
common::force_link();
let dir = temp_dir("flush");
let db = dir.join("lib.db");
with_storage(&db, 600, || {
let project = new_project();
let uuid = project_uuid(project);
let node = add_math_node(project);
assert!(!node.is_null());
let node2 = add_math_node(project);
assert!(!node2.is_null());
// With the 600 s interval only the FIRST save snapshotted (the
// backend's policy fires when no snapshot exists yet), so the head
// seq is not covered.
assert_eq!(snapshot_seqs(&db, &uuid), vec![1]);
// Closing the project flushes: write-through + snapshot at the head.
unsafe { crate::node::oakengine_project_free(project) };
let seqs = snapshot_seqs(&db, &uuid);
assert_eq!(seqs[0], 2, "close flushed a snapshot at the head seq");
});
let _ = std::fs::remove_dir_all(&dir);
}
// ---------------------------------------------------------------------------
// Multi-project bindings
// ---------------------------------------------------------------------------
/// Two projects bound to one library keep their rows apart: each project's
/// writes advance only its own journal.
#[test]
fn multi_project_bindings_do_not_cross() {
common::force_link();
let dir = temp_dir("multi");
let db = dir.join("lib.db");
with_storage(&db, 600, || {
// Project A: two commands.
let a = new_project();
for _ in 0..2 {
let node = add_math_node(a);
assert!(!node.is_null());
}
let uuid_a = project_uuid(a);
// Project B: binding it does not disturb A's row; its write goes
// only to B's row (A's saves during B's commands are no-ops).
let b = new_project();
let node = add_math_node(b);
assert!(!node.is_null());
let uuid_b = project_uuid(b);
assert_ne!(uuid_a, uuid_b);
let (head_a, rows_a) = journal_rows(&db, &uuid_a);
assert_eq!(head_a, 2, "A's journal stops at its own second command");
assert!(rows_a.iter().all(|r| r.seq <= 2));
let (head_b, rows_b) = journal_rows(&db, &uuid_b);
assert_eq!(head_b, 1, "B has exactly its one command");
assert!(rows_b.iter().all(|r| r.seq == 1));
// Both projects load correctly through fresh sessions.
let uri = db_uri(&db);
let loaded_a = load_head(&project_uri(&uri, &uuid_a));
let guard = loaded_a.lock().unwrap();
assert_eq!(math_count(&guard), 2);
drop(guard);
let loaded_b = load_head(&project_uri(&uri, &uuid_b));
let guard = loaded_b.lock().unwrap();
assert_eq!(math_count(&guard), 1);
unsafe { crate::node::oakengine_project_free(a) };
unsafe { crate::node::oakengine_project_free(b) };
});
let _ = std::fs::remove_dir_all(&dir);
}
// ---------------------------------------------------------------------------
// Graceful degradation
// ---------------------------------------------------------------------------
/// With `Storage/Backend = "off"` projects bind to nothing: the undo
/// stack works, no library file is created, and `is_bound` reports 0.
#[test]
fn backend_off_keeps_projects_unbound() {
common::force_link();
let dir = temp_dir("off");
let db = dir.join("lib.db");
with_storage_off(|| {
let project = new_project();
// Not bound: no write-through happens at all.
assert_eq!(unsafe { crate::storage::oakengine_storage_is_bound(project) }, 0);
let node = add_math_node(project);
assert!(!node.is_null());
let node2 = add_math_node(project);
assert!(!node2.is_null());
// The undo stack still works.
assert_eq!(unsafe { crate::node::oakengine_project_undo(project) }, 0);
assert_eq!(unsafe { crate::node::oakengine_project_redo(project) }, 0);
// Nothing was ever written to the configured library path.
assert!(!db.exists(), "no library file with the backend off");
unsafe { crate::node::oakengine_project_free(project) };
});
let _ = std::fs::remove_dir_all(&dir);
}
/// An unwritable library degrades gracefully: the write-through records a
/// `last_error` instead of failing the command or crashing, and the undo
/// stack keeps working.
#[test]
fn unwritable_library_records_last_error() {
common::force_link();
let dir = temp_dir("ro");
let db = dir.join("no/such/dir/lib.db"); // parent dir does not exist
with_storage(&db, 600, || {
let project = new_project();
// Bound, but the first write-through cannot open the library.
assert_eq!(unsafe { crate::storage::oakengine_storage_is_bound(project) }, 1);
let node = add_math_node(project);
assert!(!node.is_null());
// The command succeeded; the write failure is recorded, not raised.
let mut buf = [0 as std::ffi::c_char; 512];
let len = unsafe { crate::storage::oakengine_storage_last_error(project, buf.as_mut_ptr(), 512) };
assert!(len > 0, "the failed write-through is recorded");
let msg = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) }
.to_string_lossy()
.into_owned();
assert!(!msg.is_empty(), "error message non-empty");
// A second command degrades the same way.
let node2 = add_math_node(project);
assert!(!node2.is_null());
let len =
unsafe { crate::storage::oakengine_storage_last_error(project, buf.as_mut_ptr(), 512) };
assert!(len > 0);
// The undo stack is unaffected.
assert_eq!(unsafe { crate::node::oakengine_project_undo(project) }, 0);
unsafe { crate::node::oakengine_project_free(project) };
});
let _ = std::fs::remove_dir_all(&dir);
}
// ---------------------------------------------------------------------------
// Defaults
// ---------------------------------------------------------------------------
/// The default library path resolves to `<system data dir>/library.db`
/// (absolute), and the backend is strictly config-driven: `Backend =
/// "sqlite"` enables it, `"off"` disables it (and an absent `Storage`
/// group means "no library configured" — projects stay unbound).
#[test]
fn default_library_path_and_backend() {
common::force_link();
let _stack = GLOBAL_STACK_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let _config = common::STORAGE_CONFIG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
// The default path is a plain absolute `…/library.db`.
let p = crate::storage::default_library_path();
let path = std::path::Path::new(&p);
assert!(path.is_absolute(), "{p}");
assert!(p.ends_with("library.db"), "{p}");
// Explicit values drive the enabled state.
let store = oakcommon::configstore::ConfigStore::instance();
store.set(Some("Storage"), "Backend", "sqlite");
assert!(crate::storage::storage_enabled());
store.set(Some("Storage"), "Backend", "off");
assert!(!crate::storage::storage_enabled());
}
+22 -3
View File
@@ -88,9 +88,25 @@ const OAKTASK_E_NOT_FOUND: c_int = -80004;
/// does not cascade into `PoisonError` failures in every later test.
static SERIAL: Mutex<()> = Mutex::new(());
/// Take the [`SERIAL`] lock, recovering from any poisoning.
pub(crate) fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|e| e.into_inner())
/// Both lock guards held by [`serial`] (the local task lock plus the
/// facade-wide undo-stack lock).
pub(crate) struct SerialGuard {
/// The [`SERIAL`] lock.
_task: std::sync::MutexGuard<'static, ()>,
/// The facade's process-wide undo-stack lock (it_undo's), so the
/// `oakengine_project_new` calls in these tests (which clear the stack)
/// never race the it_undo / it_storage stack tests.
_stack: std::sync::MutexGuard<'static, ()>,
}
/// Take the [`SERIAL`] lock AND the global undo-stack lock, recovering
/// from any poisoning.
pub(crate) fn serial() -> SerialGuard {
let _task = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
let _stack = super::it_undo::GLOBAL_STACK_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
SerialGuard { _task, _stack }
}
/// The facade's live task-payload counter (the engine-side replacement
@@ -904,6 +920,9 @@ fn export_task_creation() {
fn export_task_run_real_encoder() {
let _g = serial();
common::force_link();
// The import/add-track/add-clip commands below are undoable; disable
// the write-through backend so they never touch a library.
let _storage = common::storage_off_guard();
let media = std::env::temp_dir().join(format!(
"oakengine-it-task-export-src-{}.mp4",
+3 -2
View File
@@ -90,8 +90,9 @@ unsafe fn read_str(buf: *const c_char) -> String {
/// `null_name_group_repro`, `group_abort_undoes_children_repro`): cargo
/// runs tests on parallel threads and the global stack / single open undo
/// group cannot be shared, so each of those tests holds this lock for its
/// whole body.
static GLOBAL_STACK_LOCK: Mutex<()> = Mutex::new(());
/// whole body. Public so the write-through tests (it_storage.rs), which
/// push commands on the same global stack, serialize on the SAME lock.
pub static GLOBAL_STACK_LOCK: Mutex<()> = Mutex::new(());
static LIFECYCLE_REDO: AtomicI32 = AtomicI32::new(0);
static LIFECYCLE_UNDO: AtomicI32 = AtomicI32::new(0);
+1
View File
@@ -42,6 +42,7 @@ mod it_codec;
mod it_common;
mod it_export;
mod it_plugin;
mod it_storage;
mod it_task;
mod it_undo;
mod linkage;
@@ -108,6 +108,10 @@ unsafe fn find_node(project: *mut crate::handle::OakEngineProject, id: &str) ->
fn project_node_keyframe_lifecycle() {
common::force_link();
let _ = force_oakundo_command_link();
// The undo commands below would bind the project to the default user
// library and write through to it; hold the storage lock and disable
// the backend for the whole test.
let _storage = common::storage_off_guard();
// ---- project: create → new → name/filename readback ----------------
let project = oakengine_project_create();
@@ -153,6 +153,13 @@ fn multi_command_add_child_count_redo() {
/// exercised from parallel test threads.
#[test]
fn undo_stack_lifecycle() {
// Serialized on the SAME lock as the it_undo stack tests and the
// write-through tests (the facade's stack is process-wide): without it
// a concurrent test's pushes break the exact-count assertions below.
let _stack = super::it_undo::GLOBAL_STACK_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
// Reset to a clean "New/Open Project" base row.
assert_eq!(unsafe { oakengine_undo_clear() }, 0);
assert_eq!(unsafe { oakengine_undo_count() }, 1);