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
82 changes: 82 additions & 0 deletions crates/zet-blocks/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,23 @@ impl Store {
Ok(store)
}

/// Open a store with an explicit SQLite busy timeout applied before
/// schema initialization. The native UI uses this; CLI and recorder
/// paths keep their established default.
pub fn open_with_busy_timeout(path: &str, timeout: std::time::Duration) -> Result<Self> {
let conn = Connection::open(path)?;
conn.busy_timeout(timeout)?;
let store = Store { conn };
store.init()?;
Ok(store)
}

/// Set the SQLite busy timeout for this connection. Useful for stores
/// opened through the ordinary path.
pub fn set_busy_timeout(&self, timeout: std::time::Duration) -> Result<()> {
self.conn.busy_timeout(timeout)
}

fn init(&self) -> Result<()> {
self.conn.execute(
"CREATE TABLE IF NOT EXISTS blocks (
Expand Down Expand Up @@ -502,6 +519,21 @@ impl Store {
.map_err(std::io::Error::other)
}

/// Open the default store with an explicit busy timeout before schema
/// initialization. Used by the native UI to avoid multi-second freezes
/// when another process holds the database lock.
pub fn open_default_with_busy_timeout(timeout: std::time::Duration) -> std::io::Result<Self> {
let dir = zet_home();
std::fs::create_dir_all(&dir)?;
Self::open_with_busy_timeout(
dir.join("blocks.sqlite")
.to_str()
.ok_or_else(|| std::io::Error::other("non-UTF8 state root"))?,
timeout,
)
.map_err(std::io::Error::other)
}

pub fn replay(&self, session: &str) -> Result<String> {
let mut out = String::new();
for block in self.list(session)? {
Expand Down Expand Up @@ -582,6 +614,26 @@ impl Store {
rows.collect()
}

/// Bounded mission list for native panel rendering. `limit` is clamped
/// to a sane range so a bad caller cannot request an unbounded read.
pub fn list_missions_bounded(&self, limit: usize) -> Result<Vec<Mission>> {
let limit = limit.clamp(1, 256) as i64;
let mut stmt = self.conn.prepare(
"SELECT id, title, description, created_at, updated_at
FROM missions ORDER BY created_at ASC, id ASC LIMIT ?1",
)?;
let rows = stmt.query_map(rusqlite::params![limit], |row| {
Ok(Mission {
id: row.get(0)?,
title: row.get(1)?,
description: row.get(2)?,
created_at: row.get(3)?,
updated_at: row.get(4)?,
})
})?;
rows.collect()
}

pub fn update_mission(&self, id: i64, title: &str, description: &str) -> Result<bool> {
let title = Self::sanitize_mission_text(title);
let description = Self::sanitize_mission_text(description);
Expand Down Expand Up @@ -692,6 +744,36 @@ impl Store {
Ok(out)
}

/// Bounded evidence list for the native Mission view. The limit is
/// clamped so panel refreshes cannot read an unbounded association set.
pub fn mission_commands_bounded(
&self,
mission_id: i64,
limit: usize,
) -> Result<Vec<MissionCommand>> {
let limit = limit.clamp(1, 256) as i64;
let mut stmt = self.conn.prepare(
"SELECT mission_id, block_id, session, provenance, created_at
FROM mission_commands WHERE mission_id = ?1
ORDER BY created_at ASC, block_id ASC LIMIT ?2",
)?;
let rows = stmt.query_map(rusqlite::params![mission_id, limit], |row| {
Ok(MissionCommand {
mission_id: row.get(0)?,
block_id: row.get(1)?,
session: row.get(2)?,
provenance: row.get(3)?,
created_at: row.get(4)?,
available: false,
})
})?;
let mut out: Vec<MissionCommand> = rows.collect::<Result<Vec<_>>>()?;
for mc in &mut out {
mc.available = self.block_available(mc.block_id, &mc.session)?;
}
Ok(out)
}

fn block_available(&self, block_id: i64, session: &str) -> Result<bool> {
let count: i64 = self.conn.query_row(
"SELECT COUNT(*) FROM blocks WHERE id = ?1 AND session = ?2",
Expand Down
45 changes: 45 additions & 0 deletions crates/zet-blocks/tests/missions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,48 @@ fn transaction_rollback_on_failed_commit() {

let _ = std::fs::remove_file(&path);
}

#[test]
fn ui_busy_timeout_fails_fast_and_retries() {
let path = std::env::temp_dir().join(format!("zet-busy-{}.sqlite", std::process::id()));
let _ = std::fs::remove_file(&path);
{
let store = Store::open(path.to_str().unwrap()).unwrap();
store.create_mission("Seed", "").unwrap();
}
let store =
Store::open_with_busy_timeout(path.to_str().unwrap(), std::time::Duration::from_millis(50))
.unwrap();
let blocker = rusqlite::Connection::open(&path).unwrap();
blocker.execute("BEGIN EXCLUSIVE", []).unwrap();

let started = std::time::Instant::now();
let err = store.create_mission("Blocked", "").unwrap_err();
let elapsed = started.elapsed();
assert!(
elapsed < std::time::Duration::from_millis(750),
"busy timeout took {elapsed:?}"
);
assert!(matches!(
err,
rusqlite::Error::SqliteFailure(
rusqlite::ffi::Error {
code: rusqlite::ErrorCode::DatabaseBusy,
..
},
_
)
));

drop(blocker);
let id = store.create_mission("Recovered", "").unwrap();
assert!(id > 0);
let store2 = Store::open(path.to_str().unwrap()).unwrap();
assert!(store2
.list_missions_bounded(16)
.unwrap()
.iter()
.any(|m| m.title == "Recovered"));

let _ = std::fs::remove_file(&path);
}
29 changes: 29 additions & 0 deletions crates/zet-gpu/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,17 @@ pub fn is_inspector_toggle(logical: &Key, pressed: bool, mods: &ModifiersState)
matches!(logical, Key::Character(s) if ctrl && shift && s.eq_ignore_ascii_case("i"))
}

/// True on Ctrl+Shift+N: switch the rail between Sessions and Missions.
/// `n` inside Mission mode opens the native New Mission overlay.
pub fn is_mission_mode(logical: &Key, pressed: bool, mods: &ModifiersState) -> bool {
if !pressed {
return false;
}
let ctrl = mods.contains(ModifiersState::CONTROL);
let shift = mods.contains(ModifiersState::SHIFT);
matches!(logical, Key::Character(s) if ctrl && shift && s.eq_ignore_ascii_case("n"))
}

/// True on Ctrl+PageDown / Ctrl+PageUp: cycle tabs. Checked before
/// [`translate`] (which would emit scrolling escapes).
pub fn is_cycle_tab(logical: &Key, pressed: bool, mods: &ModifiersState) -> Option<isize> {
Expand Down Expand Up @@ -182,3 +193,21 @@ pub fn translate(
_ => text.map(|t| t.as_bytes().to_vec()),
}
}

#[cfg(test)]
mod mission_mode_tests {
use super::*;

#[test]
fn ctrl_shift_n_is_the_mission_rail_chord() {
let mods = ModifiersState::CONTROL | ModifiersState::SHIFT;
assert!(is_mission_mode(&Key::Character("n".into()), true, &mods));
assert!(is_mission_mode(&Key::Character("N".into()), true, &mods));
assert!(!is_mission_mode(
&Key::Character("n".into()),
true,
&ModifiersState::CONTROL
));
assert!(!is_mission_mode(&Key::Character("n".into()), false, &mods));
}
}
Loading
Loading