Files
Jellymove/crates/jm-server/src/state.rs
T
IxianPixel 8ceb3c8be8
CI / test (push) Successful in 5m7s
Initial code commit
2026-11-05 14:19:37 +00:00

77 lines
2.4 KiB
Rust

use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use jm_core::{Job, JobId};
use jm_store::Store;
use jm_transfer::{Puller, PullerOptions};
use tokio::sync::{Semaphore, broadcast};
use crate::config::Config;
use crate::peer::PeerClient;
pub struct AppState {
pub cfg: Config,
pub store: Store,
pub jellyfin: jm_jellyfin::Client,
pub peer: Option<PeerClient>,
pub puller: Puller,
/// Job snapshots for the UI's live view.
pub events: broadcast::Sender<Job>,
pub job_slots: Arc<Semaphore>,
pub running: Mutex<HashSet<JobId>>,
/// Exports currently being hashed, so a duplicate request doesn't start a second pass.
pub preparing: Mutex<HashSet<String>>,
}
pub type Shared = Arc<AppState>;
impl AppState {
pub fn new(cfg: Config, store: Store) -> anyhow::Result<Self> {
let jellyfin = jm_jellyfin::Client::new(&cfg.jellyfin.url, &cfg.jellyfin.api_key)?;
// Transfers can run for hours; only bound the connect phase.
let http = reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(20))
.read_timeout(std::time::Duration::from_secs(120))
.build()?;
let peer = cfg
.peer
.as_ref()
.map(|p| PeerClient::new(http.clone(), &p.url, &p.token));
let puller = Puller::new(
http,
PullerOptions {
token: cfg.peer.as_ref().map(|p| p.token.clone()),
bytes_per_sec: cfg.bytes_per_sec(),
attempts: cfg.transfer.retries.max(1),
..Default::default()
},
);
let (events, _) = broadcast::channel(256);
let slots = cfg.transfer.max_concurrent_jobs.max(1);
Ok(Self {
cfg,
store,
jellyfin,
peer,
puller,
events,
job_slots: Arc::new(Semaphore::new(slots)),
running: Mutex::new(HashSet::new()),
preparing: Mutex::new(HashSet::new()),
})
}
pub fn peer(&self) -> anyhow::Result<&PeerClient> {
self.peer
.as_ref()
.ok_or_else(|| anyhow::anyhow!("no peer is configured on this node"))
}
/// Save a job and tell anyone watching.
pub async fn save(&self, job: &Job) -> anyhow::Result<()> {
self.store.put_job(job).await?;
let _ = self.events.send(job.clone());
Ok(())
}
}