Repository navigation
LR-BEHAV-BG-TASKS: a background task says how it ended; the engine's own jobs do (part 1 of 3) #1711
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
LR-BEHAV-BG-TASKS: a background task says how it ended; the engine's own jobs do (part 1 of 3) #1711
Changes from all commits
d89aafa
2b391ae
5b2d429
c4d90bd
17cad5d
1233e35
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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)); | ||
|
|
@@ -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})) | ||
| } | ||
|
|
||
|
|
@@ -197,31 +210,63 @@ mod download { | |
| const MAX_ZIP: u64 = 64 * 1024 * 1024; | ||
| const MAX_TEXT: usize = 256 * 1024 * 1024; | ||
|
|
||
| fn get(name: &str, base: &str, dir: &Path, cancel: &AtomicBool, task: &crate::activity::TaskHandle) -> std::result::Result<(), String> { | ||
| /// Why the download stopped: the person canceled it, or something failed. Only the first is `Stopped`; a disk or | ||
| /// mirror error that arrives after the cancel flag was set is still a failure and keeps its reason. | ||
| #[derive(Debug, PartialEq)] | ||
| pub(super) enum Stop { | ||
| Cancelled, | ||
| Failed(String), | ||
| } | ||
|
|
||
| impl From<String> for Stop { | ||
| fn from(e: String) -> Self { | ||
| Self::Failed(e) | ||
| } | ||
| } | ||
|
|
||
| impl std::fmt::Display for Stop { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| match self { | ||
| Self::Cancelled => f.write_str("cancelled"), | ||
| Self::Failed(e) => f.write_str(e), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<lightcraft_fetch::DownloadError> for Stop { | ||
| fn from(e: lightcraft_fetch::DownloadError) -> Self { | ||
| match e { | ||
| lightcraft_fetch::DownloadError::Cancelled => Self::Cancelled, | ||
| e => Self::Failed(e.to_string()), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn get(name: &str, base: &str, dir: &Path, cancel: &AtomicBool, task: &crate::activity::TaskHandle) -> std::result::Result<(), Stop> { | ||
| let _ = std::fs::remove_file(dir.join(name)); | ||
| let file = lightcraft_fetch::FileSpec { name, size: None, sha256: None, max: MAX_ZIP }; | ||
| lightcraft_fetch::download_url(&file, &format!("{base}{name}"), dir, &lightcraft_fetch::Options::default(), cancel, &mut |pr| { | ||
| task.progress(pr.done, pr.total.max(pr.done)) | ||
| }) | ||
| .map_err(|e| e.to_string()) | ||
| .map_err(Stop::from) | ||
| } | ||
|
|
||
| /// Fetch and unpack the place names into `dir`; the new files replace the old ones only when complete. | ||
| pub(super) fn run(base: &str, dir: &Path, cancel: &AtomicBool, task: &crate::activity::TaskHandle) -> std::result::Result<usize, String> { | ||
| pub(super) fn run(base: &str, dir: &Path, cancel: &AtomicBool, task: &crate::activity::TaskHandle) -> std::result::Result<usize, Stop> { | ||
| let staging = dir.join(".download"); | ||
| std::fs::create_dir_all(&staging).map_err(|e| format!("could not create {}: {e}", staging.display()))?; | ||
| get(GEONAMES_ZIP, base, &staging, cancel, task)?; | ||
| let zip = std::fs::read(staging.join(GEONAMES_ZIP)).map_err(|e| e.to_string())?; | ||
| let cities = lightcraft_geocode::unzip::extract(&zip, GEONAMES_FILES[0], MAX_TEXT).map_err(|e| e.to_string())?; | ||
| let places = GeoNames::parse(&String::from_utf8_lossy(&cities), None, None).len(); | ||
| if places == 0 { | ||
| return Err("the downloaded place list is empty".into()); | ||
| return Err(Stop::Failed("the downloaded place list is empty".into())); | ||
| } | ||
| let _ = std::fs::remove_file(staging.join(GEONAMES_ZIP)); | ||
| let write = |name: &str, data: &[u8]| std::fs::write(dir.join(name), data).map_err(|e| format!("could not save {name}: {e}")); | ||
| for name in &GEONAMES_FILES[1..] { | ||
| // optional: without them states stay blank and countries are ISO codes | ||
| match get(name, base, &staging, cancel, task).and_then(|()| std::fs::read(staging.join(name)).map_err(|e| e.to_string())) { | ||
| match get(name, base, &staging, cancel, task).and_then(|()| std::fs::read(staging.join(name)).map_err(|e| Stop::Failed(e.to_string()))) { | ||
| Ok(b) => write(name, &b)?, | ||
| Err(e) => log::warn!("place names: {name}: {e}"), | ||
| } | ||
|
|
@@ -232,6 +277,19 @@ mod download { | |
| Ok(places) | ||
| } | ||
|
|
||
| /// How the download ended, from what the worker returned (or the panic it died of). Only a real cancel is `Cancelled`: | ||
| /// a failure is a failure even when the cancel flag happens to be set by then. | ||
| pub(super) fn outcome_of(r: std::thread::Result<std::result::Result<usize, Stop>>) -> DownloadOutcome { | ||
| match r { | ||
| Ok(Ok(n)) => DownloadOutcome::Done(n), | ||
| Ok(Err(Stop::Cancelled)) => DownloadOutcome::Cancelled, | ||
| Ok(Err(Stop::Failed(e))) => { | ||
| DownloadOutcome::Failed(format!("Could not download the place names: {e}. Check the connection and try again.")) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
| Err(_) => DownloadOutcome::Failed("The place names download stopped unexpectedly. Try again.".into()), | ||
| } | ||
| } | ||
|
|
||
| /// A download base: https, or plain http to this machine's loopback address only (a test | ||
| /// server), with nothing but a port or path after the host, so `http://127.0.0.1.example.com/` | ||
| /// is refused. | ||
|
|
@@ -264,22 +322,26 @@ 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 outcome = match outcome { | ||
| Ok(Ok(n)) => DownloadOutcome::Done(n), | ||
| _ if cancel.load(std::sync::atomic::Ordering::Relaxed) => DownloadOutcome::Cancelled, | ||
| Ok(Err(e)) => DownloadOutcome::Failed(format!("Could not download the place names: {e}. Check the connection and try again.")), | ||
| Err(_) => DownloadOutcome::Failed("The place names download stopped unexpectedly. Try again.".into()), | ||
| }; | ||
| let panicked = outcome.is_err(); | ||
| let outcome = outcome_of(outcome); | ||
| 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; | ||
|
|
@@ -369,6 +431,34 @@ 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(); | ||
| let rows = s.activity.finished(); | ||
| assert!(!rows.is_empty(), "a row for the lookup"); | ||
| assert!(rows.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. | ||
|
|
@@ -516,6 +606,22 @@ mod tests { | |
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
|
|
||
| /// What the worker returned decides the ending, not the cancel flag (which may be set when a disk or mirror error | ||
| /// arrives): the row says `Failed` with the reason, and only the downloader's own `Cancelled` is `Stopped`. | ||
| #[cfg(not(target_arch = "wasm32"))] | ||
| #[test] | ||
| fn a_download_error_is_not_a_cancel_even_with_the_cancel_flag_set() { | ||
| use lightcraft_fetch::DownloadError; | ||
| for e in [DownloadError::Disk("disk full".into()), DownloadError::AllMirrorsFailed { file: "f".into(), errors: vec!["404".into()] }] { | ||
| let reason = e.to_string(); | ||
| let DownloadOutcome::Failed(why) = download::outcome_of(Ok(Err(download::Stop::from(e)))) else { panic!("a failure") }; | ||
| assert!(why.contains(&reason), "{why}"); | ||
| } | ||
| assert_eq!(download::outcome_of(Ok(Err(download::Stop::from(DownloadError::Cancelled)))), DownloadOutcome::Cancelled); | ||
| assert_eq!(download::outcome_of(Ok(Ok(3))), DownloadOutcome::Done(3)); | ||
| assert!(matches!(download::outcome_of(Err(Box::new("boom"))), DownloadOutcome::Failed(_))); | ||
| } | ||
|
|
||
| #[test] | ||
| fn download_base_is_https_or_loopback_only() { | ||
| assert!(download::base_allowed("https://download.geonames.org/export/dump/")); | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
rg -n 'fn download_url|DownloadError::Cancelled|for name in &GEONAMES_FILES|outcome_of\(outcome\)' crates/fetch/src crates/engine/src/cmd/geocode.rsRepository: storytold/lightcraft
Length of output: 1036
Script executed:
Repository: storytold/lightcraft
Length of output: 12644
Script executed:
Repository: storytold/lightcraft
Length of output: 19077
Script executed:
Repository: storytold/lightcraft
Length of output: 5354
Return cancellation from the optional-file loop.
The loop at
geocode.rs:267-274logs aStop::Cancellederror and continues. The task then writes the main file and returnsOk, so the activity row ends as Done, not Stopped. ReturnStop::Cancelledwhen a cancel reaches an optional file.Suggested fix
Committable suggestion
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Real, and handled one layer up. The optional-file loop is older than this PR (
b28b05c475), and it has always endedDoneafter a cancel. #3151 ("a place-name download that missed optional files ends with problems, and a cancel during one is stopped") is what changes that: itsfetch_optionalreturnsStop::Cancelledon a cancel, with a test. Moving it down into this PR would restack #3150, #3151, #1649 and #1933 for behavior that predates this PR, so I'm leaving this PR as it is.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@nledford Understood. Keeping the fix in
#3151avoids restacking the dependent PRs for pre-existing behavior. I won’t request this change in#1711. The finding remains valid but is deferred to#3151, not fixed here.Learnings used
You are interacting with an AI system.