Skip to content
Open
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
59 changes: 59 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,24 @@ pub enum EngineError {

pub type Result<T> = std::result::Result<T, EngineError>;

/// [`Session::before_step`]: the commit count and the length of the queue of ops not yet written to the library's log.
#[derive(Clone, Copy, Debug)]
pub(crate) struct BeforeStep {
commits: u64,
log: usize,
}

/// One step a command has just committed ([`Session::committed_step`]), to take back if the command then fails.
#[derive(Clone, Copy, Debug)]
pub(crate) struct CommittedStep {
/// [`Session::commits`] with the step committed.
commits: u64,
/// The undo stack's length with the step on top.
undo_len: usize,
/// Where the step's op waits in the queue for the library's log, while it hasn't been written.
pending: Option<usize>,
}

/// One undo step: the inverse op and a label.
#[derive(Clone, Debug)]
pub struct UndoEntry {
Expand Down Expand Up @@ -797,6 +815,47 @@ impl Session {
});
}

/// Where things stand before a command commits a step it may have to take back if it then fails
/// ([`Session::committed_step`]).
pub(crate) fn before_step(&self) -> BeforeStep {
BeforeStep { commits: self.commits, log: self.pending_log.len() }
}

/// The one step committed since `before`, for [`Session::take_back`]; `None` when no step, or more than one, was
/// committed since.
pub(crate) fn committed_step(&self, before: BeforeStep) -> Option<CommittedStep> {
(self.commits == before.commits.wrapping_add(1) && !self.undo.is_empty()).then(|| CommittedStep {
commits: self.commits,
undo_len: self.undo.len(),
pending: (self.pending_log.len() == before.log.saturating_add(1)).then_some(before.log),
})
}

/// Take back `step`, the step a command committed before it failed, as an undo would, with nothing left to redo.
/// Only that step: when anything was committed, undone or merged ([`Session::merge_undo`]) since it, the top of the
/// undo stack may be a step that isn't the command's, and this refuses instead. When the step isn't written to the
/// library's log yet, it leaves the queue, so neither it nor its reversal reaches the disk; otherwise the reversal
/// is logged like an undo. A step that can't be taken back stays on the undo stack, and the error says why.
pub(crate) fn take_back(&mut self, step: CommittedStep) -> Result<()> {
// A later commit changes the count; an undo, a redo or a merge changes the stack's length (at the cap a commit
// leaves the length as it was, but changes the count).
if self.commits != step.commits || self.undo.len() != step.undo_len {
return Err(EngineError::Other("the step to take back is no longer the last one".into()));
}
let mut e = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to take back".into()))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. Preserve the existing history when an import rolls back. The temporary file step commits first, which clears existing redo entries and can evict the oldest undo entry at the limit. Taking back the new catalog step does not restore them. Undo an edit and then attempt an import that fails during Lightroom metadata: the unrelated Redo is gone. Delay those history changes until success, or restore the pre-existing entries during rollback. Extend the failed-import fixture with an unrelated redo action.

if let Err(err) = self.apply_with_files(&mut e, &rename::RealFs) {
self.undo.push(e);
return Err(err);
}
// Dropping the queued step, rather than logging its reversal after it, keeps a write cut short (a crash, a full
// disk) from saving the step without its reversal: each op is its own record in the log.
match step.pending.filter(|at| at.saturating_add(1) == self.pending_log.len()) {
Some(at) => self.pending_log.truncate(at),
None => self.pending_log.push(e.op),
}
Ok(())
}

/// Apply without recording undo (interactive previews).
fn apply_silent(&mut self, op: Op) -> Result<()> {
self.catalog.apply(op)?;
Expand Down
151 changes: 151 additions & 0 deletions crates/engine/src/lightroom_catalog/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1245,6 +1245,157 @@ fn two_catalogs_at_the_same_path_keep_their_own_albums() {
let _ = std::fs::remove_dir_all(&root);
}

/// A catalog whose original `Photos/test.ARW` is on disk below `photos`, with the collection “Keepers” holding it and,
/// when given, the catalog's own id; written to `path`.
fn catalog_with_original(path: &Path, photos: &Path, catalog_id: Option<&str>) {
use SqlValue::{Integer as I, Null as N, Text as T};
let mut tables = one_row(photo_tables((photos.to_str().unwrap(), "")));
tables.push((
"AgLibraryCollection",
"id_local INTEGER PRIMARY KEY, creationId, name, parent, systemOnly",
vec![vec![N, T("com.adobe.ag.library.collection".into()), T("Keepers".into()), N, I(0)]],
));
tables.push(("AgLibraryCollectionImage", "id_local INTEGER PRIMARY KEY, collection, image", vec![vec![N, I(1), I(1)]]));
if let Some(id) = catalog_id {
tables.push((
"Adobe_variablesTable",
"id_local INTEGER PRIMARY KEY, id_global, name, type, value",
vec![vec![N, T("v1".into()), T("Adobe_storeProviderID".into()), N, T(id.into())]],
));
}
std::fs::create_dir_all(photos.join("Photos")).unwrap();
std::fs::write(photos.join("Photos/test.ARW"), photos.to_string_lossy().as_bytes()).unwrap();
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, native_catalog_rows(&tables, None)).unwrap();
}

/// What a library holds, to compare before and after an import: each photo's id, file, rating and flag, and each
/// album's id, name and photos.
fn library_state(s: &crate::Session) -> (Vec<(u64, String, u8, Flag)>, Vec<(u64, String, Vec<PhotoId>)>) {
let mut photos: Vec<_> = s.catalog.photos().map(|p| (p.id.0, source_path(p).unwrap_or_default().to_string(), p.rating, p.flag)).collect();
photos.sort_by_key(|p| p.0);
let mut albums: Vec<_> = s.catalog.albums().map(|a| (a.id.0, a.name.clone(), a.photos.clone())).collect();
albums.sort_by_key(|a| a.0);
(photos, albums)
}

/// An import that fails after it has added the catalog's originals takes them back: the library, its undo history,
/// its file on disk and the import index are as they were, and the error still says why. The failure here is the
/// collections' (a catalog without an id at a path an earlier catalog with one had); the originals are added before.
#[test]
fn a_failed_import_takes_back_the_originals_it_added() {
let root = std::env::temp_dir().join(format!("lightcraft-lrcat-failed-import-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let catalog = root.join("Lightroom").join("Cat.lrcat");
let lib = root.join("Library");
let mut s = crate::Session::new();
s.media.file_probe = Some(Arc::new(|_| Ok(crate::media::ProbeInfo { format: "ARW".into(), width: 20, height: 10, ..Default::default() })));
s.open_library(&lib, false).unwrap();
catalog_with_original(&catalog, &root.join("first"), Some("968AF29B-EEE2-481E-8AF9-55DD82965F49"));
s.execute("library.importLightroom", &json!({"path": catalog})).unwrap();
let before = library_state(&s);
assert_eq!((before.0.len(), before.1.len()), (1, 1), "{before:?}");
assert_eq!(s.undo.len(), 1, "an import that succeeds is one undo step, its originals' records with the rest");
let index = std::fs::read(lib.join("Interop/lightroom-index.json")).unwrap();
// the same path, now a catalog without an id whose original isn't in the library yet
catalog_with_original(&catalog, &root.join("second"), None);
let err = s.execute("library.importLightroom", &json!({"path": catalog})).unwrap_err().to_string();
assert!(err.contains("no stable identity"), "{err}");
assert_eq!(library_state(&s), before, "the original the import added is taken back");
assert_eq!(s.undo.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["Import Lightroom Catalog"], "only the first import's step");
assert!(s.redo.is_empty());
assert_eq!(std::fs::read(lib.join("Interop/lightroom-index.json")).unwrap(), index);
assert!(root.join("second/Photos/test.ARW").is_file(), "the original stays where it was");
// and so is the library on disk (its log: closing would write a snapshot of the library in memory)
drop(s);
let log = std::fs::read_to_string(lib.join(lightcraft_catalog::journal::LOG)).unwrap();
assert!(log.contains("first/Photos/test.ARW"), "the log holds the first import");
// neither the records nor their removal: a write cut short can't keep one without the other
assert!(!log.contains("second/Photos/test.ARW"), "the failed import reached the log");
let mut reopened = crate::Session::new();
reopened.open_library(&lib, false).unwrap();
assert_eq!(library_state(&reopened), before);
reopened.close_library().unwrap();
let _ = std::fs::remove_dir_all(&root);
}

/// A catalog of the files `names` below `photos/Photos/` (each written there), with each photo's Lightroom capture time.
fn catalog_with_capture_times(path: &Path, photos: &Path, names: &[(&str, &str)]) {
use SqlValue::{Integer as I, Null as N, Text as T};
let rows = |row: fn(i64, &str, &str) -> Vec<SqlValue>| names.iter().zip(1..).map(|(&(name, time), i)| row(i, name, time)).collect();
let tables: Vec<(&str, &str, Vec<Vec<SqlValue>>)> = vec![
(
"AgLibraryRootFolder",
"id_local INTEGER PRIMARY KEY, absolutePath, name, relativePathFromCatalog",
vec![vec![N, T(photos.to_str().unwrap().into()), T("Photos".into()), T(String::new())]],
),
("AgLibraryFolder", "id_local INTEGER PRIMARY KEY, rootFolder, pathFromRoot", vec![vec![N, I(1), T("Photos/".into())]]),
("AgLibraryFile", "id_local INTEGER PRIMARY KEY, folder, idx_filename", rows(|_, name, _| vec![N, I(1), T(name.into())])),
(
"Adobe_images",
"id_local INTEGER PRIMARY KEY, id_global, rootFile, fileFormat, fileWidth, fileHeight, rating, pick, captureTime",
rows(|i, name, time| vec![N, T(format!("image-{name}")), I(i), T("ARW".into()), I(20), I(10), I(4), I(1), T(time.into())]),
),
];
std::fs::create_dir_all(photos.join("Photos")).unwrap();
for (name, _) in names {
std::fs::write(photos.join("Photos").join(name), name.as_bytes()).unwrap();
}
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, native_catalog_rows(&tables, None)).unwrap();
}

/// A photo Lightroom dates by its year alone (a scanned print, #3501) fails the catalog step of an import on this
/// version. The photos the import's file step touched are then as they were: the one it added is gone, the one
/// browsed in Local is Local again, the one already in the library is unchanged; the undo history is too. The redo
/// history is not kept: the file step's commit cleared it, as any new step does.
#[test]
fn a_failed_import_leaves_the_photos_that_were_there_as_they_were() {
let root = std::env::temp_dir().join(format!("lightcraft-lrcat-failed-capture-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let photos = root.join("photos");
let catalog = root.join("Lightroom").join("Cat.lrcat");
let lib = root.join("Library");
catalog_with_capture_times(&catalog, &photos, &[("local.ARW", "2001-02-03T04:05:06"), ("there.ARW", "2002-03-04T05:06:07"), ("new.ARW", "2004")]);
let file = |name: &str| photos.join("Photos").join(name).to_string_lossy().into_owned();
let mut s = crate::Session::new();
s.media.file_probe = Some(Arc::new(|_| Ok(crate::media::ProbeInfo { format: "ARW".into(), width: 20, height: 10, ..Default::default() })));
s.open_library(&lib, false).unwrap();
let add = |s: &mut crate::Session, name: &str, local: bool| {
let mut p = Photo::new(s.catalog.alloc_photo_id(), Source::File { path: file(name) }, name, "ARW", 20, 10, "before");
p.local = local;
p.rating = 2;
s.commit("Add", Op::AddPhoto { photo: Box::new(p) }).unwrap();
};
add(&mut s, "local.ARW", true);
add(&mut s, "there.ARW", false);
let there = s.catalog.photos().find(|p| p.file_name == "there.ARW").unwrap().id;
s.commit("Rating", Op::SetRating { id: there, rating: 5 }).unwrap();
s.undo_step().unwrap();
let photos_now = |s: &crate::Session| {
let mut all: Vec<_> = s.catalog.photos().map(|p| serde_json::to_value(&**p).unwrap()).collect();
all.sort_by_key(|p| p["id"].as_u64());
all
};
let before = photos_now(&s);
let undo: Vec<_> = s.undo.iter().map(|e| e.label.clone()).collect();
assert_eq!((before.len(), s.redo.len()), (2, 1));
let err = s.execute("library.importLightroom", &json!({"path": catalog})).unwrap_err().to_string();
assert!(err.contains("not a date: 2004"), "{err}");
assert_eq!(photos_now(&s), before, "the added photo is gone and the others are as they were (the Local one still Local)");
assert!(s.catalog.photos().any(|p| p.file_name == "local.ARW" && p.local));
assert_eq!(s.undo.iter().map(|e| e.label.clone()).collect::<Vec<_>>(), undo);
assert!(s.redo.is_empty(), "the file step's commit cleared the redo history");
drop(s);
let mut reopened = crate::Session::new();
reopened.open_library(&lib, false).unwrap();
assert_eq!(reopened.catalog.len(), 2);
assert!(reopened.catalog.photos().all(|p| p.file_name != "new.ARW"));
assert!(reopened.catalog.photos().any(|p| p.file_name == "local.ARW" && p.local), "still Local after reopening");
reopened.close_library().unwrap();
let _ = std::fs::remove_dir_all(&root);
}

/// Libraries imported by earlier releases (path keys) still find their albums.
#[test]
fn collections_imported_before_the_catalog_id_was_read_are_still_matched_by_path() {
Expand Down
102 changes: 100 additions & 2 deletions crates/engine/src/lightroom_job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,10 @@ pub fn commit_prepared(s: &mut crate::Session, mut prepared: PreparedLightroom)
prepared.normal.revalidate_add(s);
let options = ImportOptions { mode: ImportMode::Add, on_deleted: crate::import::OnDeleted::Skip, ..ImportOptions::default() };
let now = prepared.now.clone();
let before = s.before_step();
let files = crate::import::commit_prepared(s, &options, &now, prepared.normal)?;
let applied = lightroom_catalog::apply_prepared(
let file_step = s.committed_step(before);
let applied = match lightroom_catalog::apply_prepared(
s,
prepared.data,
lightroom_catalog::ApplyPrepared {
Expand All @@ -314,7 +316,20 @@ pub fn commit_prepared(s: &mut crate::Session, mut prepared: PreparedLightroom)
missing_sources: &prepared.missing_sources,
undo0,
},
)?;
) {
Ok(applied) => applied,
// The file step has made the catalog's originals records, and photos browsed in Local the library's. A catalog
// the import then can't apply (a capture time that isn't a full date, collections it can't match safely, an
// album id it can't give) must not leave them so, without the catalog's ratings, flags, edits or collections,
// while it reports only the error: take that step back. It is records only: Add moves and copies no file.
Err(e) => {
let Some(step) = file_step else { return Err(e) };
return Err(match s.take_back(step) {
Ok(()) => e,
Err(back) => crate::EngineError::Other(format!("{e}; the photos it added could not be taken back: {back}")),
});
}
};
let path = prepared.token.library_dir().map(|dir| dir.join("Interop/lightroom-index.json"));
let bytes = if path.is_some() { Some(serde_json::to_vec(&applied.index).map_err(|e| error(e.to_string()))?) } else { None };
Ok(LightroomCompletion { report: applied.report, finalization: LightroomArchiveFinalization { path, bytes } })
Expand Down Expand Up @@ -574,6 +589,89 @@ mod tests {
std::fs::remove_dir_all(archive_dir).unwrap();
}

fn album_step(s: &mut crate::Session, name: &str) -> lightcraft_catalog::AlbumId {
let id = s.catalog.alloc_album_id();
s.commit(name, lightcraft_catalog::Op::AddAlbum { album: lightcraft_catalog::Album::new(id, name) }).unwrap();
id
}

fn undo_labels(s: &crate::Session) -> Vec<String> {
s.undo.iter().map(|e| e.label.clone()).collect()
}

/// The take-back a failed import uses reverses its own step and nothing older: a step committed, merged or undone
/// after it means the top of the undo stack may be someone else's, and it refuses.
#[test]
fn a_take_back_refuses_once_its_step_is_no_longer_the_last() {
type Change = fn(&mut crate::Session);
let changes: [(&str, Change); 3] = [
("committed", |s| {
album_step(s, "later");
}),
("merged", |s| s.merge_undo(2, "merged")),
("undone", |s| {
s.undo_step().unwrap();
}),
];
for (what, change) in changes {
let mut s = crate::Session::new();
album_step(&mut s, "mine");
let before = s.before_step();
album_step(&mut s, "import");
let step = s.committed_step(before).unwrap();
change(&mut s);
let (albums, undo) = (s.catalog.albums().count(), undo_labels(&s));
let e = s.take_back(step).unwrap_err();
assert!(e.to_string().contains("no longer the last one"), "{what}: {e}");
assert_eq!((s.catalog.albums().count(), undo_labels(&s)), (albums, undo), "{what}: nothing was taken back");
}
// no step, or two, since: nothing to take back
let mut s = crate::Session::new();
let before = s.before_step();
assert!(s.committed_step(before).is_none());
album_step(&mut s, "one");
album_step(&mut s, "two");
assert!(s.committed_step(before).is_none());
}

/// The step leaves the queue for the library's log when it hasn't been written, so neither it nor its reversal
/// reaches the disk; once written, its reversal is logged after it, as an undo's is.
#[test]
fn a_take_back_drops_an_unwritten_step_and_logs_the_reversal_of_a_written_one() {
for written in [false, true] {
let mut s = crate::Session::new();
album_step(&mut s, "mine");
let before = s.before_step();
let id = album_step(&mut s, "import");
let step = s.committed_step(before).unwrap();
let log = if written { s.drain_log() } else { Vec::new() };
s.take_back(step).unwrap();
assert!(s.catalog.album(id).is_none());
assert_eq!(undo_labels(&s), ["mine"], "written: {written}");
assert!(s.redo.is_empty(), "nothing to redo");
let queued = s.drain_log();
if written {
assert_eq!(log.len(), 2);
assert!(matches!(queued.as_slice(), [lightcraft_catalog::Op::RemoveAlbum { id: removed }] if *removed == id), "{queued:?}");
} else {
assert!(matches!(queued.as_slice(), [lightcraft_catalog::Op::AddAlbum { album }] if album.name == "mine"), "{queued:?}");
}
}
}

/// A step whose reversal the catalog refuses stays on the undo stack, and the error says why.
#[test]
fn a_step_that_cannot_be_taken_back_stays_on_the_undo_stack() {
let mut s = crate::Session::new();
let before = s.before_step();
let id = album_step(&mut s, "import");
let step = s.committed_step(before).unwrap();
// the album goes behind the step's back: its reversal (removing it) has nothing to remove
s.apply_system(lightcraft_catalog::Op::RemoveAlbum { id }).unwrap();
assert!(s.take_back(step).is_err());
assert_eq!(undo_labels(&s), ["import"]);
}

#[test]
fn execute_fn_import_does_not_rewrite_source_sidecar() {
let dir = std::env::temp_dir().join(format!("lightcraft-lr-job-sidecar-{}", std::process::id()));
Expand Down
Loading
Loading