rqbit/crates/librqbit/src/torrent_state/initializing.rs

154 lines
5.2 KiB
Rust
Raw Normal View History

use std::{
2024-04-29 19:28:05 +01:00
fs::OpenOptions,
2023-11-24 15:04:36 +00:00
sync::{atomic::AtomicU64, Arc},
2023-11-24 12:47:33 +00:00
time::Instant,
};
use anyhow::Context;
2023-11-24 12:47:33 +00:00
use size_format::SizeFormatterBinary as SF;
2023-11-24 12:47:33 +00:00
use tracing::{debug, info, warn};
2024-03-30 18:51:05 +00:00
use crate::{
2024-04-29 21:44:21 +01:00
chunk_tracker::ChunkTracker,
file_ops::FileOps,
opened_file::OpenedFile,
storage::{FilesystemStorage, InMemoryGarbageCollectingStorage, TorrentStorage},
2024-03-30 18:51:05 +00:00
};
use super::{paused::TorrentStatePaused, ManagedTorrentInfo};
pub struct TorrentStateInitializing {
2023-11-24 14:08:02 +00:00
pub(crate) meta: Arc<ManagedTorrentInfo>,
pub(crate) only_files: Option<Vec<usize>>,
2023-11-24 15:04:36 +00:00
pub(crate) checked_bytes: AtomicU64,
}
impl TorrentStateInitializing {
2023-11-24 12:47:17 +00:00
pub fn new(meta: Arc<ManagedTorrentInfo>, only_files: Option<Vec<usize>>) -> Self {
2023-11-24 15:04:36 +00:00
Self {
meta,
only_files,
checked_bytes: AtomicU64::new(0),
}
}
2023-11-24 18:28:46 +00:00
pub fn get_checked_bytes(&self) -> u64 {
self.checked_bytes
.load(std::sync::atomic::Ordering::Relaxed)
}
pub async fn check(&self) -> anyhow::Result<TorrentStatePaused> {
2024-04-29 21:44:21 +01:00
// Return in-memory store
let store =
InMemoryGarbageCollectingStorage::new(self.meta.lengths, self.meta.file_infos.clone())?;
let ct = ChunkTracker::new_empty(self.meta.lengths, &self.meta.file_infos)?;
Ok(TorrentStatePaused {
info: self.meta.clone(),
files: Box::new(store),
chunk_tracker: ct,
streams: Arc::new(Default::default()),
})
// self.check_disk().await
}
pub async fn check_disk(&self) -> anyhow::Result<TorrentStatePaused> {
let mut files = Vec::<OpenedFile>::new();
for file_details in self.meta.info.iter_file_details(&self.meta.lengths)? {
let mut full_path = self.meta.out_dir.clone();
let relative_path = file_details
.filename
.to_pathbuf()
.context("error converting file to path")?;
full_path.push(relative_path);
std::fs::create_dir_all(full_path.parent().context("bug: no parent")?)?;
let file = if self.meta.options.overwrite {
OpenOptions::new()
.create(true)
2024-04-24 14:19:04 +01:00
.truncate(false)
.read(true)
.write(true)
.open(&full_path)
.with_context(|| format!("error opening {full_path:?} in read/write mode"))?
} else {
// TODO: create_new does not seem to work with read(true), so calling this twice.
OpenOptions::new()
.create_new(true)
.write(true)
.open(&full_path)
.with_context(|| format!("error creating {:?}", &full_path))?;
OpenOptions::new().read(true).write(true).open(&full_path)?
};
2024-04-29 21:44:21 +01:00
files.push(OpenedFile::new(file));
}
2024-04-29 21:44:21 +01:00
let files: Box<dyn TorrentStorage> = Box::new(FilesystemStorage::new(files));
2023-11-24 15:04:36 +00:00
debug!("computed lengths: {:?}", &self.meta.lengths);
info!("Doing initial checksum validation, this might take a while...");
2023-11-24 12:47:33 +00:00
let initial_check_results = self.meta.spawner.spawn_block_in_place(|| {
2024-04-29 21:44:21 +01:00
FileOps::new(
&self.meta.info,
&files,
2024-04-29 21:44:21 +01:00
&self.meta.file_infos,
&self.meta.lengths,
)
2024-04-29 21:44:21 +01:00
.initial_check(self.only_files.as_deref(), &self.checked_bytes)
})?;
info!(
"Initial check results: have {}, needed {}, total selected {}",
SF::new(initial_check_results.have_bytes),
SF::new(initial_check_results.needed_bytes),
2024-03-30 18:51:05 +00:00
SF::new(initial_check_results.selected_bytes)
);
// Ensure file lenghts are correct, and reopen read-only.
2023-11-24 12:47:17 +00:00
self.meta.spawner.spawn_block_in_place(|| {
2024-04-29 21:44:21 +01:00
for (idx, fi) in self.meta.file_infos.iter().enumerate() {
if self
.only_files
.as_ref()
.map(|v| v.contains(&idx))
.unwrap_or(true)
{
let now = Instant::now();
2024-04-29 21:44:21 +01:00
if let Err(err) = files.ensure_file_length(idx, fi.len) {
warn!(
"Error setting length for file {:?} to {}: {:#?}",
2024-04-29 21:44:21 +01:00
fi.filename, fi.len, err
);
} else {
debug!(
"Set length for file {:?} to {} in {:?}",
2024-04-29 21:44:21 +01:00
fi.filename,
SF::new(fi.len),
now.elapsed()
);
}
}
}
Ok::<_, anyhow::Error>(())
})?;
let chunk_tracker = ChunkTracker::new(
initial_check_results.have_pieces,
2024-03-30 18:51:05 +00:00
initial_check_results.selected_pieces,
2023-11-24 15:04:36 +00:00
self.meta.lengths,
2024-04-29 21:44:21 +01:00
&self.meta.file_infos,
2024-03-30 11:46:29 +00:00
)
.context("error creating chunk tracker")?;
let paused = TorrentStatePaused {
2023-11-24 12:47:17 +00:00
info: self.meta.clone(),
files,
chunk_tracker,
2024-04-24 18:58:30 +01:00
streams: Arc::new(Default::default()),
};
Ok(paused)
}
}