Changing a movie's or series' root previously rewrote root_id and left the files behind, so the §7.4 layout stopped describing the disk and the root's policy applied to a library the files were not in. Series had no root control at all. All roots share one ZFS dataset, so the move is a rename of the title folder into the new root, never a copy — hardlinks and the seeding torrent survive it (§7.3). Disk first, row second: a destination that already holds the folder is a 409, a failed rename leaves the row unchanged, and a title with nothing on disk moves with no filesystem work. media_files rows are rewritten in the same transaction as the root_id, and a successful move triggers the §7.5 Jellyfin refresh. Issue #228 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
260 lines
9.3 KiB
Rust
260 lines
9.3 KiB
Rust
//! Moving a title between roots (issue #228). Changing a title's `root_id`
|
|
//! renames its §7.4 folder into the new root and rewrites the `media_files`
|
|
//! rows to match, so the layout keeps describing the disk and the new root's
|
|
//! policy (§5.1) applies to a library the files are actually in.
|
|
//!
|
|
//! Every root shares one filesystem — one ZFS dataset, bind-mounted — so this
|
|
//! is a directory rename, never a copy. Hardlinked files keep their inodes
|
|
//! and the torrent keeps seeding against them (§7.3).
|
|
//!
|
|
//! Ordering mirrors `remove_library_files`: the disk is touched before the
|
|
//! row changes, so a failed rename leaves the title where its files actually
|
|
//! are and the operator can retry.
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use crate::movies::{pool, title_target, ApiError};
|
|
use crate::state::AppState;
|
|
|
|
/// Which table owns the moving title's files.
|
|
#[derive(Debug, Clone, Copy)]
|
|
pub(crate) enum TitleKind {
|
|
Movie,
|
|
Series,
|
|
}
|
|
|
|
/// One rename from the old root into the new one: a §7.4 title folder, or a
|
|
/// loose file sitting straight in the root.
|
|
#[derive(Debug)]
|
|
struct PlannedRename {
|
|
source: PathBuf,
|
|
destination: PathBuf,
|
|
}
|
|
|
|
/// The renames already performed on disk and the row rewrites they imply.
|
|
/// The database half is the caller's transaction; [`Self::undo`] is for when
|
|
/// that transaction fails after the disk already changed.
|
|
#[derive(Debug)]
|
|
pub(crate) struct Relocation {
|
|
performed: Vec<PlannedRename>,
|
|
rewrites: Vec<(i64, String)>,
|
|
}
|
|
|
|
/// Rename the title's folders into the new root. Called before the row is
|
|
/// written, and only when the root actually changes.
|
|
///
|
|
/// A title with nothing on disk — no `media_files` rows, or rows whose
|
|
/// targets are already gone — changes root with no filesystem work at all.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// [`ApiError::Conflict`] when the destination already holds an entry of the
|
|
/// same name — a conflict, never an overwrite. [`ApiError::Filesystem`] when
|
|
/// a rename fails; whatever had already been renamed is moved back first, so
|
|
/// the row the caller then leaves unchanged still describes the disk.
|
|
pub(crate) async fn relocate_title(
|
|
state: &AppState,
|
|
kind: TitleKind,
|
|
title_id: i64,
|
|
old_root_id: i64,
|
|
new_root_id: i64,
|
|
) -> Result<Relocation, ApiError> {
|
|
let old_root = root_path(state, old_root_id).await?;
|
|
let new_root = root_path(state, new_root_id).await?;
|
|
let files = title_files(state, kind, title_id).await?;
|
|
|
|
let mut renames: Vec<PlannedRename> = Vec::new();
|
|
let mut rewrites: Vec<(i64, String)> = Vec::new();
|
|
for (file_id, path) in &files {
|
|
let Some(source) = title_target(&old_root, path) else {
|
|
// Outside its own root: not ours to move, and the row keeps
|
|
// pointing at where the file really is.
|
|
tracing::warn!(%path, %old_root, "media file is outside its root, not moved");
|
|
continue;
|
|
};
|
|
let Some(name) = source.file_name() else {
|
|
continue;
|
|
};
|
|
let destination = std::path::Path::new(&new_root).join(name);
|
|
if !renames.iter().any(|rename| rename.source == source) {
|
|
renames.push(PlannedRename {
|
|
source,
|
|
destination,
|
|
});
|
|
}
|
|
let relative = std::path::Path::new(path)
|
|
.strip_prefix(std::path::Path::new(&old_root))
|
|
.map_err(|error| ApiError::Filesystem(error.to_string()))?;
|
|
let rewritten = std::path::Path::new(&new_root).join(relative);
|
|
let Some(rewritten) = rewritten.to_str() else {
|
|
return Err(ApiError::Filesystem(format!(
|
|
"non-UTF-8 path under {new_root}"
|
|
)));
|
|
};
|
|
rewrites.push((*file_id, rewritten.to_owned()));
|
|
}
|
|
|
|
// Every destination is checked before anything is renamed, so a conflict
|
|
// never leaves a half-moved title behind.
|
|
for rename in &renames {
|
|
match tokio::fs::symlink_metadata(&rename.destination).await {
|
|
Ok(_) => {
|
|
return Err(ApiError::Conflict(format!(
|
|
"the destination root already has '{}'",
|
|
rename.destination.display()
|
|
)))
|
|
}
|
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
|
Err(error) => return Err(ApiError::Filesystem(error.to_string())),
|
|
}
|
|
}
|
|
|
|
let mut performed: Vec<PlannedRename> = Vec::new();
|
|
for rename in renames {
|
|
// A recorded file with nothing on disk: the rows still follow the
|
|
// title, the same way a delete treats already-gone as done. Checked
|
|
// on the source, so a missing *destination* parent stays an error.
|
|
match tokio::fs::symlink_metadata(&rename.source).await {
|
|
Ok(_) => {}
|
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
|
tracing::warn!(
|
|
source = %rename.source.display(),
|
|
"nothing on disk to move for this title"
|
|
);
|
|
continue;
|
|
}
|
|
Err(error) => {
|
|
let failed = ApiError::Filesystem(error.to_string());
|
|
Relocation {
|
|
performed,
|
|
rewrites: Vec::new(),
|
|
}
|
|
.undo()
|
|
.await;
|
|
return Err(failed);
|
|
}
|
|
}
|
|
match tokio::fs::rename(&rename.source, &rename.destination).await {
|
|
Ok(()) => {
|
|
tracing::info!(
|
|
source = %rename.source.display(),
|
|
destination = %rename.destination.display(),
|
|
"moved title folder between roots"
|
|
);
|
|
performed.push(rename);
|
|
}
|
|
Err(error) => {
|
|
let failed = ApiError::Filesystem(error.to_string());
|
|
Relocation {
|
|
performed,
|
|
rewrites: Vec::new(),
|
|
}
|
|
.undo()
|
|
.await;
|
|
return Err(failed);
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(Relocation {
|
|
performed,
|
|
rewrites,
|
|
})
|
|
}
|
|
|
|
impl Relocation {
|
|
/// Whether anything on disk actually moved — the trigger for the same
|
|
/// single Jellyfin refresh import performs (§7.5).
|
|
pub(crate) fn moved_files(&self) -> bool {
|
|
!self.performed.is_empty()
|
|
}
|
|
|
|
/// Point the `media_files` rows at the new root, inside the caller's
|
|
/// transaction so they land together with the `root_id` change or not at
|
|
/// all.
|
|
pub(crate) async fn rewrite_rows(
|
|
&self,
|
|
transaction: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
|
|
) -> Result<(), sqlx::Error> {
|
|
for (file_id, path) in &self.rewrites {
|
|
sqlx::query!(
|
|
"UPDATE media_files SET path = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?",
|
|
path,
|
|
file_id
|
|
)
|
|
.execute(&mut **transaction)
|
|
.await?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Best-effort reversal of the renames, for when the disk moved but the
|
|
/// database write failed. A reversal that itself fails is logged: at that
|
|
/// point the operator's retry is the recovery path.
|
|
pub(crate) async fn undo(&self) {
|
|
for rename in self.performed.iter().rev() {
|
|
if let Err(error) = tokio::fs::rename(&rename.destination, &rename.source).await {
|
|
tracing::error!(
|
|
source = %rename.source.display(),
|
|
destination = %rename.destination.display(),
|
|
%error,
|
|
"could not move the title folder back after a failed root change"
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// §7.5 after a move: the same single best-effort refresh import performs.
|
|
/// Failure logs and never fails the write that already committed.
|
|
pub(crate) async fn refresh_jellyfin(state: &AppState) {
|
|
if let Some(jellyfin) = state.jellyfin() {
|
|
if let Err(error) = jellyfin.refresh().await {
|
|
tracing::warn!(%error, "jellyfin refresh after a root change failed");
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn root_path(state: &AppState, root_id: i64) -> Result<String, ApiError> {
|
|
Ok(sqlx::query_scalar!(
|
|
r#"SELECT path AS "path!: String" FROM roots WHERE id = ?"#,
|
|
root_id
|
|
)
|
|
.fetch_one(pool(state)?)
|
|
.await?)
|
|
}
|
|
|
|
/// Every file the service recorded for the title: a movie's own rows, or the
|
|
/// rows of every episode below a series.
|
|
async fn title_files(
|
|
state: &AppState,
|
|
kind: TitleKind,
|
|
title_id: i64,
|
|
) -> Result<Vec<(i64, String)>, ApiError> {
|
|
Ok(match kind {
|
|
TitleKind::Movie => sqlx::query!(
|
|
r#"SELECT id AS "id!: i64", path AS "path!: String"
|
|
FROM media_files WHERE owner_kind = 'movie' AND owner_id = ?"#,
|
|
title_id
|
|
)
|
|
.fetch_all(pool(state)?)
|
|
.await?
|
|
.into_iter()
|
|
.map(|row| (row.id, row.path))
|
|
.collect(),
|
|
TitleKind::Series => sqlx::query!(
|
|
r#"SELECT mf.id AS "id!: i64", mf.path AS "path!: String"
|
|
FROM media_files mf
|
|
JOIN episodes e ON mf.owner_kind = 'episode' AND e.id = mf.owner_id
|
|
JOIN seasons se ON se.id = e.season_id
|
|
WHERE se.series_id = ?"#,
|
|
title_id
|
|
)
|
|
.fetch_all(pool(state)?)
|
|
.await?
|
|
.into_iter()
|
|
.map(|row| (row.id, row.path))
|
|
.collect(),
|
|
})
|
|
}
|