== Database selection The first window is a startup gate, not a usable document editor until Rust manages a validated Database. Setup itself performs no database I/O, so an incompatible library cannot trigger Tauri's setup-hook panic. ClojureScript owns the Create/Open choice, EDN configuration validation and error UI; Rust owns native picker paths, filesystem access and database opening on a blocking worker. Callback pickers are adapted with a oneshot; no main-thread blocking is used. Startup is serialized across webviews with a native async mutex. Release and dev builds share the platform configuration root's `candlelight/candlelight.edn`. On Linux this is `$XDG_CONFIG_HOME/candlelight/candlelight.edn`, defaulting to `~/.config/candlelight/candlelight.edn`. It contains only `{:database-path "/absolute/path/library.sqlite"}`. The EDN reader is the same bundled ClojureScript reader used by other documents. Rust writes an EDN string using JSON-compatible string escaping. No database contents or version are stored in configuration. Existing database locations are never inferred or moved. Missing, corrupt, inaccessible or incompatible selections remain on the startup page, which offers replacement selection and an explicit Quit. Creation uses exclusive file creation; even a save picker's overwrite confirmation cannot cause Candlelight to replace an existing library. Opening requires an existing regular file and never creates a missing configured path. The new selection is saved only after the database opens successfully. Atomic configuration replacement uses a same-directory temporary file followed by standard filesystem rename (a failed replacement is reported, never ignored). Attachment copies still use the application cache. Only schema compatibility separates release and dev: dev matches dev. Unstable releases inspect the actual layout, update matching version fields to the application version, and explicitly migrate registered older layouts before exposing the library. Future 1.0 requires a separate Python upgrade from 0.x; stable schema migrations cross majors only, and matching same-major layouts retain their labels. ```rust #| file: tangled/native/src/library.rs use crate::database::Database; use std::fs; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use tauri::{Manager, State}; use tauri_plugin_dialog::DialogExt; #[derive(Default)] pub struct Startup(tokio::sync::Mutex<()>); fn config_path(app: &tauri::AppHandle) -> Result { app.path().config_dir() .map(|root| root.join("candlelight").join("candlelight.edn")) .map_err(|error| format!("Locate Candlelight configuration: {error}")) } fn config_content(path: &Path) -> Result { let path = path.to_str().ok_or("Database path is not valid UTF-8")?; let quoted = serde_json::to_string(path) .map_err(|error| format!("Encode database path: {error}"))?; Ok(format!("{{:database-path {quoted}}}\n")) } fn save_config(config: &Path, database: &Path) -> Result<(), String> { let directory = config.parent().ok_or("Configuration has no parent directory")?; fs::create_dir_all(directory) .map_err(|error| format!("Create configuration directory: {error}"))?; let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) .map_err(|error| format!("Create configuration timestamp: {error}"))?.as_nanos(); let temporary = directory.join(format!("candlelight.edn.{}-{nonce}.tmp", std::process::id())); let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&temporary) .map_err(|error| format!("Create temporary database selection: {error}"))?; let result = (|| { file.write_all(config_content(database)?.as_bytes()) .map_err(|error| format!("Write database selection: {error}"))?; file.sync_all().map_err(|error| format!("Flush database selection: {error}"))?; drop(file); fs::rename(&temporary, config) .map_err(|error| format!("Save database selection: {error}")) })(); if result.is_err() { match fs::remove_file(&temporary) { Ok(()) => {}, Err(error) if error.kind() == ErrorKind::NotFound => {}, Err(error) => return Err(format!("{}; remove temporary configuration: {error}", result.unwrap_err())), } } result } fn open_selected(path: &Path, create: bool) -> Result { if !path.is_absolute() { return Err("Database location must be an absolute path".to_owned()); } if create { // Never trust a save dialog's overwrite confirmation as permission to destroy data. fs::OpenOptions::new().write(true).create_new(true).open(path) .map_err(|error| format!("Create new database {}: {error}", path.display()))?; } else { let metadata = fs::metadata(path) .map_err(|error| format!("Locate database {}: {error}", path.display()))?; if !metadata.is_file() { return Err("Database location is not a regular file".to_owned()); } } Database::open(path) } #[tauri::command] pub fn database_ready(app: tauri::AppHandle) -> bool { app.try_state::().is_some() } #[tauri::command] pub async fn read_database_config(app: tauri::AppHandle) -> Result, String> { let path = config_path(&app)?; tauri::async_runtime::spawn_blocking(move || { match fs::read_to_string(&path) { Ok(content) => Ok(Some(content)), Err(error) if error.kind() == ErrorKind::NotFound => Ok(None), Err(error) => Err(format!("Read {}: {error}", path.display())), } }).await.map_err(|error| format!("Read database configuration worker: {error}"))? } #[tauri::command] pub async fn open_configured_database( app: tauri::AppHandle, startup: State<'_, Startup>, path: String, ) -> Result<(), String> { let _guard = startup.0.lock().await; if database_ready(app.clone()) { return Ok(()); } let database = tauri::async_runtime::spawn_blocking(move || open_selected(Path::new(&path), false)) .await.map_err(|error| format!("Open database worker: {error}"))??; if !app.manage(database) { return Err("Database is already open".to_owned()); } Ok(()) } #[tauri::command] pub async fn choose_database( app: tauri::AppHandle, startup: State<'_, Startup>, create: bool, ) -> Result { let _guard = startup.0.lock().await; if database_ready(app.clone()) { return Ok(true); } let config = config_path(&app)?; let (sender, receiver) = tokio::sync::oneshot::channel(); let picker = app.dialog().file(); if create { picker.set_title("Create Candlelight database").set_file_name("candlelight.sqlite") .save_file(move |selected| { let _ = sender.send(selected); }); } else { picker.set_title("Open Candlelight database") .pick_file(move |selected| { let _ = sender.send(selected); }); } let Some(selected) = receiver.await .map_err(|error| format!("Receive database selection: {error}"))? else { return Ok(false); }; let path = selected.into_path().map_err(|error| format!("Resolve database selection: {error}"))?; let database = tauri::async_runtime::spawn_blocking(move || { let database = open_selected(&path, create)?; save_config(&config, &path)?; Ok::(database) }).await.map_err(|error| format!("Open selected database worker: {error}"))??; if !app.manage(database) { return Err("Database is already open".to_owned()); } Ok(true) } #[tauri::command] pub fn quit_startup(app: tauri::AppHandle) -> Result<(), String> { if database_ready(app.clone()) { return Err("Startup quit is unavailable after opening a database".to_owned()); } app.exit(0); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn configuration_contains_only_the_path() { let content = config_content(Path::new("/tmp/a\"b\\c.sqlite")).unwrap(); assert_eq!(content, "{:database-path \"/tmp/a\\\"b\\\\c.sqlite\"}\n"); } #[test] fn relative_locations_are_rejected() { assert!(open_selected(Path::new("relative.sqlite"), false).is_err()); } fn temporary_path() -> PathBuf { let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) .unwrap().as_nanos(); std::env::temp_dir().join(format!("candlelight-library-{}-{nonce}", std::process::id())) } #[test] fn opening_a_missing_location_does_not_create_a_database() { let path = temporary_path(); assert!(open_selected(&path, false).is_err()); assert!(!path.exists()); } #[test] fn creation_never_overwrites_existing_files() { let path = temporary_path(); fs::write(&path, b"existing library").unwrap(); let result = open_selected(&path, true); let contents = fs::read(&path).unwrap(); fs::remove_file(&path).unwrap(); assert!(result.is_err()); assert_eq!(contents, b"existing library"); } } ``` ```clojure ;| file: tangled/cljs/candlelight/startup.cljs (ns candlelight.startup (:require [candlelight.bridge :as bridge] [cljs.reader :as reader] [clojure.string :as str])) (defn decode-path "Read the single database-path setting from EDN; reject malformed configurations." [content] (let [config (reader/read-string content) path (:database-path config)] (when-not (and (map? config) (= #{:database-path} (set (keys config))) (string? path) (not (str/blank? path))) (throw (js/Error. "candlelight.edn must contain only {:database-path \"/absolute/path/library.sqlite\"}"))) path)) (defn start! "Gate the editor on a validated shared database; offer first-run selection and recovery." [start-library!] (let [root (.getElementById js/document "app") heading (.createElement js/document "h1") status (.createElement js/document "p") controls (.createElement js/document "nav") buttons (atom []) initial? (atom false)] (set! (.-textContent heading) "Choose your Candlelight database") (.setAttribute status "role" "status") (.setAttribute status "aria-live" "polite") (.setAttribute controls "class" "toolbar") (.setAttribute controls "aria-label" "Database selection") (.replaceChildren root heading status controls) (letfn [(busy! [busy?] (doseq [button @buttons] (set! (.-disabled button) busy?))) (ready! [] (.replaceChildren root) (start-library!)) (failed! [error] (set! (.-textContent status) (str "Could not open database: " error)) (busy! false)) (quit! [] (-> (bridge/invoke "quit_startup") (.catch failed!))) (choose! [create?] (busy! true) (-> (bridge/invoke "choose_database" #js {:create create?}) (.then (fn [opened?] (cond opened? (ready!) @initial? (quit!) :else (busy! false)))) (.catch failed!)))] (doseq [[label action] [["Create database…" #(choose! true)] ["Open existing database…" #(choose! false)] ["Quit" quit!]]] (let [button (.createElement js/document "button")] (set! (.-textContent button) label) (.setAttribute button "type" "button") (.addEventListener button "click" (fn [_] (action))) (.append controls button) (swap! buttons conj button))) (busy! true) (-> (bridge/invoke "database_ready") (.then (fn [ready?] (if ready? (ready!) (-> (bridge/invoke "read_database_config") (.then (fn [content] (if content (-> (bridge/invoke "open_configured_database" #js {:path (decode-path content)}) (.then (fn [_] (ready!)))) (do (reset! initial? true) (set! (.-textContent status) "Create a new database or select an existing library. Its location will be remembered.") (busy! false))))))))) (.catch failed!))))) ``` The pure configuration regressions can be run with `clojure -M -m cljs.main -re node -m candlelight.startup-test`. Native path/overwrite and schema compatibility regressions use `cargo test --manifest-path tangled/native/Cargo.toml`. ```clojure ;| file: tangled/cljs/candlelight/startup_test.cljs (ns candlelight.startup-test (:require [candlelight.startup :as startup] [cljs.test :refer-macros [deftest is run-tests]])) (deftest reads-a-single-database-location (is (= "/tmp/library.sqlite" (startup/decode-path "{:database-path \"/tmp/library.sqlite\"}")))) (deftest reads-escaped-path-characters (is (= "C:\\library\\a\"b.sqlite" (startup/decode-path "{:database-path \"C:\\\\library\\\\a\\\"b.sqlite\"}")))) (deftest rejects-unrelated-settings (is (thrown? js/Error (startup/decode-path "{:database-path \"/tmp/library.sqlite\" :version \"dev\"}")))) (deftest rejects-empty-path (is (thrown? js/Error (startup/decode-path "{:database-path \" \"}")))) (deftest rejects-non-string-path (is (thrown? js/Error (startup/decode-path "{:database-path 42}")))) (defn -main "Run configuration parsing regressions under Node." [] (run-tests 'candlelight.startup-test)) ```