Two changes developed together in one session; they share the same module
structure (db/mod.rs, the core lib root) and only compile together, so they
land as one commit.
## UserManager + per-user encryption (§9/§11)
New `users::UserManager`: owns the system.db pool plus a map
`userid -> SqlitePool` of unlocked databases. The pool *is* the unlock token —
its connect options carry the DEK as SQLCipher's raw key, so an open pool means
the key is in RAM until restart and dropping it re-locks (§9). Knows nothing
about cookies.
New `crypto` module: envelope encryption. A random 256-bit DEK encrypts
`{userid}.db`; `users.database_password` holds it sealed with AES-256-GCM under
`Argon2id(password, salt)`. The AEAD tag is the password verifier — one
derivation both authenticates and yields the key, so encrypted users store no
second hash. Cleartext users store the Argon2id output directly, compared in
constant time. Argon2 runs in spawn_blocking behind a 2-permit semaphore
(256 MiB per derivation).
- SQLCipher via `libsqlite3-sys` `bundled-sqlcipher-vendored-openssl`, pinned
<0.38 so it unifies with the one sqlx-sqlite links (a newer copy would apply
the feature to a SQLite sqlx never uses). OpenSSL is vendored and static, so
the binary stays self-contained.
- Schema split into `create_registry_tables` (instance-wide, no user key) and
`create_owner_tables` (one owner's content, identical in every file). No FK in
the owner bucket may reach the registry — enforced by a standalone test.
Dropped `chat_history.model_db_id` (write-only, and the only registry-crossing
key); moved `projects`/`project_tickets` into the owner bucket.
- Provisioning invariant: the file is written before the row, deleted after it,
so a crash leaves an orphan file, never a user without a database. `open_db`
never creates: a missing file is an error, not a silent empty database.
Not consumed yet: no login, call sites still use the shared system.db pool.
## Extract crates/skald-core
The headless core moves out of `src/` into its own crate; `skald` (server) and
the coming `skald-setup` are shells around it. Two dependencies on the shell
were inverted rather than dragged along, so the core names neither Tauri nor any
concrete plugin:
- `Plugin::tools(self: Arc<Self>)` — plugins contribute tools through this hook
(sibling of `http_router`), so the core no longer downcasts to
`MobileConnectorPlugin`.
- `tools::restart::set_restart_handler` — the desktop shell installs its
teardown-and-respawn; the core defaults to the supervisor exit code. The core
loses its `desktop` feature.
- `boot`'s stdout formatter moves to the binary (`src/boot_format.rs`); the core
only emits tracing events.
All 79 core tests pass; the binary boots and serves in a clean directory, and
the mobile-connector tools still register through the new hook.
141 lines
5.7 KiB
Rust
141 lines
5.7 KiB
Rust
//! Generic in-memory registry for pending human-in-the-loop requests.
|
|
//!
|
|
//! Approval, clarification, and elicitation all share the same shape: a request
|
|
//! is registered under an id with some display `Info`, a caller blocks on a
|
|
//! `oneshot::Receiver<Resolution>`, and later something resolves the request by
|
|
//! id — firing the sender and dropping the entry. This type factors out that
|
|
//! shared plumbing (the `Mutex<HashMap>` + oneshot bookkeeping) so each manager
|
|
//! keeps only what is genuinely its own: id minting, event emission, and any
|
|
//! extra policy (rules/bypass for approval, secret handling for elicitation).
|
|
//!
|
|
//! What deliberately stays OUT of the registry:
|
|
//! - **id minting** — the caller supplies the key (a durable `tool_call_id` for
|
|
//! approval, an internal counter for clarification/elicitation);
|
|
//! - **event emission** — the `ServerEvent` variants differ per manager, so the
|
|
//! caller broadcasts after `insert` / `resolve`;
|
|
//! - **ordering** — `list()` is unsorted; callers that need a stable order sort
|
|
//! on their own `Info` field (e.g. `created_at`).
|
|
|
|
use std::collections::HashMap;
|
|
|
|
use tokio::sync::{Mutex, oneshot};
|
|
|
|
/// One registered request: its display `Info` and the sender that unblocks the
|
|
/// waiting caller with a `Resolution`.
|
|
struct Entry<I, R> {
|
|
info: I,
|
|
tx: oneshot::Sender<R>,
|
|
}
|
|
|
|
/// Keyed store of pending requests. `I` is the cloneable public info surfaced to
|
|
/// the Inbox; `R` is the resolution payload delivered back to the blocked caller.
|
|
pub struct PendingRegistry<I, R> {
|
|
pending: Mutex<HashMap<i64, Entry<I, R>>>,
|
|
}
|
|
|
|
impl<I: Clone, R> PendingRegistry<I, R> {
|
|
pub fn new() -> Self {
|
|
Self { pending: Mutex::new(HashMap::new()) }
|
|
}
|
|
|
|
/// Registers `info` under `id` and returns the receiver the caller awaits.
|
|
/// The caller mints `id` (a durable tool_call_id or an internal counter).
|
|
pub async fn insert(&self, id: i64, info: I) -> oneshot::Receiver<R> {
|
|
let (tx, rx) = oneshot::channel();
|
|
self.pending.lock().await.insert(id, Entry { info, tx });
|
|
rx
|
|
}
|
|
|
|
/// Removes the entry for `id` and delivers `resolution` to the waiting caller.
|
|
/// Returns the entry's `info` (so the caller can broadcast a resolved event),
|
|
/// or `None` when no live entry exists (already resolved, or post-restart).
|
|
pub async fn resolve(&self, id: i64, resolution: R) -> Option<I> {
|
|
let entry = self.pending.lock().await.remove(&id)?;
|
|
let _ = entry.tx.send(resolution);
|
|
Some(entry.info)
|
|
}
|
|
|
|
/// Removes the entry for `id` WITHOUT sending a resolution: the dropped sender
|
|
/// makes the blocked caller observe `RecvError`. Used for deadline / disconnect
|
|
/// cancellation. Returns the removed `info`, or `None` if absent.
|
|
pub async fn remove(&self, id: i64) -> Option<I> {
|
|
self.pending.lock().await.remove(&id).map(|e| e.info)
|
|
}
|
|
|
|
/// Snapshot of the `info` for a single pending id, without resolving it.
|
|
pub async fn get(&self, id: i64) -> Option<I> {
|
|
self.pending.lock().await.get(&id).map(|e| e.info.clone())
|
|
}
|
|
|
|
/// Snapshot of every pending `info`, in unspecified order.
|
|
pub async fn list(&self) -> Vec<I> {
|
|
self.pending.lock().await.values().map(|e| e.info.clone()).collect()
|
|
}
|
|
|
|
/// Drops every entry whose `info` matches `pred` (their senders are dropped, so
|
|
/// the blocked callers observe `RecvError`). Returns the number removed.
|
|
pub async fn remove_where(&self, pred: impl Fn(&I) -> bool) -> usize {
|
|
let mut map = self.pending.lock().await;
|
|
let before = map.len();
|
|
map.retain(|_, e| !pred(&e.info));
|
|
before - map.len()
|
|
}
|
|
}
|
|
|
|
impl<I: Clone, R> Default for PendingRegistry<I, R> {
|
|
fn default() -> Self { Self::new() }
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[tokio::test]
|
|
async fn insert_then_resolve_delivers_and_returns_info() {
|
|
let reg: PendingRegistry<i64, String> = PendingRegistry::new();
|
|
let rx = reg.insert(42, 100).await;
|
|
// resolve returns the stored info and unblocks the waiter with the payload.
|
|
assert_eq!(reg.resolve(42, "answer".to_string()).await, Some(100));
|
|
assert_eq!(rx.await.unwrap(), "answer");
|
|
// the entry is gone afterwards.
|
|
assert!(reg.get(42).await.is_none());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn resolve_unknown_id_is_none() {
|
|
let reg: PendingRegistry<i64, String> = PendingRegistry::new();
|
|
assert_eq!(reg.resolve(1, "x".to_string()).await, None);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn remove_drops_sender_so_receiver_errors() {
|
|
let reg: PendingRegistry<i64, String> = PendingRegistry::new();
|
|
let rx = reg.insert(7, 100).await;
|
|
assert_eq!(reg.remove(7).await, Some(100));
|
|
// no resolution was sent — the dropped sender makes the waiter observe RecvError.
|
|
assert!(rx.await.is_err());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn get_and_list_reflect_pending() {
|
|
let reg: PendingRegistry<i64, String> = PendingRegistry::new();
|
|
let _rx1 = reg.insert(1, 10).await;
|
|
let _rx2 = reg.insert(2, 20).await;
|
|
assert_eq!(reg.get(1).await, Some(10));
|
|
let mut all = reg.list().await;
|
|
all.sort();
|
|
assert_eq!(all, vec![10, 20]);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn remove_where_filters_and_counts() {
|
|
let reg: PendingRegistry<i64, String> = PendingRegistry::new();
|
|
let _rx_keep = reg.insert(1, 10).await;
|
|
let rx_drop = reg.insert(2, 20).await;
|
|
// remove every entry whose info is >= 20.
|
|
assert_eq!(reg.remove_where(|info| *info >= 20).await, 1);
|
|
assert!(rx_drop.await.is_err()); // dropped entry's waiter errors
|
|
assert_eq!(reg.get(1).await, Some(10)); // the other entry stays
|
|
}
|
|
}
|