Initial code commit
CI / test (push) Successful in 5m7s

This commit is contained in:
IxianPixel committed 2026-11-05 14:19:37 +00:00
1 parent f47217d5a3
commit 8ceb3c8be8
60 files changed
+10884

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
[package]
name = "jm-transfer"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[dependencies]
axum = "0.8.9"
blake3 = { version = "1.8.7", features = ["mmap", "rayon"] }
bytes = "1.12.1"
futures = "0.3.34"
governor = "0.10.4"
jm-core = { version = "0.1.0", path = "../jm-core" }
reqwest = { version = "0.13.5", default-features = false, features = ["rustls", "stream", "http2"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
thiserror = "2.0.21"
tokio = { version = "1.54.1", features = ["full"] }
tokio-util = "0.7.20"
tracing = "0.1.44"
[dev-dependencies]
tempfile = "3.27.0"
+60
View File
@@ -0,0 +1,60 @@
//! Moving bytes between agents.
//!
//! The destination *pulls* each file from the source over HTTP with `Range`
//! requests, writing to a `.part` file in a hidden partial area inside the
//! destination library. The length of the `.part` file is the resume point, so
//! a dropped link or a restart continues where it stopped. When a file is
//! complete it is hashed with BLAKE3 and compared with the source's hash; only
//! verified files are renamed into the library.
pub mod manifest;
pub mod promote;
pub mod pull;
pub mod serve;
pub use manifest::{build_manifest, hash_file, list_relative};
pub use promote::{part_path, partial_dir, prepare_partial, promote};
pub use pull::{Puller, PullerOptions};
pub use serve::range_response;
/// Prefix for jellymove's own hidden folders inside libraries. Jellyfin skips
/// folders whose names start with a dot, and we also drop a `.ignore` file in
/// them for good measure.
pub const HIDDEN_PREFIX: &str = ".jellymove-";
#[derive(Debug, thiserror::Error)]
pub enum TransferError {
#[error("i/o error: {0}")]
Io(#[from] std::io::Error),
#[error("http error: {0}")]
Http(#[from] reqwest::Error),
#[error("peer returned HTTP {0}")]
Status(u16),
#[error("hash mismatch for {file}: expected {expected}, got {actual}")]
Integrity {
file: String,
expected: String,
actual: String,
},
#[error("size mismatch for {file}: expected {expected} bytes, got {actual}")]
Size {
file: String,
expected: u64,
actual: u64,
},
#[error("refusing to overwrite existing file {0}")]
Exists(String),
#[error("unsafe path in manifest: {0}")]
UnsafePath(String),
}
impl TransferError {
/// Errors that a retry cannot fix.
pub fn is_permanent(&self) -> bool {
match self {
TransferError::Status(code) => matches!(code, 400 | 401 | 403 | 404 | 410 | 416),
TransferError::Exists(_) | TransferError::UnsafePath(_) => true,
_ => false,
}
}
}
+104
View File
@@ -0,0 +1,104 @@
use std::path::{Path, PathBuf};
use jm_core::job::{Manifest, ManifestEntry};
use crate::{HIDDEN_PREFIX, TransferError};
/// Hash a file with BLAKE3, memory-mapped and multithreaded for large files.
pub async fn hash_file(path: &Path) -> Result<String, TransferError> {
let path = path.to_path_buf();
tokio::task::spawn_blocking(move || -> Result<String, TransferError> {
let mut hasher = blake3::Hasher::new();
hasher.update_mmap_rayon(&path)?;
Ok(hasher.finalize().to_hex().to_string())
})
.await
.expect("hash task panicked")
}
/// List every regular file below `root` (recursively), hash each, and return
/// them sorted by relative path. Symlinks and jellymove's own hidden folders
/// are skipped.
pub async fn build_manifest(root: &Path) -> Result<Manifest, TransferError> {
let root_owned = root.to_path_buf();
let listed = tokio::task::spawn_blocking(move || list_files(&root_owned))
.await
.expect("list task panicked")?;
let mut files = Vec::with_capacity(listed.len());
for (rel, abs, size) in listed {
let blake3 = hash_file(&abs).await?;
files.push(ManifestEntry {
rel_path: rel,
size,
blake3,
});
}
Ok(Manifest { files })
}
/// Relative paths (`/` separated) of every regular file below `root`, without
/// hashing. Used for the folder safety check before we spend time hashing.
pub fn list_relative(root: &Path) -> Result<Vec<String>, TransferError> {
Ok(list_files(root)?
.into_iter()
.map(|(rel, _, _)| rel)
.collect())
}
fn list_files(root: &Path) -> Result<Vec<(String, PathBuf, u64)>, TransferError> {
let mut out = Vec::new();
let mut stack = vec![PathBuf::new()];
while let Some(rel_dir) = stack.pop() {
for entry in std::fs::read_dir(root.join(&rel_dir))? {
let entry = entry?;
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with(HIDDEN_PREFIX) {
continue;
}
let ft = entry.file_type()?;
let rel = rel_dir.join(&name);
if ft.is_dir() {
stack.push(rel);
} else if ft.is_file() {
let size = entry.metadata()?.len();
let rel_str = rel
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
out.push((rel_str, entry.path(), size));
} else {
tracing::warn!(path = %entry.path().display(), "skipping symlink or special file");
}
}
}
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn manifest_lists_nested_files_and_skips_hidden() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("Season 01")).unwrap();
std::fs::create_dir_all(root.join(".jellymove-partial")).unwrap();
std::fs::write(root.join("tvshow.nfo"), b"<tvshow/>").unwrap();
std::fs::write(root.join("Season 01/S01E01.mkv"), b"video").unwrap();
std::fs::write(root.join(".jellymove-partial/0.part"), b"junk").unwrap();
let m = build_manifest(root).await.unwrap();
let names: Vec<_> = m.files.iter().map(|f| f.rel_path.as_str()).collect();
assert_eq!(names, ["Season 01/S01E01.mkv", "tvshow.nfo"]);
assert_eq!(m.files[0].size, 5);
assert_eq!(
m.files[0].blake3,
blake3::hash(b"video").to_hex().to_string()
);
}
}
+75
View File
@@ -0,0 +1,75 @@
use std::path::{Path, PathBuf};
use jm_core::job::Manifest;
use jm_core::paths::join_relative;
use crate::{HIDDEN_PREFIX, TransferError};
/// Hidden staging folder for one job, inside the destination library root so
/// the final rename stays on the same filesystem (and is therefore atomic).
pub fn partial_dir(library_root: &Path, job_id: &str) -> PathBuf {
library_root
.join(format!("{HIDDEN_PREFIX}partial"))
.join(job_id)
}
pub fn part_path(partial: &Path, idx: usize) -> PathBuf {
partial.join(format!("{idx}.part"))
}
/// Create the partial folder and mark it so Jellyfin ignores it.
pub async fn prepare_partial(partial: &Path) -> Result<(), TransferError> {
tokio::fs::create_dir_all(partial).await?;
if let Some(parent) = partial.parent() {
let marker = parent.join(".ignore");
if tokio::fs::metadata(&marker).await.is_err() {
tokio::fs::write(&marker, b"").await?;
}
}
Ok(())
}
/// Rename every verified `.part` into `target_folder`. Safe to run again after
/// a crash: files already in place (part gone, target present with the right
/// size) are skipped. Refuses to overwrite anything it didn't put there.
pub async fn promote(
partial: &Path,
target_folder: &Path,
manifest: &Manifest,
) -> Result<(), TransferError> {
// Check every destination first so we never half-promote into a clash.
for (idx, entry) in manifest.files.iter().enumerate() {
let dest = join_relative(target_folder, &entry.rel_path)
.ok_or_else(|| TransferError::UnsafePath(entry.rel_path.clone()))?;
let part_exists = tokio::fs::metadata(part_path(partial, idx)).await.is_ok();
if part_exists && tokio::fs::metadata(&dest).await.is_ok() {
return Err(TransferError::Exists(dest.display().to_string()));
}
}
for (idx, entry) in manifest.files.iter().enumerate() {
let part = part_path(partial, idx);
let dest = join_relative(target_folder, &entry.rel_path).expect("checked above");
match tokio::fs::metadata(&part).await {
Ok(_) => {
if let Some(parent) = dest.parent() {
tokio::fs::create_dir_all(parent).await?;
}
tokio::fs::rename(&part, &dest).await?;
}
Err(_) => {
// Already promoted on an earlier run?
let meta = tokio::fs::metadata(&dest).await?;
if meta.len() != entry.size {
return Err(TransferError::Size {
file: entry.rel_path.clone(),
expected: entry.size,
actual: meta.len(),
});
}
}
}
}
let _ = tokio::fs::remove_dir(partial).await;
Ok(())
}
+185
View File
@@ -0,0 +1,185 @@
use std::num::NonZeroU32;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use futures::StreamExt;
use governor::{DefaultDirectRateLimiter, Quota, RateLimiter};
use jm_core::job::ManifestEntry;
use reqwest::StatusCode;
use reqwest::header::{AUTHORIZATION, RANGE};
use tokio::io::AsyncWriteExt;
use crate::{TransferError, hash_file};
#[derive(Debug, Clone)]
pub struct PullerOptions {
/// Bearer token presented to the peer.
pub token: Option<String>,
/// Bytes per second across every transfer this puller makes. `None` = unlimited.
pub bytes_per_sec: Option<NonZeroU32>,
/// Attempts per file before giving up (resumes between attempts).
pub attempts: u32,
/// First backoff delay; doubles each attempt, capped at one minute.
pub initial_backoff: Duration,
}
impl Default for PullerOptions {
fn default() -> Self {
Self {
token: None,
bytes_per_sec: None,
attempts: 10,
initial_backoff: Duration::from_secs(2),
}
}
}
#[derive(Clone)]
pub struct Puller {
http: reqwest::Client,
opts: PullerOptions,
limiter: Option<Arc<DefaultDirectRateLimiter>>,
}
impl Puller {
pub fn new(http: reqwest::Client, opts: PullerOptions) -> Self {
let limiter = opts
.bytes_per_sec
.map(|bps| Arc::new(RateLimiter::direct(Quota::per_second(bps))));
Self {
http,
opts,
limiter,
}
}
/// Pull one file into `part`, resuming and retrying as needed, then verify
/// its BLAKE3 hash. `on_progress` receives the bytes held for this file.
pub async fn pull_verified(
&self,
url: &str,
entry: &ManifestEntry,
part: &Path,
on_progress: &mut (dyn FnMut(u64) + Send),
) -> Result<(), TransferError> {
let mut delay = self.opts.initial_backoff;
let mut attempt = 1;
loop {
match self.pull_once(url, entry, part, on_progress).await {
Ok(()) => return Ok(()),
Err(e) if e.is_permanent() || attempt >= self.opts.attempts => return Err(e),
Err(e) => {
tracing::warn!(file = %entry.rel_path, attempt, error = %e, "transfer failed; will resume");
tokio::time::sleep(delay).await;
delay = (delay * 2).min(Duration::from_secs(60));
attempt += 1;
}
}
}
}
async fn pull_once(
&self,
url: &str,
entry: &ManifestEntry,
part: &Path,
on_progress: &mut (dyn FnMut(u64) + Send),
) -> Result<(), TransferError> {
if let Some(parent) = part.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let mut have = match tokio::fs::metadata(part).await {
Ok(m) => m.len(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
if entry.size == 0 {
// Nothing to fetch; an empty file is still part of the folder.
tokio::fs::File::create(part).await?;
}
0
}
Err(e) => return Err(e.into()),
};
if have > entry.size {
// Can't be ours; start again.
tokio::fs::remove_file(part).await?;
have = 0;
}
if have < entry.size {
let mut req = self.http.get(url);
if let Some(t) = &self.opts.token {
req = req.header(AUTHORIZATION, format!("Bearer {t}"));
}
if have > 0 {
req = req.header(RANGE, format!("bytes={have}-"));
}
let resp = req.send().await?;
let mut file = match resp.status() {
StatusCode::PARTIAL_CONTENT if have > 0 => {
tokio::fs::OpenOptions::new()
.append(true)
.open(part)
.await?
}
StatusCode::OK => {
// Server ignored the range (or we asked from zero): rewrite.
have = 0;
tokio::fs::File::create(part).await?
}
s => return Err(TransferError::Status(s.as_u16())),
};
on_progress(have);
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
self.throttle(chunk.len()).await;
file.write_all(&chunk).await?;
have += chunk.len() as u64;
on_progress(have);
if have > entry.size {
break;
}
}
file.flush().await?;
file.sync_all().await?;
}
if have != entry.size {
if have > entry.size {
tokio::fs::remove_file(part).await?;
}
return Err(TransferError::Size {
file: entry.rel_path.clone(),
expected: entry.size,
actual: have,
});
}
let actual = hash_file(part).await?;
if actual != entry.blake3 {
// Corrupt; discard so the next attempt starts from scratch.
tokio::fs::remove_file(part).await?;
return Err(TransferError::Integrity {
file: entry.rel_path.clone(),
expected: entry.blake3.clone(),
actual,
});
}
Ok(())
}
async fn throttle(&self, len: usize) {
let Some(limiter) = &self.limiter else { return };
let burst = self.opts.bytes_per_sec.map(|b| b.get()).unwrap_or(u32::MAX) as usize;
let mut remaining = len;
while remaining > 0 {
let n = remaining.min(burst);
let n32 = NonZeroU32::new(n as u32).expect("n > 0");
// Can't fail: n never exceeds the burst size.
let _ = limiter.until_n_ready(n32).await;
remaining -= n;
}
}
}
+100
View File
@@ -0,0 +1,100 @@
use std::io::SeekFrom;
use std::path::Path;
use axum::body::Body;
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio_util::io::ReaderStream;
/// Serve a file with support for a single `Range: bytes=start-[end]` header.
/// The caller is responsible for deciding *which* file may be served.
pub async fn range_response(path: &Path, headers: &HeaderMap) -> Response {
let mut file = match tokio::fs::File::open(path).await {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return StatusCode::NOT_FOUND.into_response();
}
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
};
let len = match file.metadata().await {
Ok(m) => m.len(),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
};
let range = headers.get(header::RANGE).and_then(|v| v.to_str().ok());
let (start, end) = match range.map(|r| parse_range(r, len)) {
None => (0, len.saturating_sub(1)),
Some(Some(r)) => r,
Some(None) => {
let mut resp = StatusCode::RANGE_NOT_SATISFIABLE.into_response();
resp.headers_mut().insert(
header::CONTENT_RANGE,
HeaderValue::from_str(&format!("bytes */{len}")).expect("valid header"),
);
return resp;
}
};
if start > 0 {
if let Err(e) = file.seek(SeekFrom::Start(start)).await {
return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
}
}
let count = if len == 0 { 0 } else { end - start + 1 };
let stream = ReaderStream::with_capacity(file.take(count), 256 * 1024);
let mut builder = Response::builder()
.header(header::ACCEPT_RANGES, "bytes")
.header(header::CONTENT_LENGTH, count)
.header(header::CONTENT_TYPE, "application/octet-stream");
if range.is_some() {
builder = builder
.status(StatusCode::PARTIAL_CONTENT)
.header(header::CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
} else {
builder = builder.status(StatusCode::OK);
}
builder
.body(Body::from_stream(stream))
.expect("valid response")
}
/// Parse `bytes=start-` or `bytes=start-end` against a file of `len` bytes.
/// Returns an inclusive range, or `None` if unsatisfiable or malformed.
/// Suffix ranges (`bytes=-500`) and multi-range requests aren't needed by our
/// puller and are rejected.
fn parse_range(value: &str, len: u64) -> Option<(u64, u64)> {
let spec = value.strip_prefix("bytes=")?;
if spec.contains(',') {
return None;
}
let (s, e) = spec.split_once('-')?;
let start: u64 = s.trim().parse().ok()?;
if start >= len {
return None;
}
let end = match e.trim() {
"" => len - 1,
e => e.parse::<u64>().ok()?.min(len - 1),
};
(start <= end).then_some((start, end))
}
#[cfg(test)]
mod tests {
use super::parse_range;
#[test]
fn ranges() {
assert_eq!(parse_range("bytes=0-", 10), Some((0, 9)));
assert_eq!(parse_range("bytes=4-", 10), Some((4, 9)));
assert_eq!(parse_range("bytes=4-6", 10), Some((4, 6)));
assert_eq!(parse_range("bytes=4-100", 10), Some((4, 9)));
assert_eq!(parse_range("bytes=10-", 10), None);
assert_eq!(parse_range("bytes=-5", 10), None);
assert_eq!(parse_range("bytes=0-1,4-5", 10), None);
assert_eq!(parse_range("items=0-", 10), None);
assert_eq!(parse_range("bytes=6-4", 10), None);
}
}
+243
View File
@@ -0,0 +1,243 @@
//! 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 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()
);
}