Skip to content

armgit / kanzo

Public Imported from GitHub
0

Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.

Answer busy instead of waiting forever while sync runs

emanuele-em937a7d347432
diff --git a/src/home.rs b/src/home.rs
index c7f41f8..0c7ef4c 100644
--- a/src/home.rs
+++ b/src/home.rs
@@ -1,12 +1,13 @@
//! The data folder: where it is, what it holds, and the settings in `config.toml`.
-use std::fs::{self, File, OpenOptions};
+use std::fs::{self, File, OpenOptions, TryLockError};
use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use serde::Deserialize;
-use crate::store::Store;
+use crate::store::{self, Store};
pub const DEFAULT_PORT: u16 = 4242;
@@ -37,6 +38,9 @@ kanzo.lock
.DS_Store
";
+/// How long an operation waits for `kanzo sync` before giving up with "busy".
+const LOCK_WAIT: Duration = Duration::from_secs(10);
+
#[derive(Debug, Clone, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
@@ -116,12 +120,25 @@ impl Home {
/// Opens a fresh connection. Callers keep it for one operation only, so a
/// database replaced by `kanzo sync` is picked up on the next one. It holds
- /// a shared lock on `kanzo.lock`, so sync can wait for it to finish.
- pub fn store(&self) -> Result<Store> {
- let lock = self.lock_file()?;
- // Some filesystems (exFAT, network shares) have no locks; go on without.
- let lock = lock.lock_shared().ok().map(|_| lock);
- Ok(Store::open(&self.db_path(), self.config.statuses.clone(), lock)?)
+ /// a shared lock on `kanzo.lock`, so sync can wait for it to finish; while
+ /// sync holds the lock, this waits up to `LOCK_WAIT` and then reports busy.
+ pub fn store(&self) -> store::Result<Store> {
+ let lock = self.lock_file().map_err(|e| store::Error::Invalid(format!("{e:#}")))?;
+ let deadline = Instant::now() + LOCK_WAIT;
+ let lock = loop {
+ match lock.try_lock_shared() {
+ Ok(()) => break Some(lock),
+ Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(25))
+ }
+ Err(TryLockError::WouldBlock) => {
+ return Err(store::Error::Busy("kanzo sync is updating the board; try again in a moment".into()));
+ }
+ // Some filesystems (exFAT, network shares) have no locks; go on without.
+ Err(TryLockError::Error(_)) => break None,
+ }
+ };
+ Store::open(&self.db_path(), self.config.statuses.clone(), lock)
}
/// Blocks until no connection is open, and keeps new ones out until the file is dropped.
diff --git a/src/store.rs b/src/store.rs
index 01b23bf..f03df82 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -21,13 +21,15 @@ const NOW: &str = "strftime('%Y-%m-%dT%H:%M:%SZ', 'now')";
pub enum Error {
NotFound(String),
Invalid(String),
+ /// Another process holds the data folder for longer than we wait, like a long `kanzo sync`.
+ Busy(String),
Db(rusqlite::Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
- Error::NotFound(m) | Error::Invalid(m) => f.write_str(m),
+ Error::NotFound(m) | Error::Invalid(m) | Error::Busy(m) => f.write_str(m),
Error::Db(e) => write!(f, "database error: {e}"),
}
}
diff --git a/src/web.rs b/src/web.rs
index 64d1fa5..32d5bea 100644
--- a/src/web.rs
+++ b/src/web.rs
@@ -99,22 +99,22 @@ async fn with_store<T: Serialize + Send + 'static>(
f: impl FnOnce(&Store) -> store::Result<T> + Send + 'static,
) -> Response {
let outcome = tokio::task::spawn_blocking(move || {
- let store = home.store().map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")))?;
- f(&store).map_err(|e| {
- let code = match e {
- Error::NotFound(_) => StatusCode::NOT_FOUND,
- Error::Invalid(_) => StatusCode::BAD_REQUEST,
- Error::Db(_) => StatusCode::INTERNAL_SERVER_ERROR,
- };
- (code, e.to_string())
- })
+ let store = home.store()?;
+ f(&store)
})
- .await
- .unwrap_or_else(|e| Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())));
- match outcome {
- Ok(v) => Json(v).into_response(),
- Err((code, error)) => (code, Json(json!({ "error": error }))).into_response(),
- }
+ .await;
+ let error = match outcome {
+ Ok(Ok(v)) => return Json(v).into_response(),
+ Ok(Err(e)) => e,
+ Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
+ };
+ let code = match error {
+ Error::NotFound(_) => StatusCode::NOT_FOUND,
+ Error::Invalid(_) => StatusCode::BAD_REQUEST,
+ Error::Busy(_) => StatusCode::SERVICE_UNAVAILABLE,
+ Error::Db(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (code, Json(json!({ "error": error.to_string() }))).into_response()
}
async fn changes(State(home): Shared) -> Response {