Files
Jellymove/crates/jm-transfer/tests/transfer.rs
T
IxianPixel 484ac50508
CI / test (push) Successful in 1m14s
Move a single season of a TV show (#4)
Shows can be expanded to list their seasons, each with its size and its own Dry run / Move buttons. A season joins the same show on the other
server, so finished seasons can go to the big server while the current one stays on the fast one.

- Source exports a season from the show folder, with a manifest of just that season's folder plus the show's loose non-video files. Refuses
  seasons with no folder of their own, or whose folder holds otherseasons' episodes.
- Destination finds the show by provider ID, then name. If it already has the show, the show's own files are skipped (Job.skip_files) and
  never overwritten; otherwise they come with the season. Refuses if the season folder already exists.
- Only episode watch state is carried for a season.
- Source trashes just the season folder; after the last season, the leftover show folder joins it in the same trash entry if no videos
  remain. The chosen trash entry is saved so a re-run after a crash finishes in the same place.
- New GET /seasons (UI and peer). Fake Jellyfin gains season items.
- e2e tests: season into a new show, into an existing show, last season leaving, destination already has the season, misfiled episodes.
2026-11-06 17:02:40 +00:00

276 lines
9.4 KiB
Rust

//! End-to-end tests: a real axum source, a real puller, real files on disk.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use axum::Router;
use axum::body::{Body, Bytes};
use axum::extract::{Path, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use jm_transfer::{
Puller, PullerOptions, build_manifest, part_path, partial_dir, prepare_partial, promote,
};
#[derive(Clone)]
struct Src {
root: PathBuf,
rels: Arc<Vec<String>>,
/// When non-zero, the next request is cut off after this many bytes.
cut_after: Arc<AtomicUsize>,
requests: Arc<AtomicUsize>,
/// Requests that asked to resume with a Range header.
ranged: Arc<AtomicUsize>,
}
async fn file(State(s): State<Src>, Path(idx): Path<usize>, headers: HeaderMap) -> Response {
s.requests.fetch_add(1, Ordering::SeqCst);
if headers.contains_key(header::RANGE) {
s.ranged.fetch_add(1, Ordering::SeqCst);
}
let Some(rel) = s.rels.get(idx) else {
return StatusCode::NOT_FOUND.into_response();
};
let path = s.root.join(rel);
let cut = s.cut_after.swap(0, Ordering::SeqCst);
if cut == 0 {
return jm_transfer::range_response(&path, &headers).await;
}
// Simulate a dropped link: promise the whole file, send part, then error.
let data = std::fs::read(&path).unwrap();
let head = Bytes::from(data[..cut].to_vec());
let stream = futures::stream::iter(vec![
Ok::<_, std::io::Error>(head),
Err(std::io::Error::other("link dropped")),
]);
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_LENGTH, data.len())
.body(Body::from_stream(stream))
.unwrap()
}
struct Fixture {
_src_dir: tempfile::TempDir,
dst_dir: tempfile::TempDir,
src: Src,
base: String,
}
async fn fixture() -> Fixture {
let src_dir = tempfile::tempdir().unwrap();
let item = src_dir.path().join("Alien (1979)");
std::fs::create_dir_all(item.join("extras")).unwrap();
// 3 MiB of non-repeating bytes so a resume at the wrong offset is detected.
let big: Vec<u8> = (0..3 * 1024 * 1024u32)
.map(|i| (i.wrapping_mul(2654435761) >> 13) as u8)
.collect();
std::fs::write(item.join("Alien (1979).mkv"), &big).unwrap();
std::fs::write(item.join("Alien (1979).nfo"), b"<movie/>").unwrap();
std::fs::write(item.join("extras/Making of.mkv"), b"extra").unwrap();
std::fs::write(item.join("empty.txt"), b"").unwrap();
let manifest = build_manifest(&item).await.unwrap();
let src = Src {
root: item,
rels: Arc::new(manifest.files.iter().map(|f| f.rel_path.clone()).collect()),
cut_after: Arc::new(AtomicUsize::new(0)),
requests: Arc::new(AtomicUsize::new(0)),
ranged: Arc::new(AtomicUsize::new(0)),
};
let app = Router::new()
.route("/files/{idx}", get(file))
.with_state(src.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
Fixture {
_src_dir: src_dir,
dst_dir: tempfile::tempdir().unwrap(),
src,
base: format!("http://{addr}"),
}
}
fn puller() -> Puller {
Puller::new(
reqwest::Client::new(),
PullerOptions {
initial_backoff: Duration::from_millis(10),
attempts: 5,
..Default::default()
},
)
}
async fn pull_all(fx: &Fixture, p: &Puller) -> PathBuf {
let manifest = build_manifest(&fx.src.root).await.unwrap();
let lib_root = fx.dst_dir.path();
let partial = partial_dir(lib_root, "job1");
prepare_partial(&partial).await.unwrap();
for (idx, entry) in manifest.files.iter().enumerate() {
let url = format!("{}/files/{idx}", fx.base);
p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {})
.await
.unwrap();
}
let target = lib_root.join("Alien (1979)");
promote(&partial, &target, &manifest, &[]).await.unwrap();
target
}
fn assert_same_tree(a: &std::path::Path, b: &std::path::Path) {
for rel in [
"Alien (1979).mkv",
"Alien (1979).nfo",
"extras/Making of.mkv",
"empty.txt",
] {
assert_eq!(
std::fs::read(a.join(rel)).unwrap(),
std::fs::read(b.join(rel)).unwrap(),
"{rel}"
);
}
}
#[tokio::test]
async fn copies_folder_with_sidecars() {
let fx = fixture().await;
let target = pull_all(&fx, &puller()).await;
assert_same_tree(&fx.src.root, &target);
// Partial area is cleaned up and hidden from Jellyfin.
assert!(!partial_dir(fx.dst_dir.path(), "job1").exists());
assert!(
fx.dst_dir
.path()
.join(".jellymove-partial/.ignore")
.exists()
);
}
#[tokio::test]
async fn resumes_after_dropped_connection() {
let fx = fixture().await;
fx.src.cut_after.store(1024 * 1024, Ordering::SeqCst); // first request dies at 1 MiB
let target = pull_all(&fx, &puller()).await;
assert_same_tree(&fx.src.root, &target);
// 3 non-empty files (the empty one needs no request) + 1 resume.
assert_eq!(fx.src.requests.load(Ordering::SeqCst), 4);
// The retry continued from where the link dropped rather than restarting.
assert_eq!(fx.src.ranged.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn corrupt_partial_is_discarded_and_refetched() {
let fx = fixture().await;
let manifest = build_manifest(&fx.src.root).await.unwrap();
let idx = manifest
.files
.iter()
.position(|f| f.rel_path.ends_with(".mkv") && f.size > 100)
.unwrap();
let partial = partial_dir(fx.dst_dir.path(), "job1");
prepare_partial(&partial).await.unwrap();
// Plant a half-file of garbage, as if a previous run wrote bad bytes.
std::fs::write(part_path(&partial, idx), vec![0u8; 1024 * 1024]).unwrap();
let target = pull_all(&fx, &puller()).await;
assert_same_tree(&fx.src.root, &target);
}
#[tokio::test]
async fn refuses_to_overwrite_existing_files() {
let fx = fixture().await;
let target = fx.dst_dir.path().join("Alien (1979)");
std::fs::create_dir_all(&target).unwrap();
std::fs::write(target.join("Alien (1979).nfo"), b"someone else's").unwrap();
let manifest = build_manifest(&fx.src.root).await.unwrap();
let partial = partial_dir(fx.dst_dir.path(), "job1");
prepare_partial(&partial).await.unwrap();
let p = puller();
for (idx, entry) in manifest.files.iter().enumerate() {
let url = format!("{}/files/{idx}", fx.base);
p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {})
.await
.unwrap();
}
let err = promote(&partial, &target, &manifest, &[]).await.unwrap_err();
assert!(matches!(err, jm_transfer::TransferError::Exists(_)));
// Nothing was moved: the stranger's file is untouched and no video landed.
assert_eq!(
std::fs::read(target.join("Alien (1979).nfo")).unwrap(),
b"someone else's"
);
assert!(!target.join("Alien (1979).mkv").exists());
}
#[tokio::test]
async fn promote_is_idempotent() {
let fx = fixture().await;
let target = pull_all(&fx, &puller()).await;
let manifest = build_manifest(&fx.src.root).await.unwrap();
// A second promote after a "crash" finds everything already in place.
promote(&partial_dir(fx.dst_dir.path(), "job1"), &target, &manifest, &[])
.await
.unwrap();
}
#[tokio::test]
async fn promote_leaves_skipped_files_alone() {
let fx = fixture().await;
let manifest = build_manifest(&fx.src.root).await.unwrap();
let nfo = manifest
.files
.iter()
.position(|f| f.rel_path == "Alien (1979).nfo")
.unwrap();
// The target already has its own NFO; that entry is skipped and never copied.
let target = fx.dst_dir.path().join("Alien (1979)");
std::fs::create_dir_all(&target).unwrap();
std::fs::write(target.join("Alien (1979).nfo"), b"mine").unwrap();
let partial = partial_dir(fx.dst_dir.path(), "job1");
prepare_partial(&partial).await.unwrap();
let p = puller();
for (idx, entry) in manifest.files.iter().enumerate() {
if idx == nfo {
continue;
}
let url = format!("{}/files/{idx}", fx.base);
p.pull_verified(&url, entry, &part_path(&partial, idx), &mut |_| {})
.await
.unwrap();
}
promote(&partial, &target, &manifest, &[nfo]).await.unwrap();
assert_eq!(std::fs::read(target.join("Alien (1979).nfo")).unwrap(), b"mine");
assert!(target.join("Alien (1979).mkv").exists());
// And it's still idempotent.
promote(&partial, &target, &manifest, &[nfo]).await.unwrap();
}
#[tokio::test]
async fn bandwidth_limit_is_applied() {
let fx = fixture().await;
let p = Puller::new(
reqwest::Client::new(),
PullerOptions {
bytes_per_sec: std::num::NonZeroU32::new(2 * 1024 * 1024),
initial_backoff: Duration::from_millis(10),
..Default::default()
},
);
let start = std::time::Instant::now();
pull_all(&fx, &p).await;
// ~3 MiB at 2 MiB/s with a one-second burst: at least ~0.5 s.
assert!(
start.elapsed() >= Duration::from_millis(400),
"took {:?}",
start.elapsed()
);
}