Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
361 changes: 358 additions & 3 deletions crates/engine/src/activity.rs

Large diffs are not rendered by default.

53 changes: 52 additions & 1 deletion crates/engine/src/cmd/activity.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! `activity.list` / `activity.cancel`: the background tasks in flight (see [`crate::activity`]).
//! `activity.list` / `activity.cancel`: the background tasks in flight; `activity.finished` / `activity.dismiss`:
//! the ones that ended and left a row (see [`crate::activity`]).

use serde_json::{Value, json};

Expand Down Expand Up @@ -32,6 +33,32 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({"cancelled": 1}))
}
),
cmd!(
query "activity.finished",
"Finished Background Tasks",
[],
None,
"{} → {finished: [{id, kind, label, ending: done|problems|failed|stopped|died, summary, detail, failures: [{name, reason}], failed, path, ranMs, ageMs}]} — the tasks that ended and left a row, newest first: those that ran 10 s or more, and every one that did not end well (problems = not for every file, stopped = cancelled, died = its worker crashed). `failed` counts the files that failed; `failures` holds the first 500 with their reasons (none for a job that only counts them); `path` is one of the files it made. `summary` and `detail` are as the app shows them, in its language, and `summary` is empty for a job that says nothing of itself. At most 50 clean endings and 200 rows in all are kept. They stay until dismissed, for this session",
always,
|s, _| Ok(json!({"finished": s.activity.finished()}))
),
cmd!(
"activity.dismiss",
"Dismiss Finished Task",
[],
None,
"{id} | {all: true} → {dismissed: n} — let go of a finished task's row (or of all of them). An unknown id (it may have been dismissed already) is an error",
always,
|s, p| {
const C: &str = "activity.dismiss";
if p.get("all").and_then(Value::as_bool) == Some(true) {
return Ok(json!({"dismissed": s.activity.dismiss_all()}));
}
let id = p.get("id").and_then(Value::as_u64).ok_or_else(|| bad(C, "id or all"))?;
s.activity.dismiss(id).map_err(|e| bad(C, e))?;
Ok(json!({"dismissed": 1}))
}
),
]
}

Expand All @@ -54,6 +81,30 @@ mod tests {
assert!(g.is_cancelled());
}

#[test]
fn finished_and_dismiss_through_execute() {
use crate::activity::{Ending, Failure, Outcome};
let mut s = Session::new();
let g = s.activity.start("export", "Exporting", Cancel::Yes);
let id = g.id();
g.finish(Outcome {
ending: Ending::Problems,
summary: "Exported 1 of 2 photos".into(),
failures: vec![Failure { name: "IMG_2.jpg".into(), reason: "The disk is full".into() }],
..Default::default()
});
let r = s.execute("activity.finished", &json!({})).unwrap();
assert_eq!(r["finished"][0]["id"], id);
assert_eq!(r["finished"][0]["ending"], "problems");
assert_eq!(r["finished"][0]["failures"][0], json!({"name": "IMG_2.jpg", "reason": "The disk is full"}));
assert_eq!(r["finished"][0]["failed"], 1);
assert!(s.execute("activity.dismiss", &json!({})).is_err());
assert!(s.execute("activity.dismiss", &json!({"id": 999})).is_err());
assert_eq!(s.execute("activity.dismiss", &json!({"id": id})).unwrap()["dismissed"], 1);
assert_eq!(s.execute("activity.dismiss", &json!({"all": true})).unwrap()["dismissed"], 0);
assert_eq!(s.execute("activity.finished", &json!({})).unwrap()["finished"], json!([]));
}

#[test]
fn cancel_all_and_errors() {
let mut s = Session::new();
Expand Down
9 changes: 7 additions & 2 deletions crates/engine/src/cmd/browse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,9 +472,14 @@ fn move_to_folder(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({"moved": 0, "folder": folder}));
}
let plural = |k: usize| if k == 1 { "" } else { "s" };
let _task = s.activity.start("move", &format!("Moving {n} photo{}", plural(n)), crate::activity::Cancel::No);
let task = s.activity.start("move", &format!("Moving {n} photo{}", plural(n)), crate::activity::Cancel::No);
let name = dir.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_else(|| folder.to_string());
s.apply_file_plans(&crate::rename::RealFs, &plans, &|k| format!("Move {k} Photo{} to “{name}”", plural(k)))?;
let moved = s.apply_file_plans(&crate::rename::RealFs, &plans, &|k| format!("Move {k} Photo{} to “{name}”", plural(k)));
task.finish(match &moved {
Ok(_) => crate::activity::Outcome::default(),
Err(e) => crate::activity::Outcome::failed(e.to_string()),
});
moved?;
Ok(json!({"moved": n, "folder": folder}))
}

Expand Down
60 changes: 54 additions & 6 deletions crates/engine/src/cmd/geocode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,14 +146,22 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
let task = (todo.len() > 1).then(|| s.activity.start("geocode", "Looking up places", Cancel::Yes));
let mut ops = Vec::new();
let mut found = Vec::new();
// photos a place was not found for (open country: the sea, a pole): the lookup ran to its end, not for them
let mut missed = 0;
for (n, (id, at)) in todo.iter().enumerate() {
if let Some(t) = &task {
if t.cancel_flag().is_some_and(|f| f.load(std::sync::atomic::Ordering::Relaxed)) {
if let Some(t) = task {
t.finish(crate::activity::Outcome::ended(crate::activity::Ending::Stopped));
}
return Err(bad(C, "cancelled"));
}
t.progress(n as u64, todo.len() as u64);
}
let Some(mut place) = names.reverse(*at) else { continue };
let Some(mut place) = names.reverse(*at) else {
missed += 1;
continue;
};
// too far from the town found: State and Country still hold, City (and below) doesn't
let too_far = max_distance.is_some_and(|m| place.distance > m);
let nearest_city = too_far.then(|| std::mem::take(&mut place.city));
Expand All @@ -172,11 +180,16 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> {
}
found.push(entry);
}
drop(task);
let changed = ops.len();
if !bool_or(p, "dryRun", false) && changed > 0 {
s.commit("Reverse Geocode", Op::Batch { ops })?;
let committed = if !bool_or(p, "dryRun", false) && changed > 0 { s.commit("Reverse Geocode", Op::Batch { ops }) } else { Ok(()) };
if let Some(t) = task {
t.finish(match &committed {
Ok(_) if missed > 0 => crate::activity::Outcome { ending: crate::activity::Ending::Problems, failed: missed, ..Default::default() },
Ok(_) => crate::activity::Outcome::default(),
Err(e) => crate::activity::Outcome::failed(e.to_string()),
});
}
committed?;
Ok(json!({"looked": todo.len(), "found": found.len(), "changed": changed, "photos": found, "attribution": GEONAMES_ATTRIBUTION}))
}

Expand Down Expand Up @@ -264,9 +277,9 @@ mod download {
let thread_dir = dir.clone();
let thread_shared = shared.clone();
let spawned = std::thread::Builder::new().name("place-names-download".into()).spawn(move || {
// the activity row goes when the thread ends, however it ends
let _task = task;
// the activity row says how it ended when the thread ends, however it ends
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&base, &thread_dir, &cancel, &handle)));
let panicked = outcome.is_err();
let outcome = match outcome {
Ok(Ok(n)) => DownloadOutcome::Done(n),
_ if cancel.load(std::sync::atomic::Ordering::Relaxed) => DownloadOutcome::Cancelled,
Expand All @@ -276,10 +289,19 @@ mod download {
if let DownloadOutcome::Failed(e) = &outcome {
log::warn!("{e}");
}
let ended = match &outcome {
_ if panicked => crate::activity::Outcome::ended(crate::activity::Ending::Died),
DownloadOutcome::Done(_) => crate::activity::Outcome::default(),
DownloadOutcome::Cancelled => crate::activity::Outcome::ended(crate::activity::Ending::Stopped),
DownloadOutcome::Failed(why) => crate::activity::Outcome::failed(why.clone()),
};
let mut sh = thread_shared.lock().unwrap_or_else(PoisonError::into_inner);
sh.running = false;
sh.last = Some(outcome.clone());
sh.unreported = Some(outcome);
drop(sh);
// last: whoever sees the row go finds the download over
task.finish(ended);
});
if let Err(e) = spawned {
shared.lock().unwrap_or_else(PoisonError::into_inner).running = false;
Expand Down Expand Up @@ -369,6 +391,32 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}

/// A lookup that ran to its end but found no place for a photo (open country: the sea, a pole) is not a clean end:
/// its row says `Problems` and how many photos had none. When every photo found a place it is `Done`.
#[test]
fn a_lookup_that_found_no_place_for_a_photo_ends_with_problems() {
let dir = dataset("problems");
let mut s = Session::with_demo();
s.activity.keep_after(0);
let ids = s.visible_cloned();
set_gps(&mut s, ids[0], Some((48.86, 2.34)), "");
set_gps(&mut s, ids[1], Some((0.0, 0.0)), "");
set_gps(&mut s, ids[2], Some((51.5, -0.1)), "");
let both = json!({"ids": [ids[0].0, ids[1].0], "dataset": dir});
let r = s.execute("metadata.reverseGeocode", &both).unwrap();
assert_eq!((r["looked"].as_u64(), r["found"].as_u64()), (Some(2), Some(1)), "{r}");
let row = s.activity.finished().into_iter().next().expect("a row for the lookup");
assert_eq!((row.kind, row.ending, row.failed), ("geocode", crate::activity::Ending::Problems, 1));
let mut s = Session::with_demo();
s.activity.keep_after(0);
let ids = s.visible_cloned();
set_gps(&mut s, ids[0], Some((48.86, 2.34)), "");
set_gps(&mut s, ids[1], Some((51.5, -0.1)), "");
s.execute("metadata.reverseGeocode", &json!({"ids": [ids[0].0, ids[1].0], "dataset": dir})).unwrap();
assert!(s.activity.finished().iter().all(|r| r.ending == crate::activity::Ending::Done), "every photo found a place");
let _ = std::fs::remove_dir_all(&dir);
}

/// Issue #2242: the place names hold only towns of 15 000 people or more, so a photo in a
/// village finds the nearest larger town. `maxDistance` leaves City empty past that distance
/// (State and Country still fill) and says which town it was.
Expand Down
42 changes: 33 additions & 9 deletions crates/engine/src/cmd/previews.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use serde_json::{Value, json};

use super::{CommandSpec, always, bad, cmd, str_param};
use crate::activity::{Cancel, TaskGuard};
use crate::activity::{Cancel, Ending, Outcome, TaskGuard};
use crate::media::{RenderJob, THUMB_SIZES};
use crate::{Result, Session};

Expand Down Expand Up @@ -43,7 +43,7 @@ impl PreviewBuild {
"total": self.total,
"done": self.done.load(Ordering::Relaxed),
"failed": self.failed.load(Ordering::Relaxed),
"running": !self.finished.load(Ordering::Relaxed),
"running": !self.finished.load(Ordering::Acquire),
"cancelled": self.cancel.load(Ordering::Relaxed),
"what": if self.what.is_empty() { "previews" } else { self.what },
"repaired": self.repaired.load(Ordering::Relaxed),
Expand All @@ -54,6 +54,30 @@ impl PreviewBuild {
pub fn error(&self) -> Option<String> {
self.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
}

/// How the build ended, for its row: it failed as a whole, was stopped, or could not make some photos' previews.
fn outcome(&self) -> Outcome {
let failed = self.failed.load(Ordering::Relaxed);
if let Some(why) = self.error() {
return Outcome { failed, ..Outcome::failed(why) };
}
let ending = if self.cancel.load(Ordering::Relaxed) {
Ending::Stopped
} else if failed > 0 {
Ending::Problems
} else {
Ending::Done
};
Outcome { ending, failed, ..Default::default() }
}

/// The build is over: the row of how it went is kept, the build reads as finished, and only then does its running
/// row go (whoever waits for `finished` finds the row; whoever sees the running row go finds the build finished).
fn end(&self, mut task: TaskGuard) {
task.report(self.outcome());
self.finished.store(true, Ordering::Release);
drop(task);
}
}

/// The jobs that build `id`'s previews: the largest grid thumbnail and the view render at `edge`
Expand Down Expand Up @@ -226,7 +250,7 @@ pub(crate) mod test_gate {
}
}

fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard, lanes: usize) {
fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: TaskGuard, lanes: usize) {
let total = jobs.len();
let queue = std::sync::Mutex::new(jobs.into_iter());
let work = || {
Expand Down Expand Up @@ -269,7 +293,7 @@ fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard, la
let _ = lanes;
work();
}
state.finished.store(true, Ordering::Relaxed);
state.end(task);
}

fn build(s: &mut Session, p: &Value) -> Result<Value> {
Expand All @@ -282,7 +306,7 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
"full" | "1:1" => None,
other => return Err(bad(C, format!("unknown size `{other}` (standard|full)"))),
};
if s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) {
if s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Acquire)) {
return Err(bad(C, "a preview build is already running"));
}
// explicit ids, else the selection, else everything in view
Expand All @@ -297,7 +321,7 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
let lanes = lanes(jobs.len(), edge.is_none());
let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32");
if wait {
run_all(jobs, &state, &task, lanes);
run_all(jobs, &state, task, lanes);
return Ok(state.json());
}
#[cfg(not(target_arch = "wasm32"))]
Expand All @@ -306,7 +330,7 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
let st = state.clone();
std::thread::Builder::new()
.name("lc-build-previews".into())
.spawn(move || run_all(jobs, &st, &task, lanes))
.spawn(move || run_all(jobs, &st, task, lanes))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.map_err(|e| bad(C, format!("could not start: {e}")))?;
}
Ok(state.json())
Expand Down Expand Up @@ -471,7 +495,7 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
let dir = s.media.smart_dir.clone().ok_or_else(|| bad(C, "smart previews need a library on disk"))?;
let discard = p.get("discard").and_then(Value::as_bool).unwrap_or(false);
let background = p.get("background").and_then(Value::as_bool).unwrap_or(false);
if background && s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Relaxed)) {
if background && s.preview_build.as_ref().is_some_and(|b| !b.finished.load(Ordering::Acquire)) {
return Err(bad(C, "a preview build is already running"));
}
let ids = if p.get("ids").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() };
Expand Down Expand Up @@ -499,7 +523,7 @@ fn smart(s: &mut Session, p: &Value) -> Result<Value> {
log::warn!("{C}: {e}");
*st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e);
}
st.finished.store(true, Ordering::Relaxed);
st.end(task);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})
.map_err(|e| bad(C, format!("could not start: {e}")))?;
return Ok(state.json());
Expand Down
41 changes: 38 additions & 3 deletions crates/engine/src/face_download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use crate::activity::{Activity, Cancel, TaskHandle, Unit};
use crate::activity::{Activity, Cancel, Ending, Outcome, TaskHandle, Unit};

use lightcraft_faces::known::Download;

Expand Down Expand Up @@ -91,15 +91,16 @@ impl Downloads {
let shared = Arc::new(Shared { state: Mutex::new(State::Running { bytes: 0, total }), cancel, task: Some(task.handle()) });
let worker = shared.clone();
let id = spec.id.clone();
let name = name.to_string();
std::thread::Builder::new()
.name("face-model-download".into())
.spawn(move || {
// the row goes when the thread ends, however it ends
let _task = task;
// the row says how it ended when the thread ends, however it ends
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&spec, spec.base(), &staging, &worker)));
if outcome.is_err() {
worker.set(State::Failed("the download stopped unexpectedly".into()));
}
task.finish(if outcome.is_err() { Outcome::ended(Ending::Died) } else { ended(&worker.get()) }.about(&name));
})
.map_err(|e| format!("could not start the download: {e}"))?;
self.jobs.insert(id, shared);
Expand Down Expand Up @@ -222,6 +223,17 @@ fn fetch(_: &Download, _: &str, _: &Path, _: &Shared) -> Result<(), String> {
Err("the web build downloads no models".into())
}

/// How a download that ran ended, for its row.
fn ended(state: &State) -> Outcome {
match state {
State::Done { .. } | State::Installed => Outcome::default(),
State::Failed(why) => Outcome::failed(why.clone()),
State::Cancelled => Outcome::ended(Ending::Stopped),
// (the thread ended without saying how)
State::Running { .. } => Outcome::ended(Ending::Died),
}
}

/// The whole job: reuse a verified earlier copy, else fetch, check and stage. Always ends in a final [`State`].
fn run(spec: &Download, mirror: &str, staging: &Path, shared: &Shared) {
let target = staging.join(&spec.file_name);
Expand Down Expand Up @@ -355,6 +367,29 @@ mod tests {
wait("the download never stopped", || !d.running());
assert_eq!(d.jobs["test-model"].get(), State::Cancelled);
wait("the row stayed", || activity.list().is_empty());
let row = activity.finished().remove(0);
assert_eq!(row.ending, crate::activity::Ending::Stopped, "a stopped download says so");
assert_eq!(row.detail, "Test Model", "the row names the model");
let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_download_that_failed_leaves_a_row_with_the_reason() {
use crate::activity::{Activity, Ending};
let dir = scratch("failed-row");
let activity = Activity::default();
let mut d = Downloads::default();
let mut spec = spec_for(b"abc");
spec.url = format!("{}/{}", serve("404 Not Found", b"not found".to_vec()), spec.file_name);
d.start(spec, &dir, &activity, "Test Model").unwrap();
wait("the failed download's row never ended", || activity.list().is_empty() && !activity.finished().is_empty());
let row = activity.finished().remove(0);
assert_eq!((row.kind, row.ending), ("download", Ending::Failed));
assert!(
row.detail.starts_with("Test Model: ") && row.detail.len() > "Test Model: ".len(),
"the model and the reason are kept: {}",
row.detail
);
let _ = std::fs::remove_dir_all(&dir);
}

Expand Down
Loading
Loading