Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Principles:

### Rust back-end

- ⚠️ **A command taking the lock is `async` and runs its body in `db::blocking`**; with an `AppHandle`, generic over `R: Runtime`, registered as `name::<tauri::Wry>`. One lock serialises everything. ⚠️ HTTP sends and WebSockets never hold it; `open_library` closes every socket. → "Persistence (Rust)", "Who holds the lock", "Sending a request, and its answer", "A WebSocket".
- ⚠️ **A command taking the lock is `async` and runs its body in `db::blocking`**, on the engine's one db thread, in order (`lock` asserts it in debug); a send writes only into the library it read from (`Library::number`); with an `AppHandle`, generic over `R: Runtime`, registered as `name::<tauri::Wry>`. One lock serialises everything. ⚠️ HTTP sends and WebSockets never hold it; `open_library` closes every socket. → "Persistence (Rust)", "Who holds the lock", "Sending a request, and its answer", "A WebSocket".
- HTTP history masks before sealing; the cookie jar is sealed whole and matched in Rust. → "The history of what was sent", "How a request travels, and the cookie jar".
- A module holding commands is `pub`, the rest `pub(crate)`.
- **Migrations are append-only** (`crates/engine/migrations/`); `db/schema.rs` is hand-written, so add a column in both. `PRAGMA foreign_keys` is per connection (`db::configure`); `db::iso8601` always writes milliseconds. → "Persistence (Rust)", "How far back an upgrade reaches".
Expand Down
43 changes: 37 additions & 6 deletions crates/engine/src/db.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
pub mod migration;
pub(crate) mod queue;
pub mod schema;

use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};

use diesel::connection::SimpleConnection;
Expand All @@ -22,9 +24,23 @@ pub struct Library {
/// Shared, so a read can take the key past the lock: see [`Library::shared_vault`].
vault: Arc<Vault>,
directory: PathBuf,
/// Drawn from a counter of the process when the library is opened: what a send read from
/// is what it may write to, and a library opened since is another number.
number: u64,
}

/// Starts at 1: no library is numbered 0.
static OPENED: AtomicU64 = AtomicU64::new(1);

fn next_number() -> u64 {
OPENED.fetch_add(1, Ordering::Relaxed)
}

impl Library {
pub fn number(&self) -> u64 {
self.number
}

/// The connection, for the Diesel call that needs it by that name.
pub fn db(&mut self) -> &mut SqliteConnection {
&mut self.connection
Expand Down Expand Up @@ -77,7 +93,14 @@ impl Library {
pub type Db = Mutex<Option<Library>>;

/// A poisoned mutex means a command panicked while holding it.
///
/// ⚠️ On the db thread alone (`queue`), checked in debug builds; the crate's own unit tests
/// lock their in-memory libraries on the test thread.
pub(crate) fn lock(db: &Db) -> Result<LibraryGuard<'_>, StorageError> {
debug_assert!(
cfg!(test) || queue::on_db_thread(),
"the library is locked off the db thread"
);
let guard = db.lock().map_err(|_| StorageError::Unavailable)?;
if guard.is_none() {
return Err(StorageError::Locked);
Expand All @@ -91,9 +114,9 @@ pub(crate) fn engine<R: Runtime>(app: &AppHandle<R>) -> Arc<Engine> {
Arc::clone(&app.state::<Arc<Engine>>())
}

/// A command's body, on Tokio's blocking pool rather than on a runtime worker: waiting on the
/// lock, or holding it through a whole-corpus read, would park a worker the updater and the
/// plugins share. A body that panics answers as the lock it would have poisoned.
/// A command's body, on the engine's db queue: one thread, in the order the bodies arrive, so
/// two writes sent in a row land in that order. A body that panics answers as the lock it
/// would have poisoned.
pub(crate) async fn blocking<R, T, F>(app: AppHandle<R>, body: F) -> Result<T, AppError>
where
R: Runtime,
Expand All @@ -109,9 +132,15 @@ where
T: Send + 'static,
F: FnOnce(&Engine, &Db) -> Result<T, AppError> + Send + 'static,
{
tauri::async_runtime::spawn_blocking(move || body(&engine, &engine.db))
.await
.map_err(|_| StorageError::Unavailable)?
let held = Arc::clone(&engine);
engine.queue.run(move || body(&held, &held.db)).await
}

/// The library a send read from, if it is still the one open: `None` once another was opened.
pub(crate) fn lock_library(db: &Db, number: u64) -> Result<Option<LibraryGuard<'_>>, StorageError> {
let connection = lock(db)?;

Ok((connection.number() == number).then_some(connection))
}

/// The guard, narrowed to a library that is definitely there — [`lock`] refused otherwise.
Expand Down Expand Up @@ -184,6 +213,7 @@ pub fn open(path: &Path, vault: Vault) -> Result<Library, StorageError> {
connection,
vault: Arc::new(vault),
directory: path.parent().map(Path::to_path_buf).unwrap_or_default(),
number: next_number(),
})
}

Expand All @@ -201,6 +231,7 @@ pub fn open_in_memory() -> Result<Library, StorageError> {
// Named, never created: a test writing beside the library fails loudly.
directory: std::env::temp_dir()
.join(format!("devnotes-in-memory-{}", uuid::Uuid::new_v4())),
number: next_number(),
})
}

Expand Down
109 changes: 109 additions & 0 deletions crates/engine/src/db/queue.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
//! The one thread that touches the database, running its jobs in the order they arrive.
//!
//! Two writes sent one after the other land in that order, and the lock is never contended. A
//! job never waits on another job of the queue, nor on the network: that would deadlock it.

use std::cell::Cell;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::mpsc;

use tokio::sync::oneshot;

use crate::error::{AppError, StorageError};

type Job = Box<dyn FnOnce() + Send>;

thread_local! {
static ON_DB_THREAD: Cell<bool> = const { Cell::new(false) };
}

/// Whether the caller runs on the queue's thread, which `lock` checks in debug builds.
pub(crate) fn on_db_thread() -> bool {
ON_DB_THREAD.get()
}

pub(crate) struct DbQueue(mpsc::Sender<Job>);

impl DbQueue {
/// The thread ends once the queue is dropped and its last job has run.
pub(crate) fn start() -> Self {
let (sender, jobs) = mpsc::channel::<Job>();
std::thread::Builder::new()
.name("db".to_string())
.spawn(move || {
ON_DB_THREAD.set(true);
for job in jobs {
job();
}
})
.expect("the db thread starts");

Self(sender)
}

/// Waits for `job` without holding a thread. A job that panics answers as the lock it
/// would have poisoned, and the queue goes on with the next one.
pub(crate) async fn run<T, F>(&self, job: F) -> Result<T, AppError>
where
T: Send + 'static,
F: FnOnce() -> Result<T, AppError> + Send + 'static,
{
let (answer, answered) = oneshot::channel();
let job: Job = Box::new(move || {
let result = catch_unwind(AssertUnwindSafe(job))
.unwrap_or_else(|_| Err(StorageError::Unavailable.into()));
let _ = answer.send(result);
});
self.0.send(job).map_err(|_| StorageError::Unavailable)?;

answered.await.map_err(|_| StorageError::Unavailable)?
}
}

#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};

use super::*;
use crate::error::ErrorCode;

fn block_on<T>(future: impl Future<Output = T>) -> T {
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(future)
}

#[test]
fn jobs_run_on_the_db_thread_in_the_order_they_were_sent() {
let queue = DbQueue::start();
let order = Arc::new(Mutex::new(Vec::new()));
let job = |n: u32| {
let order = Arc::clone(&order);
queue.run(move || {
order.lock().unwrap().push((n, on_db_thread()));
Ok(())
})
};

block_on(async {
let (a, b, c) = tokio::join!(job(1), job(2), job(3));
a.and(b).and(c)
})
.unwrap();

assert_eq!(*order.lock().unwrap(), [(1, true), (2, true), (3, true)]);
assert!(!on_db_thread());
}

#[test]
fn a_job_that_panics_answers_an_error_and_the_next_one_runs() {
let queue = DbQueue::start();

let panicked = block_on(queue.run(|| -> Result<(), AppError> { panic!("on purpose") }));
let next = block_on(queue.run(|| Ok(7)));

assert_eq!(panicked.unwrap_err().code, ErrorCode::StorageUnavailable);
assert_eq!(next.unwrap(), 7);
}
}
60 changes: 45 additions & 15 deletions crates/engine/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use std::sync::Arc;
use chrono::Utc;
use tauri::{AppHandle, Runtime};

use crate::db::{blocking, blocking_on, engine, lock};
use crate::db::{blocking, blocking_on, engine, lock, lock_library};
use crate::error::{AppError, FileContext};
use crate::tools::off_thread;
use crate::{Engine, EngineEvent};
Expand Down Expand Up @@ -485,6 +485,8 @@ struct Prepared {
layers: Vec<variables::VariableLayer>,
environment: Option<environments::Environment>,
jar: Option<Vec<cookies::JarCookie>>,
/// The number of the library read from: the writes go to it or nowhere.
library: u64,
}

/// One send and the scripts around it, from the command's side: their host, the jar's copy
Expand All @@ -493,6 +495,8 @@ struct Prepared {
struct Flight {
engine: Arc<Engine>,
id: String,
/// The library the send read from (`Prepared::library`); 0 until it has read.
library: u64,
session: Option<Session>,
/// The jar's copy while no session holds it.
jar: Option<Vec<cookies::JarCookie>>,
Expand Down Expand Up @@ -535,6 +539,7 @@ impl Flight {
Self {
engine,
id: id.to_string(),
library: 0,
session: None,
jar: None,
transport: transport::Transport::default(),
Expand Down Expand Up @@ -576,6 +581,7 @@ impl Flight {
mut layers,
environment,
jar,
library,
} = prepare(
&self.engine,
&document,
Expand All @@ -586,6 +592,7 @@ impl Flight {
.await?;
let around = Around::of(&document.scripts, &name, &inherited);
self.jar = jar;
self.library = library;
self.transport = inherited.transport.over(&document.transport);
self.environment = environment;
self.confirmed = confirmed;
Expand All @@ -605,11 +612,12 @@ impl Flight {
let resolver = variables::Resolver::new(&going.layers);
let (filled, above) = variables::resolve(&going.document, &inherited, &resolver);
let method = going.method;
let mut outgoing = tauri::async_runtime::spawn_blocking(move || {
send::compose(kind, method, &filled, &above)
})
.await
.map_err(|error| AppError::from(send::SendError::Network(error.to_string())))??;
let mut outgoing = self
.engine
.runtime
.spawn_blocking(move || send::compose(kind, method, &filled, &above))
.await
.map_err(|error| AppError::from(send::SendError::Network(error.to_string())))??;
outgoing.secret_values = resolver.secrets();
if outgoing.transport.use_cookies {
outgoing.jar = self.jar();
Expand Down Expand Up @@ -677,7 +685,11 @@ impl Flight {
id: &str,
outgoing: send::Outgoing,
) -> Result<Result<send::SentResponse, AppError>, AppError> {
let (answer, cookies_set) = self.engine.sending.run(id, outgoing).await;
let (answer, cookies_set) = self
.engine
.sending
.run(&self.engine.runtime, id, outgoing)
.await;
if matches!(answer, Err(send::SendError::Cancelled)) {
return Err(send::SendError::Cancelled.into());
}
Expand Down Expand Up @@ -858,11 +870,14 @@ impl Flight {
};
let killer = session.killer();
self.engine.sending.watch(&self.id, Some(killer.clone()));
let ran = tauri::async_runtime::spawn_blocking(move || {
let outcome = session.run(&job);
(session, outcome)
})
.await;
let ran = self
.engine
.runtime
.spawn_blocking(move || {
let outcome = session.run(&job);
(session, outcome)
})
.await;
self.engine.sending.watch(&self.id, None);
let outcome = match ran {
Ok((mut session, outcome)) => {
Expand Down Expand Up @@ -996,8 +1011,12 @@ impl Flight {
.map(|environment| environment.id.clone());
let collection_id = self.collection_id.clone();
let by = self.by.clone();
let library = self.library;
let kept = blocking_on(Arc::clone(&self.engine), move |_, db| {
let mut connection = lock(db)?;
let Some(mut connection) = lock_library(db, library)? else {
log::warn!("A script wrote into a library closed since: nothing kept");
return Ok(false);
};
Ok(keep_writes(
&mut connection,
&writes,
Expand All @@ -1017,6 +1036,7 @@ impl Flight {
async fn keep(self) {
let Self {
engine,
library,
sent,
changes,
..
Expand All @@ -1026,7 +1046,10 @@ impl Flight {
}
let kept = blocking_on(engine, move |_, db| {
let now = Utc::now();
let mut connection = lock(db)?;
let Some(mut connection) = lock_library(db, library)? else {
log::warn!("A send ended after its library was closed: its history and cookies are not kept");
return Ok(());
};
if let Some(sent) = &sent {
let (summary, record) = history::record_of(sent);
history::store::record(
Expand Down Expand Up @@ -1092,6 +1115,7 @@ async fn prepare(
layers,
environment,
jar,
library: connection.number(),
})
})
.await
Expand Down Expand Up @@ -1827,7 +1851,13 @@ pub async fn connect_websocket<R: Runtime>(
let engine = engine(&app);
Ok(engine
.sockets
.connect(Arc::clone(&engine.events), id, outgoing, &protocols)
.connect(
&engine.runtime,
Arc::clone(&engine.events),
id,
outgoing,
&protocols,
)
.await?)
}

Expand Down
5 changes: 3 additions & 2 deletions crates/engine/src/http/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1206,15 +1206,16 @@ impl Sending {
/// the cookie of a login whose landing page did not load.
pub async fn run(
&self,
runtime: &tokio::runtime::Handle,
id: &str,
outgoing: Outgoing,
) -> (Result<SentResponse, SendError>, Vec<Change>) {
let changes: Arc<Mutex<Vec<Change>>> = Arc::default();
let task = tauri::async_runtime::spawn(send(outgoing, Arc::clone(&changes)));
let task = runtime.spawn(send(outgoing, Arc::clone(&changes)));
let number = self.started.fetch_add(1, Ordering::Relaxed);
if let Ok(mut running) = self.running.lock()
&& let Some((_, previous)) =
running.insert(id.to_string(), (number, task.inner().abort_handle()))
running.insert(id.to_string(), (number, task.abort_handle()))
{
previous.abort();
}
Expand Down
Loading