//! The C ABI: six functions, and no seventh, ever. //! //! Design M1. Everything the app can ask is a METHOD NAME inside `cotton_call`, //! so the header, the module map and the build never move again. Requests and //! answers are JSON; **bytes never cross this boundary** (M4) — a media method //! answers a PATH and Swift reads the file itself. //! //! Three rules hold at every entry point: //! //! 1. **No panic crosses.** Every body is wrapped in `catch_unwind` and a panic //! becomes an ordinary error answer carrying the panic's own message. A bug //! in a worker must not take the person's server down. //! 2. **Strings cross as owned `CString`s**, and Swift frees every one through //! `cotton_string_free`. No borrowed pointers, no lifetimes across the //! boundary — the single exception is the event line, which is borrowed for //! the duration of the callback (see `events`). //! 3. **A null pointer is an answer, not a crash.** A caller that hands in //! nothing is told so. //! //! The header `include/cotton_ffi.h` is GENERATED from this file by //! `tests/header.rs` (cbindgen) and committed; `cargo test -p cotton-ffi` fails //! when the two drift. use std::any::Any; use std::ffi::{c_char, c_void, CStr, CString}; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::sync::Arc; use serde_json::{json, Value}; use crate::handle::{CottonHandle, OpenConfig, OpenError}; use crate::methods::{dispatch_across_swaps, MethodError}; /// Open the core: prepare the data directory, build the runtime, hand back the /// handle. /// /// Answers `NULL` and writes a JSON object into `out_error` /// (`{ "code", "title", "message" }`, owned by the caller, freed with /// `cotton_string_free`) when it cannot. /// /// # Safety /// `config_json` must be a NUL-terminated UTF-8 string. `out_error`, when not /// null, must point at a writable `char *`. #[no_mangle] pub unsafe extern "C" fn cotton_open( config_json: *const c_char, out_error: *mut *mut c_char, ) -> *mut CottonHandle { unsafe { open_declaring(config_json, out_error, &cotton_core::flavor::declare) } } /// [`cotton_open`], with WHERE the flavor is declared handed in. /// /// **The app's open is where this PROCESS becomes CottonDB or Cotton Dev** /// (`cotton_core::flavor::declare`): the declaration is process-wide and set /// once, and every relay-name seam below reads it. A unit test shares its /// process with every other test in the crate, so it opens through /// [`open_quietly`] and declares nothing — one test's open must not decide /// which app every other test is. /// /// # Safety /// As [`cotton_open`]. unsafe fn open_declaring( config_json: *const c_char, out_error: *mut *mut c_char, declare: &dyn Fn(cotton_core::flavor::Flavor) -> Result<(), String>, ) -> *mut CottonHandle { let opened = catch_unwind(AssertUnwindSafe(|| { let Some(text) = (unsafe { borrow_str(config_json) }) else { return Err(OpenError::new( "bad_config", "CottonDB could not start", "The app started the core without a configuration.", )); }; let config: OpenConfig = serde_json::from_str(text).map_err(|error| { OpenError::new( "bad_config", "CottonDB could not start", format!("The app's configuration could not be read ({error})."), ) })?; // BEFORE the data directory: which app this is decides which folder // is its own. if let Some(manifest) = config.manifest.as_ref().filter(|_| config.flavor == cotton_core::flavor::Flavor::Business) { let business = cotton_core::flavor::BusinessManifest::from_json(&manifest.to_string()) .map_err(|reason| OpenError::new("manifest_refused", "This business manifest could not be read", reason))?; cotton_core::flavor::declare_business(business) .map_err(|reason| OpenError::new("manifest_refused", "This business manifest could not be opened", reason))?; } declare(config.flavor).map_err(|reason| { OpenError::new( "flavor_mismatch", "CottonDB could not start", format!("This process cannot open as {} — {reason}.", config.flavor.as_str()), ) })?; CottonHandle::open(config) })); let result = match opened { Ok(result) => result, Err(payload) => Err(OpenError::new( "panic", "CottonDB could not start", panic_message(payload), )), }; match result { // AN `Arc`, NOT A BOX: the control socket the core binds when its // server starts answers a shell's verbs by running methods on this // very handle, from threads of its own, so it holds the handle weakly // and a request in flight holds it for the request's length // (`CottonHandle::shared`). Swift sees the same opaque pointer. Ok(handle) => Arc::into_raw(handle.shared()) as *mut CottonHandle, Err(error) => { if !out_error.is_null() { let text = serde_json::to_string(&error) .unwrap_or_else(|_| r#"{"code":"panic","title":"CottonDB could not start","message":"the core failed and could not say why"}"#.to_string()); unsafe { *out_error = into_c_string(text) }; } std::ptr::null_mut() } } } /// [`cotton_open`] for a unit test: everything but the process-wide flavor /// declaration (see [`open_declaring`]). /// /// # Safety /// As [`cotton_open`]. #[cfg(test)] pub(crate) unsafe fn open_quietly( config_json: *const c_char, out_error: *mut *mut c_char, ) -> *mut CottonHandle { unsafe { open_declaring(config_json, out_error, &|_| Ok(())) } } /// Close the core. Idempotent from the caller's side in the only way that /// matters: a null pointer is ignored. /// /// **It ALWAYS comes back.** `CottonHandle::close` stops the server and lets go /// of the replica first and then gives the runtime's blocking pool a deadline, /// because this call blocks the thread Swift made it on and that thread was a /// cooperative-pool one the night a hung close parked a whole CI runner /// (Cotton note "Repo landmines — why the build's rules exist"). A step that will not finish is left /// to the operating system with a line in the log; it never becomes the /// caller's problem. /// /// # Safety /// `handle` must be a pointer `cotton_open` returned and not already closed. #[no_mangle] pub unsafe extern "C" fn cotton_close(handle: *mut CottonHandle) { if handle.is_null() { return; } // A panic while closing must not unwind into Swift either. let _ = catch_unwind(AssertUnwindSafe(|| { CottonHandle::close_shared(unsafe { Arc::from_raw(handle as *const CottonHandle) }); })); } /// Ask the core something. Always answers one JSON object, owned by the caller: /// /// ```json /// { "ok": true, "data": … } /// { "ok": false, "error": { "code", "message", "details" } } /// ``` /// /// # Safety /// `handle` must be a live pointer from `cotton_open`; `method` and /// `request_json` must be NUL-terminated UTF-8 or null. #[no_mangle] pub unsafe extern "C" fn cotton_call( handle: *mut CottonHandle, method: *const c_char, request_json: *const c_char, ) -> *mut c_char { let answered = catch_unwind(AssertUnwindSafe(|| { let Some(method) = (unsafe { borrow_str(method) }) else { return MethodError::new("no_method", "a call named no method").envelope(); }; let Some(core) = (unsafe { handle.as_ref() }) else { // The ONE method a null handle answers: an iPhone's notification extension opening a c2 box to draw an // alert (`phone::chat_ratchet::peek`), with no database to open and nothing to change. Still a method // name inside `cotton_call`: the ABI stays six functions. if method == crate::phone::chat_ratchet::PEEK { let request = unsafe { borrow_str(request_json) }.and_then(|text| serde_json::from_str::(text).ok()).unwrap_or(Value::Null); return match crate::phone::chat_ratchet::peek(&request) { Ok(data) => json!({ "ok": true, "data": data }), Err(error) => error.envelope(), }; } return MethodError::new("no_core", "the core is not open").envelope(); }; let request = match unsafe { borrow_str(request_json) } { // An absent body reads as `{}`: a method that takes nothing should // not need a caller to spell an empty object. None | Some("") => Value::Object(Default::default()), Some(text) => match serde_json::from_str::(text) { Ok(value) => value, Err(error) => { return MethodError::new( "bad_request", format!("the request for `{method}` is not JSON ({error})"), ) .envelope() } }, }; let request = crate::phone::records::asking_said(method, request); let outcome = dispatch_across_swaps(core, method, &request); let build = crate::shell::diagnostics::said(); for diagnostic in cotton_tools::definitions::take_definition_diagnostics() { let revision = diagnostic.revision.map_or_else(|| "unknown".to_string(), |revision| revision.to_string()); crate::shell::diagnostics::method_failed(core.log(), core.events(), "definition", &format!( "{} · revision {} · bundled revision {} · build {} · bundle {} · {}", diagnostic.id, revision, diagnostic.bundled_revision, build.build.as_deref().unwrap_or("unknown"), build.bundle_id.as_deref().unwrap_or("unknown"), diagnostic.cause, )); } match outcome { Ok(data) => json!({ "ok": true, "data": data }), // The person reads a sentence; the raw text goes to the log only. // A server-bound call on a database no server serves is not a // failure: it is listed as not used (ruling C1). Err(error) if error.code == crate::phone::database_calls::NOT_SERVED => { crate::shell::diagnostics::not_used(core.log(), core.events(), method); error.for_person().0.envelope() } Err(error) => { let raw = format!("{}: {}", error.code, error.message); let (said, logged) = error.for_person(); crate::shell::diagnostics::method_failed(core.log(), core.events(), method, logged.as_deref().unwrap_or(&raw)); said.envelope() } } })); let answer = match answered { Ok(answer) => answer, // The panic's own message, carried out as a refusal the app can draw and // report. This is the net M2 asks for: the server nets a panic // in-process, and the boundary nets it again. Err(payload) => { let (said, logged) = MethodError::new("panic", panic_message(payload)).for_person(); if let Some(raw) = logged { tracing::error!(raw = %raw, "a call panicked"); } said.envelope() } }; into_c_string(answer.to_string()) } /// Register the ONE subscriber for the event stream, and replay whatever was /// buffered before it arrived. /// /// `ctx` is handed back to the callback untouched; a null `on_event` clears the /// subscription. The line the callback receives is borrowed for the duration of /// the call — copy it, do not free it. /// /// # Safety /// `handle` must be a live pointer from `cotton_open`, and `ctx` must stay valid /// until the subscription is cleared or the core is closed. #[no_mangle] pub unsafe extern "C" fn cotton_subscribe( handle: *mut CottonHandle, ctx: *mut c_void, on_event: Option, ) { let _ = catch_unwind(AssertUnwindSafe(|| { if let Some(core) = unsafe { handle.as_ref() } { core.events().subscribe(ctx, on_event); } })); } /// The core's version — the crate's own, which is the app's core version — /// with the commit it was built from as build metadata (`0.1.0+1a2b3c4d5`, /// `.dirty` after it when crates/ held edits; `crate::build_commit`). /// Owned by the caller. #[no_mangle] pub extern "C" fn cotton_version() -> *mut c_char { let version = env!("CARGO_PKG_VERSION"); into_c_string(match crate::build_commit().short() { Some(built) => format!("{version}+{built}"), None => version.to_string(), }) } /// Free a string this ABI handed out. Ignores null. /// /// # Safety /// `text` must be a pointer this library returned, freed exactly once. #[no_mangle] pub unsafe extern "C" fn cotton_string_free(text: *mut c_char) { if text.is_null() { return; } drop(unsafe { CString::from_raw(text) }); } /// # Safety /// `ptr` must be null or a NUL-terminated string. unsafe fn borrow_str<'a>(ptr: *const c_char) -> Option<&'a str> { if ptr.is_null() { return None; } CStr::from_ptr(ptr).to_str().ok() } fn into_c_string(text: String) -> *mut c_char { // Only a string with an interior NUL can fail, which no `serde_json` output // ever holds one (it escapes the byte rather than emitting it). The fallback // is still an ANSWER rather than a null pointer, because a caller handed // null has nothing to report. CString::new(text) .unwrap_or_else(|_| { CString::new(r#"{"ok":false,"error":{"code":"bad_answer","message":"the answer held a NUL byte","details":null}}"#) .expect("a literal with no NUL") }) .into_raw() } fn panic_message(payload: Box) -> String { if let Some(text) = payload.downcast_ref::<&str>() { return (*text).to_string(); } if let Some(text) = payload.downcast_ref::() { return text.clone(); } "the core panicked without a message".to_string() } #[cfg(test)] mod tests { use super::*; /// Everything a caller does with a returned string: read it, then free it. fn take(text: *mut c_char) -> String { assert!(!text.is_null(), "this ABI never answers a null string"); let owned = unsafe { CStr::from_ptr(text) } .to_string_lossy() .to_string(); unsafe { cotton_string_free(text) }; owned } fn c(text: &str) -> CString { CString::new(text).expect("a fixture with no NUL") } const PROBE: &str = "datadir.status"; fn open_config(dir: &std::path::Path) -> CString { c(&format!( r#"{{"containerPath":{},"appVersion":"0.1.0","flavor":"dev"}}"#, serde_json::to_string(&dir.to_string_lossy()).expect("a JSON string") )) } fn open_on(home: &std::path::Path) -> *mut CottonHandle { let config = open_config(home); let mut error: *mut c_char = std::ptr::null_mut(); let handle = unsafe { open_quietly(config.as_ptr(), &mut error) }; assert!(error.is_null(), "an open that worked writes no error"); assert!(!handle.is_null()); handle } fn call(handle: *mut CottonHandle, method: &str, request: &str) -> Value { let method = c(method); let request = c(request); let answer = take(unsafe { cotton_call(handle, method.as_ptr(), request.as_ptr()) }); serde_json::from_str(&answer).expect("one JSON object") } /// RULE: build.facts answers what the core of this build knows about itself — the schema it writes, the built-in definitions revision it ships and the app version it was opened with — on either build, so About and the dev corner read one call. #[test] fn build_facts_answer_the_schema_the_definitions_and_the_app_version() { let home = tempfile::tempdir().expect("a temp home"); let handle = open_on(home.path()); let answer = call(handle, "build.facts", "{}"); assert_eq!(answer["ok"], true, "{answer}"); assert_eq!(answer["data"]["schemaVersion"], cotton_store::schema::ddl::SCHEMA_VERSION); assert_eq!(answer["data"]["definitionsRevision"].as_str(), Some(cotton_core::definitions::BUILTIN_DEFINITIONS_HASH)); assert_eq!(answer["data"]["appVersion"], "0.1.0", "the version the app opened the core with"); unsafe { cotton_close(handle) }; } #[test] fn an_absent_request_body_reads_as_an_empty_object() { let home = tempfile::tempdir().expect("a temp home"); let handle = open_on(home.path()); let method = c(PROBE); let answer: Value = serde_json::from_str(&take(unsafe { cotton_call(handle, method.as_ptr(), std::ptr::null()) })) .expect("one JSON object"); assert_eq!(answer["ok"], true); unsafe { cotton_close(handle) }; } /// RULE: A Home read's internal failure stays in the phone Debug log after the ABI returns plain words; otherwise the post-unpack failure cannot be diagnosed from the owner's report. #[test] fn a_home_failure_through_the_abi_reaches_the_phone_debug_log() { let container = tempfile::tempdir().expect("a synthetic phone container"); let config = c(&serde_json::json!({ "containerPath": container.path(), "flavor": "dev", "timeZone": "Etc/UTC" }).to_string()); let mut error = std::ptr::null_mut(); let handle = unsafe { open_quietly(config.as_ptr(), &mut error) }; assert!(error.is_null()); assert!(!handle.is_null()); assert_eq!(call(handle, "workspace.startLocal", r#"{"deviceName":"Synthetic phone"}"#)["ok"], true); assert_eq!(call(handle, "read.home", "{}")["ok"], true, "the synthetic Home initially reads"); let replica = unsafe { &*handle }.client().replica().expect("the local replica"); replica.lock().unwrap().driver.exec("DROP TABLE cotton_todos").expect("an invented missing table"); let answer = call(handle, "read.home", "{}"); assert_eq!(answer["ok"], false, "the missing table must fail the read: {answer}"); let debug = call(handle, "diagnostics.debug", "{}"); let lines = debug.to_string(); assert!(lines.contains("read.home failed") && lines.contains("cotton_todos"), "failure: {answer}; debug: {debug}"); drop(replica); unsafe { cotton_close(handle) }; } // RULE: a fresh business install holds zero databases, and every Personal arrival refuses without founding a hidden file. #[test] fn genesis_none_keeps_a_fresh_business_install_empty() { let container = tempfile::tempdir().unwrap(); // The manifest is per handle here; declaring a process flavour in a // unit test would change the other tests sharing this process. let mut config = crate::handle::phone_config(container.path()); config.manifest = Some(serde_json::json!({"flavour": "sharmila", "genesis": "none"})); let handle = std::sync::Arc::into_raw(std::sync::Arc::new(CottonHandle::open(config).unwrap())) as *mut CottonHandle; assert!(unsafe { &*handle }.client().databases().unwrap().is_empty()); let listed = call(handle, "read.databases", "{}"); assert_eq!(listed["data"]["databases"], serde_json::json!([]), "{listed}"); for method in ["workspace.startLocal", "read.you", "import.whatsappExport", "message.import.run"] { let answer = call(handle, method, "{}"); assert_eq!(answer["ok"], false, "{method}: {answer}"); assert_eq!(answer["error"]["code"], "no_personal_database_in_flavour", "{method}: {answer}"); } assert!(unsafe { &*handle }.client().databases().unwrap().is_empty()); assert!(cotton_client::join::held_workspaces(unsafe { &*handle }.layout(), "").is_empty()); unsafe { cotton_close(handle) }; } // RULE: existing synthetic installs keep their Personal file working under none, but Databases never shows it. #[test] fn genesis_none_preserves_an_existing_personal_without_showing_it() { let container = tempfile::tempdir().unwrap(); let mut error = std::ptr::null_mut(); let config = c(&serde_json::json!({"containerPath": container.path()}).to_string()); let handle = unsafe { open_quietly(config.as_ptr(), &mut error) }; assert!(!handle.is_null()); assert_eq!(call(handle, "workspace.startLocal", "{}")["ok"], true); let client = unsafe { &*handle }.client(); let own = client.databases().unwrap()[0].id.clone(); cotton_core::genesis::Genesis::None.keep(unsafe { &*handle }.layout().root()).unwrap(); assert!(client.require_personal().is_ok()); assert!(client.scoped_databases().unwrap().is_empty()); assert_eq!(client.show_database(&own).unwrap_err(), cotton_core::genesis::NO_PERSONAL_MESSAGE); let page = call(handle, "read.home", &serde_json::json!({"database": own}).to_string()); assert_eq!(page["error"]["code"], "no_personal_database_in_flavour"); assert_eq!(client.databases().unwrap()[0].id, own); assert!(unsafe { &*handle }.layout().replica(&own).exists()); unsafe { cotton_close(handle) }; } // RULE: a business in the primary connection slot is still shared; no selected-file shortcut may label it Personal. #[test] fn genesis_none_lists_a_joined_business_as_shared() { let container = tempfile::tempdir().unwrap(); let mut error = std::ptr::null_mut(); let config = c(&serde_json::json!({"containerPath": container.path()}).to_string()); let handle = unsafe { open_quietly(config.as_ptr(), &mut error) }; assert!(!handle.is_null()); assert_eq!(call(handle, "workspace.startLocal", "{}")["ok"], true); let client = unsafe { &*handle }.client(); // Synthetic shared-file fixture in the same slot a business join uses. client.with_writer(|file| file.driver.exec("UPDATE cotton_workspaces SET kind = 'shared', name = 'Synthetic studio'").map_err(|error| error.to_string())).unwrap(); cotton_core::genesis::Genesis::None.keep(unsafe { &*handle }.layout().root()).unwrap(); let held = client.scoped_databases().unwrap(); assert_eq!(held.len(), 1); assert!(!held[0].personal); assert_eq!(held[0].name, "Synthetic studio"); assert!(client.require_personal().is_err()); unsafe { cotton_close(handle) }; } // RULE: an explicit personal genesis founds one Personal, and another start never creates a second file. // The scripts guard checks that Cotton's shipped manifest selects this policy. #[test] fn genesis_personal_keeps_cotton_at_exactly_one_personal_database() { let container = tempfile::tempdir().unwrap(); let mut config = crate::handle::phone_config(container.path()); config.manifest = Some(serde_json::json!({"genesis": "personal", "databases": "single", "database": "personal"})); let handle = std::sync::Arc::into_raw(std::sync::Arc::new(CottonHandle::open(config).unwrap())) as *mut CottonHandle; let first = call(handle, "workspace.startLocal", "{}"); assert_eq!(first["ok"], true, "{first}"); let again = call(handle, "workspace.startLocal", "{}"); assert_eq!(again["error"]["code"], "already_started", "{again}"); let listed = call(handle, "read.databases", "{}"); let databases = listed["data"]["databases"].as_array().unwrap(); assert_eq!(databases.len(), 1); assert_eq!(databases[0]["kind"], "personal"); assert_eq!(databases[0]["databaseId"], first["data"]["workspaceId"]); assert_eq!(cotton_client::join::held_workspaces(unsafe { &*handle }.layout(), "").len(), 1); unsafe { cotton_close(handle) }; } #[test] fn a_phone_starts_its_database_through_the_public_abi() { let container = tempfile::tempdir().expect("a synthetic phone container"); let config = c(&serde_json::json!({ "containerPath": container.path() }).to_string()); let mut error = std::ptr::null_mut(); let handle = unsafe { open_quietly(config.as_ptr(), &mut error) }; assert!(error.is_null()); assert!(!handle.is_null()); let started = call(handle, "workspace.startLocal", r#"{"deviceName":"Test phone"}"#); assert_eq!(started["ok"], true, "{started}"); assert_eq!(started["data"]["state"], "noServerYet"); assert_eq!(call(handle, "read.boot", "{}")["data"]["paired"], true); assert_eq!(call(handle, "read.syncStatus", "{}")["data"]["state"], "noServerYet"); // The dispatch must preserve the existing command's refusal on a second start. let repeated = call(handle, "workspace.startLocal", "{}"); assert_eq!(repeated["ok"], false, "{repeated}"); assert_eq!(repeated["error"]["code"], "already_started"); unsafe { cotton_close(handle) }; } #[test] fn a_panic_inside_a_method_comes_back_as_an_error_carrying_its_own_message() { let home = tempfile::tempdir().expect("a temp home"); let handle = open_on(home.path()); // The default hook would print the backtrace and make a passing test // look like a failing one; the panic is still caught either way. let previous = std::panic::take_hook(); std::panic::set_hook(Box::new(|_| ())); let answer = call( handle, "debug.panic", r#"{"message":"the worker fell over"}"#, ); std::panic::set_hook(previous); assert_eq!(answer["ok"], false); assert_eq!(answer["error"]["code"], "panic"); assert_eq!(answer["error"]["message"], "the worker fell over"); // And the core is still usable afterwards — that is the whole point. assert_eq!(call(handle, PROBE, "{}")["ok"], true); unsafe { cotton_close(handle) }; } #[test] fn an_unknown_method_is_a_refusal_that_says_what_is_known() { let home = tempfile::tempdir().expect("a temp home"); let handle = open_on(home.path()); let answer = call(handle, "server.launch", "{}"); assert_eq!(answer["error"]["code"], "unknown_method"); assert!(answer["error"]["details"]["known"] .as_array() .expect("the known list") .contains(&Value::from(PROBE))); unsafe { cotton_close(handle) }; } #[test] fn a_request_that_is_not_json_is_refused_by_name() { let home = tempfile::tempdir().expect("a temp home"); let handle = open_on(home.path()); let answer = call(handle, PROBE, "{ not json"); assert_eq!(answer["error"]["code"], "bad_request"); assert!(answer["error"]["message"] .as_str() .expect("a sentence") .contains(PROBE)); unsafe { cotton_close(handle) }; } #[test] fn a_call_on_no_core_and_a_close_of_nothing_are_answers_not_crashes() { let method = c("server.status"); let answer: Value = serde_json::from_str(&take(unsafe { cotton_call(std::ptr::null_mut(), method.as_ptr(), std::ptr::null()) })) .expect("one JSON object"); assert_eq!(answer["error"]["code"], "no_core"); unsafe { cotton_close(std::ptr::null_mut()); cotton_string_free(std::ptr::null_mut()); cotton_subscribe(std::ptr::null_mut(), std::ptr::null_mut(), None); } } /// THE DECLARATION IS THE OPEN'S, AND A PROCESS IS ONE APP: an open that /// would make this process the other app is refused, as JSON, before any /// folder is touched. #[test] fn an_open_as_the_other_app_than_this_process_already_is_refused() { let home = tempfile::tempdir().expect("a temp home"); let config = open_config(home.path()); let mut error: *mut c_char = std::ptr::null_mut(); let declared = std::cell::Cell::new(None); let handle = unsafe { open_declaring(config.as_ptr(), &mut error, &|flavor| { declared.set(Some(flavor)); Err("this process is already real and cannot become dev".to_string()) }) }; assert!(handle.is_null()); assert_eq!(declared.get(), Some(cotton_core::flavor::Flavor::Dev)); let refusal: Value = serde_json::from_str(&take(error)).expect("one JSON object"); assert_eq!(refusal["code"], "flavor_mismatch"); assert!(std::fs::read_dir(home.path()).expect("the home").next().is_none(), "nothing was made"); } #[test] fn an_open_with_no_configuration_at_all_is_refused_rather_than_guessed() { let mut error: *mut c_char = std::ptr::null_mut(); assert!(unsafe { cotton_open(std::ptr::null(), &mut error) }.is_null()); let refusal: Value = serde_json::from_str(&take(error)).expect("one JSON object"); assert_eq!(refusal["code"], "bad_config"); } /// RULE: The version the app shows is the core's own crate version, followed by `+` and the first nine characters of the commit it was built from — with `.dirty` when the tree had changes — whenever the build knows that commit (`scripts/core-fresh.sh` reads the same stamp); a build with no commit says the bare version. The string is the caller's to free. #[test] fn the_version_is_the_core_s_own_and_is_freed_by_the_caller() { let version = take(cotton_version()); let commit = env!("COTTON_BUILD_COMMIT"); let expected = match commit.get(..9) { Some(short) if env!("COTTON_BUILD_DIRTY") == "1" => format!("{}+{short}.dirty", env!("CARGO_PKG_VERSION")), Some(short) => format!("{}+{short}", env!("CARGO_PKG_VERSION")), None => env!("CARGO_PKG_VERSION").to_string(), }; assert_eq!(version, expected); } }