1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-12-04 18:56:44 +01:00

fix: link a capture job to its run as soon as the run exists

capture_jobs.run_uid was only set when the job ended, so a non-admin creator
could not see their own in-progress run in /runs. CaptureConfig carries the
job uid and perform_capture / perform_text_capture_for_job link it right after
create_archive_run (best effort, once only).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
TheGeneralist 2026-10-09 19:44:36 +02:00
parent 0833a6a2f2
commit ba9c21b480
Signed by: thegeneralist01
SSH key fingerprint: SHA256:pp9qddbCNmVNoSjevdvQvM5z0DHN7LTa8qBMbcMq/R4
4 changed files with 118 additions and 1 deletions

View file

@ -110,6 +110,9 @@ pub struct CaptureConfig {
pub sync: bool,
/// Download subtitles for YouTube videos (manual preferred, auto fallback). Default true.
pub download_subtitles: bool,
/// `capture_jobs` row to link to the run as soon as the run exists, so the job's creator
/// can see the in-progress run (the job otherwise learns its `run_uid` only when it ends).
pub job_uid: Option<String>,
}
impl Default for CaptureConfig {
@ -124,6 +127,7 @@ impl Default for CaptureConfig {
per_item_quality: HashMap::new(),
sync: false,
download_subtitles: true,
job_uid: None,
}
}
}
@ -1217,6 +1221,16 @@ fn fail_run(
anyhow::anyhow!("{}", message)
}
/// Records `run_uid` on the capture job (if any) the moment the run exists. Best effort: a
/// failure must never fail the capture itself, it only delays the link until the job ends.
fn link_job_to_run(conn: &rusqlite::Connection, job_uid: Option<&str>, run_uid: &str) {
if let Some(job_uid) = job_uid {
if let Err(e) = database::link_capture_job_run(conn, job_uid, run_uid) {
eprintln!("warn: could not link capture job {job_uid} to run {run_uid}: {e:#}");
}
}
}
pub fn perform_capture(
archive_paths: &ArchivePaths,
locator: &str,
@ -1245,6 +1259,7 @@ pub fn perform_capture(
// Create the run record before probing so every attempt — including
// probe failures — is visible in /runs with a proper status and error.
let run = database::create_archive_run(&conn, user_id, 1)?;
link_job_to_run(&conn, config.job_uid.as_deref(), &run.run_uid);
// For generic http/https URLs, probe Content-Type to decide whether to
// treat the URL as a raw file download or an HTML page for SingleFile.
@ -2130,11 +2145,23 @@ pub fn perform_capture(
/// * Unsupported MIME type
/// * Database or file system errors
pub fn perform_text_capture(
archive_paths: &ArchivePaths,
title: &str,
body: &str,
mime: &str,
archive_id: Option<&str>,
) -> Result<CaptureResult> {
perform_text_capture_for_job(archive_paths, title, body, mime, archive_id, None)
}
/// [`perform_text_capture`] for a capture job: links `job_uid` to the run as soon as it exists.
pub fn perform_text_capture_for_job(
archive_paths: &ArchivePaths,
title: &str,
body: &str,
mime: &str,
_archive_id: Option<&str>,
job_uid: Option<&str>,
) -> Result<CaptureResult> {
// Validate title
let title = title.trim();
@ -2172,6 +2199,7 @@ pub fn perform_text_capture(
// Create run and item
let run = database::create_archive_run(&conn, user_id, 1)?;
link_job_to_run(&conn, job_uid, &run.run_uid);
let source_kind = "text";
let entity_kind = "document";
let item = database::create_archive_run_item(
@ -3052,6 +3080,51 @@ mod tests {
let _ = fs::remove_dir_all(&base_path);
}
#[test]
fn capture_links_its_job_to_the_run_as_soon_as_the_run_exists() {
let base_path = env::temp_dir().join(format!(
"archivr-job-link-test-{}",
Local::now().format("%Y%m%d%H%M%S%3f")
));
let _ = fs::remove_dir_all(&base_path);
let store_path = base_path.join("store");
let archive_path = base_path.join(".archivr");
archive::initialize_store_directories(&store_path).unwrap();
fs::create_dir_all(&archive_path).unwrap();
fs::write(archive_path.join("name"), "test-archive").unwrap();
fs::write(archive_path.join("store_path"), store_path.to_str().unwrap()).unwrap();
let archive_paths = ArchivePaths {
archive_path: archive_path.clone(),
store_path,
name: "test-archive".to_string(),
};
let conn = database::open_or_initialize(&archive_path).unwrap();
let linked = database::create_capture_job_as(&conn, "test", Some("user_x")).unwrap();
let unlinked = database::create_capture_job_as(&conn, "test", Some("user_x")).unwrap();
let result = perform_text_capture_for_job(
&archive_paths, "Linked", "body", "text/plain", None, Some(&linked),
)
.unwrap();
// The job row was never moved out of `pending` (that is the server's job at the end of
// the capture), yet it already points at the run, so its creator can see the run.
let job = database::get_capture_job(&conn, &linked).unwrap().unwrap();
assert_eq!(job.status, "pending");
assert_eq!(job.run_uid.as_deref(), Some(result.run_uid.as_str()));
// The plain entry point and an unrelated job are untouched.
perform_text_capture(&archive_paths, "Plain", "body", "text/plain", None).unwrap();
assert_eq!(database::get_capture_job(&conn, &unlinked).unwrap().unwrap().run_uid, None);
// Linking is once-only: a later run never overwrites the first one.
database::link_capture_job_run(&conn, &linked, "run_other").unwrap();
let job = database::get_capture_job(&conn, &linked).unwrap().unwrap();
assert_eq!(job.run_uid.as_deref(), Some(result.run_uid.as_str()));
let _ = fs::remove_dir_all(&base_path);
}
#[test]
fn test_text_capture_plain() {
let base_path = env::temp_dir().join(format!(

View file

@ -1693,6 +1693,17 @@ pub fn update_capture_job_status(
Ok(())
}
/// Links a capture job to the run it is executing, once, as soon as the run exists. Does
/// nothing if the job already has a run (the final status update sets it again anyway).
pub fn link_capture_job_run(conn: &Connection, job_uid: &str, run_uid: &str) -> Result<()> {
conn.execute(
"UPDATE capture_jobs SET run_uid = ?2, updated_at = ?3 \
WHERE job_uid = ?1 AND run_uid IS NULL",
params![job_uid, run_uid, now_timestamp()],
)?;
Ok(())
}
/// Returns a capture job by uid.
pub fn get_capture_job(conn: &Connection, job_uid: &str) -> Result<Option<CaptureJobRecord>> {
conn.query_row(

View file

@ -546,6 +546,35 @@ mod tests {
assert_eq!(run_uids(&l).len(), 2);
}
#[tokio::test]
async fn creator_sees_their_run_while_the_job_is_still_in_progress() {
let f = fixture();
let alice = make_role_session(&f.auth_path, "alice", &["user"]);
let bob = make_role_session(&f.auth_path, "bob", &["user"]);
let alice_uid = user_uid(&f.auth_path, "alice");
// A job that created its run but has not finished: still `pending` in the jobs table.
let job_uid = {
let conn = database::open_or_initialize(&f.archive_path).unwrap();
database::create_capture_job_as(&conn, "test", Some(&alice_uid)).unwrap()
};
let paths = archivr_core::archive::read_archive_paths(&f.archive_path).unwrap();
let result = archivr_core::capture::perform_text_capture_for_job(
&paths, "In flight", "body", "text/plain", None, Some(&job_uid),
)
.unwrap();
hide_all_entries_from_users(&f.archive_path);
let runs = "/api/archives/test/runs";
let (_, l) = get(&f.router, runs, Some(&alice)).await;
assert_eq!(run_uids(&l), vec![result.run_uid.clone()], "the creator sees it at once");
let (_, l) = get(&f.router, runs, Some(&bob)).await;
assert!(run_uids(&l).is_empty(), "other users see neither the run nor its entry");
let conn = database::open_or_initialize(&f.archive_path).unwrap();
let job = database::get_capture_job(&conn, &job_uid).unwrap().unwrap();
assert_eq!(job.status, "pending");
}
#[tokio::test]
async fn runs_support_limit_and_offset() {
let f = fixture();

View file

@ -1744,6 +1744,7 @@ async fn capture_handler(
download_subtitles: body.download_subtitles.unwrap_or(true),
per_item_quality: body.per_item_quality.clone(),
sync: body.sync,
job_uid: Some(job_uid.clone()),
};
// Spawn background capture.
@ -1897,12 +1898,13 @@ async fn capture_text_handler(
};
database::update_capture_job_status(&conn, &job_uid_bg, "running", None, None, None).ok();
match capture::perform_text_capture(
match capture::perform_text_capture_for_job(
&archive_paths,
&title,
&text_body,
&mime_str,
Some(&archive_id_bg),
Some(&job_uid_bg),
) {
Ok(result) => {
let job_status = if result.status == "completed" {
@ -2144,6 +2146,8 @@ async fn rearchive_handler(
download_subtitles: true,
per_item_quality: std::collections::HashMap::new(),
sync: false,
// Rearchive replaces an entry's artifacts in place and creates no run to link.
job_uid: None,
};
let job_uid_bg = job_uid.clone();