A high-performance inference engine for AI models
file download group
eugene1c9e31d05255
diff --git a/Cargo.lock b/Cargo.lockindex dd0484afa..d098fff3b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1807,27 +1807,39 @@ version = "0.5.26"dependencies = ["async-trait","base64 0.22.1",+ "bindings",+ "bindings-types","block2",- "chrono",+ "bon","crc32c","futures-util",+ "inventory","kiban",- "libc","mock-registry",- "objc-sys",+ "napi",+ "napi-build",+ "napi-derive","objc2","objc2-foundation",+ "pyo3",+ "pyo3-async-runtimes",+ "pyo3-build-config",+ "pyo3-stub-gen","reqwest 0.13.4","rstest","serde",+ "serde-wasm-bindgen","serde_json","tempfile","thiserror 2.0.18","tokio","tokio-stream","tracing",+ "tsify",+ "uniffi","uuid",- "web-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures","wiremock",]@@ -3268,7 +3280,6 @@ version = "0.5.26"dependencies = ["async-trait","futures-util",- "libc","tokio","wasm-bindgen","wasm-bindgen-futures",@@ -4130,12 +4141,6 @@ version = "0.4.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fac6bb46461d099d52dbd345e021b92d21d1be9be967ef2bb4430b23af439a4f"-[[package]]-name = "objc-sys"-version = "0.3.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"-[[package]]name = "objc2"version = "0.6.4"@@ -4248,19 +4253,6 @@ dependencies = ["objc2-foundation",]-[[package]]-name = "objc2-security"-version = "0.3.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"-dependencies = [- "bitflags 2.13.0",- "block2",- "libc",- "objc2",- "objc2-core-foundation",-]-[[package]]name = "once_cell"version = "1.21.4"@@ -7600,7 +7592,6 @@ dependencies = ["backend-remote","bindings","bindings-types",- "bitflags 2.13.0","bon","chrono","confy",@@ -7623,7 +7614,6 @@ dependencies = ["napi-derive","objc2","objc2-foundation",- "objc2-security","parking_lot","pyo3","pyo3-async-runtimes",diff --git a/Cargo.toml b/Cargo.tomlindex 6864360be..7af9607f5 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -75,7 +75,6 @@ objc2 = "0.6.4"objc2-foundation = "0.3.2"objc2-core-foundation = "0.3.2"objc2-io-kit = { version = "0.3.2", default-features = false, features = ["libc", "ps"] }-objc2-security = "0.3.2"obfstr = "0.4.4"zstd = "0.13.3"metal = { package = "mtl-rs", version = "0.2.0" }@@ -143,7 +142,6 @@ reqwest = { version = "0.13.2", features = ["blocking","query",] }-objc-sys = "0.3.5"crc32c = "0.6.8"base64 = "0.22.1"bitflags = "2.11.1"diff --git a/apps/playground/Sources/Views/ModelListView.swift b/apps/playground/Sources/Views/ModelListView.swiftindex 437b626db..3458f551f 100644--- a/apps/playground/Sources/Views/ModelListView.swift+++ b/apps/playground/Sources/Views/ModelListView.swift@@ -160,9 +160,9 @@ struct ModelListView: View {private var chooseBottomBar: some View {if let state = selectedModelState {switch state.phase {- case .notDownloaded, .paused, .locked:+ case .notDownloaded, .paused:downloadButton- case .downloading:+ case .downloading, .locked:waitingTextcase .error:retryButton@@ -197,10 +197,12 @@ struct ModelListView: View {private var manageBottomBar: some View {if let state = selectedModelState {switch state.phase {- case .notDownloaded, .error, .locked:+ case .notDownloaded, .error:downloadButtoncase .downloading:pauseButton+ case .locked:+ waitingTextcase .paused:resumeButtoncase .downloaded:@@ -508,7 +510,7 @@ struct ModelListView: View {case .paused: return .pausedcase .notDownloaded: return .notInstalledcase .error: return .notInstalled- case .locked: return .notInstalled+ case .locked: return .installing}}diff --git a/apps/playground/Sources/Views/ModelRowView.swift b/apps/playground/Sources/Views/ModelRowView.swiftindex 5d726e41f..2672781fb 100644--- a/apps/playground/Sources/Views/ModelRowView.swift+++ b/apps/playground/Sources/Views/ModelRowView.swift@@ -51,7 +51,7 @@ struct ModelRowView: View, Equatable {}}- if state.phase == .downloading || state.phase == .paused {+ if state.isInProgress() || state.phase == .paused {let progress = min(max(state.progress(), 0.0), 1.0)VStack(alignment: .leading, spacing: 4) {ProgressView(value: progress)@@ -105,9 +105,9 @@ struct ModelRowView: View, Equatable {.font(statusFont).foregroundColor(.red)case .locked:- Text("locked")+ Text("installing elsewhere…").font(statusFont)- .foregroundColor(.red)+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)}}@@ -129,7 +129,7 @@ struct ModelRowView: View, Equatable {private var bytesInfo: String? {switch state.phase {- case .downloading, .paused:+ case .downloading, .paused, .locked:return "\(formatBytes(state.downloadedBytes)) / \(formatBytes(state.totalBytes))"case .notDownloaded:return formatBytes(state.totalBytes)diff --git a/crates/legacy/cli-tools/src/languages/swift_extensions.rs b/crates/legacy/cli-tools/src/languages/swift_extensions.rsindex c1a199fa4..fe84dcc8c 100644--- a/crates/legacy/cli-tools/src/languages/swift_extensions.rs+++ b/crates/legacy/cli-tools/src/languages/swift_extensions.rs@@ -1,4 +1,5 @@use std::{+ collections::BTreeMap,fs,path::{Path, PathBuf},};@@ -11,8 +12,8 @@ pub fn generate_swift_extensions(crates_path: PathBuf,destination_path: PathBuf,) -> Result<()> {- let (factories, callback_factories, stream_bridges) = collect_all(&crates_path)?;- let swift_source = render_extensions_file(&factories, &callback_factories, &stream_bridges);+ let (aliases, factories, callback_factories, stream_bridges) = collect_all(&crates_path)?;+ let swift_source = render_extensions_file(&aliases, &factories, &callback_factories, &stream_bridges);fs::write(&destination_path, swift_source)?;Ok(())}@@ -48,7 +49,10 @@ struct StreamBridge {cancel_getter_name: Option<String>,}-fn collect_all(crates_path: &Path) -> Result<(Vec<Factory>, Vec<CallbackFactory>, Vec<StreamBridge>)> {+fn collect_all(+ crates_path: &Path+) -> Result<(BTreeMap<String, String>, Vec<Factory>, Vec<CallbackFactory>, Vec<StreamBridge>)> {+ let mut aliases: BTreeMap<String, String> = BTreeMap::new();let mut factories: Vec<Factory> = Vec::new();let mut callback_factories: Vec<CallbackFactory> = Vec::new();let mut stream_bridges: Vec<StreamBridge> = Vec::new();@@ -64,7 +68,7 @@ fn collect_all(crates_path: &Path) -> Result<(Vec<Factory>, Vec<CallbackFactory>let Ok(file) = syn::parse_file(&source) else {continue;};- collect_from_items(&file.items, &mut factories, &mut callback_factories, &mut stream_bridges);+ collect_from_items(&file.items, &mut aliases, &mut factories, &mut callback_factories, &mut stream_bridges);}factories.sort_by(|lhs, rhs| lhs.type_name.cmp(&rhs.type_name).then_with(|| lhs.method_name.cmp(&rhs.method_name)));@@ -75,11 +79,12 @@ fn collect_all(crates_path: &Path) -> Result<(Vec<Factory>, Vec<CallbackFactory>stream_bridges.sort_by(|lhs, rhs| lhs.type_name.cmp(&rhs.type_name));stream_bridges.dedup_by(|lhs, rhs| lhs.type_name == rhs.type_name);- Ok((factories, callback_factories, stream_bridges))+ Ok((aliases, factories, callback_factories, stream_bridges))}fn collect_from_items(items: &[syn::Item],+ aliases: &mut BTreeMap<String, String>,factories: &mut Vec<Factory>,callback_factories: &mut Vec<CallbackFactory>,stream_bridges: &mut Vec<StreamBridge>,@@ -87,9 +92,16 @@ fn collect_from_items(for item in items {match item {syn::Item::Impl(item_impl) => collect_from_impl(item_impl, factories, callback_factories, stream_bridges),+ syn::Item::Type(item_type)+ if item_type.attrs.iter().any(|attribute| is_bindings_export_with(attribute, "Alias")) =>+ {+ if let Some(swift_type) = rust_type_to_swift(&item_type.ty, "") {+ aliases.insert(item_type.ident.to_string(), swift_type);+ }+ },syn::Item::Mod(item_mod) => {if let Some((_, nested)) = &item_mod.content {- collect_from_items(nested, factories, callback_factories, stream_bridges);+ collect_from_items(nested, aliases, factories, callback_factories, stream_bridges);}},_ => {},@@ -395,12 +407,16 @@ fn is_bindings_export_with(}fn render_extensions_file(+ aliases: &BTreeMap<String, String>,factories: &[Factory],callback_factories: &[CallbackFactory],stream_bridges: &[StreamBridge],) -> String {let mut output = String::new();output.push_str("// Auto-generated by cli-tools — do not edit.\n\n");+ for (name, swift_type) in aliases {+ output.push_str(&format!("public typealias {name} = {swift_type}\n\n"));+ }for factory in factories {output.push_str(&render_factory(factory));output.push('\n');diff --git a/crates/legacy/cli-tools/src/types/command.rs b/crates/legacy/cli-tools/src/types/command.rsindex d268cba31..08a62d4e4 100644--- a/crates/legacy/cli-tools/src/types/command.rs+++ b/crates/legacy/cli-tools/src/types/command.rs@@ -10,6 +10,15 @@ use indexmap::IndexMap;use crate::types::Configuration;+const DEPLOYMENT_TARGET_ENVS: [&str; 6] = [+ "IPHONEOS_DEPLOYMENT_TARGET",+ "MACOSX_DEPLOYMENT_TARGET",+ "TVOS_DEPLOYMENT_TARGET",+ "WATCHOS_DEPLOYMENT_TARGET",+ "XROS_DEPLOYMENT_TARGET",+ "DRIVERKIT_DEPLOYMENT_TARGET",+];+#[derive(Debug, Clone)]pub struct Command {current_path: Option<PathBuf>,@@ -147,6 +156,9 @@ impl Command {command.current_dir(current_path);}command.args(&self.arguments);+ for key in DEPLOYMENT_TARGET_ENVS {+ command.env_remove(key);+ }for (key, value) in &self.envs {command.env(key, value);}diff --git a/crates/legacy/cli/src/interactive/components/application.rs b/crates/legacy/cli/src/interactive/components/application.rsindex 3a93f0bb2..09a7856f4 100644--- a/crates/legacy/cli/src/interactive/components/application.rs+++ b/crates/legacy/cli/src/interactive/components/application.rs@@ -8,7 +8,7 @@ use shoji::types::{use uzu::{engine::Engine,settings::Settings,- storage::types::{DownloadPhase, DownloadState},+ storage::{DownloadPhase, DownloadState},};use crate::{@@ -173,7 +173,7 @@ pub fn Application(}state.write().model_state = Some(ModelState {model,- download_state: DownloadState::not_downloaded(0),+ download_state: DownloadState::default(),session_state: None,thinking: ThinkingSupport::default(),sampling_defaults: SamplingParameters::default(),diff --git a/crates/legacy/cli/src/interactive/components/command_input.rs b/crates/legacy/cli/src/interactive/components/command_input.rsindex 4edb685e7..40cbc672d 100644--- a/crates/legacy/cli/src/interactive/components/command_input.rs+++ b/crates/legacy/cli/src/interactive/components/command_input.rs@@ -1,6 +1,6 @@use iocraft::prelude::*;use unicode_width::UnicodeWidthStr;-use uzu::storage::types::DownloadPhase;+use uzu::storage::DownloadPhase;use crate::interactive::{components::{ApplicationState, InputType, Selector, SelectorItem, SelectorStyle, TextInput, TextInputFocus},diff --git a/crates/legacy/cli/src/interactive/components/selected_model.rs b/crates/legacy/cli/src/interactive/components/selected_model.rsindex f44e929bb..da9b1a524 100644--- a/crates/legacy/cli/src/interactive/components/selected_model.rs+++ b/crates/legacy/cli/src/interactive/components/selected_model.rs@@ -2,7 +2,7 @@ use std::time::{Duration, Instant};use iocraft::prelude::*;use tokio_stream::StreamExt;-use uzu::storage::types::DownloadPhase;+use uzu::storage::DownloadPhase;use crate::{common::thinking::ThinkingSupport,@@ -45,7 +45,7 @@ pub fn SelectedModel(let identifier = model.identifier.clone();let downloader = engine.downloader(&model);- let mut stream = engine.storage_subscribe().await;+ let mut stream = engine.storage_subscribe();let mut was_downloaded = false;if let Some(initial) = downloader.state().await {@@ -65,7 +65,7 @@ pub fn SelectedModel(continue;}- if matches!(event_state.phase, DownloadPhase::Downloading {}) {+ if event_state.is_in_progress() {if last_progress_rendered_at.is_some_and(|rendered_at| rendered_at.elapsed() < DOWNLOAD_PROGRESS_UPDATE_INTERVAL){@@ -121,7 +121,9 @@ pub fn SelectedModel(},DownloadPhase::Paused {}| DownloadPhase::NotDownloaded {}- | DownloadPhase::Locked {}+ | DownloadPhase::Locked {+ ..+ }| DownloadPhase::Error {..} => {@@ -179,25 +181,26 @@ pub fn SelectedModel(None => element! { View }.into(),Some((model, download_state, session_status, thinking_support)) => {let is_downloaded = matches!(download_state.phase, DownloadPhase::Downloaded {});- let is_downloading = matches!(download_state.phase, DownloadPhase::Downloading {});- let status = if is_downloading {- let percent = (download_state.progress() * 100.0).round() as u32;- format!("{}%", percent)- } else if is_downloaded {- model+ let is_downloading = download_state.is_in_progress();+ let percent = (download_state.progress() * 100.0).round() as u32;+ let status = match download_state.phase {+ DownloadPhase::Downloading {} => format!("{percent}%"),+ DownloadPhase::Locked {+ ..+ } => format!("Locked {percent}%"),+ DownloadPhase::Downloaded {} => model.specializations.iter().map(|specializations| specializations.name()).collect::<Vec<String>>()- .join(", ")- } else {- download_state.name()+ .join(", "),+ _ => download_state.name(),};let progress_value = download_state.progress();let progress_size = format!("{:.2}/{:.2} GB",- download_state.downloaded_bytes.max(0) as f64 / 1_000_000_000.0,- download_state.total_bytes.max(0) as f64 / 1_000_000_000.0,+ download_state.downloaded_bytes as f64 / 1_000_000_000.0,+ download_state.total_bytes as f64 / 1_000_000_000.0,);let padding = theme.padding();let padding_wide = theme.padding_wide();diff --git a/crates/legacy/cli/src/interactive/flows/models.rs b/crates/legacy/cli/src/interactive/flows/models.rsindex 4a705d020..28635a74d 100644--- a/crates/legacy/cli/src/interactive/flows/models.rs+++ b/crates/legacy/cli/src/interactive/flows/models.rs@@ -1,8 +1,11 @@use std::{collections::HashMap, sync::Arc};use iocraft::prelude::*;-use shoji::types::{basic::SamplingParameters, model::Model};-use uzu::storage::types::DownloadState;+use shoji::types::{+ basic::SamplingParameters,+ model::{Model, ModelIdentifier},+};+use uzu::storage::DownloadState;use crate::{common::thinking::ThinkingSupport,@@ -50,7 +53,7 @@ fn Models(let family_id = props.family_id.clone();let state = *hooks.use_context::<State<ApplicationState>>();let mut models_state = hooks.use_state(|| None::<Vec<Model>>);- let mut model_download_statuses_state = hooks.use_state(|| None::<HashMap<String, DownloadState>>);+ let mut model_download_statuses_state = hooks.use_state(|| None::<HashMap<ModelIdentifier, DownloadState>>);hooks.use_future({let engine = state.read().engine.clone();@@ -103,8 +106,7 @@ fn Models(let on_event = on_event.clone();let mut state = state;async move {- let download_state =- engine.download_state(&model).await.unwrap_or_else(|| DownloadState::not_downloaded(0));+ let download_state = engine.download_state(&model).await.unwrap_or_default();let preferences_result = {let mut app_state = state.write();app_state.model_state = Some(ModelState {diff --git a/crates/legacy/cli/src/storage/app.rs b/crates/legacy/cli/src/storage/app.rsindex 6de1272f4..a080ceae4 100644--- a/crates/legacy/cli/src/storage/app.rs+++ b/crates/legacy/cli/src/storage/app.rs@@ -3,9 +3,12 @@ use std::{collections::HashMap, sync::Arc};use crossterm::event::KeyCode;use futures_util::StreamExt;use ratatui::widgets::ListState;-use shoji::types::model::Model;+use shoji::types::model::{Model, ModelIdentifier};use tokio::{sync::Mutex as TokioMutex, task::JoinHandle};-use uzu::{engine::Engine, storage::types::DownloadState};+use uzu::{+ engine::Engine,+ storage::{DownloadPhase, DownloadState},+};use super::{events::AppEvent, models::ModelOrganizer, sections::Section};@@ -18,7 +21,7 @@ pub struct ModelWithState {pub struct App {pub engine: Arc<Engine>,- pub models: Arc<TokioMutex<HashMap<String, ModelWithState>>>,+ pub models: Arc<TokioMutex<HashMap<ModelIdentifier, ModelWithState>>>,pub active_section: Section,pub list_states: HashMap<Section, ListState>,pub should_quit: bool,@@ -67,7 +70,7 @@ impl App {pub async fn spawn_state_listener(&mut self) {let models = Arc::clone(&self.models);let engine = Arc::clone(&self.engine);- let mut updates = self.engine.storage_subscribe().await;+ let mut updates = self.engine.storage_subscribe();let handle = self.tokio_handle.spawn(async move {while let Some(Ok((model_id, state))) = updates.next().await {@@ -173,8 +176,8 @@ impl App {pub fn get_selected_model_id(&self,- models: &HashMap<String, ModelWithState>,- ) -> Option<String> {+ models: &HashMap<ModelIdentifier, ModelWithState>,+ ) -> Option<ModelIdentifier> {let state = self.list_states.get(&self.active_section)?;let selected_idx = state.selected()?;let section_models = ModelOrganizer::filter_for_section(models, self.active_section);@@ -190,15 +193,7 @@ impl App {if let Some(id) = model_id {let models_guard = self.models.lock().await;if let Some(model_with_state) = models_guard.get(&id) {- use uzu::storage::types::DownloadPhase::*;- match model_with_state.state.phase {- Downloaded {} => {- // Already installed; ignore download command- },- _ => {- let _ = self.engine.downloader(&model_with_state.model).resume().await;- },- }+ let _ = self.engine.downloader(&model_with_state.model).resume().await;}}}@@ -211,7 +206,9 @@ impl App {if let Some(id) = model_id {let models_guard = self.models.lock().await;- if let Some(model_with_state) = models_guard.get(&id) {+ if let Some(model_with_state) = models_guard.get(&id)+ && model_with_state.state.can_pause()+ {let _ = self.engine.downloader(&model_with_state.model).pause().await;}}@@ -225,73 +222,41 @@ impl App {if let Some(id) = model_id {let models_guard = self.models.lock().await;- if let Some(model_with_state) = models_guard.get(&id) {- // Can delete from any section: Downloading, Paused, Downloaded, Installed+ if let Some(model_with_state) = models_guard.get(&id)+ && model_with_state.state.can_delete()+ {let _ = self.engine.downloader(&model_with_state.model).delete().await;}}}- /// Get helper text based on current section and selectionpub fn get_helpers(&self,- models: &HashMap<String, ModelWithState>,+ models: &HashMap<ModelIdentifier, ModelWithState>,) -> Vec<String> {- let selected_model_id = self.get_selected_model_id(models);-- match self.active_section {- Section::Available => {- if selected_model_id.is_some() {- vec![- "↑↓: Navigate".to_string(),- "←→: Switch section".to_string(),- "d/Enter: Download".to_string(),- "q: Quit".to_string(),- ]- } else {- vec!["←→: Switch section".to_string(), "q: Quit".to_string()]- }- },- Section::Downloading => {- if let Some(_id) = &selected_model_id {- // Check if model is paused- // Note: This is a synchronous context, so we'll use a blocking approach- // In a real scenario, this should be refactored to async- let is_paused = false; // Simplified for now - models are dynamic-- if is_paused {- vec![- "↑↓: Navigate".to_string(),- "←→: Switch section".to_string(),- "d/Enter: Resume".to_string(),- "x: Delete".to_string(),- "q: Quit".to_string(),- ]- } else {- vec![- "↑↓: Navigate".to_string(),- "←→: Switch section".to_string(),- "p: Pause".to_string(),- "x: Delete".to_string(),- "q: Quit".to_string(),- ]- }- } else {- vec!["←→: Switch section".to_string(), "q: Quit".to_string()]- }- },- Section::Installed => {- if selected_model_id.is_some() {- vec![- "↑↓: Navigate".to_string(),- "←→: Switch section".to_string(),- "x: Delete".to_string(),- "q: Quit".to_string(),- ]- } else {- vec!["←→: Switch section".to_string(), "q: Quit".to_string()]- }- },+ let mut helpers = vec!["←→: Switch section".to_string()];+ if let Some(model_with_state) = self.get_selected_model_id(models).and_then(|id| models.get(&id)) {+ helpers.insert(0, "↑↓: Navigate".to_string());+ match &model_with_state.state.phase {+ DownloadPhase::NotDownloaded {} => helpers.push("d/Enter: Download".to_string()),+ DownloadPhase::Paused {}+ | DownloadPhase::Error {+ ..+ } => {+ helpers.push("d/Enter: Resume".to_string());+ helpers.push("x: Delete".to_string());+ },+ DownloadPhase::Downloading {} => {+ helpers.push("p: Pause".to_string());+ helpers.push("x: Delete".to_string());+ },+ DownloadPhase::Downloaded {} => helpers.push("x: Delete".to_string()),+ DownloadPhase::Locked {+ manager_id,+ } => helpers.push(format!("Locked by {manager_id}, waiting")),+ }}+ helpers.push("q: Quit".to_string());+ helpers}}diff --git a/crates/legacy/cli/src/storage/mod.rs b/crates/legacy/cli/src/storage/mod.rsindex 57a4b0f0f..c62761ab2 100644--- a/crates/legacy/cli/src/storage/mod.rs+++ b/crates/legacy/cli/src/storage/mod.rs@@ -13,7 +13,10 @@ use crossterm::{terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},};use ratatui::{Terminal, backend::CrosstermBackend};-use uzu::engine::{DownloadManagerType, Engine, EngineConfig};+use uzu::{+ engine::{Engine, EngineConfig},+ storage::DownloadManagerType,+};use self::{app::App, events::EventHandler};diff --git a/crates/legacy/cli/src/storage/models.rs b/crates/legacy/cli/src/storage/models.rsindex 5c0fbbbd7..fd20746f3 100644--- a/crates/legacy/cli/src/storage/models.rs+++ b/crates/legacy/cli/src/storage/models.rs@@ -1,5 +1,7 @@use std::collections::HashMap;+use shoji::types::model::ModelIdentifier;+use super::{app::ModelWithState, sections::Section};pub struct ModelOrganizer;@@ -7,10 +9,10 @@ pub struct ModelOrganizer;impl ModelOrganizer {/// Filter models for a specific sectionpub fn filter_for_section(- models: &HashMap<String, ModelWithState>,+ models: &HashMap<ModelIdentifier, ModelWithState>,section: Section,- ) -> Vec<(String, ModelWithState)> {- let mut filtered: Vec<(String, ModelWithState)> = models+ ) -> Vec<(ModelIdentifier, ModelWithState)> {+ let mut filtered: Vec<(ModelIdentifier, ModelWithState)> = models.iter().filter(|(_, model_with_state)| {let model_section = Section::for_model(model_with_state);diff --git a/crates/legacy/cli/src/storage/sections.rs b/crates/legacy/cli/src/storage/sections.rsindex d10ffbdc5..d70728d92 100644--- a/crates/legacy/cli/src/storage/sections.rs+++ b/crates/legacy/cli/src/storage/sections.rs@@ -1,4 +1,4 @@-use uzu::storage::types::DownloadPhase;+use uzu::storage::DownloadPhase;use super::app::ModelWithState;@@ -40,7 +40,9 @@ impl Section {DownloadPhase::Downloaded {} => Section::Installed,DownloadPhase::Downloading {}| DownloadPhase::Paused {}- | DownloadPhase::Locked {}+ | DownloadPhase::Locked {+ ..+ }| DownloadPhase::Error {..} => Section::Downloading,diff --git a/crates/legacy/cli/src/storage/ui.rs b/crates/legacy/cli/src/storage/ui.rsindex 34140f8ae..21190f556 100644--- a/crates/legacy/cli/src/storage/ui.rs+++ b/crates/legacy/cli/src/storage/ui.rs@@ -1,9 +1,13 @@+use std::collections::HashMap;+use ratatui::{layout::{Constraint, Direction, Layout, Rect},prelude::Frame,style::{Color, Modifier, Style},widgets::{Block, Borders, Gauge, List, ListItem, Paragraph},};+use shoji::types::model::ModelIdentifier;+use uzu::storage::DownloadPhase;use super::{app::{App, ModelWithState},@@ -46,7 +50,7 @@ fn render_section(frame: &mut Frame,area: Rect,app: &mut App,- models: &std::collections::HashMap<String, ModelWithState>,+ models: &HashMap<ModelIdentifier, ModelWithState>,section: Section,) {let is_active = app.active_section == section;@@ -62,8 +66,8 @@ fn render_section(let items: Vec<ListItem> = section_models.iter().map(|(id, model_with_state)| match &model_with_state.state.phase {- uzu::storage::types::DownloadPhase::Downloaded {} => ListItem::new(format!("✓ {}", id)),- uzu::storage::types::DownloadPhase::NotDownloaded {} => {+ DownloadPhase::Downloaded {} => ListItem::new(format!("✓ {}", id)),+ DownloadPhase::NotDownloaded {} => {let size_mb = model_with_state.state.total_bytes as f64 / 1_000_000.0;ListItem::new(format!("{} ({:.1} MB)", id, size_mb))},@@ -109,7 +113,7 @@ fn render_downloading_section(frame: &mut Frame,area: Rect,app: &mut App,- section_models: &[(String, ModelWithState)],+ section_models: &[(ModelIdentifier, ModelWithState)],is_active: bool,) {let border_style = if is_active {@@ -166,75 +170,40 @@ fn render_downloading_section(fn render_downloading_model(frame: &mut Frame,area: Rect,- id: &str,+ id: &ModelIdentifier,model_with_state: &ModelWithState,is_selected: bool,) {- let progress = model_with_state.state.progress() as f64;- let downloaded_mb = model_with_state.state.downloaded_bytes as f64 / 1_000_000.0;- let total_mb = model_with_state.state.total_bytes as f64 / 1_000_000.0;-- // Calculate available width (subtract borders: 2 chars)- let available_width = area.width.saturating_sub(2) as usize;-- let (base_label, gauge_color, border_color) = match &model_with_state.state.phase {- uzu::storage::types::DownloadPhase::Downloading {} => {- let progress_info = format!(" ({:.1}/{:.1} MB - {:.1}%)", downloaded_mb, total_mb, progress * 100.0);- let name = truncate_name_for_label(id, &progress_info, available_width, is_selected);- (- format!("{}{}", name, progress_info),- Color::Cyan,- if is_selected {- Color::Blue- } else {- Color::Gray- },- )- },- uzu::storage::types::DownloadPhase::Paused {} => {- let progress_info =- format!(" [PAUSED] ({:.1}/{:.1} MB - {:.1}%)", downloaded_mb, total_mb, progress * 100.0);- let name = truncate_name_for_label(id, &progress_info, available_width, is_selected);- (- format!("{}{}", name, progress_info),- Color::Yellow,- if is_selected {- Color::Yellow- } else {- Color::Gray- },- )- },- uzu::storage::types::DownloadPhase::Error {- message: err,- } => {- let error_info = format!(" [ERROR: {}]", err);- let name = truncate_name_for_label(id, &error_info, available_width, is_selected);- (- format!("{}{}", name, error_info),- Color::Red,- if is_selected {- Color::Red- } else {- Color::Gray- },- )- },- _ => (- truncate_text(id, available_width),- Color::Gray,- if is_selected {- Color::White- } else {- Color::Gray- },- ),+ let state = &model_with_state.state;+ let progress = state.progress() as f64;+ let bytes_info = format!(+ "({:.1}/{:.1} MB - {:.1}%)",+ state.downloaded_bytes as f64 / 1_000_000.0,+ state.total_bytes as f64 / 1_000_000.0,+ progress * 100.0+ );+ let (info, gauge_color, selected_border) = match &state.phase {+ DownloadPhase::Downloading {} => (format!(" {bytes_info}"), Color::Cyan, Color::Blue),+ DownloadPhase::Paused {} => (format!(" [PAUSED] {bytes_info}"), Color::Yellow, Color::Yellow),+ DownloadPhase::Locked {+ manager_id,+ } => (format!(" [LOCKED BY {manager_id}] {bytes_info}"), Color::Yellow, Color::Yellow),+ DownloadPhase::Error {+ message,+ } => (format!(" [ERROR: {message}]"), Color::Red, Color::Red),+ DownloadPhase::NotDownloaded {} | DownloadPhase::Downloaded {} => (String::new(), Color::Gray, Color::White),};-+ let available_width = area.width.saturating_sub(2) as usize;+ let name = truncate_name_for_label(id, &info, available_width, is_selected);let label = if is_selected {- format!("▶ {}", base_label)+ format!("▶ {name}{info}")+ } else {+ format!("{name}{info}")+ };+ let border_color = if is_selected {+ selected_border} else {- base_label+ Color::Gray};let gauge_style = if is_selected {@@ -262,7 +231,7 @@ fn render_help(frame: &mut Frame,area: Rect,app: &App,- models: &std::collections::HashMap<String, ModelWithState>,+ models: &HashMap<ModelIdentifier, ModelWithState>,) {let helpers = app.get_helpers(models);let help_text = helpers.join(" | ");diff --git a/crates/legacy/download-manager/Cargo.toml b/crates/legacy/download-manager/Cargo.tomlindex 12d78a82b..e25ed7a1d 100644--- a/crates/legacy/download-manager/Cargo.toml+++ b/crates/legacy/download-manager/Cargo.toml@@ -8,8 +8,45 @@ homepage.workspace = truerepository.workspace = truelicense.workspace = true+[lib]+crate-type = ["lib", "cdylib", "staticlib"]++[features]+default = []+bindings = [+ "bindings-uniffi",+ "bindings-napi",+ "bindings-pyo3",+ "bindings-wasm",+]+bindings-uniffi = ["bindings-types/bindings-uniffi", "dep:uniffi"]+bindings-napi = [+ "bindings-types/bindings-napi",+ "dep:napi",+ "dep:napi-derive",+ "dep:napi-build",+]+bindings-pyo3 = [+ "bindings-types/bindings-pyo3",+ "dep:pyo3",+ "dep:pyo3-build-config",+ "dep:pyo3-async-runtimes",+ "dep:pyo3-stub-gen",+ "dep:inventory",+]+bindings-wasm = [+ "bindings-types/bindings-wasm",+ "dep:wasm-bindgen",+ "dep:serde-wasm-bindgen",+ "dep:wasm-bindgen-futures",+ "dep:tsify",+]+[dependencies]+bindings-types.workspace = true+bindings.workspace = truekiban.workspace = true+bon.workspace = truefutures-util.workspace = trueserde.workspace = trueserde_json.workspace = true@@ -18,26 +55,30 @@ thiserror.workspace = truecrc32c.workspace = truebase64.workspace = truetracing.workspace = true-chrono.workspace = truereqwest.workspace = truetokio = { workspace = true, features = ["macros", "sync"] }+tokio-stream.workspace = true+uniffi = { workspace = true, optional = true }+napi = { workspace = true, optional = true }+napi-derive = { workspace = true, optional = true }+pyo3 = { workspace = true, optional = true }+pyo3-async-runtimes = { workspace = true, optional = true }+pyo3-stub-gen = { workspace = true, optional = true }+inventory = { workspace = true, optional = true }+wasm-bindgen = { workspace = true, optional = true }+serde-wasm-bindgen = { workspace = true, optional = true }+wasm-bindgen-futures = { workspace = true, optional = true }+tsify = { workspace = true, optional = true }[target.'cfg(target_vendor = "apple")'.dependencies]objc2.workspace = trueobjc2-foundation.workspace = trueblock2.workspace = true-objc-sys.workspace = true--[target.'cfg(unix)'.dependencies]-libc.workspace = true[target.'cfg(target_family = "wasm")'.dependencies]-tokio-stream = { workspace = true, features = ["sync"] }uuid = { workspace = true, features = ["js"] }-web-sys = { workspace = true, features = ["console"] }[target.'cfg(not(target_family = "wasm"))'.dependencies]-tokio-stream.workspace = trueuuid.workspace = true[dev-dependencies]@@ -46,11 +87,10 @@ tempfile.workspace = truerstest.workspace = truemock-registry.workspace = truewiremock.workspace = true-chrono.workspace = true++[build-dependencies]+napi-build = { workspace = true, optional = true }+pyo3-build-config = { workspace = true, optional = true }[lints]workspace = true--[[test]]-name = "unit"-path = "tests/unit/test_entry.rs"diff --git a/crates/legacy/download-manager/build.rs b/crates/legacy/download-manager/build.rsnew file mode 100644index 000000000..43dd98946--- /dev/null+++ b/crates/legacy/download-manager/build.rs@@ -0,0 +1,6 @@+fn main() {+ #[cfg(feature = "bindings-napi")]+ napi_build::setup();+ #[cfg(feature = "bindings-pyo3")]+ pyo3_build_config::add_extension_module_link_args();+}diff --git a/crates/legacy/download-manager/docs/STATE_REDUCTION_DECISION_MATRIX.md b/crates/legacy/download-manager/docs/STATE_REDUCTION_DECISION_MATRIX.mddeleted file mode 100644index ec256fab7..000000000--- a/crates/legacy/download-manager/docs/STATE_REDUCTION_DECISION_MATRIX.md+++ /dev/null@@ -1,383 +0,0 @@-# State Reduction & Reconciliation Decision Matrix--This document provides a comprehensive decision matrix for the state reduction and reconciliation system used in file download management and model storage.--## Overview--The system uses a three-stage pipeline for determining state:--1. **Validation** (`reduce_to_checked_file_state`) - Validates file integrity using CRC-2. **Display State** (`reduce_to_file_download_state`) - Determines user-facing state-3. **Reconciliation** (`reconcile_to_internal_state`) - Performs cleanup and determines internal operational state--## File Download Task State Machine--### Stage 1: Validation (reduce_to_checked_file_state)--Determines if a file on disk is valid, invalid, or missing based on CRC validation.--**Inputs:**--- `file_state`: Exists | Missing-- `crc_file_state`: Exists | Missing-- `expected_crc`: Some(crc) | None--**Output:** `CheckedFileState`--| File State | CRC File | Expected CRC | Action | Result |-| ---------- | -------- | ------------ | -------------------------------------- | ------------------------------------------- |-| Missing | - | - | - | **Missing** |-| Exists | Exists | Some(crc) | Read cached CRC, compare with expected | **Valid** if match, recalculate if mismatch |-| Exists | Missing | Some(crc) | Calculate CRC, save cache | **Valid** if match, **Invalid** otherwise |-| Exists | - | None | No validation needed | **Valid** |--**CRC Caching Optimization:**--- Valid files get a `.crc` cache file to avoid recalculation on next launch-- Makes subsequent launches ~100x faster for large files-- Cache is invalidated when file changes-------### Stage 2: Display State (reduce_to_file_download_state)--Maps validation results to user-facing download states.--**Inputs:**--- `checked_state`: Valid | Invalid | Missing-- `resume_state`: Exists | Missing-- `task_state`: None | Running | Suspended | Completed | Canceling-- `expected_bytes`: Option<u64>--**Output:** `FileDownloadState` (for UI display)--#### Valid File Cases--| Checked | Resume | Task | Output |-| ------- | ------ | ---- | -------------------------------- |-| Valid | - | - | **Downloaded** (file_size bytes) |--*Any valid file is immediately shown as downloaded, regardless of other state.*-------#### Invalid File Cases--| Checked | Resume | Task | Output | Bytes |-| ------- | ------- | ------------------- | ----------------- | -------------------------- |-| Invalid | Missing | None | **NotDownloaded** | 0 / expected |-| Invalid | Exists | None | **Paused** | resume_bytes / expected |-| Invalid | - | Running | **Downloading** | task_bytes / task_expected |-| Invalid | - | Suspended | **Paused** | task_bytes / task_expected |-| Invalid | - | Completed/Canceling | **NotDownloaded** | 0 / expected |--*Invalid files with active tasks show progress from task state.*-------#### Missing File Cases--| Checked | Resume | Task | Output | Bytes |-| ------- | ------- | --------- | ----------------- | -------------------------- |-| Missing | Missing | None | **NotDownloaded** | 0 / expected |-| Missing | Exists | None | **Paused** | resume_bytes / expected |-| Missing | - | Running | **Downloading** | task_bytes / task_expected |-| Missing | - | Suspended | **Paused** | task_bytes / task_expected |-| Missing | - | Completed | **NotDownloaded** | 0 / expected |-| Missing | - | Canceling | **NotDownloaded** | 0 / expected |--*Missing files rely on resume data or active tasks for progress info.*-------### Stage 3: Reconciliation (reconcile_to_internal_state)--Performs cleanup and determines operational state. This is where side effects happen (file deletion, task cancellation).--**Inputs:**--- `checked_file`: Valid | Invalid | Missing-- `resume_file`: Exists | Missing-- `url_session_task`: None | Some(task)-- `expected_bytes`: Option<u64> (for partial download detection)--**Output:** `InternalDownloadState` (for operations)--#### Valid File Reconciliation (Cases 1-10)--| Checked | Resume | Task | Actions | Internal State |-| ------- | ------- | ---- | ------------------------------------------- | -------------- |-| Valid | Missing | None | Keep file & CRC | **Downloaded** |-| Valid | Exists | None | Delete resume, keep file & CRC | **Downloaded** |-| Valid | - | Any | Cancel task, delete resume, keep file & CRC | **Downloaded** |--*Valid files always result in Downloaded state with cleanup of unnecessary artifacts.*-------#### Invalid File Reconciliation (Cases 11-20)--| Checked | Resume | Task | File Action | Resume Action | Task Action | Internal State |-| ------- | ------- | ------------------- | ------------------------------------- | --------------------- | -------------- | --------------------------------------------- |-| Invalid | Missing | None | Check size: partial=keep, full=delete | - | - | **NotDownloaded** |-| Invalid | Exists | None | Delete | Keep | - | **Paused** |-| Invalid | - | Running | Delete | Delete | Keep | **Downloading** |-| Invalid | Missing | Suspended | Delete | Produce from task | Cancel+produce | **Paused** if success, else **NotDownloaded** |-| Invalid | Exists | Suspended | Delete | Compare & keep better | Cancel+produce | **Paused** |-| Invalid | - | Completed/Canceling | Delete | Delete | Cancel | **NotDownloaded** |--**Special Case - Partial Download Detection (Case 11):**--- If `file_size < expected_bytes`: File is partial, **preserve it** (don't delete)-- If `file_size >= expected_bytes`: File is corrupted, **delete it**-- This prevents deleting incomplete downloads that can be resumed-------#### Missing File Reconciliation (Cases 21-30)--| Checked | Resume | Task | Resume Action | Task Action | Internal State |-| ------- | ------- | ------------- | --------------------- | -------------- | ----------------------------------- |-| Missing | Missing | None | - | - | **NotDownloaded** |-| Missing | Exists | None | Keep | - | **Paused** |-| Missing | - | Running | Delete | Keep | **Downloading** |-| Missing | Missing | Suspended | Produce from task | Cancel+produce | **Paused** if success |-| Missing | Exists | Suspended | Compare & keep better | Cancel+produce | **Paused** |-| Missing | - | **Completed** | Delete | **Keep alive** | **Downloading** (awaiting delegate) |-| Missing | - | Canceling | Delete | Cancel | **NotDownloaded** |--**Critical Case - Background Download Completion (Cases 27-28):**--- When task is `Completed` but file is missing: delegate callback is pending-- **Do NOT cancel task** - keep it alive in Downloading state-- This allows URLSession delegate to move the file to final destination-- Common scenario when download completes while app is closed-------## Model State Reduction--Models aggregate the states of multiple file download tasks into a single model-level state.--**Inputs:** Array of `FileDownloadState` from all files in the model--**Output:** `ModelDownloadState`--### Model State Priority Order--The reducer checks conditions in this priority order:--| Priority | Condition | Model State | Bytes |-| -------- | ---------------------------------------------- | ----------------------------- | ---------------------------- |-| 1 | All files Downloaded | **Downloaded** | sum(file_bytes) |-| 2 | Any file Downloading | **Downloading** | sum(downloaded) / sum(total) |-| 3 | Any file Paused | **Paused** | sum(downloaded) / sum(total) |-| 4 | Any file Error | **Error** | First error message |-| 5 | Some files Downloaded AND downloaded_bytes > 0 | **Paused** (partial progress) | sum(downloaded) / sum(total) |-| 6 | Default (all NotDownloaded) | **NotDownloaded** | 0 / sum(total) |--**Key Insight - Priority 5 (Partial Progress Detection):**--- If ANY files are downloaded but NOT ALL files are downloaded-- AND total downloaded bytes > 0-- AND nothing is actively downloading or paused-- THEN treat as **Paused** (resumable partial progress)-- This correctly represents scenarios like: config.json ✓ + tokenizer.json ✓ + model.safetensors ✗-------## Special Case Handling--### Background Download Completion--**Scenario:** App closed while downloading, URLSession completes in background, app relaunched.--**Detection in `initialize_task_cache()`:**--```rust-if task.state() == Completed && checked_file_state == Valid {- // Delegate callback was missed, manually trigger completion- file_task.handle_download_completion().await;-}-```--**Actions:**--1. Detect: Completed task + Valid file (CRC may be missing)-2. Trigger: `handle_download_completion()`-3. Result: CRC validated, cached, state transitions to Downloaded-------### Partial Download Preservation--**Scenario:** Incomplete file exists without resume data (e.g., interrupted download, app crash).--**Detection in Reconciliation Case 11:**--```rust-if file_size < expected_bytes {- // Partial download - preserve file- remove_crc_cache();- return NotDownloaded;-} else {- // Corrupted full-size file - delete- delete_file_and_crc();- return NotDownloaded;-}-```--**Purpose:** Prevent deleting large partial downloads that might be resumable in future.-------### Resume Data Comparison--**Scenario:** Both file-based resume data and URLSession task resume data exist.--**Resolution in Cases 16, 26:**--1. Read existing resume data bytes: `existing_bytes`-2. Produce resume data from suspended task: `new_bytes`-3. Compare: `if new_bytes > existing_bytes`-4. Keep the resume data with more progress-5. Ensures we never lose download progress-------## State Transition Rules--### Internal State Transitions--```-NotDownloaded → Downloading (via download())-Downloading → Paused (via pause())-Downloading → Downloaded (on completion)-Paused → Downloading (via download())-Downloaded → NotDownloaded (via cancel())-Any → NotDownloaded (via cancel())-```--### Invalid Transitions--- `Downloaded → Downloading`: Cannot re-download existing file-- `Downloaded → Paused`: Cannot pause completed download-------## File Lifecycle Examples--### Example 1: Fresh Download--```-Initial: file=Missing, crc=Missing, resume=Missing, task=None-↓-Checked: Missing-Display: NotDownloaded (0 / 1.1GB)-Internal: NotDownloaded-↓ User clicks Download-Create: task=Running-Display: Downloading (0 / 1.1GB)-Internal: Downloading-↓ Download progresses-Display: Downloading (500MB / 1.1GB)-↓ Download completes-Delegate: Moves file, validates CRC, caches CRC-Checked: Valid-Display: Downloaded (1.1GB)-Internal: Downloaded-```-------### Example 2: Resume After Interruption--```-Initial: file=Missing, crc=Missing, resume=Exists(500MB), task=None-↓-Checked: Missing-Display: Paused (500MB / 1.1GB)-Internal: Paused-↓ User clicks Resume-Create: task=Running (with resume data)-Display: Downloading (500MB / 1.1GB)-Internal: Downloading-↓ Download progresses from 500MB-Display: Downloading (800MB / 1.1GB)-```-------### Example 3: Background Completion--```-App Closed: task=Running, downloading...-↓-URLSession: Completes download, moves file (no delegate callback)-↓-Relaunch: file=Exists, crc=Missing, task=Completed-↓-Checked: Valid (calculates CRC)-Detected: Completed task + Valid file-Trigger: handle_download_completion()-Result: Validates CRC, caches CRC-Display: Downloaded (1.1GB)-Internal: Downloaded-Cleanup: Cancel completed task-```-------### Example 4: Partial File Preservation--```-Initial: file=Exists(100MB), crc=Missing, resume=Missing, task=None- expected=1.1GB-↓-Checked: Invalid (file incomplete, fails CRC)-Reconcile: Detect: 100MB < 1.1GB (partial)-Action: PRESERVE file, remove CRC cache-Internal: NotDownloaded-Display: NotDownloaded (0 / 1.1GB)-↓ Future download can resume from partial file if URLSession supports it-```-------### Example 5: Multi-File Model Partial Download--```-Model Files: config.json, tokenizer.json, model.safetensors--File States:-- config.json: Downloaded (9KB / 9KB)-- tokenizer.json: Downloaded (11MB / 11MB)-- model.safetensors: NotDownloaded (0 / 1.1GB)--Model Reducer:-- all_downloaded: false-- any_downloading: false-- any_paused: false-- any_downloaded: true-- downloaded_bytes: 11MB-↓-Priority 5 Match: Some downloaded + progress > 0-Result: Paused (11MB / 1.1GB)-```-------## Summary--The state reduction system provides:--1. **Deterministic State**: Same inputs always produce same outputs-2. **CRC Optimization**: Cache validation results for fast subsequent launches-3. **Partial Progress**: Preserve and resume incomplete downloads-4. **Background Safety**: Handle downloads that complete while app closed-5. **Data Integrity**: Validate files before marking as complete-6. **Progress Preservation**: Never lose download progress through resume data comparison-7. **Clean Semantics**: Clear user-facing states (NotDownloaded, Downloading, Paused, Downloaded, Error)--The system handles edge cases gracefully while maintaining clear separation between validation (pure), display (pure), and reconciliation (side effects).diff --git a/crates/legacy/download-manager/examples/cross_platform_download.rs b/crates/legacy/download-manager/examples/cross_platform_download.rsindex 0f8b81dcb..44821d0e5 100644--- a/crates/legacy/download-manager/examples/cross_platform_download.rs+++ b/crates/legacy/download-manager/examples/cross_platform_download.rs@@ -1,44 +1,33 @@-use std::path::PathBuf;+use std::{env, path::PathBuf};-/// Cross-platform download example-/// This example shows how to use FileDownloadManager trait-/// which works on both Apple and non-Apple platforms-use download_manager::{FileCheck, FileDownloadManager};+use download_manager::{DownloadManager, DownloadManagerType, DownloadPhase, DownloadTaskRequest};use kiban::rt::RuntimeHandle;+use tokio_stream::StreamExt;#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> {- let runtime_handle = RuntimeHandle::current();-- let manager = <dyn FileDownloadManager>::system_default(runtime_handle).await?;-- let url = "https://huggingface.co/Qwen/Qwen3.5-0.8B/resolve/main/tokenizer.json".to_string();-- let destination = PathBuf::from("/tmp/test_tokenizer.json");- if destination.exists() {- std::fs::remove_file(&destination)?;- }-- println!("Creating download task...");- let task = manager.file_download_task(&url, &destination, FileCheck::None, None).await?;-- println!("Starting download...");- let mut progress_stream = task.progress().await?;+ let mut args = env::args().skip(1);+ let source_url = args+ .next()+ .unwrap_or_else(|| "https://huggingface.co/Qwen/Qwen3.5-0.8B/resolve/main/tokenizer.json".to_string());+ let destination = args.next().unwrap_or_else(|| "/tmp/test_tokenizer.json".to_string());+ let manager = DownloadManager::new(DownloadManagerType::default(), RuntimeHandle::current());+ let request = DownloadTaskRequest::file().destination(PathBuf::from(destination)).source_url(source_url).build();+ let task = manager.download_task(request).await?;+ println!("Initial state: {:?}", task.state());++ let mut progress = task.progress();task.download().await?;-- use tokio_stream::StreamExt;- while let Some(Ok(state)) = progress_stream.next().await {+ if !task.state().is_in_progress() {+ println!("Final state: {:?}", task.state());+ return Ok(());+ }+ while let Some(state) = progress.next().await {println!("Progress: {} / {} bytes ({:?})", state.downloaded_bytes, state.total_bytes, state.phase);-- if matches!(- state.phase,- download_manager::FileDownloadPhase::Downloaded | download_manager::FileDownloadPhase::Error(_)- ) {+ if matches!(state.phase, DownloadPhase::Downloaded {} | DownloadPhase::Error { .. }) {break;}}-- task.wait().await;- println!("Download finished!");+ println!("Final state: {:?}", task.state());Ok(())}diff --git a/crates/legacy/download-manager/examples/wasm/Cargo.lock b/crates/legacy/download-manager/examples/wasm/Cargo.lockindex 4b6e300b7..9f0d54a68 100644--- a/crates/legacy/download-manager/examples/wasm/Cargo.lock+++ b/crates/legacy/download-manager/examples/wasm/Cargo.lock@@ -2,24 +2,15 @@# It is not intended for manual editing.version = 4-[[package]]-name = "android_system_properties"-version = "0.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"-dependencies = [- "libc",-]-[[package]]name = "async-trait"-version = "0.1.89"+version = "0.1.92"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"dependencies = ["proc-macro2","quote",- "syn",+ "syn 3.0.5",][[package]]@@ -28,12 +19,6 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"-[[package]]-name = "autocfg"-version = "1.5.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"-[[package]]name = "aws-lc-rs"version = "1.17.1"@@ -63,6 +48,20 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "bindings"+version = "0.5.26"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 2.0.118",+]++[[package]]+name = "bindings-types"+version = "0.5.26"+[[package]]name = "bitflags"version = "2.13.0"@@ -78,6 +77,29 @@ dependencies = ["objc2",]+[[package]]+name = "bon"+version = "3.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e3fac94a66da67200398458a25412bcc3f9b6443b5119a6cad9cf3ccfcd8cc6"+dependencies = [+ "bon-macros",+]++[[package]]+name = "bon-macros"+version = "3.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4654961ad0494e4774c5c60b4cb4cd0ae9b9d92d039d901638b1dba97ebebf5"+dependencies = [+ "darling",+ "ident_case",+ "prettyplease",+ "proc-macro2",+ "quote",+ "syn 3.0.5",+]+[[package]]name = "bumpalo"version = "3.20.3"@@ -125,20 +147,6 @@ dependencies = ["rand_core",]-[[package]]-name = "chrono"-version = "0.4.45"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"-dependencies = [- "iana-time-zone",- "js-sys",- "num-traits",- "serde",- "wasm-bindgen",- "windows-link",-]-[[package]]name = "cmake"version = "0.1.58"@@ -212,6 +220,40 @@ dependencies = ["rustc_version",]+[[package]]+name = "darling"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 3.0.5",+]++[[package]]+name = "darling_macro"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"+dependencies = [+ "darling_core",+ "quote",+ "syn 3.0.5",+]+[[package]]name = "dispatch2"version = "0.3.1"@@ -230,22 +272,22 @@ checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]name = "download-manager"-version = "0.5.12"+version = "0.5.26"dependencies = ["async-trait","base64",+ "bindings",+ "bindings-types","block2",- "chrono",+ "bon","crc32c","futures-util","kiban",- "libc",- "objc-sys","objc2","objc2-foundation","reqwest",@@ -256,7 +298,6 @@ dependencies = ["tokio-stream","tracing","uuid",- "web-sys",][[package]]@@ -287,7 +328,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -347,7 +388,7 @@ checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]@@ -430,6 +471,12 @@ version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]name = "http"version = "1.4.2"@@ -530,30 +577,6 @@ dependencies = ["windows-registry",]-[[package]]-name = "iana-time-zone"-version = "0.1.65"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"-dependencies = [- "android_system_properties",- "core-foundation-sys",- "iana-time-zone-haiku",- "js-sys",- "log",- "wasm-bindgen",- "windows-core",-]--[[package]]-name = "iana-time-zone-haiku"-version = "0.1.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"-dependencies = [- "cc",-]-[[package]]name = "icu_collections"version = "2.2.0"@@ -636,6 +659,12 @@ dependencies = ["zerovec",]+[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"+[[package]]name = "idna"version = "1.1.0"@@ -706,7 +735,7 @@ dependencies = ["quote","rustc_version","simd_cesu8",- "syn",+ "syn 2.0.118",][[package]]@@ -725,7 +754,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"dependencies = ["quote",- "syn",+ "syn 2.0.118",][[package]]@@ -751,11 +780,10 @@ dependencies = [[[package]]name = "kiban"-version = "0.5.12"+version = "0.5.26"dependencies = ["async-trait","futures-util",- "libc","tokio","wasm-bindgen","wasm-bindgen-futures",@@ -819,21 +847,6 @@ dependencies = ["windows-sys 0.61.2",]-[[package]]-name = "num-traits"-version = "0.2.19"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"-dependencies = [- "autocfg",-]--[[package]]-name = "objc-sys"-version = "0.3.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"-[[package]]name = "objc2"version = "0.6.4"@@ -935,6 +948,16 @@ dependencies = ["zerovec",]+[[package]]+name = "prettyplease"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"+dependencies = [+ "proc-macro2",+ "syn 3.0.5",+]+[[package]]name = "proc-macro2"version = "1.0.106"@@ -1292,7 +1315,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]@@ -1386,6 +1409,12 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]name = "subtle"version = "2.6.1"@@ -1403,6 +1432,17 @@ dependencies = ["unicode-ident",]+[[package]]+name = "syn"+version = "3.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "sync_wrapper"version = "1.0.2"@@ -1420,7 +1460,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]@@ -1461,7 +1501,7 @@ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]@@ -1514,7 +1554,7 @@ checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]@@ -1616,7 +1656,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]@@ -1761,7 +1801,7 @@ dependencies = ["bumpalo","proc-macro2","quote",- "syn",+ "syn 2.0.118","wasm-bindgen-shared",]@@ -1825,41 +1865,6 @@ dependencies = ["windows-sys 0.61.2",]-[[package]]-name = "windows-core"-version = "0.62.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"-dependencies = [- "windows-implement",- "windows-interface",- "windows-link",- "windows-result",- "windows-strings",-]--[[package]]-name = "windows-implement"-version = "0.60.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"-dependencies = [- "proc-macro2",- "quote",- "syn",-]--[[package]]-name = "windows-interface"-version = "0.59.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"-dependencies = [- "proc-macro2",- "quote",- "syn",-]-[[package]]name = "windows-link"version = "0.2.1"@@ -2002,7 +2007,7 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118","synstructure",]@@ -2023,7 +2028,7 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118","synstructure",]@@ -2063,7 +2068,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"dependencies = ["proc-macro2","quote",- "syn",+ "syn 2.0.118",][[package]]diff --git a/crates/legacy/download-manager/examples/wasm/src/lib.rs b/crates/legacy/download-manager/examples/wasm/src/lib.rsindex 474369046..86d2d209c 100644--- a/crates/legacy/download-manager/examples/wasm/src/lib.rs+++ b/crates/legacy/download-manager/examples/wasm/src/lib.rs@@ -1,12 +1,20 @@-use std::{error::Error, path::PathBuf};--use download_manager::{DownloadError, FileCheck, FileDownloadManager, FileDownloadPhase, compute_download_id};-use kiban::{eprintf, fs, printf, rt::RuntimeHandle};+use std::{+ collections::HashMap,+ error::Error,+ path::PathBuf,+ sync::{Arc, LazyLock, Mutex, PoisonError},+};++use download_manager::{+ DownloadManager, DownloadManagerType, DownloadPhase, DownloadTask, DownloadTaskRequest,+};+use kiban::{eprintf, printf, rt::RuntimeHandle};use tokio::sync::OnceCell;use tokio_stream::StreamExt;use wasm_bindgen::{JsError, JsValue, prelude::wasm_bindgen};-static MANAGER: OnceCell<Box<dyn FileDownloadManager>> = OnceCell::const_new();+static MANAGER: OnceCell<DownloadManager> = OnceCell::const_new();+static TASKS: LazyLock<Mutex<HashMap<String, Arc<DownloadTask>>>> = LazyLock::new(Default::default);#[wasm_bindgen(getter_with_clone)]pub struct JsFileDownloadState {@@ -37,98 +45,74 @@ pub async fn download(#[wasm_bindgen]pub async fn pause(task_id: String) -> Result<(), JsError> {- let manager = get_manager().await?;- let all_tasks = manager.get_all_file_tasks().await?;- for task in all_tasks {- if task.download_id().to_string() == task_id {- task.pause().await?;- }+ if let Some(task) = task(&task_id) {+ task.pause().await?;}-Ok(())}#[wasm_bindgen]pub async fn resume(task_id: String) -> Result<(), JsError> {- let manager = get_manager().await?;- let all_tasks = manager.get_all_file_tasks().await?;- for task in all_tasks {- if task.download_id().to_string() == task_id {- task.download().await?;- }+ if let Some(task) = task(&task_id) {+ task.download().await?;}-Ok(())}+fn task(task_id: &str) -> Option<Arc<DownloadTask>> {+ TASKS.lock().unwrap_or_else(PoisonError::into_inner).get(task_id).cloned()+}+async fn download_internal(url: String,file_path_str: String,callback: impl Fn(JsFileDownloadState),) -> Result<(), Box<dyn Error>> {- let file_path = PathBuf::from(file_path_str);- let manager = get_manager().await?;- manager.remove_file_task(compute_download_id(&file_path)).await?;-- if fs::asyn::try_exists(&file_path).await? {- fs::asyn::remove_file(&file_path).await?;- }-- let task = manager.file_download_task(&url, &file_path, FileCheck::None, None).await?;- let mut progress_stream = task.progress().await?;+ let request = DownloadTaskRequest::file().destination(PathBuf::from(file_path_str)).source_url(url).build();+ let task_id = request.download_id().to_string();+ let manager = MANAGER.get_or_init(|| async { DownloadManager::new(DownloadManagerType::default(), RuntimeHandle::current()) }).await;+ let task = manager.download_task(request).await?;+ task.delete().await?;+ TASKS.lock().unwrap_or_else(PoisonError::into_inner).insert(task_id.clone(), Arc::clone(&task));++ let mut progress = task.progress();task.download().await?;-- let mut download_error = None;- while let Some(Ok(state)) = progress_stream.next().await {+ while let Some(state) = progress.next().await {let (phase, message) = match &state.phase {- FileDownloadPhase::NotDownloaded => ("not_downloaded", None),- FileDownloadPhase::Downloading => ("downloading", None),- FileDownloadPhase::Paused => ("paused", None),- FileDownloadPhase::Downloaded => ("downloaded", None),- FileDownloadPhase::LockedByOther(id) => ("locked", Some(id.clone())),- FileDownloadPhase::Error(err) => ("error", Some(err.clone())),+ DownloadPhase::NotDownloaded {} => ("not_downloaded", None),+ DownloadPhase::Downloading {} => ("downloading", None),+ DownloadPhase::Paused {} => ("paused", None),+ DownloadPhase::Downloaded {} => ("downloaded", None),+ DownloadPhase::Locked {+ manager_id,+ } => ("locked", Some(manager_id.clone())),+ DownloadPhase::Error {+ message,+ } => ("error", Some(message.clone())),};- let js_state = JsFileDownloadState {- task_id: task.download_id().to_string(),+ callback(JsFileDownloadState {+ task_id: task_id.clone(),phase: phase.to_owned(),downloaded_bytes: state.downloaded_bytes as f64,total_bytes: state.total_bytes as f64,message,- };- callback(js_state);-+ });match state.phase {- FileDownloadPhase::Downloading => {- printf!("Progress: {} / {} bytes ({:?})", state.downloaded_bytes, state.total_bytes, state.phase);+ DownloadPhase::Downloading {} => {+ printf!("Progress: {} / {} bytes", state.downloaded_bytes, state.total_bytes);},- FileDownloadPhase::Downloaded => {- printf!("Downloaded state");+ DownloadPhase::Downloaded {} => {+ printf!("Downloaded");break;},- FileDownloadPhase::Error(err) => {- eprintf!("Error: {err}");- download_error = Some(err);- break;+ DownloadPhase::Error {+ message,+ } => {+ eprintf!("Error: {message}");+ return Err(message.into());},- _ => (),+ _ => {},}}- task.wait().await;-- if let Some(err) = download_error {- return Err(DownloadError::Backend(err).into());- }-- if let FileDownloadPhase::Error(err) = task.state().await.phase {- return Err(DownloadError::Backend(err).into());- }-Ok(())}--async fn get_manager() -> Result<&'static dyn FileDownloadManager, DownloadError> {- MANAGER- .get_or_try_init(|| <dyn FileDownloadManager>::system_default(RuntimeHandle::current()))- .await- .map(Box::as_ref)-}diff --git a/crates/legacy/download-manager/examples/wasm/www/index.js b/crates/legacy/download-manager/examples/wasm/www/index.jsindex 1fcac2666..b7b9ad24b 100644--- a/crates/legacy/download-manager/examples/wasm/www/index.js+++ b/crates/legacy/download-manager/examples/wasm/www/index.js@@ -1,8 +1,6 @@const STATE_NOT_DOWNLOADED = "not_downloaded";const STATE_DOWNLOADING = "downloading";const STATE_PAUSED = "paused";-const STATE_DOWNLOADED = "downloaded";-const STATE_LOCKED = "locked";const STATE_ERROR = "error";const downloadButton = document.getElementById("btn-download");diff --git a/crates/legacy/download-manager/src/backends/active_task.rs b/crates/legacy/download-manager/src/backends/active_task.rsnew file mode 100644index 000000000..e9f3521ec--- /dev/null+++ b/crates/legacy/download-manager/src/backends/active_task.rs@@ -0,0 +1,14 @@+use std::path::Path;++use crate::backends::BackendError;++#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]+#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]+pub trait ActiveTask: Send + Sync {+ async fn pause(+ self: Box<Self>,+ resume_artifact_path: &Path,+ ) -> Result<(), BackendError>;++ async fn cancel(self: Box<Self>);+}diff --git a/crates/legacy/download-manager/src/backends/apple/active_task.rs b/crates/legacy/download-manager/src/backends/apple/active_task.rsdeleted file mode 100644index 764147991..000000000--- a/crates/legacy/download-manager/src/backends/apple/active_task.rs+++ /dev/null@@ -1,100 +0,0 @@-use std::{- path::{Path, PathBuf},- sync::{Arc, Mutex},-};--use objc2::rc::Retained;-use objc2_foundation::NSURLSessionDownloadTask;-use tokio::sync::oneshot::channel as tokio_oneshot_channel;--use crate::{- DownloadId,- backends::apple::{- AppleBackend, AppleBackendError, AppleEventRegistry, AppleSinkKey, resume_data_handler::ResumeDataHandler,- task_ext::AppleDownloadTaskExt,- },- traits::{ActiveTask, CancelOutcome, DownloadBackend},-};--#[derive(Debug)]-pub struct AppleActiveTask {- task: Retained<NSURLSessionDownloadTask>,- event_registry: AppleEventRegistry,- sink_key: AppleSinkKey,-}--impl AppleActiveTask {- pub fn new(- task: Retained<NSURLSessionDownloadTask>,- event_registry: AppleEventRegistry,- download_id: DownloadId,- ) -> Self {- let sink_key = (download_id, task.task_identifier());- Self {- task,- event_registry,- sink_key,- }- }-- fn unregister_event_sink(&self) {- if let Ok(mut event_registry) = self.event_registry.lock() {- event_registry.remove(&self.sink_key);- }- }-}--impl Drop for AppleActiveTask {- fn drop(&mut self) {- self.unregister_event_sink();- self.task.cancel();- }-}--#[async_trait::async_trait]-impl ActiveTask for AppleActiveTask {- type Backend = AppleBackend;-- async fn pause(- self,- destination: &Path,- ) -> Result<PathBuf, <Self::Backend as DownloadBackend>::Error> {- let resume_artifact_path = destination.with_extension("resume_data");- let (resume_data_sender, resume_data_receiver) = tokio_oneshot_channel::<Box<[u8]>>();- let pending_resume_data_sender = Arc::new(Mutex::new(Some(resume_data_sender)));- self.unregister_event_sink();- {- let pending_resume_data_sender = Arc::clone(&pending_resume_data_sender);- let handler = ResumeDataHandler::new_bytes(move |resume_data_bytes| {- let resume_data_sender = match pending_resume_data_sender.lock() {- Ok(mut resume_data_sender) => resume_data_sender.take(),- Err(poisoned_sender) => {- let mut resume_data_sender = poisoned_sender.into_inner();- resume_data_sender.take()- },- };- if let Some(resume_data_sender) = resume_data_sender {- let _ = resume_data_sender.send(resume_data_bytes);- }- });- unsafe {- self.task.cancelByProducingResumeData(&handler);- }- }- let resume_data_bytes =- resume_data_receiver.await.map_err(|error| AppleBackendError::ResumeData(error.to_string()))?;- tokio::fs::write(&resume_artifact_path, resume_data_bytes)- .await- .map_err(|error| AppleBackendError::Io(error.to_string()))?;- Ok(resume_artifact_path)- }-- async fn cancel(- self,- _destination: &Path,- ) -> CancelOutcome {- self.unregister_event_sink();- self.task.cancel();- CancelOutcome::BestEffort- }-}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_active_task.rs b/crates/legacy/download-manager/src/backends/apple/apple_active_task.rsnew file mode 100644index 000000000..52cb36acf--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_active_task.rs@@ -0,0 +1,66 @@+use std::{+ path::Path,+ sync::{Mutex, PoisonError},+};++use block2::RcBlock;+use kiban::fs;+use objc2::rc::Retained;+use objc2_foundation::{NSData, NSURLSessionDownloadTask};+use tokio::sync::oneshot::channel as tokio_oneshot_channel;++use crate::backends::{+ ActiveTask, BackendError,+ apple::{AppleBackendError, AppleEventRegistry},+};++pub struct AppleActiveTask {+ task: Retained<NSURLSessionDownloadTask>,+ event_registry: AppleEventRegistry,+}++impl AppleActiveTask {+ pub fn new(+ task: Retained<NSURLSessionDownloadTask>,+ event_registry: AppleEventRegistry,+ ) -> Self {+ Self {+ task,+ event_registry,+ }+ }++ fn unregister(&self) {+ self.event_registry.lock().unwrap_or_else(PoisonError::into_inner).remove(&self.task.taskIdentifier());+ }+}++#[async_trait::async_trait]+impl ActiveTask for AppleActiveTask {+ async fn pause(+ self: Box<Self>,+ resume_artifact_path: &Path,+ ) -> Result<(), BackendError> {+ self.unregister();+ let (sender, receiver) = tokio_oneshot_channel::<Vec<u8>>();+ {+ let sender = Mutex::new(Some(sender));+ let handler = RcBlock::new(move |resume_data: *mut NSData| {+ if let Some(sender) = sender.lock().unwrap_or_else(PoisonError::into_inner).take() {+ let _ = sender.send(unsafe { resume_data.as_ref() }.map(|data| data.to_vec()).unwrap_or_default());+ }+ });+ unsafe {+ self.task.cancelByProducingResumeData(&handler);+ }+ }+ let resume_data = receiver.await.map_err(AppleBackendError::CallbackDropped)?;+ fs::asyn::write(resume_artifact_path, resume_data).await?;+ Ok(())+ }++ async fn cancel(self: Box<Self>) {+ self.unregister();+ self.task.cancel();+ }+}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_backend.rs b/crates/legacy/download-manager/src/backends/apple/apple_backend.rsnew file mode 100644index 000000000..dbb0b9c21--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_backend.rs@@ -0,0 +1,207 @@+use std::{+ path::Path,+ ptr::NonNull,+ sync::{Arc, Mutex, PoisonError},+};++use block2::RcBlock;+use kiban::{fs, rt::RuntimeHandle};+use objc2::{rc::Retained, runtime::ProtocolObject};+use objc2_foundation::{+ NSArray, NSBundle, NSData, NSString, NSURL, NSURLSession, NSURLSessionConfiguration, NSURLSessionDataTask,+ NSURLSessionDelegate, NSURLSessionDownloadTask, NSURLSessionTaskState, NSURLSessionUploadTask,+};+use tokio::sync::{OnceCell as TokioOnceCell, oneshot::channel as tokio_oneshot_channel};++use crate::{+ backends::{+ ActiveTask, Backend, BackendError, BackendEventSender, DownloadGeneration,+ apple::{+ AppleActiveTask, AppleBackendError, AppleEventRegistry, AppleEventSink, AppleSessionDelegate,+ AppleTaskDescription, ResumeData,+ },+ },+ file_download::DownloadConfig,+};++pub struct AppleBackend {+ session: Retained<NSURLSession>,+ _delegate_protocol_object: Retained<ProtocolObject<dyn NSURLSessionDelegate>>,+ event_registry: AppleEventRegistry,+ runtime_handle: RuntimeHandle,+ pending_tasks: TokioOnceCell<Mutex<Vec<Retained<NSURLSessionDownloadTask>>>>,+}++unsafe impl Send for AppleBackend {}+unsafe impl Sync for AppleBackend {}++impl AppleBackend {+ pub fn new(runtime_handle: RuntimeHandle) -> Self {+ let event_registry = AppleEventRegistry::default();+ let delegate_protocol_object = ProtocolObject::<dyn NSURLSessionDelegate>::from_retained(+ AppleSessionDelegate::new(Arc::clone(&event_registry)),+ );+ let bundle_id = Self::bundle_identifier();+ let configuration = if bundle_id.is_empty() {+ NSURLSessionConfiguration::ephemeralSessionConfiguration()+ } else {+ let session_id = NSString::from_str(&format!("{bundle_id}.trymirai.download-manager"));+ let configuration = NSURLSessionConfiguration::backgroundSessionConfigurationWithIdentifier(&session_id);+ configuration.setSessionSendsLaunchEvents(true);+ configuration.setDiscretionary(false);+ configuration.setWaitsForConnectivity(true);+ configuration+ };+ let session = unsafe {+ NSURLSession::sessionWithConfiguration_delegate_delegateQueue(+ &configuration,+ Some(&delegate_protocol_object),+ None,+ )+ };+ Self {+ session,+ _delegate_protocol_object: delegate_protocol_object,+ event_registry,+ runtime_handle,+ pending_tasks: TokioOnceCell::new(),+ }+ }++ pub fn bundle_identifier() -> String {+ NSBundle::mainBundle().bundleIdentifier().unwrap_or_default().to_string()+ }++ async fn pending_tasks(&self) -> Result<&Mutex<Vec<Retained<NSURLSessionDownloadTask>>>, BackendError> {+ self.pending_tasks+ .get_or_try_init(|| async {+ let (tasks_sender, tasks_receiver) = tokio_oneshot_channel();+ {+ let tasks_sender = Mutex::new(Some(tasks_sender));+ let handler = RcBlock::new(+ move |_data_tasks: NonNull<NSArray<NSURLSessionDataTask>>,+ _upload_tasks: NonNull<NSArray<NSURLSessionUploadTask>>,+ download_tasks: NonNull<NSArray<NSURLSessionDownloadTask>>| {+ if let Some(sender) = tasks_sender.lock().unwrap_or_else(PoisonError::into_inner).take() {+ let _ = sender.send(unsafe { download_tasks.as_ref() }.to_vec());+ }+ },+ );+ unsafe {+ self.session.getTasksWithCompletionHandler(&handler);+ }+ }+ let tasks = tasks_receiver.await.map_err(AppleBackendError::CallbackDropped)?;+ Ok(Mutex::new(tasks))+ })+ .await+ }++ fn activate(+ &self,+ task: Retained<NSURLSessionDownloadTask>,+ config: &DownloadConfig,+ generation: DownloadGeneration,+ events: BackendEventSender,+ ) -> Box<dyn ActiveTask> {+ if let Ok(json) = serde_json::to_string(&AppleTaskDescription::from(config)) {+ task.setTaskDescription(Some(&NSString::from_str(&json)));+ }+ self.event_registry.lock().unwrap_or_else(PoisonError::into_inner).insert(+ task.taskIdentifier(),+ AppleEventSink {+ generation,+ destination: config.destination.clone(),+ events,+ runtime_handle: self.runtime_handle.clone(),+ },+ );+ task.resume();+ Box::new(AppleActiveTask::new(task, Arc::clone(&self.event_registry)))+ }++ fn is_live(task: &NSURLSessionDownloadTask) -> bool {+ matches!(task.state(), NSURLSessionTaskState::Running | NSURLSessionTaskState::Suspended)+ }+}++#[async_trait::async_trait]+impl Backend for AppleBackend {+ fn name(&self) -> &'static str {+ "apple"+ }++ fn resume_artifact_extension(&self) -> &'static str {+ "resume_data"+ }++ async fn start(+ &self,+ config: Arc<DownloadConfig>,+ generation: DownloadGeneration,+ events: BackendEventSender,+ ) -> Result<Box<dyn ActiveTask>, BackendError> {+ let resume_data = fs::asyn::read(&config.resume_artifact_path).await.unwrap_or_default();+ let task = if resume_data.is_empty() {+ let url = NSURL::URLWithString(&NSString::from_str(&config.source_url))+ .ok_or_else(|| AppleBackendError::InvalidUrl(config.source_url.clone()))?;+ self.session.downloadTaskWithURL(&url)+ } else {+ self.session.downloadTaskWithResumeData(&NSData::with_bytes(&resume_data))+ };+ Ok(self.activate(task, &config, generation, events))+ }++ async fn read_resume_progress(+ &self,+ resume_artifact_path: &Path,+ ) -> u64 {+ ResumeData::new(fs::asyn::read(resume_artifact_path).await.unwrap_or_default()).bytes_received().unwrap_or(0)+ }++ async fn has_pending_task(+ &self,+ config: &DownloadConfig,+ ) -> Result<bool, BackendError> {+ let pending_tasks = self.pending_tasks().await?.lock().unwrap_or_else(PoisonError::into_inner);+ Ok(pending_tasks.iter().any(|task| {+ Self::is_live(task)+ && AppleTaskDescription::of(task)+ .is_some_and(|description| description.download_id == config.download_id)+ }))+ }++ async fn attach_pending_task(+ &self,+ config: Arc<DownloadConfig>,+ generation: DownloadGeneration,+ events: BackendEventSender,+ ) -> Result<Option<Box<dyn ActiveTask>>, BackendError> {+ let candidates = {+ let mut pending_tasks = self.pending_tasks().await?.lock().unwrap_or_else(PoisonError::into_inner);+ let (candidates, rest): (Vec<_>, Vec<_>) =+ std::mem::take(&mut *pending_tasks).into_iter().partition(|task| {+ AppleTaskDescription::of(task)+ .is_some_and(|description| description.download_id == config.download_id)+ });+ *pending_tasks = rest;+ candidates+ };+ let mut attached = None;+ for task in candidates {+ if attached.is_none()+ && Self::is_live(&task)+ && AppleTaskDescription::of(&task).is_some_and(|description| {+ description.download_id == config.download_id+ && description.source_url == config.source_url+ && description.crc32c == config.expected_crc32c+ })+ {+ attached = Some(self.activate(task, &config, generation, events.clone()));+ } else {+ task.cancel();+ }+ }+ Ok(attached)+ }+}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_backend_error.rs b/crates/legacy/download-manager/src/backends/apple/apple_backend_error.rsnew file mode 100644index 000000000..8a46d6643--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_backend_error.rs@@ -0,0 +1,9 @@+use tokio::sync::oneshot::error::RecvError;++#[derive(Debug, thiserror::Error)]+pub enum AppleBackendError {+ #[error("invalid url: {0}")]+ InvalidUrl(String),+ #[error("URLSession callback dropped: {0}")]+ CallbackDropped(#[from] RecvError),+}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_event_registry.rs b/crates/legacy/download-manager/src/backends/apple/apple_event_registry.rsnew file mode 100644index 000000000..8d794c144--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_event_registry.rs@@ -0,0 +1,10 @@+use std::{+ collections::HashMap,+ sync::{Arc, Mutex},+};++use objc2_foundation::NSUInteger;++use crate::backends::apple::AppleEventSink;++pub type AppleEventRegistry = Arc<Mutex<HashMap<NSUInteger, AppleEventSink>>>;diff --git a/crates/legacy/download-manager/src/backends/apple/apple_event_sink.rs b/crates/legacy/download-manager/src/backends/apple/apple_event_sink.rsnew file mode 100644index 000000000..7c5bed6b4--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_event_sink.rs@@ -0,0 +1,13 @@+use std::path::PathBuf;++use kiban::rt::RuntimeHandle;++use crate::backends::{BackendEventSender, DownloadGeneration};++#[derive(Clone, Debug)]+pub struct AppleEventSink {+ pub generation: DownloadGeneration,+ pub destination: PathBuf,+ pub events: BackendEventSender,+ pub runtime_handle: RuntimeHandle,+}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_session_delegate.rs b/crates/legacy/download-manager/src/backends/apple/apple_session_delegate.rsnew file mode 100644index 000000000..a8e382ad7--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_session_delegate.rs@@ -0,0 +1,134 @@+use std::{path::PathBuf, sync::PoisonError};++use objc2::{+ ClassType, DefinedClass, define_class, msg_send,+ rc::{Allocated, Retained},+};+use objc2_foundation::{+ NSError, NSObject, NSObjectProtocol, NSURL, NSURLSession, NSURLSessionDelegate, NSURLSessionDownloadDelegate,+ NSURLSessionDownloadTask, NSURLSessionTask, NSURLSessionTaskDelegate,+};++use crate::backends::{+ BackendEvent,+ apple::{AppleEventRegistry, AppleSessionDelegateIvars},+};++define_class!(+ #[unsafe(super(NSObject))]+ #[derive(Debug)]+ #[ivars = AppleSessionDelegateIvars]+ pub struct AppleSessionDelegate;++ unsafe impl NSObjectProtocol for AppleSessionDelegate {}++ unsafe impl NSURLSessionDelegate for AppleSessionDelegate {}++ unsafe impl NSURLSessionTaskDelegate for AppleSessionDelegate {+ #[unsafe(method(URLSession:task:didCompleteWithError:))]+ fn did_complete_with_error(+ &self,+ _session: &NSURLSession,+ task: &NSURLSessionTask,+ error: Option<&NSError>,+ ) {+ let Some(error) = error else {+ return;+ };+ let Some(sink) = Self::ivars(self)+ .event_registry+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .remove(&task.taskIdentifier())+ else {+ return;+ };+ let message = error.localizedDescription().to_string();+ sink.runtime_handle.clone().spawn(async move {+ sink.events+ .send_terminal(BackendEvent::Error {+ generation: sink.generation,+ message,+ })+ .await;+ });+ }+ }++ unsafe impl NSURLSessionDownloadDelegate for AppleSessionDelegate {+ #[unsafe(method(URLSession:downloadTask:didFinishDownloadingToURL:))]+ fn did_finish_downloading_to_url(+ &self,+ _session: &NSURLSession,+ download_task: &NSURLSessionDownloadTask,+ location: &NSURL,+ ) {+ let Some(sink) = Self::ivars(self)+ .event_registry+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .remove(&download_task.taskIdentifier())+ else {+ return;+ };+ let Some(temporary_path) = location.path().map(|path| PathBuf::from(path.to_string())) else {+ return;+ };+ if let Some(parent) = sink.destination.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ let moved = std::fs::rename(&temporary_path, &sink.destination).or_else(|_| {+ std::fs::copy(&temporary_path, &sink.destination)?;+ let _ = std::fs::remove_file(&temporary_path);+ Ok::<(), std::io::Error>(())+ });+ let event = match moved {+ Ok(()) => BackendEvent::Completed {+ generation: sink.generation,+ },+ Err(error) => BackendEvent::Error {+ generation: sink.generation,+ message: format!("move into destination failed: {error}"),+ },+ };+ sink.runtime_handle.clone().spawn(async move {+ sink.events.send_terminal(event).await;+ });+ }++ #[unsafe(method(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:))]+ fn did_write_data(+ &self,+ _session: &NSURLSession,+ download_task: &NSURLSessionDownloadTask,+ _bytes_written_since_last_callback: i64,+ cumulative_bytes_written: i64,+ total_expected_bytes_to_write: i64,+ ) {+ let Some(sink) = Self::ivars(self)+ .event_registry+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .get(&download_task.taskIdentifier())+ .cloned()+ else {+ return;+ };+ let downloaded_bytes = cumulative_bytes_written.max(0) as u64;+ let total_bytes = (total_expected_bytes_to_write > 0).then_some(total_expected_bytes_to_write as u64);+ sink.events.send_progress(sink.generation, downloaded_bytes, total_bytes);+ }+ }+);++impl AppleSessionDelegate {+ pub fn new(event_registry: AppleEventRegistry) -> Retained<Self> {+ unsafe {+ let allocated: Allocated<Self> = msg_send![Self::class(), alloc];+ let allocated_with_ivars = allocated.set_ivars(AppleSessionDelegateIvars {+ event_registry,+ });+ msg_send![super(allocated_with_ivars), init]+ }+ }+}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_session_delegate_ivars.rs b/crates/legacy/download-manager/src/backends/apple/apple_session_delegate_ivars.rsnew file mode 100644index 000000000..34e5d78bb--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_session_delegate_ivars.rs@@ -0,0 +1,6 @@+use crate::backends::apple::AppleEventRegistry;++#[derive(Debug, Clone)]+pub struct AppleSessionDelegateIvars {+ pub event_registry: AppleEventRegistry,+}diff --git a/crates/legacy/download-manager/src/backends/apple/apple_task_description.rs b/crates/legacy/download-manager/src/backends/apple/apple_task_description.rsnew file mode 100644index 000000000..b0d29cb52--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/apple_task_description.rs@@ -0,0 +1,29 @@+use objc2_foundation::NSURLSessionDownloadTask;+use serde::{Deserialize, Serialize};++use crate::{Crc32c, DownloadId, file_download::DownloadConfig};++#[derive(Serialize, Deserialize, Debug)]+pub struct AppleTaskDescription {+ #[serde(default)]+ pub download_id: DownloadId,+ pub source_url: String,+ #[serde(default)]+ pub crc32c: Option<Crc32c>,+}++impl From<&DownloadConfig> for AppleTaskDescription {+ fn from(config: &DownloadConfig) -> Self {+ Self {+ download_id: config.download_id,+ source_url: config.source_url.clone(),+ crc32c: config.expected_crc32c.clone(),+ }+ }+}++impl AppleTaskDescription {+ pub fn of(task: &NSURLSessionDownloadTask) -> Option<Self> {+ serde_json::from_str(&task.taskDescription()?.to_string()).ok()+ }+}diff --git a/crates/legacy/download-manager/src/backends/apple/backend.rs b/crates/legacy/download-manager/src/backends/apple/backend.rsdeleted file mode 100644index 63d9db66b..000000000--- a/crates/legacy/download-manager/src/backends/apple/backend.rs+++ /dev/null@@ -1,87 +0,0 @@-use std::{path::Path, sync::Arc};--use kiban::rt::RuntimeHandle;-use objc2_foundation::NSURLSessionTaskState;--use crate::{- DownloadError,- backends::{- apple::{- AppleActiveTask, AppleBackendContext, AppleBackendError, resume_data_parser, task_ext::AppleDownloadTaskExt,- },- common::{self, InitialTaskAttachment},- },- lock_manager::DestinationLockLease,- traits::{ActiveDownloadGeneration, BackendEventSender, DownloadBackend, DownloadConfig},-};--#[derive(Clone, Debug, Default)]-pub struct AppleBackend;--impl DownloadBackend for AppleBackend {- type Context = AppleBackendContext;- type ActiveTask = AppleActiveTask;- type Error = AppleBackendError;-- async fn read_resume_progress(part_path: &Path) -> Option<u64> {- resume_data_parser::read_resume_progress(part_path)- }-}--#[async_trait::async_trait]-impl common::Backend for AppleBackend {- const RESUME_ARTIFACT_EXTENSION: &'static str = "resume_data";- const SUPPORTS_INITIAL_TASK_ATTACHMENT: bool = true;-- fn manager_suffix() -> &'static str {- "apple"- }-- fn create_context(runtime_handle: RuntimeHandle) -> Result<Self::Context, DownloadError> {- Ok(AppleBackendContext::new(runtime_handle))- }-- async fn initial_task_attachment(- context: &Self::Context,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- backend_event_sender: BackendEventSender,- _destination_lease: &DestinationLockLease,- ) -> Result<InitialTaskAttachment<Self>, DownloadError> {- let Some(task) = context- .claim_matching_download_task(&config)- .await- .map_err(|error| DownloadError::Backend(error.to_string()))?- else {- return Ok(InitialTaskAttachment::None);- };-- match task.state() {- NSURLSessionTaskState::Running | NSURLSessionTaskState::Suspended => {- let initial_downloaded_bytes = task.count_of_bytes_received();- let total_bytes = match task.count_of_bytes_expected_to_receive() {- 0 => config.expected_bytes,- total_bytes => Some(total_bytes),- };- context.attach_existing_task(&task, Arc::clone(&config), generation, backend_event_sender);- if matches!(task.state(), NSURLSessionTaskState::Suspended) {- task.resume();- }- Ok(InitialTaskAttachment::Downloading {- active_task: AppleActiveTask::new(task, context.event_registry(), config.download_id),- initial_downloaded_bytes,- total_bytes,- })- },- NSURLSessionTaskState::Completed | NSURLSessionTaskState::Canceling => Ok(InitialTaskAttachment::None),- _ => Ok(InitialTaskAttachment::None),- }- }-- async fn has_initial_task_to_claim(- context: &Self::Context,- config: &DownloadConfig,- ) -> Result<bool, DownloadError> {- context.has_download_task_to_claim(config).await.map_err(|error| DownloadError::Backend(error.to_string()))- }-}diff --git a/crates/legacy/download-manager/src/backends/apple/context.rs b/crates/legacy/download-manager/src/backends/apple/context.rsdeleted file mode 100644index 4d59921ff..000000000--- a/crates/legacy/download-manager/src/backends/apple/context.rs+++ /dev/null@@ -1,282 +0,0 @@-use std::{- collections::HashMap,- path::Path,- sync::{Arc, Mutex},-};--use kiban::rt::RuntimeHandle;-use objc2::{rc::Retained, runtime::ProtocolObject};-use objc2_foundation::{- NSBundle, NSData, NSString, NSURL, NSURLSession, NSURLSessionConfiguration, NSURLSessionDelegate,- NSURLSessionDownloadTask, NSURLSessionTaskState,-};-use tokio::sync::oneshot::channel as tokio_oneshot_channel;--use crate::{- DownloadInfo, FileCheck,- backends::apple::{- AppleActiveTask, AppleBackend, AppleBackendError, AppleEventRegistry, AppleEventSink, AppleGetTasksHandler,- AppleSessionDelegate, task_ext::AppleDownloadTaskExt,- },- lock_manager::DestinationLockLease,- traits::{ActiveDownloadGeneration, BackendContext, BackendEventSender, DownloadConfig},-};--pub struct AppleBackendContext {- session: Retained<NSURLSession>,- _delegate: Retained<AppleSessionDelegate>,- _delegate_protocol_object: Retained<ProtocolObject<dyn NSURLSessionDelegate>>,- event_registry: AppleEventRegistry,- runtime_handle: RuntimeHandle,-}--impl std::fmt::Debug for AppleBackendContext {- fn fmt(- &self,- formatter: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- formatter.debug_struct("AppleBackendContext").finish_non_exhaustive()- }-}--impl AppleBackendContext {- pub fn new(runtime_handle: RuntimeHandle) -> Self {- let event_registry = Arc::new(Mutex::new(HashMap::new()));- let delegate = AppleSessionDelegate::new(Arc::clone(&event_registry));- let delegate_protocol_object = AppleSessionDelegate::protocol_object(delegate.clone());- let session = unsafe {- NSURLSession::sessionWithConfiguration_delegate_delegateQueue(- &automatic_session_configuration(),- Some(&delegate_protocol_object),- None,- )- };-- Self {- session,- _delegate: delegate,- _delegate_protocol_object: delegate_protocol_object,- event_registry,- runtime_handle,- }- }-- pub(crate) async fn claim_matching_download_task(- &self,- config: &DownloadConfig,- ) -> Result<Option<Retained<NSURLSessionDownloadTask>>, AppleBackendError> {- self.find_download_task(config).await- }-- pub(crate) async fn has_download_task_to_claim(- &self,- config: &DownloadConfig,- ) -> Result<bool, AppleBackendError> {- let download_tasks = self.download_tasks().await?;- Ok(download_tasks- .iter()- .any(|task| task.download_id() == Some(config.download_id) && is_live_task_state(task.state())))- }-- #[cfg(test)]- #[allow(dead_code)]- pub(crate) fn event_sink_count_for_download(- &self,- download_id: crate::DownloadId,- ) -> usize {- self.event_registry- .lock()- .map(|registry| registry.keys().filter(|(id, _)| *id == download_id).count())- .unwrap_or(0)- }-- #[cfg(test)]- #[allow(dead_code)]- pub(crate) fn event_sink_task_identifiers_for_download(- &self,- download_id: crate::DownloadId,- ) -> Vec<u64> {- self.event_registry- .lock()- .map(|registry| {- registry- .keys()- .filter_map(|(id, task_identifier)| (*id == download_id).then_some(*task_identifier))- .collect()- })- .unwrap_or_default()- }-- async fn find_download_task(- &self,- config: &DownloadConfig,- ) -> Result<Option<Retained<NSURLSessionDownloadTask>>, AppleBackendError> {- let download_tasks = self.download_tasks().await?;- Ok(select_matching_download_task(download_tasks, config))- }-- async fn download_tasks(&self) -> Result<Box<[Retained<NSURLSessionDownloadTask>]>, AppleBackendError> {- let (download_tasks_sender, download_tasks_receiver) = tokio_oneshot_channel();- let pending_download_tasks_sender = Arc::new(Mutex::new(Some(download_tasks_sender)));- let handler = AppleGetTasksHandler::new({- let pending_download_tasks_sender = Arc::clone(&pending_download_tasks_sender);- move |_data_tasks, _upload_tasks, download_tasks| {- let download_tasks_sender = match pending_download_tasks_sender.lock() {- Ok(mut download_tasks_sender) => download_tasks_sender.take(),- Err(poisoned_sender) => {- let mut download_tasks_sender = poisoned_sender.into_inner();- download_tasks_sender.take()- },- };- if let Some(download_tasks_sender) = download_tasks_sender {- let _ = download_tasks_sender.send(download_tasks);- }- }- });- unsafe {- self.session.getTasksWithCompletionHandler(&handler);- }- download_tasks_receiver.await.map_err(|error| {- AppleBackendError::TaskEnumeration(format!("URLSession task enumeration callback dropped: {error}"))- })- }-- pub fn attach_existing_task(- &self,- task: &NSURLSessionDownloadTask,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- backend_event_sender: BackendEventSender,- ) {- self.prepare_task(task, config, generation, backend_event_sender);- }-- pub(crate) fn event_registry(&self) -> AppleEventRegistry {- Arc::clone(&self.event_registry)- }-}--fn select_matching_download_task(- download_tasks: Box<[Retained<NSURLSessionDownloadTask>]>,- config: &DownloadConfig,-) -> Option<Retained<NSURLSessionDownloadTask>> {- let mut live_match = None;- for task in download_tasks {- if task.download_id() != Some(config.download_id) {- continue;- }- let task_state = task.state();- if !is_live_task_state(task_state) {- continue;- }- let info = task.download_info();- let source_url_matches = info.as_ref().map(|info| info.source_url == config.source_url).unwrap_or(false);- let crc_matches = info.as_ref().map(|info| info.crc32c == config.file_check.expected_crc()).unwrap_or(false);- if !(source_url_matches && crc_matches) {- task.cancel();- continue;- }- if live_match.is_none() {- live_match = Some(task);- } else {- task.cancel();- }- }- live_match-}--fn is_live_task_state(state: NSURLSessionTaskState) -> bool {- matches!(state, NSURLSessionTaskState::Running | NSURLSessionTaskState::Suspended)-}--fn automatic_session_configuration() -> Retained<NSURLSessionConfiguration> {- let bundle_id = NSBundle::mainBundle().bundleIdentifier().unwrap_or_default().to_string();- if bundle_id.is_empty() {- NSURLSessionConfiguration::ephemeralSessionConfiguration()- } else {- let session_id = NSString::from_str(&format!("{bundle_id}.trymirai.download-manager"));- let configuration = NSURLSessionConfiguration::backgroundSessionConfigurationWithIdentifier(&session_id);- configuration.setSessionSendsLaunchEvents(true);- configuration.setDiscretionary(false);- configuration.setWaitsForConnectivity(true);- configuration- }-}--unsafe impl Send for AppleBackendContext {}-unsafe impl Sync for AppleBackendContext {}--#[async_trait::async_trait]-impl BackendContext for AppleBackendContext {- type Backend = AppleBackend;-- async fn download(- &self,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- backend_event_sender: BackendEventSender,- _destination_lease: &DestinationLockLease,- ) -> Result<AppleActiveTask, AppleBackendError> {- let ns_url = NSURL::URLWithString(&NSString::from_str(&config.source_url)).ok_or(AppleBackendError::BadUrl)?;- let task = self.session.downloadTaskWithURL(&ns_url);- self.prepare_task(&task, Arc::clone(&config), generation, backend_event_sender);- task.resume();- Ok(AppleActiveTask::new(task, Arc::clone(&self.event_registry), config.download_id))- }-- async fn resume(- &self,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- resume_artifact_path: &Path,- backend_event_sender: BackendEventSender,- _destination_lease: &DestinationLockLease,- ) -> Result<AppleActiveTask, AppleBackendError> {- let resume_data =- tokio::fs::read(resume_artifact_path).await.map_err(|error| AppleBackendError::Io(error.to_string()))?;- let task = if resume_data.is_empty() {- let ns_url =- NSURL::URLWithString(&NSString::from_str(&config.source_url)).ok_or(AppleBackendError::BadUrl)?;- self.session.downloadTaskWithURL(&ns_url)- } else {- let ns_data = NSData::with_bytes(&resume_data);- self.session.downloadTaskWithResumeData(&ns_data)- };- self.prepare_task(&task, Arc::clone(&config), generation, backend_event_sender);- task.resume();- Ok(AppleActiveTask::new(task, Arc::clone(&self.event_registry), config.download_id))- }-}--impl AppleBackendContext {- fn prepare_task(- &self,- task: &NSURLSessionDownloadTask,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- backend_event_sender: BackendEventSender,- ) {- let download_info = match &config.file_check {- FileCheck::CRC(crc) => DownloadInfo::with_crc(- config.source_url.clone(),- config.destination.to_string_lossy().to_string(),- crc.clone(),- ),- FileCheck::None => {- DownloadInfo::new(config.source_url.clone(), config.destination.to_string_lossy().to_string())- },- };- task.set_download_info(&download_info);- if let Ok(mut registry) = self.event_registry.lock() {- registry.insert(- (config.download_id, task.task_identifier()),- AppleEventSink {- generation,- destination: config.destination.clone(),- backend_event_sender,- runtime_handle: self.runtime_handle.clone(),- },- );- }- }-}diff --git a/crates/legacy/download-manager/src/backends/apple/delegate.rs b/crates/legacy/download-manager/src/backends/apple/delegate.rsdeleted file mode 100644index 2f272c8e7..000000000--- a/crates/legacy/download-manager/src/backends/apple/delegate.rs+++ /dev/null@@ -1,171 +0,0 @@-use std::{- collections::HashMap,- path::PathBuf,- sync::{Arc, Mutex},-};--use kiban::rt::RuntimeHandle;-use objc2::{- ClassType, DefinedClass, define_class, msg_send,- rc::{Allocated, Retained},- runtime::ProtocolObject,-};-use objc2_foundation::{- NSError, NSObject, NSObjectProtocol, NSURL, NSURLSession, NSURLSessionDelegate, NSURLSessionDownloadDelegate,- NSURLSessionDownloadTask, NSURLSessionTask, NSURLSessionTaskDelegate,-};--use crate::{- DownloadId,- backends::apple::task_ext::AppleDownloadTaskExt,- file_download_task_actor::BackendEvent,- traits::{ActiveDownloadGeneration, BackendEventSender},-};--#[derive(Clone, Debug)]-pub struct AppleEventSink {- pub generation: ActiveDownloadGeneration,- pub destination: PathBuf,- pub backend_event_sender: BackendEventSender,- pub runtime_handle: RuntimeHandle,-}--pub type AppleSinkKey = (DownloadId, u64);-pub type AppleEventRegistry = Arc<Mutex<HashMap<AppleSinkKey, AppleEventSink>>>;--#[derive(Debug, Clone)]-pub struct AppleSessionDelegateIvars {- pub event_registry: AppleEventRegistry,-}--define_class!(- #[unsafe(super(NSObject))]- #[derive(Debug)]- #[ivars = AppleSessionDelegateIvars]- pub struct AppleSessionDelegate;-- unsafe impl NSObjectProtocol for AppleSessionDelegate {}-- unsafe impl NSURLSessionDelegate for AppleSessionDelegate {- #[unsafe(method(URLSession:didBecomeInvalidWithError:))]- fn did_become_invalid_with_error(- &self,- _session: &NSURLSession,- _error: Option<&NSError>,- ) {- }- }-- unsafe impl NSURLSessionTaskDelegate for AppleSessionDelegate {- #[unsafe(method(URLSession:task:didCompleteWithError:))]- fn did_complete_with_error(- &self,- _session: &NSURLSession,- task: &NSURLSessionTask,- error: Option<&NSError>,- ) {- let Some(download_task) = task.downcast_ref::<NSURLSessionDownloadTask>() else {- return;- };- let Some(error) = error else {- return;- };- let Some(download_id) = download_task.download_id() else {- return;- };- let key: AppleSinkKey = (download_id, download_task.task_identifier());- let Some(sink) =- Self::ivars(self).event_registry.lock().ok().and_then(|mut registry| registry.remove(&key))- else {- return;- };- let message = error.localizedDescription().to_string();- sink.runtime_handle.clone().spawn(async move {- let _ = sink.backend_event_sender.send_terminal(BackendEvent::error(sink.generation, message)).await;- });- }- }-- unsafe impl NSURLSessionDownloadDelegate for AppleSessionDelegate {- #[unsafe(method(URLSession:downloadTask:didFinishDownloadingToURL:))]- fn did_finish_downloading_to_url(- &self,- _session: &NSURLSession,- download_task: &NSURLSessionDownloadTask,- location: &NSURL,- ) {- let Some(download_id) = download_task.download_id() else {- return;- };- let key: AppleSinkKey = (download_id, download_task.task_identifier());- let Some(sink) =- Self::ivars(self).event_registry.lock().ok().and_then(|mut registry| registry.remove(&key))- else {- return;- };- let Some(temporary_path) = location.path().map(|path| PathBuf::from(path.to_string())) else {- return;- };-- // Move synchronously: NSURLSession deletes the temp file as soon as this method returns.- if let Some(parent) = sink.destination.parent() {- let _ = std::fs::create_dir_all(parent);- }- let move_result = std::fs::rename(&temporary_path, &sink.destination).or_else(|_| {- std::fs::copy(&temporary_path, &sink.destination)?;- let _ = std::fs::remove_file(&temporary_path);- Ok::<(), std::io::Error>(())- });-- let terminal_event = match move_result {- Ok(()) => BackendEvent::completed(sink.generation),- Err(error) => BackendEvent::error(sink.generation, format!("move into destination failed: {error}")),- };- sink.runtime_handle.clone().spawn(async move {- let _ = sink.backend_event_sender.send_terminal(terminal_event).await;- });- }-- #[unsafe(method(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:))]- fn did_write_data(- &self,- _session: &NSURLSession,- download_task: &NSURLSessionDownloadTask,- _bytes_written_since_last_callback: i64,- cumulative_bytes_written: i64,- total_expected_bytes_to_write: i64,- ) {- let Some(download_id) = download_task.download_id() else {- return;- };- let key: AppleSinkKey = (download_id, download_task.task_identifier());- let Some(sink) =- Self::ivars(self).event_registry.lock().ok().and_then(|registry| registry.get(&key).cloned())- else {- return;- };- let downloaded_bytes = cumulative_bytes_written.max(0) as u64;- let total_bytes = (total_expected_bytes_to_write > 0).then_some(total_expected_bytes_to_write as u64);-- sink.runtime_handle.clone().spawn(async move {- sink.backend_event_sender.send_progress(sink.generation, downloaded_bytes, total_bytes).await;- });- }- }-);--impl AppleSessionDelegate {- pub fn new(event_registry: AppleEventRegistry) -> Retained<Self> {- unsafe {- let allocated: Allocated<Self> = msg_send![Self::class(), alloc];- let allocated_with_ivars = allocated.set_ivars(AppleSessionDelegateIvars {- event_registry,- });- msg_send![super(allocated_with_ivars), init]- }- }-- pub fn protocol_object(delegate: Retained<Self>) -> Retained<ProtocolObject<dyn NSURLSessionDelegate>> {- ProtocolObject::<dyn NSURLSessionDelegate>::from_retained(delegate)- }-}diff --git a/crates/legacy/download-manager/src/backends/apple/error.rs b/crates/legacy/download-manager/src/backends/apple/error.rsdeleted file mode 100644index 3efbc188f..000000000--- a/crates/legacy/download-manager/src/backends/apple/error.rs+++ /dev/null@@ -1,11 +0,0 @@-#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]-pub enum AppleBackendError {- #[error("bad url")]- BadUrl,- #[error("resume data error: {0}")]- ResumeData(String),- #[error("io error: {0}")]- Io(String),- #[error("task enumeration error: {0}")]- TaskEnumeration(String),-}diff --git a/crates/legacy/download-manager/src/backends/apple/get_tasks_handler.rs b/crates/legacy/download-manager/src/backends/apple/get_tasks_handler.rsdeleted file mode 100644index b96d4b10d..000000000--- a/crates/legacy/download-manager/src/backends/apple/get_tasks_handler.rs+++ /dev/null@@ -1,54 +0,0 @@-use std::{ops::Deref, ptr::NonNull};--use block2::{Block, RcBlock};-use objc2::rc::Retained;-use objc2_foundation::{NSArray, NSURLSessionDataTask, NSURLSessionDownloadTask, NSURLSessionUploadTask};--type AppleGetTasksBlock = dyn Fn(- NonNull<NSArray<NSURLSessionDataTask>>,- NonNull<NSArray<NSURLSessionUploadTask>>,- NonNull<NSArray<NSURLSessionDownloadTask>>,-);--pub struct AppleGetTasksHandler(RcBlock<AppleGetTasksBlock>);--impl AppleGetTasksHandler {- pub fn new(- handler: impl Fn(- Box<[Retained<NSURLSessionDataTask>]>,- Box<[Retained<NSURLSessionUploadTask>]>,- Box<[Retained<NSURLSessionDownloadTask>]>,- ) + Send- + Sync- + 'static- ) -> Self {- Self(RcBlock::new(- move |data_tasks_pointer: NonNull<NSArray<NSURLSessionDataTask>>,- upload_tasks_pointer: NonNull<NSArray<NSURLSessionUploadTask>>,- download_tasks_pointer: NonNull<NSArray<NSURLSessionDownloadTask>>| {- let data_tasks = unsafe { data_tasks_pointer.as_ref() };- let upload_tasks = unsafe { upload_tasks_pointer.as_ref() };- let download_tasks = unsafe { download_tasks_pointer.as_ref() };-- handler(- data_tasks.to_vec().into_boxed_slice(),- upload_tasks.to_vec().into_boxed_slice(),- download_tasks.to_vec().into_boxed_slice(),- );- },- ))- }-}--// SAFETY: ctor requires `Send + Sync + 'static` captures, and the block copies-// Objective-C arrays into owned retained values before invoking the Rust closure.-unsafe impl Send for AppleGetTasksHandler {}-unsafe impl Sync for AppleGetTasksHandler {}--impl Deref for AppleGetTasksHandler {- type Target = Block<AppleGetTasksBlock>;-- fn deref(&self) -> &Self::Target {- &self.0- }-}diff --git a/crates/legacy/download-manager/src/backends/apple/manager.rs b/crates/legacy/download-manager/src/backends/apple/manager.rsdeleted file mode 100644index a34befaef..000000000--- a/crates/legacy/download-manager/src/backends/apple/manager.rs+++ /dev/null@@ -1,3 +0,0 @@-use crate::backends::{apple::AppleBackend, common::DownloadManager};--pub type AppleDownloadManager = DownloadManager<AppleBackend>;diff --git a/crates/legacy/download-manager/src/backends/apple/mod.rs b/crates/legacy/download-manager/src/backends/apple/mod.rsindex 351e3b951..0c7b20341 100644--- a/crates/legacy/download-manager/src/backends/apple/mod.rs+++ b/crates/legacy/download-manager/src/backends/apple/mod.rs@@ -1,18 +1,19 @@-mod active_task;-mod backend;-mod context;-mod delegate;-mod error;-mod get_tasks_handler;-mod manager;-mod resume_data_handler;-mod resume_data_parser;-mod task_ext;+mod apple_active_task;+mod apple_backend;+mod apple_backend_error;+mod apple_event_registry;+mod apple_event_sink;+mod apple_session_delegate;+mod apple_session_delegate_ivars;+mod apple_task_description;+mod resume_data;-pub use active_task::AppleActiveTask;-pub use backend::AppleBackend;-pub use context::AppleBackendContext;-pub(crate) use delegate::{AppleEventRegistry, AppleEventSink, AppleSessionDelegate, AppleSinkKey};-pub use error::AppleBackendError;-pub(crate) use get_tasks_handler::AppleGetTasksHandler;-pub use manager::AppleDownloadManager;+pub use apple_active_task::AppleActiveTask;+pub use apple_backend::AppleBackend;+pub use apple_backend_error::AppleBackendError;+pub use apple_event_registry::AppleEventRegistry;+pub use apple_event_sink::AppleEventSink;+pub use apple_session_delegate::AppleSessionDelegate;+pub use apple_session_delegate_ivars::AppleSessionDelegateIvars;+pub use apple_task_description::AppleTaskDescription;+pub use resume_data::ResumeData;diff --git a/crates/legacy/download-manager/src/backends/apple/resume_data.rs b/crates/legacy/download-manager/src/backends/apple/resume_data.rsnew file mode 100644index 000000000..c197930e5--- /dev/null+++ b/crates/legacy/download-manager/src/backends/apple/resume_data.rs@@ -0,0 +1,45 @@+use objc2::{AnyThread, rc::Retained, runtime::AnyObject};+use objc2_foundation::{+ NSData, NSDictionary, NSKeyedUnarchiver, NSNumber, NSPropertyListFormat, NSPropertyListMutabilityOptions,+ NSPropertyListSerialization, NSString,+};++pub struct ResumeData(Vec<u8>);++impl ResumeData {+ pub fn new(bytes: Vec<u8>) -> Self {+ Self(bytes)+ }++ pub fn bytes_received(&self) -> Option<u64> {+ if self.0.is_empty() {+ return None;+ }+ let data = NSData::with_bytes(&self.0);+ let dictionary =+ Self::keyed_archive(&data).or_else(|| Self::property_list(&data))?.downcast::<NSDictionary>().ok()?;+ let value = dictionary.objectForKey(&NSString::from_str("NSURLSessionResumeBytesReceived"))?;+ Some(value.downcast::<NSNumber>().ok()?.unsignedLongLongValue())+ }++ fn keyed_archive(data: &NSData) -> Option<Retained<AnyObject>> {+ unsafe {+ let unarchiver = NSKeyedUnarchiver::initForReadingFromData_error(NSKeyedUnarchiver::alloc(), data).ok()?;+ unarchiver.setRequiresSecureCoding(false);+ let object = unarchiver.decodeObjectForKey(&NSString::from_str("NSKeyedArchiveRootObjectKey"));+ unarchiver.finishDecoding();+ object+ }+ }++ fn property_list(data: &NSData) -> Option<Retained<AnyObject>> {+ unsafe {+ NSPropertyListSerialization::propertyListWithData_options_format_error(+ data,+ NSPropertyListMutabilityOptions::MutableContainersAndLeaves,+ std::ptr::null_mut::<NSPropertyListFormat>(),+ )+ .ok()+ }+ }+}diff --git a/crates/legacy/download-manager/src/backends/apple/resume_data_handler.rs b/crates/legacy/download-manager/src/backends/apple/resume_data_handler.rsdeleted file mode 100644index db5410520..000000000--- a/crates/legacy/download-manager/src/backends/apple/resume_data_handler.rs+++ /dev/null@@ -1,32 +0,0 @@-use std::ops::Deref;--use block2::{Block, RcBlock};-use objc2_foundation::NSData;--pub struct ResumeDataHandler(RcBlock<dyn Fn(*mut NSData)>);--impl ResumeDataHandler {- pub fn new_bytes(handler: impl Fn(Box<[u8]>) + Send + Sync + 'static) -> Self {- Self(RcBlock::new(move |data_pointer: *mut NSData| {- let resume_data_bytes = if let Some(data) = unsafe { data_pointer.as_ref() } {- data.to_vec().into_boxed_slice()- } else {- Box::new([])- };- handler(resume_data_bytes);- }))- }-}--// SAFETY: ctor requires `Send + Sync + 'static` captures, and the block copies-// `NSData` into owned bytes before invoking the Rust closure.-unsafe impl Send for ResumeDataHandler {}-unsafe impl Sync for ResumeDataHandler {}--impl Deref for ResumeDataHandler {- type Target = Block<dyn Fn(*mut NSData)>;-- fn deref(&self) -> &Self::Target {- &self.0- }-}diff --git a/crates/legacy/download-manager/src/backends/apple/resume_data_parser.rs b/crates/legacy/download-manager/src/backends/apple/resume_data_parser.rsdeleted file mode 100644index c1364b04a..000000000--- a/crates/legacy/download-manager/src/backends/apple/resume_data_parser.rs+++ /dev/null@@ -1,83 +0,0 @@-use std::path::Path;--use objc2::{AnyThread, class, msg_send, rc::Retained, runtime::AnyObject};-use objc2_foundation::{- NSData, NSDictionary, NSKeyedUnarchiver, NSNumber, NSObject, NSObjectProtocol, NSPropertyListFormat,- NSPropertyListMutabilityOptions, NSPropertyListSerialization, NSString,-};--const RESUME_BYTES_RECEIVED_KEY: &str = "NSURLSessionResumeBytesReceived";--pub(crate) fn read_resume_progress(part_path: &Path) -> Option<u64> {- let bytes = std::fs::read(part_path).ok()?;- let nsdata = NSData::with_bytes(&bytes);- let dict = parse_resume_dict(&nsdata)?;- read_unsigned(&dict, RESUME_BYTES_RECEIVED_KEY)-}--fn parse_resume_dict(data: &NSData) -> Option<Retained<NSDictionary<NSString, NSObject>>> {- // Newer OS releases use NSKeyedArchive; older ones use a plain plist.- if let Some(dict) = parse_via_keyed_unarchiver(data) {- return Some(dict);- }- parse_via_property_list(data)-}--fn parse_via_keyed_unarchiver(data: &NSData) -> Option<Retained<NSDictionary<NSString, NSObject>>> {- unsafe {- let allocated = NSKeyedUnarchiver::alloc();- let unarchiver = NSKeyedUnarchiver::initForReadingFromData_error(allocated, data).ok()?;- unarchiver.setRequiresSecureCoding(false);-- let key = NSString::from_str("NSKeyedArchiveRootObjectKey");- let object = unarchiver.decodeObjectForKey(&key);- unarchiver.finishDecoding();-- let object = object?;- let dict_class = class!(NSDictionary);- let raw: *mut AnyObject = Retained::into_raw(object).cast();- let is_dict: bool = msg_send![raw, isKindOfClass: dict_class];- if !is_dict {- // Balance the `into_raw` by reclaiming ownership so the object drops.- let _ = Retained::<AnyObject>::from_raw(raw);- return None;- }- let typed_ptr = raw.cast::<NSDictionary<NSString, NSObject>>();- Retained::from_raw(typed_ptr)- }-}--fn parse_via_property_list(data: &NSData) -> Option<Retained<NSDictionary<NSString, NSObject>>> {- unsafe {- let object = NSPropertyListSerialization::propertyListWithData_options_format_error(- data,- NSPropertyListMutabilityOptions::MutableContainersAndLeaves,- core::ptr::null_mut::<NSPropertyListFormat>(),- )- .ok()?;- let dict_class = class!(NSDictionary);- let raw: *mut AnyObject = Retained::into_raw(object).cast();- let is_dict: bool = msg_send![raw, isKindOfClass: dict_class];- if !is_dict {- // Balance the `into_raw` by reclaiming ownership so the object drops.- let _ = Retained::<AnyObject>::from_raw(raw);- return None;- }- let typed_ptr = raw.cast::<NSDictionary<NSString, NSObject>>();- Retained::from_raw(typed_ptr)- }-}--fn read_unsigned(- dict: &NSDictionary<NSString, NSObject>,- key: &str,-) -> Option<u64> {- let key_ns = NSString::from_str(key);- let object = dict.objectForKey(&key_ns)?;- let number_class = class!(NSNumber);- if !object.isKindOfClass(number_class) {- return None;- }- let number = unsafe { Retained::cast_unchecked::<NSNumber>(object) };- Some(number.unsignedLongLongValue())-}diff --git a/crates/legacy/download-manager/src/backends/apple/task_ext.rs b/crates/legacy/download-manager/src/backends/apple/task_ext.rsdeleted file mode 100644index 2b50fca55..000000000--- a/crates/legacy/download-manager/src/backends/apple/task_ext.rs+++ /dev/null@@ -1,59 +0,0 @@-use std::path::PathBuf;--use objc2::msg_send;-use objc2_foundation::{NSString, NSURLSessionDownloadTask, NSURLSessionTaskState};--use crate::{DownloadId, DownloadInfo, compute_download_id};--pub trait AppleDownloadTaskExt {- fn set_download_info(- &self,- info: &DownloadInfo,- );- fn download_info(&self) -> Option<DownloadInfo>;- fn download_id(&self) -> Option<DownloadId>;- fn state(&self) -> NSURLSessionTaskState;- fn count_of_bytes_expected_to_receive(&self) -> u64;- fn count_of_bytes_received(&self) -> u64;- fn task_identifier(&self) -> u64;-}--impl AppleDownloadTaskExt for NSURLSessionDownloadTask {- fn set_download_info(- &self,- info: &DownloadInfo,- ) {- if let Ok(json) = info.to_json() {- let ns_string = NSString::from_str(&json);- self.setTaskDescription(Some(&ns_string));- }- }-- fn download_info(&self) -> Option<DownloadInfo> {- self.taskDescription()- .map(|description| description.to_string())- .and_then(|description| DownloadInfo::from_json(&description).ok())- }-- fn download_id(&self) -> Option<DownloadId> {- self.download_info().map(|info| compute_download_id(PathBuf::from(info.destination_path).as_path()))- }-- fn state(&self) -> NSURLSessionTaskState {- unsafe { msg_send![self, state] }- }-- fn count_of_bytes_expected_to_receive(&self) -> u64 {- let bytes_expected: i64 = unsafe { msg_send![self, countOfBytesExpectedToReceive] };- bytes_expected.max(0) as u64- }-- fn count_of_bytes_received(&self) -> u64 {- let bytes_received: i64 = unsafe { msg_send![self, countOfBytesReceived] };- bytes_received.max(0) as u64- }-- fn task_identifier(&self) -> u64 {- unsafe { msg_send![self, taskIdentifier] }- }-}diff --git a/crates/legacy/download-manager/src/backends/backend.rs b/crates/legacy/download-manager/src/backends/backend.rsnew file mode 100644index 000000000..8a031b4d9--- /dev/null+++ b/crates/legacy/download-manager/src/backends/backend.rs@@ -0,0 +1,150 @@+use std::{+ path::{Path, PathBuf},+ sync::Arc,+};++use kiban::fs;++use crate::{+ DownloadPhase, DownloadState,+ backends::{ActiveTask, BackendError, BackendEventSender, DownloadGeneration, VerifyError},+ crc_receipt::CrcReceipt,+ file_download::DownloadConfig,+ locks::{DestinationLock, LockError},+};++#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]+#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]+pub trait Backend: Send + Sync {+ fn name(&self) -> &'static str;++ fn resume_artifact_extension(&self) -> &'static str;++ async fn start(+ &self,+ config: Arc<DownloadConfig>,+ generation: DownloadGeneration,+ events: BackendEventSender,+ ) -> Result<Box<dyn ActiveTask>, BackendError>;++ async fn read_resume_progress(+ &self,+ resume_artifact_path: &Path,+ ) -> u64;++ async fn has_pending_task(+ &self,+ config: &DownloadConfig,+ ) -> Result<bool, BackendError>;++ async fn attach_pending_task(+ &self,+ config: Arc<DownloadConfig>,+ generation: DownloadGeneration,+ events: BackendEventSender,+ ) -> Result<Option<Box<dyn ActiveTask>>, BackendError>;++ fn resume_artifact_path(+ &self,+ destination: &Path,+ ) -> PathBuf {+ PathBuf::from(format!("{}.{}", destination.display(), self.resume_artifact_extension()))+ }++ async fn reconcile(+ &self,+ config: &DownloadConfig,+ ) -> Result<(DownloadState, Option<DestinationLock>), BackendError> {+ let untouched = !fs::asyn::is_file(&config.destination).await+ && !fs::asyn::is_file(&config.resume_artifact_path).await+ && !CrcReceipt::exists(&config.destination).await+ && DestinationLock::foreign_owner(&config.destination, &config.owner).await.is_none();+ let pending_task = self.has_pending_task(config).await?;+ if untouched && !pending_task {+ return Ok((DownloadState::new(config, DownloadPhase::NotDownloaded {}, 0, None), None));+ }+ let lock = match DestinationLock::acquire(&config.destination, &config.owner).await {+ Ok(lock) => lock,+ Err(LockError::LockedByOther {+ manager_id,+ }) => return Ok((self.observe(config, Some(manager_id)).await, None)),+ Err(error) => return Err(error.into()),+ };+ let state = self.observe(config, None).await;+ let attach = pending_task && state.phase != (DownloadPhase::Downloaded {});+ Ok((state, attach.then_some(lock)))+ }++ async fn observe(+ &self,+ config: &DownloadConfig,+ foreign_owner: Option<String>,+ ) -> DownloadState {+ let resume_bytes = if fs::asyn::is_file(&config.resume_artifact_path).await {+ Some(self.read_resume_progress(&config.resume_artifact_path).await)+ } else {+ None+ };+ let downloaded = if fs::asyn::is_file(&config.destination).await {+ self.verify(config).await.ok()+ } else {+ None+ };+ if foreign_owner.is_none() {+ if downloaded.is_some() {+ let _ = fs::asyn::remove_file(&config.resume_artifact_path).await;+ } else {+ let _ = fs::asyn::remove_file(&config.destination).await;+ CrcReceipt::remove(&config.destination).await;+ }+ }+ let (phase, downloaded_bytes, total_bytes) = match (downloaded, resume_bytes, foreign_owner) {+ (Some(size), _, _) => (DownloadPhase::Downloaded {}, size, Some(size)),+ (None, downloaded_bytes, Some(manager_id)) => (+ DownloadPhase::Locked {+ manager_id,+ },+ downloaded_bytes.unwrap_or(0),+ None,+ ),+ (None, Some(downloaded_bytes), None) => (DownloadPhase::Paused {}, downloaded_bytes, None),+ (None, None, None) => (DownloadPhase::NotDownloaded {}, 0, None),+ };+ DownloadState::new(config, phase, downloaded_bytes, total_bytes)+ }++ async fn verify(+ &self,+ config: &DownloadConfig,+ ) -> Result<u64, VerifyError> {+ let actual = fs::asyn::file_length(&config.destination).await?;+ if let Some(expected) = config.expected_bytes+ && expected != actual+ {+ return Err(VerifyError::Size {+ expected,+ actual,+ });+ }+ let Some(crc) = &config.expected_crc32c else {+ return Ok(actual);+ };+ if CrcReceipt::matches(&config.destination, crc).await {+ return Ok(actual);+ }+ if !crc.verify(&config.destination).await? {+ return Err(VerifyError::Crc);+ }+ let _ = CrcReceipt::save(&config.destination, crc).await;+ Ok(actual)+ }++ async fn remove_files(+ &self,+ config: &DownloadConfig,+ ) {+ let _ = fs::asyn::remove_file(&config.resume_artifact_path).await;+ let _ = fs::asyn::remove_file(&config.destination).await;+ CrcReceipt::remove(&config.destination).await;+ }+}diff --git a/crates/legacy/download-manager/src/backends/backend_error.rs b/crates/legacy/download-manager/src/backends/backend_error.rsnew file mode 100644index 000000000..94c4b760b--- /dev/null+++ b/crates/legacy/download-manager/src/backends/backend_error.rs@@ -0,0 +1,12 @@+use crate::locks::LockError;++#[derive(Debug, thiserror::Error)]+pub enum BackendError {+ #[error(transparent)]+ Io(#[from] std::io::Error),+ #[error(transparent)]+ Lock(#[from] LockError),+ #[cfg(target_vendor = "apple")]+ #[error(transparent)]+ Apple(#[from] crate::backends::AppleBackendError),+}diff --git a/crates/legacy/download-manager/src/backends/backend_event.rs b/crates/legacy/download-manager/src/backends/backend_event.rsnew file mode 100644index 000000000..bc2ef317a--- /dev/null+++ b/crates/legacy/download-manager/src/backends/backend_event.rs@@ -0,0 +1,26 @@+use crate::backends::DownloadGeneration;++#[derive(Debug)]+pub enum BackendEvent {+ Completed {+ generation: DownloadGeneration,+ },+ Error {+ generation: DownloadGeneration,+ message: String,+ },+}++impl BackendEvent {+ pub fn generation(&self) -> DownloadGeneration {+ match self {+ Self::Completed {+ generation,+ }+ | Self::Error {+ generation,+ ..+ } => *generation,+ }+ }+}diff --git a/crates/legacy/download-manager/src/backends/backend_event_sender.rs b/crates/legacy/download-manager/src/backends/backend_event_sender.rsnew file mode 100644index 000000000..25f2a0a34--- /dev/null+++ b/crates/legacy/download-manager/src/backends/backend_event_sender.rs@@ -0,0 +1,51 @@+use tokio::sync::{mpsc::Sender as TokioMpscSender, watch::Sender as TokioWatchSender};++use crate::{+ DownloadId,+ backends::{BackendEvent, BackendProgress, DownloadGeneration},+};++#[derive(Clone, Debug)]+pub struct BackendEventSender {+ download_id: DownloadId,+ terminal: TokioMpscSender<BackendEvent>,+ progress: TokioWatchSender<Option<BackendProgress>>,+}++impl BackendEventSender {+ pub fn new(+ download_id: DownloadId,+ terminal: TokioMpscSender<BackendEvent>,+ progress: TokioWatchSender<Option<BackendProgress>>,+ ) -> Self {+ Self {+ download_id,+ terminal,+ progress,+ }+ }++ pub async fn send_terminal(+ &self,+ event: BackendEvent,+ ) {+ tracing::debug!(download_id = %self.download_id, ?event, "backend terminal event");+ if let Err(dropped) = self.terminal.send(event).await {+ tracing::debug!(download_id = %self.download_id, event = ?dropped.0, "worker gone, terminal event dropped");+ }+ }++ pub fn send_progress(+ &self,+ generation: DownloadGeneration,+ downloaded_bytes: u64,+ total_bytes: Option<u64>,+ ) {+ tracing::trace!(download_id = %self.download_id, ?generation, downloaded_bytes, total_bytes, "backend progress");+ self.progress.send_replace(Some(BackendProgress {+ generation,+ downloaded_bytes,+ total_bytes,+ }));+ }+}diff --git a/crates/legacy/download-manager/src/backends/backend_progress.rs b/crates/legacy/download-manager/src/backends/backend_progress.rsnew file mode 100644index 000000000..ccd3ad64e--- /dev/null+++ b/crates/legacy/download-manager/src/backends/backend_progress.rs@@ -0,0 +1,8 @@+use crate::backends::DownloadGeneration;++#[derive(Clone, Copy, Debug)]+pub struct BackendProgress {+ pub generation: DownloadGeneration,+ pub downloaded_bytes: u64,+ pub total_bytes: Option<u64>,+}diff --git a/crates/legacy/download-manager/src/backends/common/action_executor.rs b/crates/legacy/download-manager/src/backends/common/action_executor.rsdeleted file mode 100644index 19f836b01..000000000--- a/crates/legacy/download-manager/src/backends/common/action_executor.rs+++ /dev/null@@ -1,47 +0,0 @@-use std::path::Path;--use kiban::fs;--use crate::{- DownloadError,- crc_utils::save_crc_file,- lock_manager::DestinationLockLease,- reducer::{Action, ActionPlan},-};--pub async fn apply_actions(- action_plan: &ActionPlan,- _destination_lease: &DestinationLockLease,-) -> Result<(), DownloadError> {- for action in action_plan.as_slice() {- match action {- Action::DeleteFile {- path,- }- | Action::DeleteCrcCache {- path,- }- | Action::DeleteResumeArtifact {- path,- } => {- remove_file_if_present(path).await?;- },- Action::SaveCrcCache {- destination,- crc,- } => {- save_crc_file(destination, crc).await?;- },- }- }-- Ok(())-}--async fn remove_file_if_present(path: &Path) -> Result<(), DownloadError> {- match fs::asyn::remove_file(path).await {- Ok(()) => Ok(()),- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),- Err(error) => Err(DownloadError::from(error)),- }-}diff --git a/crates/legacy/download-manager/src/backends/common/backend.rs b/crates/legacy/download-manager/src/backends/common/backend.rsdeleted file mode 100644index b79d4d0d3..000000000--- a/crates/legacy/download-manager/src/backends/common/backend.rs+++ /dev/null@@ -1,47 +0,0 @@-use std::{fmt::Debug, sync::Arc};--use kiban::rt::RuntimeHandle;--use crate::{- DownloadError,- lock_manager::DestinationLockLease,- traits::{ActiveDownloadGeneration, BackendEventSender, DownloadBackend, DownloadConfig},-};--pub enum InitialTaskAttachment<B: Backend> {- None,- #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))]- Downloading {- active_task: B::ActiveTask,- initial_downloaded_bytes: u64,- total_bytes: Option<u64>,- },-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-pub trait Backend: DownloadBackend + Debug + Clone + Send + Sync + Sized + 'static {- const RESUME_ARTIFACT_EXTENSION: &'static str;- const SUPPORTS_INITIAL_TASK_ATTACHMENT: bool = false;-- fn manager_suffix() -> &'static str;-- fn create_context(runtime_handle: RuntimeHandle) -> Result<Self::Context, DownloadError>;-- async fn initial_task_attachment(- _context: &Self::Context,- _config: Arc<DownloadConfig>,- _generation: ActiveDownloadGeneration,- _backend_event_sender: BackendEventSender,- _destination_lease: &DestinationLockLease,- ) -> Result<InitialTaskAttachment<Self>, DownloadError> {- Ok(InitialTaskAttachment::None)- }-- async fn has_initial_task_to_claim(- _context: &Self::Context,- _config: &DownloadConfig,- ) -> Result<bool, DownloadError> {- Ok(false)- }-}diff --git a/crates/legacy/download-manager/src/backends/common/manager.rs b/crates/legacy/download-manager/src/backends/common/manager.rsdeleted file mode 100644index 423a9d668..000000000--- a/crates/legacy/download-manager/src/backends/common/manager.rs+++ /dev/null@@ -1,315 +0,0 @@-use std::sync::Arc;--use kiban::rt::RuntimeHandle;-use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;--use crate::{- DownloadError, DownloadEvent, FileCheck, FileDownloadManager, FileDownloadTask, LockFileState,- backends::common::{Backend, DownloadManagerState, Startup},- check_lock_file, compute_download_id,- download_log_event::{DownloadLogEvent, log},- file_download_task::CachedFileDownloadTask,- file_download_task_actor::GenericFileDownloadTask,- lock_manager::{DestinationLockLease, lock_path_for_destination},- reducer::InitialLifecycleState,-};--#[derive(Clone, Debug)]-pub struct DownloadManager<B: Backend> {- pub(crate) state: DownloadManagerState,- pub(crate) context: Arc<B::Context>,-}--impl<B: Backend> DownloadManager<B> {- pub fn from_runtime_handle(runtime_handle: RuntimeHandle) -> Result<Self, DownloadError> {- let context = B::create_context(runtime_handle)?;- let state = DownloadManagerState::new(B::manager_suffix());- log(DownloadLogEvent::ManagerCreated {- manager_id: state.manager_id.clone(),- });- Ok(Self {- state,- context: Arc::new(context),- })- }-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-impl<B: Backend> FileDownloadManager for DownloadManager<B> {- fn manager_id(&self) -> &str {- &self.state.manager_id- }-- fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<DownloadEvent> {- self.state.subscribe_to_all_downloads()- }-- fn global_broadcast_sender(&self) -> crate::SharedDownloadEventSender {- self.state.global_broadcast_sender()- }-- async fn get_all_file_tasks(&self) -> Result<Vec<Arc<dyn FileDownloadTask>>, DownloadError> {- self.state.get_all_file_tasks().await- }-- async fn remove_file_task(- &self,- download_id: crate::DownloadId,- ) -> Result<(), DownloadError> {- let construction_lock = self.state.construction_lock(download_id).await;- let _construction_guard = construction_lock.lock().await;- let shutdown_result = match self.state.take_task(download_id).await {- Some(task) => task.managed().shutdown_for_removal().await,- None => Ok(()),- };- self.state.remove_construction_lock_if_unshared(download_id, &construction_lock).await;- match shutdown_result {- Ok(()) | Err(DownloadError::TaskStopped | DownloadError::ChannelClosed) => Ok(()),- Err(error) => Err(error),- }- }-- async fn file_download_task(- &self,- source_url: &str,- destination_path: &std::path::Path,- file_check: FileCheck,- expected_bytes: Option<u64>,- ) -> Result<Arc<dyn FileDownloadTask>, DownloadError> {- let download_id = compute_download_id(destination_path);- if let Some(cached_task) = self.state.get_task(download_id).await- && !cached_task.is_stopped()- {- let task = cached_task.public();- ensure_cached_task_matches(&task, source_url, &file_check, expected_bytes)?;- return Ok(task);- }-- let construction_lock = self.state.construction_lock(download_id).await;- let _construction_guard = construction_lock.lock().await;- let result = async {- let cached_task_result = match self.state.get_task(download_id).await {- Some(cached_task) if !cached_task.is_stopped() => {- let task = cached_task.public();- ensure_cached_task_matches(&task, source_url, &file_check, expected_bytes)?;- Some(Ok(task))- },- Some(_) => {- let _ = self.state.take_task(download_id).await;- None- },- None => None,- };- if let Some(cached_task_result) = cached_task_result {- cached_task_result- } else {- let startup = observe_startup::<B>(- download_id,- source_url,- destination_path,- file_check.clone(),- expected_bytes,- &self.state.manager_id,- self.state.instance_id,- )- .await?;- let (startup, startup_lease) = prepare_startup::<B>(- startup,- self.context.as_ref(),- download_id,- source_url,- destination_path,- file_check,- expected_bytes,- &self.state.manager_id,- self.state.instance_id,- )- .await?;-- log(DownloadLogEvent::StartupReconciled {- download_id,- initial_lifecycle_state: startup.initial_lifecycle_state.name(),- action_count: startup.action_plan.as_slice().len(),- });-- let task = Arc::new(- GenericFileDownloadTask::<B>::spawn_with_initial_attachment(- startup.config,- Arc::clone(&self.context),- startup.initial_lifecycle_state,- startup.initial_projection,- startup.initial_progress,- startup_lease,- )- .await?,- );- log(DownloadLogEvent::TaskSpawned {- download_id,- });- let public_task: Arc<dyn FileDownloadTask> = task.clone();- let managed_task = task;- self.state- .insert_task(download_id, CachedFileDownloadTask::new(Arc::clone(&public_task), managed_task))- .await;- Ok(public_task)- }- }- .await;- if result.is_err() {- self.state.remove_construction_lock_if_unshared(download_id, &construction_lock).await;- }- result- }-- async fn destination_foreign_lock(- &self,- destination_path: &std::path::Path,- ) -> Option<String> {- let lock_path = lock_path_for_destination(destination_path);- match check_lock_file(&lock_path, &self.state.manager_id, self.state.instance_id, kiban::process::id()).await {- LockFileState::OwnedByOtherApp(info) => Some(info.manager_id),- _ => None,- }- }-}--pub(crate) async fn observe_startup<B: Backend>(- download_id: crate::DownloadId,- source_url: &str,- destination_path: &std::path::Path,- file_check: FileCheck,- expected_bytes: Option<u64>,- manager_id: &str,- manager_instance_id: uuid::Uuid,-) -> Result<Startup, DownloadError> {- Startup::observe::<B>(- download_id,- source_url,- destination_path,- file_check,- expected_bytes,- manager_id,- manager_instance_id,- )- .await-}--pub(crate) async fn prepare_startup<B: Backend>(- startup: Startup,- context: &B::Context,- download_id: crate::DownloadId,- source_url: &str,- destination_path: &std::path::Path,- file_check: FileCheck,- expected_bytes: Option<u64>,- manager_id: &str,- manager_instance_id: uuid::Uuid,-) -> Result<(Startup, Option<DestinationLockLease>), DownloadError> {- if !startup_requires_destination_lease::<B>(&startup, context).await? {- return Ok((startup, None));- }-- let lease =- match DestinationLockLease::acquire_for_destination(destination_path, manager_id, manager_instance_id).await {- Ok(lease) => lease,- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {- let startup = observe_startup::<B>(- download_id,- source_url,- destination_path,- file_check,- expected_bytes,- manager_id,- manager_instance_id,- )- .await?;- if startup.lock_state.is_conflict() {- return Ok((startup, None));- }- return Err(DownloadError::from(error));- },- Err(error) => return Err(DownloadError::from(error)),- };- let startup = match observe_startup::<B>(- download_id,- source_url,- destination_path,- file_check,- expected_bytes,- manager_id,- manager_instance_id,- )- .await- {- Ok(startup) => startup,- Err(error) => {- let _ = lease.release().await;- return Err(error);- },- };-- if let Err(error) = startup.apply_actions(&lease).await {- let _ = lease.release().await;- return Err(error);- }-- if startup_can_attach_initial_task::<B>(&startup) {- Ok((startup, Some(lease)))- } else {- lease.release().await?;- Ok((startup, None))- }-}--async fn startup_requires_destination_lease<B: Backend>(- startup: &Startup,- context: &B::Context,-) -> Result<bool, DownloadError> {- if startup.lock_state.is_conflict() || !startup.action_plan.is_empty() {- return Ok(!startup.lock_state.is_conflict());- }-- if !startup_can_attach_initial_task::<B>(startup) {- return Ok(false);- }-- B::has_initial_task_to_claim(context, startup.config.as_ref()).await-}--fn startup_can_attach_initial_task<B: Backend>(startup: &Startup) -> bool {- B::SUPPORTS_INITIAL_TASK_ATTACHMENT- && !startup.lock_state.is_conflict()- && !matches!(startup.initial_lifecycle_state, InitialLifecycleState::Downloaded)-}--fn ensure_cached_task_matches(- cached: &Arc<dyn FileDownloadTask>,- source_url: &str,- file_check: &FileCheck,- expected_bytes: Option<u64>,-) -> Result<(), DownloadError> {- if cached.source_url() != source_url {- return Err(DownloadError::ConflictingConfig(format!(- "{} already requested with source_url {:?}; cannot reuse for {:?}",- cached.destination().display(),- cached.source_url(),- source_url,- )));- }- if cached.file_check() != file_check {- return Err(DownloadError::ConflictingConfig(format!(- "{} already requested with a different file_check",- cached.destination().display(),- )));- }- if cached.expected_bytes() != expected_bytes {- return Err(DownloadError::ConflictingConfig(format!(- "{} already requested with expected_bytes {:?}; got {:?}",- cached.destination().display(),- cached.expected_bytes(),- expected_bytes,- )));- }- Ok(())-}diff --git a/crates/legacy/download-manager/src/backends/common/manager_state.rs b/crates/legacy/download-manager/src/backends/common/manager_state.rsdeleted file mode 100644index 1d6a4211e..000000000--- a/crates/legacy/download-manager/src/backends/common/manager_state.rs+++ /dev/null@@ -1,124 +0,0 @@-use std::{collections::HashMap, sync::Arc};--use tokio::sync::{Mutex as TokioMutex, broadcast::channel as tokio_broadcast_channel};-use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;-use uuid::Uuid;--use crate::{- DownloadError, DownloadEvent, DownloadId, FileDownloadTask, SharedDownloadEventSender,- file_download_task::CachedFileDownloadTask,-};--type TaskCache = Arc<TokioMutex<HashMap<DownloadId, CachedFileDownloadTask>>>;-type ConstructionLocks = Arc<TokioMutex<HashMap<DownloadId, Arc<TokioMutex<()>>>>>;--#[derive(Clone)]-pub struct DownloadManagerState {- pub manager_id: String,- pub instance_id: Uuid,- pub global_broadcast_sender: SharedDownloadEventSender,- task_cache: TaskCache,- construction_locks: ConstructionLocks,-}--impl std::fmt::Debug for DownloadManagerState {- fn fmt(- &self,- formatter: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- formatter- .debug_struct("DownloadManagerState")- .field("manager_id", &self.manager_id)- .field("instance_id", &self.instance_id)- .finish()- }-}--impl DownloadManagerState {- pub fn new(suffix: &str) -> Self {- let (global_broadcast_sender, _) = tokio_broadcast_channel::<DownloadEvent>(256);- Self {- manager_id: generate_manager_id(suffix),- instance_id: Uuid::new_v4(),- global_broadcast_sender: Arc::new(global_broadcast_sender),- task_cache: Arc::new(TokioMutex::new(HashMap::new())),- construction_locks: Arc::new(TokioMutex::new(HashMap::new())),- }- }-- pub fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<DownloadEvent> {- TokioBroadcastStream::new(self.global_broadcast_sender.subscribe())- }-- pub fn global_broadcast_sender(&self) -> SharedDownloadEventSender {- Arc::clone(&self.global_broadcast_sender)- }-- pub async fn get_all_file_tasks(&self) -> Result<Vec<Arc<dyn FileDownloadTask>>, DownloadError> {- Ok(self.task_cache.lock().await.values().map(CachedFileDownloadTask::public).collect())- }-- pub(crate) async fn get_task(- &self,- download_id: DownloadId,- ) -> Option<CachedFileDownloadTask> {- self.task_cache.lock().await.get(&download_id).cloned()- }-- pub(crate) async fn insert_task(- &self,- download_id: DownloadId,- task: CachedFileDownloadTask,- ) {- self.task_cache.lock().await.insert(download_id, task);- }-- pub(crate) async fn take_task(- &self,- download_id: DownloadId,- ) -> Option<CachedFileDownloadTask> {- self.task_cache.lock().await.remove(&download_id)- }-- pub async fn remove_construction_lock_if_unshared(- &self,- download_id: DownloadId,- construction_lock: &Arc<TokioMutex<()>>,- ) {- let mut construction_locks = self.construction_locks.lock().await;- let Some(cached_lock) = construction_locks.get(&download_id) else {- return;- };- // Only remove if no other caller is racing with us — otherwise they'd serialize on a different mutex.- if Arc::ptr_eq(cached_lock, construction_lock) && Arc::strong_count(construction_lock) == 2 {- construction_locks.remove(&download_id);- }- }-- pub async fn construction_lock(- &self,- download_id: DownloadId,- ) -> Arc<TokioMutex<()>> {- let mut construction_locks = self.construction_locks.lock().await;- construction_locks.entry(download_id).or_insert_with(|| Arc::new(TokioMutex::new(()))).clone()- }-}--fn generate_manager_id(suffix: &str) -> String {- #[cfg(target_vendor = "apple")]- {- use objc2_foundation::NSBundle;-- let bundle_id = NSBundle::mainBundle().bundleIdentifier().unwrap_or_default().to_string();- if bundle_id.is_empty() {- format!("mirai.{suffix}")- } else {- format!("{bundle_id}.mirai.{suffix}")- }- }-- #[cfg(not(target_vendor = "apple"))]- {- format!("mirai.{suffix}")- }-}diff --git a/crates/legacy/download-manager/src/backends/common/mod.rs b/crates/legacy/download-manager/src/backends/common/mod.rsdeleted file mode 100644index a3c10609a..000000000--- a/crates/legacy/download-manager/src/backends/common/mod.rs+++ /dev/null@@ -1,10 +0,0 @@-mod action_executor;-mod backend;-pub(crate) mod manager;-mod manager_state;-mod startup;--pub use backend::{Backend, InitialTaskAttachment};-pub use manager::DownloadManager;-pub use manager_state::DownloadManagerState;-pub use startup::Startup;diff --git a/crates/legacy/download-manager/src/backends/common/startup.rs b/crates/legacy/download-manager/src/backends/common/startup.rsdeleted file mode 100644index f8629828e..000000000--- a/crates/legacy/download-manager/src/backends/common/startup.rs+++ /dev/null@@ -1,105 +0,0 @@-use std::{path::Path, sync::Arc};--use kiban::fs;--use crate::{- DownloadError, DownloadId, FileCheck, FileState, LockFileState,- backends::common::{Backend, action_executor::apply_actions},- check_lock_file,- crc_utils::crc_path_for_file,- file_download_task_actor::{ProgressCounters, PublicProjection},- lock_manager::{DestinationLockLease, lock_path_for_destination},- reducer::{ActionPlan, DiskObservation, InitialLifecycleState, LockObservation, decide, validate},- traits::DownloadConfig,-};--#[derive(Clone, Debug)]-pub struct Startup {- pub config: Arc<DownloadConfig>,- pub initial_lifecycle_state: InitialLifecycleState,- pub initial_projection: PublicProjection,- pub initial_progress: ProgressCounters,- pub action_plan: ActionPlan,- pub lock_state: LockFileState,-}--impl Startup {- pub async fn observe<B: Backend>(- download_id: DownloadId,- source_url: &str,- destination_path: &Path,- file_check: FileCheck,- expected_bytes: Option<u64>,- manager_id: &str,- manager_instance_id: uuid::Uuid,- ) -> Result<Self, DownloadError> {- let resume_artifact_path = destination_path.with_extension(B::RESUME_ARTIFACT_EXTENSION);- let expected_crc = match &file_check {- FileCheck::CRC(crc) => Some(crc.clone()),- FileCheck::None => None,- };- let crc_path = crc_path_for_file(destination_path);- let resume_state = file_state(&resume_artifact_path).await;- let resume_size = match resume_state {- FileState::Exists => B::read_resume_progress(&resume_artifact_path).await,- FileState::Missing => None,- };- let observation = DiskObservation {- destination_state: file_state(destination_path).await,- crc_state: file_state(&crc_path).await,- resume_state,- destination_size: fs::asyn::file_length(destination_path).await.ok(),- resume_size,- expected_crc,- expected_bytes,- destination_path: destination_path.to_path_buf(),- crc_path: Some(crc_path),- resume_artifact_path: Some(resume_artifact_path),- };- let lock_state = check_lock_file(- &lock_path_for_destination(destination_path),- manager_id,- manager_instance_id,- kiban::process::id(),- )- .await;- let lock_observation = LockObservation {- state: lock_state.clone(),- };- let validation = validate(&observation).await;- let decision = decide(&observation, &lock_observation, &validation);- let config = Arc::new(DownloadConfig {- download_id,- source_url: source_url.to_string(),- destination: destination_path.to_path_buf(),- file_check,- expected_bytes,- manager_id: manager_id.to_string(),- manager_instance_id,- });-- Ok(Self {- config,- initial_lifecycle_state: decision.initial_lifecycle_state,- initial_projection: decision.initial_projection,- initial_progress: decision.initial_progress,- action_plan: decision.action_plan,- lock_state,- })- }-- pub(crate) async fn apply_actions(- &self,- destination_lease: &DestinationLockLease,- ) -> Result<(), DownloadError> {- apply_actions(&self.action_plan, destination_lease).await- }-}--async fn file_state(path: &Path) -> FileState {- if fs::asyn::try_exists(path).await.is_ok() && fs::asyn::is_file(path).await {- FileState::Exists- } else {- FileState::Missing- }-}diff --git a/crates/legacy/download-manager/src/backends/download_generation.rs b/crates/legacy/download-manager/src/backends/download_generation.rsnew file mode 100644index 000000000..6c8b04336--- /dev/null+++ b/crates/legacy/download-manager/src/backends/download_generation.rs@@ -0,0 +1,9 @@+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct DownloadGeneration(u64);++impl DownloadGeneration {+ pub fn advance(&mut self) -> Self {+ self.0 += 1;+ *self+ }+}diff --git a/crates/legacy/download-manager/src/backends/mod.rs b/crates/legacy/download-manager/src/backends/mod.rsindex cef4bb201..2dad26391 100644--- a/crates/legacy/download-manager/src/backends/mod.rs+++ b/crates/legacy/download-manager/src/backends/mod.rs@@ -1,4 +1,23 @@+mod active_task;#[cfg(target_vendor = "apple")]-pub mod apple;-pub mod common;-pub mod universal;+mod apple;+mod backend;+mod backend_error;+mod backend_event;+mod backend_event_sender;+mod backend_progress;+mod download_generation;+mod universal;+mod verify_error;++pub use active_task::ActiveTask;+#[cfg(target_vendor = "apple")]+pub use apple::{AppleBackend, AppleBackendError};+pub use backend::Backend;+pub use backend_error::BackendError;+pub use backend_event::BackendEvent;+pub use backend_event_sender::BackendEventSender;+pub use backend_progress::BackendProgress;+pub use download_generation::DownloadGeneration;+pub use universal::UniversalBackend;+pub use verify_error::VerifyError;diff --git a/crates/legacy/download-manager/src/backends/universal/active_task.rs b/crates/legacy/download-manager/src/backends/universal/active_task.rsdeleted file mode 100644index 7bd4cd323..000000000--- a/crates/legacy/download-manager/src/backends/universal/active_task.rs+++ /dev/null@@ -1,91 +0,0 @@-use std::path::{Path, PathBuf};--use kiban::rt::TaskJoinHandle;-use tokio::sync::{oneshot::Receiver as TokioOneshotReceiver, watch::Sender as TokioWatchSender};--use crate::{- backends::universal::UniversalBackend,- traits::{ActiveTask, CancelOutcome, DownloadBackend},-};--pub struct UniversalActiveTask {- task_handles: Box<[Box<dyn TaskJoinHandle<()>>]>,- pause_sender: Option<TokioWatchSender<bool>>,- completion_receiver: Option<TokioOneshotReceiver<()>>,- resume_artifact_path: PathBuf,-}--impl std::fmt::Debug for UniversalActiveTask {- fn fmt(- &self,- formatter: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- formatter- .debug_struct("UniversalActiveTask")- .field("resume_artifact_path", &self.resume_artifact_path)- .finish_non_exhaustive()- }-}--impl UniversalActiveTask {- pub fn new(- task_handles: Box<[Box<dyn TaskJoinHandle<()>>]>,- pause_sender: TokioWatchSender<bool>,- completion_receiver: TokioOneshotReceiver<()>,- resume_artifact_path: PathBuf,- ) -> Self {- Self {- task_handles,- pause_sender: Some(pause_sender),- completion_receiver: Some(completion_receiver),- resume_artifact_path,- }- }-}--impl Drop for UniversalActiveTask {- fn drop(&mut self) {- for handle in self.task_handles.iter() {- handle.abort();- }- }-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-impl ActiveTask for UniversalActiveTask {- type Backend = UniversalBackend;-- async fn pause(- mut self,- _destination: &Path,- ) -> Result<PathBuf, <Self::Backend as DownloadBackend>::Error> {- if let Some(pause_sender) = self.pause_sender.take() {- let _ = pause_sender.send(true);- }-- let completed = match self.completion_receiver.take() {- Some(completion_receiver) => completion_receiver.await.is_ok(),- None => false,- };-- if completed {- let _ = std::mem::take(&mut self.task_handles);- } else {- for task_handle in std::mem::take(&mut self.task_handles) {- task_handle.abort_and_join().await;- }- }- Ok(std::mem::take(&mut self.resume_artifact_path))- }-- async fn cancel(- mut self,- _destination: &Path,- ) -> CancelOutcome {- for task_handle in std::mem::take(&mut self.task_handles) {- task_handle.abort_and_join().await;- }- CancelOutcome::BestEffort- }-}diff --git a/crates/legacy/download-manager/src/backends/universal/backend.rs b/crates/legacy/download-manager/src/backends/universal/backend.rsdeleted file mode 100644index 117cf6092..000000000--- a/crates/legacy/download-manager/src/backends/universal/backend.rs+++ /dev/null@@ -1,31 +0,0 @@-use kiban::rt::RuntimeHandle;--use crate::{- DownloadError,- backends::{- common,- universal::{UniversalActiveTask, UniversalBackendContext, UniversalBackendError},- },- traits::DownloadBackend,-};--#[derive(Clone, Debug, Default)]-pub struct UniversalBackend;--impl DownloadBackend for UniversalBackend {- type Context = UniversalBackendContext;- type ActiveTask = UniversalActiveTask;- type Error = UniversalBackendError;-}--impl common::Backend for UniversalBackend {- const RESUME_ARTIFACT_EXTENSION: &'static str = "part";-- fn manager_suffix() -> &'static str {- "universal"- }-- fn create_context(runtime_handle: RuntimeHandle) -> Result<Self::Context, DownloadError> {- Ok(UniversalBackendContext::new(runtime_handle))- }-}diff --git a/crates/legacy/download-manager/src/backends/universal/content_range.rs b/crates/legacy/download-manager/src/backends/universal/content_range.rsnew file mode 100644index 000000000..ff466c8f9--- /dev/null+++ b/crates/legacy/download-manager/src/backends/universal/content_range.rs@@ -0,0 +1,27 @@+use reqwest::header::HeaderValue;++use crate::backends::universal::UniversalBackendError;++pub struct ContentRange {+ pub start: Option<u64>,+ pub total: Option<u64>,+}++impl ContentRange {+ pub fn parse(header: Option<&HeaderValue>) -> Result<Self, UniversalBackendError> {+ let value = header+ .ok_or_else(|| {+ UniversalBackendError::Protocol("server returned 206 without Content-Range header".to_string())+ })?+ .to_str()+ .map_err(|error| UniversalBackendError::Protocol(format!("non-utf8 Content-Range header: {error}")))?;+ let malformed =+ || UniversalBackendError::Protocol(format!("server returned malformed Content-Range header: {value}"));+ let (range, total) =+ value.strip_prefix("bytes ").ok_or_else(malformed)?.trim_start().split_once('/').ok_or_else(malformed)?;+ Ok(Self {+ start: range.split_once('-').and_then(|(start, _)| start.parse().ok()),+ total: total.parse().ok(),+ })+ }+}diff --git a/crates/legacy/download-manager/src/backends/universal/context.rs b/crates/legacy/download-manager/src/backends/universal/context.rsdeleted file mode 100644index 361b62e38..000000000--- a/crates/legacy/download-manager/src/backends/universal/context.rs+++ /dev/null@@ -1,298 +0,0 @@-use std::{- path::{Path, PathBuf},- sync::Arc,- time::Duration,-};--use futures_util::StreamExt;-use kiban::{fs, fs::PartFile, rt::RuntimeHandle, time::Instant};-use reqwest::{- StatusCode,- header::{CONTENT_LENGTH, CONTENT_RANGE, RANGE},-};-use tokio::sync::{- oneshot::channel as tokio_oneshot_channel,- watch::{Receiver as TokioWatchReceiver, channel as tokio_watch_channel},-};--use crate::{- backends::universal::{UniversalActiveTask, UniversalBackend, UniversalBackendError},- file_download_task_actor::BackendEvent,- lock_manager::DestinationLockLease,- traits::{ActiveDownloadGeneration, BackendContext, BackendEventSender, DownloadConfig},-};--#[derive(Clone, Debug)]-pub struct UniversalBackendContext {- runtime_handle: RuntimeHandle,- pub retries: u16,- pub progress_interval_ms: u64,-}--impl UniversalBackendContext {- pub fn new(runtime_handle: RuntimeHandle) -> Self {- Self {- runtime_handle,- retries: 3,- progress_interval_ms: 500,- }- }-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-impl BackendContext for UniversalBackendContext {- type Backend = UniversalBackend;-- async fn download(- &self,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- backend_event_sender: BackendEventSender,- _destination_lease: &DestinationLockLease,- ) -> Result<UniversalActiveTask, UniversalBackendError> {- let resume_artifact_path = config.destination.with_extension("part");- self.start(config, generation, resume_artifact_path, backend_event_sender).await- }-- async fn resume(- &self,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- resume_artifact_path: &Path,- backend_event_sender: BackendEventSender,- _destination_lease: &DestinationLockLease,- ) -> Result<UniversalActiveTask, UniversalBackendError> {- self.start(config, generation, resume_artifact_path.to_path_buf(), backend_event_sender).await- }-}--impl UniversalBackendContext {- async fn start(- &self,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- resume_artifact_path: PathBuf,- backend_event_sender: BackendEventSender,- ) -> Result<UniversalActiveTask, UniversalBackendError> {- if let Some(parent) = config.destination.parent() {- fs::asyn::create_dir_all(parent).await.map_err(|error| UniversalBackendError::Io(error.to_string()))?;- }-- let retry_count = self.retries;- let progress_interval = Duration::from_millis(self.progress_interval_ms);- let (pause_sender, pause_receiver) = tokio_watch_channel(false);- let (completion_sender, completion_receiver) = tokio_oneshot_channel();- let task_handle = self.runtime_handle.spawn(download_streaming(- config,- generation,- resume_artifact_path.clone(),- backend_event_sender,- retry_count,- progress_interval,- pause_receiver,- completion_sender,- ));-- Ok(UniversalActiveTask::new(Box::from([task_handle]), pause_sender, completion_receiver, resume_artifact_path))- }-}--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum DownloadStreamCompletion {- Completed,- Paused,-}--async fn download_streaming(- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- resume_artifact_path: PathBuf,- backend_event_sender: BackendEventSender,- retry_count: u16,- progress_interval: Duration,- pause_receiver: TokioWatchReceiver<bool>,- completion_sender: tokio::sync::oneshot::Sender<()>,-) {- let mut pause_receiver = pause_receiver;- let result = download_streaming_with_retries(- Arc::clone(&config),- generation,- &resume_artifact_path,- &backend_event_sender,- retry_count,- progress_interval,- &mut pause_receiver,- )- .await;-- match result {- Ok(DownloadStreamCompletion::Completed) => {- let _ = backend_event_sender.send_terminal(BackendEvent::completed(generation)).await;- },- Ok(DownloadStreamCompletion::Paused) => {},- Err(error) => {- let _ = backend_event_sender.send_terminal(BackendEvent::error(generation, error)).await;- },- }- let _ = completion_sender.send(());-}--async fn download_streaming_with_retries(- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- resume_artifact_path: &Path,- backend_event_sender: &BackendEventSender,- retry_count: u16,- progress_interval: Duration,- pause_receiver: &mut TokioWatchReceiver<bool>,-) -> Result<DownloadStreamCompletion, String> {- let mut attempt = 0_u16;- loop {- match download_once(- Arc::clone(&config),- generation,- resume_artifact_path,- backend_event_sender,- progress_interval,- pause_receiver,- )- .await- {- Ok(completion) => return Ok(completion),- Err(error) if attempt < retry_count => {- attempt = attempt.saturating_add(1);- kiban::time::sleep(Duration::from_millis(250)).await;- tracing::debug!("retrying universal download after error: {error}");- },- Err(error) => return Err(error),- }- }-}--async fn download_once(- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- resume_artifact_path: &Path,- backend_event_sender: &BackendEventSender,- progress_interval: Duration,- pause_receiver: &mut TokioWatchReceiver<bool>,-) -> Result<DownloadStreamCompletion, String> {- let client = reqwest::Client::new();- let resume_from_bytes = fs::asyn::file_length(resume_artifact_path).await.unwrap_or(0);- let mut request = client.get(&config.source_url);- if resume_from_bytes > 0 {- request = request.header(RANGE, format!("bytes={resume_from_bytes}-"));- }-- let response = tokio::select! {- _ = wait_for_pause(pause_receiver) => return Ok(DownloadStreamCompletion::Paused),- response = request.send() => response.map_err(|error| error.to_string())?,- };- let status = response.status();- let content_range = response.headers().get(CONTENT_RANGE).cloned();- let resume_from_bytes = if resume_from_bytes > 0 {- match status {- StatusCode::PARTIAL_CONTENT => {- let header = content_range- .as_ref()- .ok_or_else(|| "server returned 206 without Content-Range header".to_string())?;- let header_value =- header.to_str().map_err(|error| format!("non-utf8 Content-Range header: {error}"))?;- let advertised_start = parse_content_range_start(header_value)- .ok_or_else(|| format!("server returned malformed Content-Range header: {header_value}"))?;- if advertised_start != resume_from_bytes {- return Err(format!(- "server returned bytes starting at {advertised_start} but client requested {resume_from_bytes}"- ));- }- resume_from_bytes- },- StatusCode::OK => 0,- StatusCode::RANGE_NOT_SATISFIABLE => {- let advertised_total =- content_range.as_ref().and_then(|header| header.to_str().ok()).and_then(parse_content_range_total);- if advertised_total == Some(resume_from_bytes) {- backend_event_sender.send_progress(generation, resume_from_bytes, Some(resume_from_bytes)).await;- return fs::asyn::rename(resume_artifact_path, &config.destination)- .await- .map(|()| DownloadStreamCompletion::Completed)- .map_err(|error| error.to_string());- }- let _ = fs::asyn::remove_file(resume_artifact_path).await;- return Err(format!("server did not honor range request: status {status}"));- },- _ => return Err(format!("server did not honor range request: status {status}")),- }- } else {- resume_from_bytes- };- let response = response.error_for_status().map_err(|error| error.to_string())?;- let remaining_bytes = response- .headers()- .get(CONTENT_LENGTH)- .and_then(|value| value.to_str().ok())- .and_then(|value| value.parse::<u64>().ok());- let total_bytes = remaining_bytes- .map(|remaining_bytes| remaining_bytes.saturating_add(resume_from_bytes))- .or(config.expected_bytes);-- let mut file =- <dyn PartFile>::new(resume_artifact_path, resume_from_bytes).await.map_err(|error| error.to_string())?;- let mut downloaded_bytes = resume_from_bytes;- let mut last_progress_emit = Instant::now().checked_sub(progress_interval).unwrap_or_else(Instant::now);- let mut stream = response.bytes_stream();-- loop {- let chunk = tokio::select! {- _ = wait_for_pause(pause_receiver) => {- file.flush().await.map_err(|error| error.to_string())?;- backend_event_sender.send_progress(generation, downloaded_bytes, total_bytes).await;- return Ok(DownloadStreamCompletion::Paused);- },- chunk = stream.next() => chunk,- };-- let Some(chunk) = chunk else {- break;- };- let chunk = chunk.map_err(|error| error.to_string())?;- file.write_all(&chunk).await.map_err(|error| error.to_string())?;- downloaded_bytes = downloaded_bytes.saturating_add(chunk.len() as u64);-- if last_progress_emit.elapsed() >= progress_interval {- backend_event_sender.send_progress(generation, downloaded_bytes, total_bytes).await;- last_progress_emit = Instant::now();- }- }-- file.flush().await.map_err(|error| error.to_string())?;- backend_event_sender.send_progress(generation, downloaded_bytes, total_bytes.or(Some(downloaded_bytes))).await;- fs::asyn::rename(resume_artifact_path, &config.destination)- .await- .map(|()| DownloadStreamCompletion::Completed)- .map_err(|error| error.to_string())-}--async fn wait_for_pause(pause_receiver: &mut TokioWatchReceiver<bool>) {- if *pause_receiver.borrow() {- return;- }- let _ = pause_receiver.changed().await;-}--fn parse_content_range_start(header_value: &str) -> Option<u64> {- let value = header_value.strip_prefix("bytes ")?.trim_start();- let (range, _) = value.split_once('/')?;- let (start, _) = range.split_once('-')?;- start.parse::<u64>().ok()-}--fn parse_content_range_total(header_value: &str) -> Option<u64> {- let value = header_value.strip_prefix("bytes ")?.trim_start();- let (_, total) = value.split_once('/')?;- if total == "*" {- return None;- }- total.parse::<u64>().ok()-}diff --git a/crates/legacy/download-manager/src/backends/universal/error.rs b/crates/legacy/download-manager/src/backends/universal/error.rsdeleted file mode 100644index 693d24a51..000000000--- a/crates/legacy/download-manager/src/backends/universal/error.rs+++ /dev/null@@ -1,5 +0,0 @@-#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]-pub enum UniversalBackendError {- #[error("io error: {0}")]- Io(String),-}diff --git a/crates/legacy/download-manager/src/backends/universal/manager.rs b/crates/legacy/download-manager/src/backends/universal/manager.rsdeleted file mode 100644index 864434dda..000000000--- a/crates/legacy/download-manager/src/backends/universal/manager.rs+++ /dev/null@@ -1,3 +0,0 @@-use crate::backends::{common::DownloadManager, universal::UniversalBackend};--pub type UniversalDownloadManager = DownloadManager<UniversalBackend>;diff --git a/crates/legacy/download-manager/src/backends/universal/mod.rs b/crates/legacy/download-manager/src/backends/universal/mod.rsindex 3dda3aac1..35ef1efeb 100644--- a/crates/legacy/download-manager/src/backends/universal/mod.rs+++ b/crates/legacy/download-manager/src/backends/universal/mod.rs@@ -1,11 +1,11 @@-mod active_task;-mod backend;-mod context;-mod error;-mod manager;+mod content_range;+mod universal_active_task;+mod universal_backend;+mod universal_backend_error;+mod universal_stream;-pub use active_task::UniversalActiveTask;-pub use backend::UniversalBackend;-pub use context::UniversalBackendContext;-pub use error::UniversalBackendError;-pub use manager::UniversalDownloadManager;+pub use content_range::ContentRange;+pub use universal_active_task::UniversalActiveTask;+pub use universal_backend::UniversalBackend;+pub use universal_backend_error::UniversalBackendError;+pub use universal_stream::UniversalStream;diff --git a/crates/legacy/download-manager/src/backends/universal/universal_active_task.rs b/crates/legacy/download-manager/src/backends/universal/universal_active_task.rsnew file mode 100644index 000000000..8683492b4--- /dev/null+++ b/crates/legacy/download-manager/src/backends/universal/universal_active_task.rs@@ -0,0 +1,44 @@+use std::path::Path;++use kiban::rt::TaskJoinHandle;+use tokio::sync::{oneshot::Receiver as TokioOneshotReceiver, watch::Sender as TokioWatchSender};++use crate::backends::{ActiveTask, BackendError};++pub struct UniversalActiveTask {+ task_handle: Box<dyn TaskJoinHandle<()>>,+ pause: TokioWatchSender<bool>,+ completion: TokioOneshotReceiver<()>,+}++impl UniversalActiveTask {+ pub fn new(+ task_handle: Box<dyn TaskJoinHandle<()>>,+ pause: TokioWatchSender<bool>,+ completion: TokioOneshotReceiver<()>,+ ) -> Self {+ Self {+ task_handle,+ pause,+ completion,+ }+ }+}++#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]+#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]+impl ActiveTask for UniversalActiveTask {+ async fn pause(+ self: Box<Self>,+ _resume_artifact_path: &Path,+ ) -> Result<(), BackendError> {+ let _ = self.pause.send(true);+ let _ = self.completion.await;+ self.task_handle.abort_and_join().await;+ Ok(())+ }++ async fn cancel(self: Box<Self>) {+ self.task_handle.abort_and_join().await;+ }+}diff --git a/crates/legacy/download-manager/src/backends/universal/universal_backend.rs b/crates/legacy/download-manager/src/backends/universal/universal_backend.rsnew file mode 100644index 000000000..729fffd17--- /dev/null+++ b/crates/legacy/download-manager/src/backends/universal/universal_backend.rs@@ -0,0 +1,75 @@+use std::{path::Path, sync::Arc};++use kiban::{fs, rt::RuntimeHandle};+use tokio::sync::{oneshot::channel as tokio_oneshot_channel, watch::channel as tokio_watch_channel};++use crate::{+ backends::{+ ActiveTask, Backend, BackendError, BackendEventSender, DownloadGeneration,+ universal::{UniversalActiveTask, UniversalStream},+ },+ file_download::DownloadConfig,+};++pub struct UniversalBackend {+ runtime_handle: RuntimeHandle,+}++impl UniversalBackend {+ pub fn new(runtime_handle: RuntimeHandle) -> Self {+ Self {+ runtime_handle,+ }+ }+}++#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]+#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]+impl Backend for UniversalBackend {+ fn name(&self) -> &'static str {+ "universal"+ }++ fn resume_artifact_extension(&self) -> &'static str {+ "part"+ }++ async fn start(+ &self,+ config: Arc<DownloadConfig>,+ generation: DownloadGeneration,+ events: BackendEventSender,+ ) -> Result<Box<dyn ActiveTask>, BackendError> {+ if let Some(parent) = config.destination.parent() {+ fs::asyn::create_dir_all(parent).await?;+ }+ let (pause_sender, pause_receiver) = tokio_watch_channel(false);+ let (completion_sender, completion_receiver) = tokio_oneshot_channel();+ let stream = UniversalStream::new(config, generation, events, pause_receiver, completion_sender);+ let task_handle = self.runtime_handle.spawn(stream.run());+ Ok(Box::new(UniversalActiveTask::new(task_handle, pause_sender, completion_receiver)))+ }++ async fn read_resume_progress(+ &self,+ resume_artifact_path: &Path,+ ) -> u64 {+ fs::asyn::file_length(resume_artifact_path).await.unwrap_or(0)+ }++ async fn has_pending_task(+ &self,+ _config: &DownloadConfig,+ ) -> Result<bool, BackendError> {+ Ok(false)+ }++ async fn attach_pending_task(+ &self,+ _config: Arc<DownloadConfig>,+ _generation: DownloadGeneration,+ _events: BackendEventSender,+ ) -> Result<Option<Box<dyn ActiveTask>>, BackendError> {+ Ok(None)+ }+}diff --git a/crates/legacy/download-manager/src/backends/universal/universal_backend_error.rs b/crates/legacy/download-manager/src/backends/universal/universal_backend_error.rsnew file mode 100644index 000000000..e7982d141--- /dev/null+++ b/crates/legacy/download-manager/src/backends/universal/universal_backend_error.rs@@ -0,0 +1,9 @@+#[derive(Debug, thiserror::Error)]+pub enum UniversalBackendError {+ #[error(transparent)]+ Io(#[from] std::io::Error),+ #[error(transparent)]+ Http(#[from] reqwest::Error),+ #[error("{0}")]+ Protocol(String),+}diff --git a/crates/legacy/download-manager/src/backends/universal/universal_stream.rs b/crates/legacy/download-manager/src/backends/universal/universal_stream.rsnew file mode 100644index 000000000..5422e6532--- /dev/null+++ b/crates/legacy/download-manager/src/backends/universal/universal_stream.rs@@ -0,0 +1,173 @@+use std::{sync::Arc, time::Duration};++use futures_util::StreamExt;+use kiban::{fs, fs::PartFile, time::Instant};+use reqwest::{+ Client, StatusCode,+ header::{CONTENT_LENGTH, CONTENT_RANGE, RANGE},+};+use tokio::sync::{oneshot::Sender as TokioOneshotSender, watch::Receiver as TokioWatchReceiver};++use crate::{+ backends::{+ BackendEvent, BackendEventSender, DownloadGeneration,+ universal::{ContentRange, UniversalBackendError},+ },+ file_download::DownloadConfig,+};++const RETRIES: u16 = 3;+const RETRY_DELAY: Duration = Duration::from_millis(250);+const PROGRESS_INTERVAL: Duration = Duration::from_millis(500);++pub struct UniversalStream {+ client: Client,+ config: Arc<DownloadConfig>,+ generation: DownloadGeneration,+ events: BackendEventSender,+ pause: TokioWatchReceiver<bool>,+ completion: TokioOneshotSender<()>,+}++impl UniversalStream {+ pub fn new(+ config: Arc<DownloadConfig>,+ generation: DownloadGeneration,+ events: BackendEventSender,+ pause: TokioWatchReceiver<bool>,+ completion: TokioOneshotSender<()>,+ ) -> Self {+ Self {+ client: Client::new(),+ config,+ generation,+ events,+ pause,+ completion,+ }+ }++ pub async fn run(mut self) {+ let mut attempt = 0_u16;+ let outcome = loop {+ match self.attempt().await {+ Err(error @ (UniversalBackendError::Http(_) | UniversalBackendError::Io(_))) if attempt < RETRIES => {+ attempt += 1;+ tracing::debug!(%error, attempt, "retrying universal download");+ kiban::time::sleep(RETRY_DELAY).await;+ },+ outcome => break outcome,+ }+ };+ match outcome {+ Ok(true) => {},+ Ok(false) => {+ self.events+ .send_terminal(BackendEvent::Completed {+ generation: self.generation,+ })+ .await+ },+ Err(error) => {+ self.events+ .send_terminal(BackendEvent::Error {+ generation: self.generation,+ message: error.to_string(),+ })+ .await+ },+ }+ let _ = self.completion.send(());+ }++ async fn attempt(&mut self) -> Result<bool, UniversalBackendError> {+ let config = &self.config;+ let artifact = config.resume_artifact_path.as_path();+ let mut resume_from = fs::asyn::file_length(artifact).await.unwrap_or(0);+ let mut request = self.client.get(&config.source_url);+ if resume_from > 0 {+ request = request.header(RANGE, format!("bytes={resume_from}-"));+ }+ let response = tokio::select! {+ _ = Self::paused(&mut self.pause) => return Ok(true),+ response = request.send() => response?,+ };+ let status = response.status();+ if resume_from > 0 {+ match status {+ StatusCode::PARTIAL_CONTENT => {+ let range = ContentRange::parse(response.headers().get(CONTENT_RANGE))?;+ if range.start != Some(resume_from) {+ return Err(UniversalBackendError::Protocol(format!(+ "server returned bytes starting at {} but client requested {resume_from}",+ range.start.unwrap_or(0)+ )));+ }+ },+ StatusCode::OK => resume_from = 0,+ StatusCode::RANGE_NOT_SATISFIABLE => {+ let total =+ ContentRange::parse(response.headers().get(CONTENT_RANGE)).ok().and_then(|range| range.total);+ if total == Some(resume_from) {+ self.events.send_progress(self.generation, resume_from, Some(resume_from));+ fs::asyn::rename(artifact, &config.destination).await?;+ return Ok(false);+ }+ let _ = fs::asyn::remove_file(artifact).await;+ return Err(UniversalBackendError::Protocol(format!(+ "server did not honor range request: status {status}"+ )));+ },+ _ => {+ response.error_for_status_ref()?;+ return Err(UniversalBackendError::Protocol(format!(+ "server did not honor range request: status {status}"+ )));+ },+ }+ }+ let response = response.error_for_status()?;+ let total_bytes = response+ .headers()+ .get(CONTENT_LENGTH)+ .and_then(|value| value.to_str().ok())+ .and_then(|value| value.parse::<u64>().ok())+ .map(|remaining| remaining.saturating_add(resume_from));++ let mut file = <dyn PartFile>::new(artifact, resume_from).await?;+ let mut downloaded_bytes = resume_from;+ let mut last_progress = Instant::now().checked_sub(PROGRESS_INTERVAL).unwrap_or_else(Instant::now);+ let mut body = response.bytes_stream();+ loop {+ let chunk = tokio::select! {+ _ = Self::paused(&mut self.pause) => {+ file.flush().await?;+ self.events.send_progress(self.generation, downloaded_bytes, total_bytes);+ return Ok(true);+ },+ chunk = body.next() => chunk,+ };+ let Some(chunk) = chunk else {+ break;+ };+ let chunk = chunk?;+ file.write_all(&chunk).await?;+ downloaded_bytes += chunk.len() as u64;+ if last_progress.elapsed() >= PROGRESS_INTERVAL {+ self.events.send_progress(self.generation, downloaded_bytes, total_bytes);+ last_progress = Instant::now();+ }+ }+ file.flush().await?;+ self.events.send_progress(self.generation, downloaded_bytes, total_bytes);+ fs::asyn::rename(artifact, &config.destination).await?;+ Ok(false)+ }++ async fn paused(pause: &mut TokioWatchReceiver<bool>) {+ if *pause.borrow() {+ return;+ }+ let _ = pause.changed().await;+ }+}diff --git a/crates/legacy/download-manager/src/backends/verify_error.rs b/crates/legacy/download-manager/src/backends/verify_error.rsnew file mode 100644index 000000000..4ef38fe67--- /dev/null+++ b/crates/legacy/download-manager/src/backends/verify_error.rs@@ -0,0 +1,12 @@+#[derive(Debug, thiserror::Error)]+pub enum VerifyError {+ #[error(transparent)]+ Io(#[from] std::io::Error),+ #[error("downloaded file is {actual} bytes but registry declared {expected}")]+ Size {+ expected: u64,+ actual: u64,+ },+ #[error("CRC verification failed")]+ Crc,+}diff --git a/crates/legacy/download-manager/src/cached_download_task.rs b/crates/legacy/download-manager/src/cached_download_task.rsnew file mode 100644index 000000000..e88a08168--- /dev/null+++ b/crates/legacy/download-manager/src/cached_download_task.rs@@ -0,0 +1,10 @@+use std::sync::Weak;++use tokio::sync::watch::Receiver as TokioWatchReceiver;++use crate::{DownloadState, DownloadTask};++pub struct CachedDownloadTask {+ pub task: Weak<DownloadTask>,+ pub live_state: Option<TokioWatchReceiver<DownloadState>>,+}diff --git a/crates/legacy/download-manager/src/checked_file_state.rs b/crates/legacy/download-manager/src/checked_file_state.rsdeleted file mode 100644index 8b1104c9e..000000000--- a/crates/legacy/download-manager/src/checked_file_state.rs+++ /dev/null@@ -1,8 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum CheckedFileState {- Valid,- Invalid,- Missing,-}diff --git a/crates/legacy/download-manager/src/crc32c.rs b/crates/legacy/download-manager/src/crc32c.rsnew file mode 100644index 000000000..2ae831586--- /dev/null+++ b/crates/legacy/download-manager/src/crc32c.rs@@ -0,0 +1,49 @@+use std::{+ io::{Error as IoError, ErrorKind},+ path::Path,+};++use base64::Engine;+use kiban::fs;+use serde::{Deserialize, Serialize};++const READ_CHUNK_SIZE: u64 = 8 * 1024 * 1024;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(transparent)]+pub struct Crc32c(String);++impl From<String> for Crc32c {+ fn from(encoded: String) -> Self {+ Self(encoded)+ }+}++impl Crc32c {+ pub async fn verify(+ &self,+ path: &Path,+ ) -> Result<bool, IoError> {+ let Some(expected) = self.decode() else {+ return Ok(false);+ };+ let length = fs::asyn::file_length(path).await?;+ let mut checksum = 0_u32;+ let mut offset = 0_u64;+ while offset < length {+ let end = offset.saturating_add(READ_CHUNK_SIZE).min(length);+ let chunk = fs::asyn::read_range(path, offset..end).await?;+ if chunk.len() as u64 != end - offset {+ return Err(IoError::new(ErrorKind::UnexpectedEof, "file changed during CRC verification"));+ }+ checksum = ::crc32c::crc32c_append(checksum, &chunk);+ offset = end;+ }+ Ok(checksum == expected)+ }++ fn decode(&self) -> Option<u32> {+ let bytes = base64::engine::general_purpose::STANDARD.decode(&self.0).ok()?;+ Some(u32::from_be_bytes(bytes.try_into().ok()?))+ }+}diff --git a/crates/legacy/download-manager/src/crc_receipt.rs b/crates/legacy/download-manager/src/crc_receipt.rsnew file mode 100644index 000000000..1f2ac377d--- /dev/null+++ b/crates/legacy/download-manager/src/crc_receipt.rs@@ -0,0 +1,71 @@+use std::{+ io,+ path::{Path, PathBuf},+};++use kiban::{fs, time::SystemTime};+use serde::{Deserialize, Serialize};++use crate::Crc32c;++#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct CrcReceipt {+ version: u8,+ crc: Crc32c,+ file_size: u64,+ modified_unix_seconds: u64,+ modified_nanos: u32,+}++impl CrcReceipt {+ pub async fn matches(+ destination: &Path,+ crc: &Crc32c,+ ) -> bool {+ matches!(+ (Self::load(destination).await, Self::for_file(destination, crc).await),+ (Some(saved), Some(current)) if saved == current+ )+ }++ pub async fn save(+ destination: &Path,+ crc: &Crc32c,+ ) -> Result<(), io::Error> {+ let Some(receipt) = Self::for_file(destination, crc).await else {+ return Ok(());+ };+ fs::asyn::write(Self::path_for(destination), serde_json::to_vec(&receipt).map_err(io::Error::other)?).await+ }++ pub async fn exists(destination: &Path) -> bool {+ fs::asyn::is_file(Self::path_for(destination)).await+ }++ pub async fn remove(destination: &Path) {+ let _ = fs::asyn::remove_file(Self::path_for(destination)).await;+ }++ async fn load(destination: &Path) -> Option<Self> {+ serde_json::from_str(&fs::asyn::read_to_string(Self::path_for(destination)).await.ok()?).ok()+ }++ async fn for_file(+ destination: &Path,+ crc: &Crc32c,+ ) -> Option<Self> {+ let file_size = fs::asyn::file_length(destination).await.ok()?;+ let modified = fs::asyn::file_modified(destination).await.ok()?.duration_since(SystemTime::UNIX_EPOCH).ok()?;+ Some(Self {+ version: 1,+ crc: crc.clone(),+ file_size,+ modified_unix_seconds: modified.as_secs(),+ modified_nanos: modified.subsec_nanos(),+ })+ }++ fn path_for(destination: &Path) -> PathBuf {+ PathBuf::from(format!("{}.crc", destination.display()))+ }+}diff --git a/crates/legacy/download-manager/src/crc_utils.rs b/crates/legacy/download-manager/src/crc_utils.rsdeleted file mode 100644index 12583efbd..000000000--- a/crates/legacy/download-manager/src/crc_utils.rs+++ /dev/null@@ -1,111 +0,0 @@-use std::{- io::{Error as IoError, ErrorKind},- path::{Path, PathBuf},-};--use base64::Engine;-use kiban::{fs, time::SystemTime};-use serde::{Deserialize, Serialize};--const CRC_CACHE_VERSION: u8 = 1;-const CRC_READ_CHUNK_SIZE: u64 = 8 * 1024 * 1024;--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-struct CrcCacheReceipt {- version: u8,- crc: String,- file_size: u64,- modified_unix_seconds: u64,- modified_nanos: u32,-}--pub async fn calculate_and_verify_crc(- file_path: &Path,- expected_crc32c_base64: &str,-) -> Result<bool, IoError> {- let Some(expected_crc) = decode_crc32c(expected_crc32c_base64) else {- return Ok(false);- };-- let file_len = kiban::fs::asyn::file_length(file_path).await?;- let mut offset = 0;- let mut actual_crc = 0;- while offset < file_len {- let end = offset.saturating_add(CRC_READ_CHUNK_SIZE).min(file_len);- let chunk = kiban::fs::asyn::read_range(file_path, offset..end).await?;- if chunk.len() != (end - offset) as usize {- return Err(IoError::new(ErrorKind::UnexpectedEof, "file changed during CRC verification"));- }- actual_crc = crc32c::crc32c_append(actual_crc, &chunk);- offset = end;- }-- Ok(actual_crc == expected_crc)-}--pub async fn crc_cache_matches(- file_path: &Path,- expected_crc32c_base64: &str,-) -> bool {- if decode_crc32c(expected_crc32c_base64).is_none() {- return false;- }-- let Ok(cache_contents) = kiban::fs::asyn::read_to_string(crc_path_for_file(file_path)).await else {- return false;- };- let Ok(cached_receipt) = serde_json::from_str::<CrcCacheReceipt>(&cache_contents) else {- return false;- };- let Some(current_receipt) = CrcCacheReceipt::from_file(file_path, expected_crc32c_base64).await else {- return false;- };-- cached_receipt == current_receipt-}--pub async fn save_crc_file(- file_path: &Path,- crc_value: &str,-) -> Result<(), IoError> {- let Some(receipt) = CrcCacheReceipt::from_file(file_path, crc_value).await else {- return Ok(());- };- let receipt_json = serde_json::to_vec(&receipt).map_err(IoError::other)?;- fs::asyn::write(crc_path_for_file(file_path), receipt_json).await-}--pub fn crc_path_for_file(file_path: &Path) -> PathBuf {- PathBuf::from(format!("{}.crc", file_path.display()))-}--impl CrcCacheReceipt {- async fn from_file(- file_path: &Path,- crc: &str,- ) -> Option<Self> {- if !fs::asyn::is_file(file_path).await {- return None;- }-- let file_size = fs::asyn::file_length(file_path).await.ok()?;- let modified = fs::asyn::file_modified(file_path).await.ok()?.duration_since(SystemTime::UNIX_EPOCH).ok()?;- Some(Self {- version: CRC_CACHE_VERSION,- crc: crc.to_string(),- file_size,- modified_unix_seconds: modified.as_secs(),- modified_nanos: modified.subsec_nanos(),- })- }-}--fn decode_crc32c(expected_crc32c_base64: &str) -> Option<u32> {- let expected_bytes = base64::engine::general_purpose::STANDARD.decode(expected_crc32c_base64).ok()?;-- if expected_bytes.len() != 4 {- return None;- }-- Some(u32::from_be_bytes([expected_bytes[0], expected_bytes[1], expected_bytes[2], expected_bytes[3]]))-}diff --git a/crates/legacy/download-manager/src/download_error.rs b/crates/legacy/download-manager/src/download_error.rsindex 169ce3a23..00b636a75 100644--- a/crates/legacy/download-manager/src/download_error.rs+++ b/crates/legacy/download-manager/src/download_error.rs@@ -1,55 +1,13 @@-#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]+use crate::{backends::BackendError, file_download::FileDownloadError, locks::LockError};++#[derive(Debug, thiserror::Error)]pub enum DownloadError {- #[error("io error: {0}")]- Io(String),- #[error("json error: {0}")]- SerdeJson(String),- #[error("http error: status {0}")]- HttpStatus(u16),- #[error("canceled")]- Canceled,- #[error("resume unsupported")]- ResumeUnsupported,- #[error("bad url")]- BadUrl,- #[error("missing download info for task")]- MissingDownloadInfo,- #[error("resume data read failed")]- ResumeDataReadFailed,- #[error("resume data parsing or handling error")]- ResumeDataError,- #[error("download task not found")]- DownloadTaskNotFound,- #[error("task not found after creation")]- TaskNotFoundAfterCreation,- #[error("no matching download task to pause")]- NoMatchingTaskToPause,- #[error("unknown download handle")]- UnknownDownloadHandle,- #[error("mutex poisoned")]- MutexPoisoned,- #[error("invalid state transition")]- InvalidStateTransition,- #[error("file locked by another manager: {0}")]- LockedByOther(String),+ #[error(transparent)]+ Lock(#[from] LockError),+ #[error(transparent)]+ Backend(#[from] BackendError),+ #[error(transparent)]+ FileDownload(#[from] FileDownloadError),#[error("conflicting download config for destination: {0}")]ConflictingConfig(String),- #[error("task stopped")]- TaskStopped,- #[error("channel closed")]- ChannelClosed,- #[error("backend error: {0}")]- Backend(String),-}--impl From<std::io::Error> for DownloadError {- fn from(error: std::io::Error) -> Self {- Self::Io(error.to_string())- }-}--impl From<serde_json::Error> for DownloadError {- fn from(error: serde_json::Error) -> Self {- Self::SerdeJson(error.to_string())- }}diff --git a/crates/legacy/download-manager/src/download_id.rs b/crates/legacy/download-manager/src/download_id.rsnew file mode 100644index 000000000..cc4ed581f--- /dev/null+++ b/crates/legacy/download-manager/src/download_id.rs@@ -0,0 +1 @@+pub type DownloadId = uuid::Uuid;diff --git a/crates/legacy/download-manager/src/download_info.rs b/crates/legacy/download-manager/src/download_info.rsdeleted file mode 100644index 6dfa71d44..000000000--- a/crates/legacy/download-manager/src/download_info.rs+++ /dev/null@@ -1,42 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub struct DownloadInfo {- pub source_url: String,- pub destination_path: String,- #[serde(default)]- pub crc32c: Option<String>,-}--impl DownloadInfo {- pub fn new<U: Into<String>, P: Into<String>>(- source_url: U,- destination_path: P,- ) -> Self {- Self {- source_url: source_url.into(),- destination_path: destination_path.into(),- crc32c: None,- }- }-- pub fn with_crc<U: Into<String>, P: Into<String>, C: Into<String>>(- source_url: U,- destination_path: P,- crc32c: C,- ) -> Self {- Self {- source_url: source_url.into(),- destination_path: destination_path.into(),- crc32c: Some(crc32c.into()),- }- }-- pub fn to_json(&self) -> Result<String, serde_json::Error> {- serde_json::to_string(self)- }-- pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {- serde_json::from_str(json)- }-}diff --git a/crates/legacy/download-manager/src/download_log_event.rs b/crates/legacy/download-manager/src/download_log_event.rsdeleted file mode 100644index 13c587275..000000000--- a/crates/legacy/download-manager/src/download_log_event.rs+++ /dev/null@@ -1,50 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::{DownloadId, FileDownloadEvent, file_download_task_actor::BackendEvent, traits::ActiveDownloadGeneration};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub(crate) enum DownloadLogEvent {- ManagerCreated {- manager_id: String,- },- StartupReconciled {- download_id: DownloadId,- initial_lifecycle_state: &'static str,- action_count: usize,- },- TaskSpawned {- download_id: DownloadId,- },- StateTransition {- download_id: DownloadId,- from: &'static str,- to: &'static str,- },- BackendProgress {- download_id: DownloadId,- generation: ActiveDownloadGeneration,- downloaded_bytes: u64,- total_bytes: Option<u64>,- },- BackendTerminal {- download_id: DownloadId,- event: BackendEvent,- },- PublicEventEmitted {- download_id: DownloadId,- event: FileDownloadEvent,- },-}--pub(crate) fn log(event: DownloadLogEvent) {- match &event {- DownloadLogEvent::BackendProgress {- ..- } => {- tracing::trace!(download_log_event = ?event, "download manager event");- },- _ => {- tracing::debug!(download_log_event = ?event, "download manager event");- },- }-}diff --git a/crates/legacy/download-manager/src/download_manager.rs b/crates/legacy/download-manager/src/download_manager.rsnew file mode 100644index 000000000..f3af154d7--- /dev/null+++ b/crates/legacy/download-manager/src/download_manager.rs@@ -0,0 +1,176 @@+use std::{+ collections::HashMap,+ sync::{Arc, Mutex, PoisonError},+};++use kiban::rt::RuntimeHandle;+use tokio::sync::Mutex as TokioMutex;+use uuid::Uuid;++use crate::{+ DownloadError, DownloadId, DownloadManagerType, DownloadTask, DownloadTaskKind, DownloadTaskRequest,+ GroupDownloadTask,+ backends::{Backend, UniversalBackend},+ cached_download_task::CachedDownloadTask,+ file_download::{DownloadConfig, FileDownloadWorker},+ locks::LockOwner,+};++pub struct DownloadManager {+ owner: LockOwner,+ backend: Arc<dyn Backend>,+ tasks: Mutex<HashMap<DownloadId, CachedDownloadTask>>,+ construction_locks: Mutex<HashMap<DownloadId, Arc<TokioMutex<()>>>>,+}++impl DownloadManager {+ pub fn new(+ kind: DownloadManagerType,+ runtime_handle: RuntimeHandle,+ ) -> Self {+ let backend: Arc<dyn Backend> = match kind {+ #[cfg(target_vendor = "apple")]+ DownloadManagerType::Native => Arc::new(crate::backends::AppleBackend::new(runtime_handle)),+ DownloadManagerType::Universal => Arc::new(UniversalBackend::new(runtime_handle)),+ };+ #[cfg(target_vendor = "apple")]+ let bundle_id = crate::backends::AppleBackend::bundle_identifier();+ #[cfg(not(target_vendor = "apple"))]+ let bundle_id = String::new();+ let manager_id = if bundle_id.is_empty() {+ format!("mirai.{}", backend.name())+ } else {+ format!("{bundle_id}.mirai.{}", backend.name())+ };+ tracing::debug!(%manager_id, "download manager created");+ Self {+ owner: LockOwner {+ manager_id,+ instance_id: Uuid::new_v4(),+ },+ backend,+ tasks: Mutex::default(),+ construction_locks: Mutex::default(),+ }+ }++ pub async fn download_task(+ &self,+ request: DownloadTaskRequest,+ ) -> Result<Arc<DownloadTask>, DownloadError> {+ self.task(request, &[]).await+ }++ async fn task(+ &self,+ request: DownloadTaskRequest,+ ancestors: &[DownloadId],+ ) -> Result<Arc<DownloadTask>, DownloadError> {+ let download_id = request.download_id();+ if ancestors.contains(&download_id) {+ return Err(DownloadError::ConflictingConfig(request.destination.display().to_string()));+ }+ if let Some(cached) = self.cached(download_id, &request) {+ return cached;+ }+ let construction_lock = self+ .construction_locks+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .entry(download_id)+ .or_default()+ .clone();+ let _construction_guard = construction_lock.lock().await;+ if let Some(cached) = self.cached(download_id, &request) {+ return cached;+ }+ let stopping = self+ .tasks+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .get(&download_id)+ .and_then(|cached| cached.live_state.clone());+ if let Some(mut live_state) = stopping {+ while live_state.changed().await.is_ok() {}+ }+ let task = Arc::new(self.build(&request, ancestors).await?);+ let live_state = match &*task {+ DownloadTask::File(file) => Some(file.live_state()),+ DownloadTask::Group(_) => None,+ };+ {+ let mut tasks = self.tasks.lock().unwrap_or_else(PoisonError::into_inner);+ tasks.retain(|_, cached| {+ cached.task.strong_count() > 0+ || cached.live_state.as_ref().is_some_and(|live_state| live_state.has_changed().is_ok())+ });+ tasks.insert(+ download_id,+ CachedDownloadTask {+ task: Arc::downgrade(&task),+ live_state,+ },+ );+ }+ self.construction_locks+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .retain(|_, lock| Arc::strong_count(lock) > 1);+ Ok(task)+ }++ fn cached(+ &self,+ download_id: DownloadId,+ request: &DownloadTaskRequest,+ ) -> Option<Result<Arc<DownloadTask>, DownloadError>> {+ let task = self.tasks.lock().unwrap_or_else(PoisonError::into_inner).get(&download_id)?.task.upgrade()?;+ Some(if task.request() == request {+ Ok(task)+ } else {+ Err(DownloadError::ConflictingConfig(request.destination.display().to_string()))+ })+ }++ async fn build(+ &self,+ request: &DownloadTaskRequest,+ ancestors: &[DownloadId],+ ) -> Result<DownloadTask, DownloadError> {+ match &request.kind {+ DownloadTaskKind::File {+ source_url,+ expected_crc32c,+ expected_bytes,+ } => {+ let config = Arc::new(DownloadConfig {+ download_id: request.download_id(),+ source_url: source_url.clone(),+ destination: request.destination.clone(),+ resume_artifact_path: self.backend.resume_artifact_path(&request.destination),+ expected_crc32c: expected_crc32c.clone(),+ expected_bytes: *expected_bytes,+ owner: self.owner.clone(),+ });+ let (state, attach_lock) = self.backend.reconcile(&config).await?;+ tracing::debug!(+ download_id = %config.download_id,+ phase = ?state.phase,+ "startup reconciled"+ );+ let task =+ FileDownloadWorker::spawn(Arc::clone(&self.backend), request.clone(), config, state, attach_lock)+ .await?;+ Ok(DownloadTask::File(task))+ },+ DownloadTaskKind::Group(subrequests) => {+ let ancestors = [ancestors, &[request.download_id()][..]].concat();+ let mut children = Vec::with_capacity(subrequests.len());+ for subrequest in subrequests {+ children.push(Box::pin(self.task(subrequest.clone(), &ancestors)).await?);+ }+ Ok(DownloadTask::Group(GroupDownloadTask::new(request.clone(), children)))+ },+ }+ }+}diff --git a/crates/legacy/download-manager/src/download_manager_type.rs b/crates/legacy/download-manager/src/download_manager_type.rsnew file mode 100644index 000000000..4b5f62955--- /dev/null+++ b/crates/legacy/download-manager/src/download_manager_type.rs@@ -0,0 +1,12 @@+use serde::{Deserialize, Serialize};++#[bindings::export(Enumeration)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum DownloadManagerType {+ #[cfg(target_vendor = "apple")]+ #[default]+ Native,+ #[cfg_attr(not(target_vendor = "apple"), default)]+ Universal,+}diff --git a/crates/legacy/uzu/src/storage/types/download_phase.rs b/crates/legacy/download-manager/src/download_phase.rssimilarity index 54%rename from crates/legacy/uzu/src/storage/types/download_phase.rsrename to crates/legacy/download-manager/src/download_phase.rsindex 1ce4fd709..0dfff4b33 100644--- a/crates/legacy/uzu/src/storage/types/download_phase.rs+++ b/crates/legacy/download-manager/src/download_phase.rs@@ -7,7 +7,9 @@ pub enum DownloadPhase {Downloading {},Paused {},Downloaded {},- Locked {},+ Locked {+ manager_id: String,+ },Error {message: String,},@@ -15,15 +17,6 @@ pub enum DownloadPhase {impl DownloadPhase {pub fn is_in_progress(&self) -> bool {- matches!(self, Self::Downloading {})- }-- pub fn can_pause(&self) -> bool {- matches!(self, Self::Downloading {})- }-- pub fn can_delete(&self) -> bool {- // Allow delete in all states except NotDownloaded- !matches!(self, Self::NotDownloaded {})+ matches!(self, Self::Downloading {} | Self::Locked { .. })}}diff --git a/crates/legacy/download-manager/src/download_state.rs b/crates/legacy/download-manager/src/download_state.rsindex 86983b1a7..9b6c4c0ef 100644--- a/crates/legacy/download-manager/src/download_state.rs+++ b/crates/legacy/download-manager/src/download_state.rs@@ -1,11 +1,79 @@use serde::{Deserialize, Serialize};-#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum DownloadState {- Downloading,- Paused,- NotDownloaded,- Interrupted,- Completed,- Error,+use crate::{DownloadPhase, file_download::DownloadConfig};++#[bindings::export(Structure(Class))]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub struct DownloadState {+ pub total_bytes: i64,+ pub downloaded_bytes: i64,+ pub phase: DownloadPhase,+}++impl Default for DownloadState {+ fn default() -> Self {+ Self {+ total_bytes: 0,+ downloaded_bytes: 0,+ phase: DownloadPhase::NotDownloaded {},+ }+ }+}++#[bindings::export(Implementation)]+impl DownloadState {+ #[bindings::export(Method(Getter))]+ pub fn progress(&self) -> f32 {+ if self.total_bytes == 0 {+ 0.0+ } else {+ self.downloaded_bytes as f32 / self.total_bytes as f32+ }+ }++ #[bindings::export(Method(Getter))]+ pub fn is_in_progress(&self) -> bool {+ self.phase.is_in_progress()+ }++ #[bindings::export(Method(Getter))]+ pub fn can_pause(&self) -> bool {+ matches!(self.phase, DownloadPhase::Downloading {})+ }++ #[bindings::export(Method(Getter))]+ pub fn can_delete(&self) -> bool {+ !matches!(self.phase, DownloadPhase::NotDownloaded {} | DownloadPhase::Locked { .. })+ }++ #[bindings::export(Method(Getter))]+ pub fn name(&self) -> String {+ match &self.phase {+ DownloadPhase::NotDownloaded {} => "Not Downloaded".to_string(),+ DownloadPhase::Downloading {} => "Downloading".to_string(),+ DownloadPhase::Paused {} => "Paused".to_string(),+ DownloadPhase::Downloaded {} => "Downloaded".to_string(),+ DownloadPhase::Locked {+ ..+ } => "Locked".to_string(),+ DownloadPhase::Error {+ ..+ } => "Error".to_string(),+ }+ }+}++impl DownloadState {+ pub fn new(+ config: &DownloadConfig,+ phase: DownloadPhase,+ downloaded_bytes: u64,+ total_bytes: Option<u64>,+ ) -> Self {+ Self {+ total_bytes: config.expected_bytes.or(total_bytes).unwrap_or(downloaded_bytes) as i64,+ downloaded_bytes: downloaded_bytes as i64,+ phase,+ }+ }}diff --git a/crates/legacy/download-manager/src/download_task.rs b/crates/legacy/download-manager/src/download_task.rsnew file mode 100644index 000000000..9cccd868e--- /dev/null+++ b/crates/legacy/download-manager/src/download_task.rs@@ -0,0 +1,68 @@+use std::sync::Arc;++use kiban::stream::BoxStream;++use crate::{DownloadError, DownloadState, DownloadTaskRequest, FileDownloadTask, GroupDownloadTask};++pub enum DownloadTask {+ File(FileDownloadTask),+ Group(GroupDownloadTask),+}++impl DownloadTask {+ pub fn request(&self) -> &DownloadTaskRequest {+ match self {+ Self::File(file) => &file.request,+ Self::Group(group) => &group.request,+ }+ }++ pub fn subtasks(&self) -> &[Arc<DownloadTask>] {+ match self {+ Self::File(_) => &[],+ Self::Group(group) => group.subtasks(),+ }+ }++ pub fn state(&self) -> DownloadState {+ match self {+ Self::File(file) => file.state(),+ Self::Group(group) => group.state(),+ }+ }++ pub fn progress(&self) -> BoxStream<'static, DownloadState> {+ match self {+ Self::File(file) => file.progress(),+ Self::Group(group) => group.progress(),+ }+ }++ pub async fn download(&self) -> Result<(), DownloadError> {+ match self {+ Self::File(file) => file.download().await,+ Self::Group(group) => group.download().await,+ }+ }++ pub async fn pause(&self) -> Result<(), DownloadError> {+ match self {+ Self::File(file) => file.pause().await,+ Self::Group(group) => group.pause().await,+ }+ }++ pub async fn delete(&self) -> Result<(), DownloadError> {+ match self {+ Self::File(file) => file.delete().await,+ Self::Group(group) => group.delete().await,+ }+ }++ pub async fn foreign_owner(&self) -> Option<String> {+ match self {+ Self::File(file) => file.foreign_owner().await,+ Self::Group(group) => group.foreign_owner().await,+ }+ }+}diff --git a/crates/legacy/download-manager/src/download_task_kind.rs b/crates/legacy/download-manager/src/download_task_kind.rsnew file mode 100644index 000000000..3176b89d3--- /dev/null+++ b/crates/legacy/download-manager/src/download_task_kind.rs@@ -0,0 +1,11 @@+use crate::{Crc32c, DownloadTaskRequest};++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum DownloadTaskKind {+ File {+ source_url: String,+ expected_crc32c: Option<Crc32c>,+ expected_bytes: Option<u64>,+ },+ Group(Vec<DownloadTaskRequest>),+}diff --git a/crates/legacy/download-manager/src/download_task_request.rs b/crates/legacy/download-manager/src/download_task_request.rsnew file mode 100644index 000000000..8434b9a52--- /dev/null+++ b/crates/legacy/download-manager/src/download_task_request.rs@@ -0,0 +1,64 @@+use std::path::{Path, PathBuf};++use bon::bon;+use uuid::Uuid;++use crate::{Crc32c, DownloadId, DownloadTaskKind};++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct DownloadTaskRequest {+ pub destination: PathBuf,+ pub kind: DownloadTaskKind,+}++#[bon]+impl DownloadTaskRequest {+ #[builder(finish_fn = build)]+ pub fn file(+ #[builder(into)] destination: PathBuf,+ #[builder(into)] source_url: String,+ #[builder(into)] expected_crc32c: Option<Crc32c>,+ expected_bytes: Option<u64>,+ ) -> Self {+ Self {+ destination,+ kind: DownloadTaskKind::File {+ source_url,+ expected_crc32c,+ expected_bytes,+ },+ }+ }++ #[builder(finish_fn = build)]+ pub fn group(+ #[builder(into)] destination: PathBuf,+ subrequests: Vec<Self>,+ ) -> Self {+ Self {+ kind: DownloadTaskKind::Group(+ subrequests.into_iter().map(|subrequest| subrequest.resolved(&destination)).collect(),+ ),+ destination,+ }+ }++ pub fn download_id(&self) -> DownloadId {+ Uuid::new_v5(&Uuid::NAMESPACE_URL, self.destination.to_string_lossy().as_bytes())+ }++ fn resolved(+ self,+ parent: &Path,+ ) -> Self {+ Self {+ destination: parent.join(&self.destination),+ kind: match self.kind {+ DownloadTaskKind::Group(subrequests) => DownloadTaskKind::Group(+ subrequests.into_iter().map(|subrequest| subrequest.resolved(parent)).collect(),+ ),+ kind => kind,+ },+ }+ }+}diff --git a/crates/legacy/download-manager/src/file_check.rs b/crates/legacy/download-manager/src/file_check.rsdeleted file mode 100644index 21857f77a..000000000--- a/crates/legacy/download-manager/src/file_check.rs+++ /dev/null@@ -1,16 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum FileCheck {- CRC(String),- None,-}--impl FileCheck {- pub fn expected_crc(&self) -> Option<String> {- match self {- Self::CRC(crc) => Some(crc.clone()),- Self::None => None,- }- }-}diff --git a/crates/legacy/download-manager/src/file_download/command.rs b/crates/legacy/download-manager/src/file_download/command.rsnew file mode 100644index 000000000..9aa9ace17--- /dev/null+++ b/crates/legacy/download-manager/src/file_download/command.rs@@ -0,0 +1,6 @@+#[derive(Clone, Copy, Debug)]+pub enum Command {+ Download,+ Pause,+ Delete,+}diff --git a/crates/legacy/download-manager/src/file_download/download_config.rs b/crates/legacy/download-manager/src/file_download/download_config.rsnew file mode 100644index 000000000..157d715e7--- /dev/null+++ b/crates/legacy/download-manager/src/file_download/download_config.rs@@ -0,0 +1,13 @@+use std::path::PathBuf;++use crate::{Crc32c, DownloadId, locks::LockOwner};++pub struct DownloadConfig {+ pub download_id: DownloadId,+ pub source_url: String,+ pub destination: PathBuf,+ pub resume_artifact_path: PathBuf,+ pub expected_crc32c: Option<Crc32c>,+ pub expected_bytes: Option<u64>,+ pub owner: LockOwner,+}diff --git a/crates/legacy/download-manager/src/file_download/file_download_error.rs b/crates/legacy/download-manager/src/file_download/file_download_error.rsnew file mode 100644index 000000000..9c7ecc580--- /dev/null+++ b/crates/legacy/download-manager/src/file_download/file_download_error.rs@@ -0,0 +1,11 @@+use crate::{backends::BackendError, locks::LockError};++#[derive(Debug, thiserror::Error)]+pub enum FileDownloadError {+ #[error("channel closed")]+ ChannelClosed,+ #[error(transparent)]+ Lock(#[from] LockError),+ #[error(transparent)]+ Backend(#[from] BackendError),+}diff --git a/crates/legacy/download-manager/src/file_download/file_download_task.rs b/crates/legacy/download-manager/src/file_download/file_download_task.rsnew file mode 100644index 000000000..25a38dc07--- /dev/null+++ b/crates/legacy/download-manager/src/file_download/file_download_task.rs@@ -0,0 +1,75 @@+use std::sync::Arc;++use kiban::stream::BoxStream;+use tokio::sync::{+ mpsc::Sender as TokioMpscSender,+ oneshot::{Sender as TokioOneshotSender, channel as tokio_oneshot_channel},+ watch::Receiver as TokioWatchReceiver,+};+use tokio_stream::wrappers::WatchStream;++use crate::{+ DownloadError, DownloadState, DownloadTaskRequest,+ file_download::{Command, DownloadConfig, FileDownloadError},+ locks::DestinationLock,+};++pub struct FileDownloadTask {+ pub request: DownloadTaskRequest,+ config: Arc<DownloadConfig>,+ commands: TokioMpscSender<(Command, TokioOneshotSender<Result<(), FileDownloadError>>)>,+ state: TokioWatchReceiver<DownloadState>,+}++impl FileDownloadTask {+ pub fn new(+ request: DownloadTaskRequest,+ config: Arc<DownloadConfig>,+ commands: TokioMpscSender<(Command, TokioOneshotSender<Result<(), FileDownloadError>>)>,+ state: TokioWatchReceiver<DownloadState>,+ ) -> Self {+ Self {+ request,+ config,+ commands,+ state,+ }+ }++ pub fn state(&self) -> DownloadState {+ self.state.borrow().clone()+ }++ pub fn live_state(&self) -> TokioWatchReceiver<DownloadState> {+ self.state.clone()+ }++ pub fn progress(&self) -> BoxStream<'static, DownloadState> {+ Box::pin(WatchStream::from_changes(self.state.clone()))+ }++ pub async fn download(&self) -> Result<(), DownloadError> {+ Ok(self.send(Command::Download).await?)+ }++ pub async fn pause(&self) -> Result<(), DownloadError> {+ Ok(self.send(Command::Pause).await?)+ }++ pub async fn delete(&self) -> Result<(), DownloadError> {+ Ok(self.send(Command::Delete).await?)+ }++ pub async fn foreign_owner(&self) -> Option<String> {+ DestinationLock::foreign_owner(&self.config.destination, &self.config.owner).await+ }++ async fn send(+ &self,+ command: Command,+ ) -> Result<(), FileDownloadError> {+ let (reply, response) = tokio_oneshot_channel();+ self.commands.send((command, reply)).await.map_err(|_| FileDownloadError::ChannelClosed)?;+ response.await.unwrap_or(Err(FileDownloadError::ChannelClosed))+ }+}diff --git a/crates/legacy/download-manager/src/file_download/file_download_worker.rs b/crates/legacy/download-manager/src/file_download/file_download_worker.rsnew file mode 100644index 000000000..dfa248184--- /dev/null+++ b/crates/legacy/download-manager/src/file_download/file_download_worker.rs@@ -0,0 +1,330 @@+use std::{sync::Arc, time::Duration};++use kiban::{fs, rt};+use tokio::sync::{+ mpsc::{Receiver as TokioMpscReceiver, channel as tokio_mpsc_channel},+ oneshot::Sender as TokioOneshotSender,+ watch::{Receiver as TokioWatchReceiver, Sender as TokioWatchSender, channel as tokio_watch_channel},+};++use crate::{+ DownloadPhase, DownloadState, DownloadTaskRequest,+ backends::{ActiveTask, Backend, BackendEvent, BackendEventSender, BackendProgress, DownloadGeneration},+ file_download::{Command, DownloadConfig, FileDownloadError, FileDownloadTask},+ locks::{DestinationLock, LockError},+};++const OBSERVE_INTERVAL: Duration = Duration::from_secs(1);++pub struct FileDownloadWorker {+ backend: Arc<dyn Backend>,+ config: Arc<DownloadConfig>,+ state: DownloadState,+ active: Option<(Box<dyn ActiveTask>, DestinationLock)>,+ generation: DownloadGeneration,+ wants_download: bool,+ events: BackendEventSender,+ commands: TokioMpscReceiver<(Command, TokioOneshotSender<Result<(), FileDownloadError>>)>,+ backend_events: TokioMpscReceiver<BackendEvent>,+ backend_progress: TokioWatchReceiver<Option<BackendProgress>>,+ published: TokioWatchSender<DownloadState>,+}++impl FileDownloadWorker {+ pub async fn spawn(+ backend: Arc<dyn Backend>,+ request: DownloadTaskRequest,+ config: Arc<DownloadConfig>,+ state: DownloadState,+ attach_lock: Option<DestinationLock>,+ ) -> Result<FileDownloadTask, FileDownloadError> {+ let (command_sender, commands) = tokio_mpsc_channel(64);+ let (terminal_sender, backend_events) = tokio_mpsc_channel(64);+ let (progress_sender, backend_progress) = tokio_watch_channel(None);+ let (published, state_receiver) = tokio_watch_channel(state.clone());+ let mut worker = Self {+ backend,+ config: Arc::clone(&config),+ state,+ active: None,+ generation: DownloadGeneration::default(),+ wants_download: false,+ events: BackendEventSender::new(config.download_id, terminal_sender, progress_sender),+ commands,+ backend_events,+ backend_progress,+ published,+ };+ if let Some(lock) = attach_lock {+ worker.attach(lock).await?;+ }+ worker.publish();+ rt::spawn(worker.run());+ Ok(FileDownloadTask::new(request, config, command_sender, state_receiver))+ }++ async fn run(mut self) {+ loop {+ tokio::select! {+ command = self.commands.recv() => {+ let Some((command, reply)) = command else { break };+ let result = match command {+ Command::Download => self.download().await,+ Command::Pause => self.pause().await,+ Command::Delete => self.delete().await,+ };+ self.publish();+ let _ = reply.send(result);+ },+ event = self.backend_events.recv() => {+ let Some(event) = event else { break };+ self.on_backend_event(event).await;+ self.publish();+ },+ changed = self.backend_progress.changed() => {+ if changed.is_err() {+ break;+ }+ self.on_backend_progress();+ self.publish();+ },+ _ = kiban::time::sleep(OBSERVE_INTERVAL), if matches!(self.state.phase, DownloadPhase::Locked { .. }) => {+ self.observe().await;+ self.publish();+ },+ }+ }+ if self.active.is_some() {+ let _ = self.pause().await;+ self.publish();+ }+ }++ async fn download(&mut self) -> Result<(), FileDownloadError> {+ self.wants_download = true;+ match self.state.phase {+ DownloadPhase::NotDownloaded {}+ | DownloadPhase::Paused {}+ | DownloadPhase::Error {+ ..+ } => self.start().await,+ DownloadPhase::Downloading {}+ | DownloadPhase::Downloaded {}+ | DownloadPhase::Locked {+ ..+ } => Ok(()),+ }+ }++ async fn start(&mut self) -> Result<(), FileDownloadError> {+ let lock = match self.lock().await {+ Ok(lock) => lock,+ Err(FileDownloadError::Lock(LockError::LockedByOther {+ ..+ })) => return Ok(()),+ Err(error) => return Err(error),+ };+ let generation = self.generation.advance();+ let downloaded_bytes = self.backend.read_resume_progress(&self.config.resume_artifact_path).await;+ match self.backend.start(Arc::clone(&self.config), generation, self.events.clone()).await {+ Ok(task) => {+ self.active = Some((task, lock));+ self.set(DownloadPhase::Downloading {}, downloaded_bytes, None);+ Ok(())+ },+ Err(error) => {+ let _ = fs::asyn::remove_file(&self.config.resume_artifact_path).await;+ Err(self.fail(error.into()))+ },+ }+ }++ async fn pause(&mut self) -> Result<(), FileDownloadError> {+ self.wants_download = false;+ let Some((task, _lock)) = self.active.take() else {+ return Ok(());+ };+ if let Err(error) = task.pause(&self.config.resume_artifact_path).await {+ return Err(self.fail(error.into()));+ }+ if fs::asyn::is_file(&self.config.destination).await {+ self.complete().await;+ } else {+ let downloaded_bytes = self.backend.read_resume_progress(&self.config.resume_artifact_path).await;+ self.set(DownloadPhase::Paused {}, downloaded_bytes, None);+ }+ Ok(())+ }++ async fn delete(&mut self) -> Result<(), FileDownloadError> {+ self.wants_download = false;+ let _lock = match self.active.take() {+ Some((task, lock)) => {+ task.cancel().await;+ lock+ },+ None => self.lock().await?,+ };+ self.backend.remove_files(&self.config).await;+ self.set(DownloadPhase::NotDownloaded {}, 0, None);+ Ok(())+ }++ async fn lock(&mut self) -> Result<DestinationLock, FileDownloadError> {+ match DestinationLock::acquire(&self.config.destination, &self.config.owner).await {+ Ok(lock) => Ok(lock),+ Err(LockError::LockedByOther {+ manager_id,+ }) => {+ let downloaded_bytes = self.backend.read_resume_progress(&self.config.resume_artifact_path).await;+ self.set(+ DownloadPhase::Locked {+ manager_id: manager_id.clone(),+ },+ downloaded_bytes,+ None,+ );+ Err(LockError::LockedByOther {+ manager_id,+ }+ .into())+ },+ Err(error) => Err(error.into()),+ }+ }++ async fn attach(+ &mut self,+ lock: DestinationLock,+ ) -> Result<(), FileDownloadError> {+ let generation = self.generation.advance();+ if let Some(task) =+ self.backend.attach_pending_task(Arc::clone(&self.config), generation, self.events.clone()).await?+ {+ self.active = Some((task, lock));+ self.set(DownloadPhase::Downloading {}, 0, None);+ }+ Ok(())+ }++ async fn complete(&mut self) {+ match self.backend.verify(&self.config).await {+ Ok(total_bytes) => {+ let _ = fs::asyn::remove_file(&self.config.resume_artifact_path).await;+ self.set(DownloadPhase::Downloaded {}, total_bytes, Some(total_bytes));+ },+ Err(error) => {+ self.backend.remove_files(&self.config).await;+ self.set(+ DownloadPhase::Error {+ message: error.to_string(),+ },+ 0,+ None,+ );+ },+ }+ }++ async fn on_backend_event(+ &mut self,+ event: BackendEvent,+ ) {+ if event.generation() != self.generation {+ return;+ }+ let Some((task, _lock)) = self.active.take() else {+ return;+ };+ match event {+ BackendEvent::Completed {+ ..+ } => self.complete().await,+ BackendEvent::Error {+ message,+ ..+ } => {+ task.cancel().await;+ let _ = fs::asyn::remove_file(&self.config.resume_artifact_path).await;+ self.set(+ DownloadPhase::Error {+ message,+ },+ 0,+ None,+ );+ },+ }+ }++ fn on_backend_progress(&mut self) {+ let Some(progress) = *self.backend_progress.borrow_and_update() else {+ return;+ };+ if progress.generation == self.generation && self.active.is_some() {+ self.set(DownloadPhase::Downloading {}, progress.downloaded_bytes, progress.total_bytes);+ }+ }++ async fn observe(&mut self) {+ match self.backend.reconcile(&self.config).await {+ Ok((state, lock)) => {+ self.state = state;+ if let Some(lock) = lock+ && let Err(error) = self.attach(lock).await+ {+ self.fail(error);+ }+ if self.wants_download+ && matches!(self.state.phase, DownloadPhase::NotDownloaded {} | DownloadPhase::Paused {})+ {+ let _ = self.start().await;+ }+ },+ Err(error) => {+ self.fail(error.into());+ },+ }+ }++ fn fail(+ &mut self,+ error: FileDownloadError,+ ) -> FileDownloadError {+ self.set(+ DownloadPhase::Error {+ message: error.to_string(),+ },+ 0,+ None,+ );+ error+ }++ fn set(+ &mut self,+ phase: DownloadPhase,+ downloaded_bytes: u64,+ total_bytes: Option<u64>,+ ) {+ self.state = DownloadState::new(&self.config, phase, downloaded_bytes, total_bytes);+ }++ fn publish(&self) {+ self.published.send_if_modified(|current| {+ if *current == self.state {+ return false;+ }+ if current.phase != self.state.phase {+ tracing::debug!(+ download_id = %self.config.download_id,+ from = ?current.phase,+ to = ?self.state.phase,+ "download phase changed"+ );+ }+ *current = self.state.clone();+ true+ });+ }+}diff --git a/crates/legacy/download-manager/src/file_download/mod.rs b/crates/legacy/download-manager/src/file_download/mod.rsnew file mode 100644index 000000000..85a8a3d76--- /dev/null+++ b/crates/legacy/download-manager/src/file_download/mod.rs@@ -0,0 +1,11 @@+mod command;+mod download_config;+mod file_download_error;+mod file_download_task;+mod file_download_worker;++pub use command::Command;+pub use download_config::DownloadConfig;+pub use file_download_error::FileDownloadError;+pub use file_download_task::FileDownloadTask;+pub use file_download_worker::FileDownloadWorker;diff --git a/crates/legacy/download-manager/src/file_download_event.rs b/crates/legacy/download-manager/src/file_download_event.rsdeleted file mode 100644index 3f88f84c8..000000000--- a/crates/legacy/download-manager/src/file_download_event.rs+++ /dev/null@@ -1,19 +0,0 @@-use std::path::PathBuf;--use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum FileDownloadEvent {- DownloadCompleted {- tmp_path: PathBuf,- final_destination: PathBuf,- },- ProgressUpdate {- bytes_written: u64,- total_bytes_written: u64,- total_bytes_expected: u64,- },- Error {- message: String,- },-}diff --git a/crates/legacy/download-manager/src/file_download_manager.rs b/crates/legacy/download-manager/src/file_download_manager.rsdeleted file mode 100644index db5554aa4..000000000--- a/crates/legacy/download-manager/src/file_download_manager.rs+++ /dev/null@@ -1,88 +0,0 @@-use std::{path::Path, sync::Arc};--use kiban::rt::RuntimeHandle;-use tokio::sync::broadcast::Sender as TokioBroadcastSender;-use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;--#[cfg(target_vendor = "apple")]-use crate::backends::apple::AppleDownloadManager;-use crate::{- DownloadError, DownloadId, FileCheck, FileDownloadEvent, FileDownloadTask,- backends::universal::UniversalDownloadManager,-};--pub type DownloadEvent = (DownloadId, FileDownloadEvent);-pub type DownloadEventSender = TokioBroadcastSender<DownloadEvent>;-pub type SharedDownloadEventSender = Arc<DownloadEventSender>;--#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]-#[serde(rename_all = "snake_case")]-pub enum FileDownloadManagerType {- Universal,- #[cfg(target_vendor = "apple")]- Apple,-}--impl Default for FileDownloadManagerType {- #[allow(unreachable_code)]- fn default() -> Self {- #[cfg(target_vendor = "apple")]- return Self::Apple;- Self::Universal- }-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-pub trait FileDownloadManager: Send + Sync + 'static {- fn manager_id(&self) -> &str;- fn subscribe_to_all_downloads(&self) -> TokioBroadcastStream<DownloadEvent>;- fn global_broadcast_sender(&self) -> SharedDownloadEventSender;-- async fn get_all_file_tasks(&self) -> Result<Vec<Arc<dyn FileDownloadTask>>, DownloadError>;-- async fn remove_file_task(- &self,- download_id: DownloadId,- ) -> Result<(), DownloadError>;-- async fn file_download_task(- &self,- source_url: &str,- destination_path: &Path,- file_check: FileCheck,- expected_bytes: Option<u64>,- ) -> Result<Arc<dyn FileDownloadTask>, DownloadError>;-- async fn destination_foreign_lock(- &self,- _destination_path: &Path,- ) -> Option<String> {- None- }-}--impl dyn FileDownloadManager {- pub async fn new(- file_download_manager_type: FileDownloadManagerType,- runtime_handle: RuntimeHandle,- ) -> Result<Box<dyn FileDownloadManager>, DownloadError> {- match file_download_manager_type {- FileDownloadManagerType::Universal => {- let manager: Box<dyn FileDownloadManager> =- Box::new(UniversalDownloadManager::from_runtime_handle(runtime_handle)?);- Ok(manager)- },- #[cfg(target_vendor = "apple")]- FileDownloadManagerType::Apple => {- let manager: Box<dyn FileDownloadManager> =- Box::new(AppleDownloadManager::from_runtime_handle(runtime_handle)?);- Ok(manager)- },- }- }-- pub async fn system_default(runtime_handle: RuntimeHandle) -> Result<Box<dyn FileDownloadManager>, DownloadError> {- Self::new(FileDownloadManagerType::default(), runtime_handle).await- }-}diff --git a/crates/legacy/download-manager/src/file_download_phase.rs b/crates/legacy/download-manager/src/file_download_phase.rsdeleted file mode 100644index e5165fc8c..000000000--- a/crates/legacy/download-manager/src/file_download_phase.rs+++ /dev/null@@ -1,11 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum FileDownloadPhase {- NotDownloaded,- Downloading,- Paused,- Downloaded,- LockedByOther(String),- Error(String),-}diff --git a/crates/legacy/download-manager/src/file_download_state.rs b/crates/legacy/download-manager/src/file_download_state.rsdeleted file mode 100644index 9e439c58f..000000000--- a/crates/legacy/download-manager/src/file_download_state.rs+++ /dev/null@@ -1,66 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::FileDownloadPhase;--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub struct FileDownloadState {- pub total_bytes: u64,- pub downloaded_bytes: u64,- pub phase: FileDownloadPhase,-}--impl FileDownloadState {- pub fn not_downloaded(total_bytes: u64) -> Self {- Self {- total_bytes,- downloaded_bytes: 0,- phase: FileDownloadPhase::NotDownloaded,- }- }-- pub fn downloading(- downloaded_bytes: u64,- total_bytes: u64,- ) -> Self {- Self {- total_bytes,- downloaded_bytes,- phase: FileDownloadPhase::Downloading,- }- }-- pub fn paused(- downloaded_bytes: u64,- total_bytes: u64,- ) -> Self {- Self {- total_bytes,- downloaded_bytes,- phase: FileDownloadPhase::Paused,- }- }-- pub fn downloaded(total_bytes: u64) -> Self {- Self {- total_bytes,- downloaded_bytes: total_bytes,- phase: FileDownloadPhase::Downloaded,- }- }-- pub fn locked_by_other(manager_id: String) -> Self {- Self {- total_bytes: 0,- downloaded_bytes: 0,- phase: FileDownloadPhase::LockedByOther(manager_id),- }- }-- pub fn error(message: String) -> Self {- Self {- total_bytes: 0,- downloaded_bytes: 0,- phase: FileDownloadPhase::Error(message),- }- }-}diff --git a/crates/legacy/download-manager/src/file_download_task.rs b/crates/legacy/download-manager/src/file_download_task.rsdeleted file mode 100644index b699588f9..000000000--- a/crates/legacy/download-manager/src/file_download_task.rs+++ /dev/null@@ -1,68 +0,0 @@-use std::{fmt::Debug, path::Path, sync::Arc};--use tokio::sync::broadcast::Sender as TokioBroadcastSender;-use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;--use crate::{DownloadError, DownloadEventSender, DownloadId, FileCheck, FileDownloadState};--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-pub trait FileDownloadTask: Send + Sync + Debug {- fn download_id(&self) -> DownloadId;- fn source_url(&self) -> &str;- fn destination(&self) -> &Path;- fn file_check(&self) -> &FileCheck;- fn expected_bytes(&self) -> Option<u64>;-- async fn download(&self) -> Result<(), DownloadError>;- async fn pause(&self) -> Result<(), DownloadError>;- async fn cancel(&self) -> Result<(), DownloadError>;- async fn state(&self) -> FileDownloadState;- async fn progress(&self) -> Result<TokioBroadcastStream<FileDownloadState>, DownloadError>;-- async fn start_listening(- &self,- global_broadcast: DownloadEventSender,- );- async fn stop_listening(&self);- async fn wait(&self);-- fn broadcast_sender(&self) -> TokioBroadcastSender<FileDownloadState>;-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-pub(crate) trait ManagedFileDownloadTask: FileDownloadTask {- async fn shutdown_for_removal(&self) -> Result<(), DownloadError>;- fn is_stopped(&self) -> bool;-}--#[derive(Clone)]-pub(crate) struct CachedFileDownloadTask {- public: Arc<dyn FileDownloadTask>,- managed: Arc<dyn ManagedFileDownloadTask>,-}--impl CachedFileDownloadTask {- pub(crate) fn new(- public: Arc<dyn FileDownloadTask>,- managed: Arc<dyn ManagedFileDownloadTask>,- ) -> Self {- Self {- public,- managed,- }- }-- pub(crate) fn public(&self) -> Arc<dyn FileDownloadTask> {- Arc::clone(&self.public)- }-- pub(crate) fn managed(&self) -> Arc<dyn ManagedFileDownloadTask> {- Arc::clone(&self.managed)- }-- pub(crate) fn is_stopped(&self) -> bool {- self.managed.is_stopped()- }-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/actor_state.rs b/crates/legacy/download-manager/src/file_download_task_actor/actor_state.rsdeleted file mode 100644index f685eba71..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/actor_state.rs+++ /dev/null@@ -1,68 +0,0 @@-use std::{fmt, path::PathBuf};--use crate::{- lock_manager::DestinationLockLease,- reducer::InitialLifecycleState,- traits::{ActiveDownloadGeneration, DownloadBackend},-};--pub(crate) enum DownloadActorState<B: DownloadBackend> {- NotDownloaded,- Paused {- part_path: PathBuf,- },- Downloading {- active_task: B::ActiveTask,- generation: ActiveDownloadGeneration,- destination_lease: DestinationLockLease,- },- Downloaded,-}--impl<B: DownloadBackend> DownloadActorState<B> {- pub(crate) fn name(&self) -> &'static str {- match self {- Self::NotDownloaded => "NotDownloaded",- Self::Paused {- ..- } => "Paused",- Self::Downloading {- ..- } => "Downloading",- Self::Downloaded => "Downloaded",- }- }-}--impl<B: DownloadBackend> fmt::Debug for DownloadActorState<B> {- fn fmt(- &self,- formatter: &mut fmt::Formatter<'_>,- ) -> fmt::Result {- match self {- Self::NotDownloaded => formatter.debug_struct("NotDownloaded").finish(),- Self::Paused {- part_path,- } => formatter.debug_struct("Paused").field("part_path", part_path).finish(),- Self::Downloading {- generation,- ..- } => formatter.debug_struct("Downloading").field("generation", generation).finish_non_exhaustive(),- Self::Downloaded => formatter.debug_struct("Downloaded").finish(),- }- }-}--impl<B: DownloadBackend> From<InitialLifecycleState> for DownloadActorState<B> {- fn from(initial_lifecycle_state: InitialLifecycleState) -> Self {- match initial_lifecycle_state {- InitialLifecycleState::NotDownloaded => Self::NotDownloaded,- InitialLifecycleState::Paused {- part_path,- } => Self::Paused {- part_path,- },- InitialLifecycleState::Downloaded => Self::Downloaded,- }- }-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/backend_event.rs b/crates/legacy/download-manager/src/file_download_task_actor/backend_event.rsdeleted file mode 100644index e05154479..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/backend_event.rs+++ /dev/null@@ -1,30 +0,0 @@-use crate::traits::ActiveDownloadGeneration;--#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum BackendEvent {- Completed {- generation: ActiveDownloadGeneration,- },- Error {- generation: ActiveDownloadGeneration,- message: String,- },-}--impl BackendEvent {- pub fn completed(generation: ActiveDownloadGeneration) -> Self {- Self::Completed {- generation,- }- }-- pub fn error(- generation: ActiveDownloadGeneration,- message: String,- ) -> Self {- Self::Error {- generation,- message,- }- }-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/backend_progress.rs b/crates/legacy/download-manager/src/file_download_task_actor/backend_progress.rsdeleted file mode 100644index a875ba66a..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/backend_progress.rs+++ /dev/null@@ -1,8 +0,0 @@-use crate::traits::ActiveDownloadGeneration;--#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub struct BackendProgress {- pub generation: ActiveDownloadGeneration,- pub downloaded_bytes: u64,- pub total_bytes: Option<u64>,-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/download_task_actor.rs b/crates/legacy/download-manager/src/file_download_task_actor/download_task_actor.rsdeleted file mode 100644index f83822e0c..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/download_task_actor.rs+++ /dev/null@@ -1,658 +0,0 @@-use std::{- io::ErrorKind,- path::{Path, PathBuf},- sync::Arc,- time::Duration,-};--use kiban::fs;-use tokio::sync::{- Mutex as TokioMutex,- broadcast::Sender as TokioBroadcastSender,- mpsc::Receiver as TokioMpscReceiver,- oneshot::Sender as TokioOneshotSender,- watch::{Receiver as TokioWatchReceiver, Sender as TokioWatchSender},-};--use crate::{- DownloadError, FileCheck, FileDownloadState, LockFileState, check_lock_file,- crc_utils::{calculate_and_verify_crc, crc_path_for_file, save_crc_file},- download_log_event::{DownloadLogEvent, log},- file_download_task_actor::{- BackendEvent, DownloadActorState, PendingProgressSlot, ProgressCounters, PublicProjection, TaskCommand,- TerminalOutcome, project_runtime_public_state,- },- lock_manager::{DestinationLockLease, lock_path_for_destination},- release_lock_if_owned,- traits::{- ActiveDownloadGeneration, ActiveDownloadGenerationCounter, ActiveTask, BackendContext, BackendEventSender,- DownloadBackend, DownloadConfig,- },-};--enum ActorLoopExit {- AlreadyStopped,- PreserveArtifacts,-}--pub struct DownloadTaskActor<B: DownloadBackend> {- config: Arc<DownloadConfig>,- context: Arc<B::Context>,- backend_event_sender: BackendEventSender,- generation_counter: ActiveDownloadGenerationCounter,- state: DownloadActorState<B>,- projection: PublicProjection,- progress_counters: ProgressCounters,- command_receiver: TokioMpscReceiver<TaskCommand>,- backend_event_receiver: TokioMpscReceiver<BackendEvent>,- pending_progress: Arc<TokioMutex<PendingProgressSlot>>,- progress_waker_receiver: TokioWatchReceiver<()>,- public_state_sender: TokioWatchSender<FileDownloadState>,- progress_sender: TokioBroadcastSender<FileDownloadState>,- terminal_sender: TokioWatchSender<TerminalOutcome>,- pending_terminal_outcome: Option<TerminalOutcome>,-}--impl<B: DownloadBackend> DownloadTaskActor<B> {- pub fn new(- config: Arc<DownloadConfig>,- context: Arc<B::Context>,- backend_event_sender: BackendEventSender,- generation_counter: ActiveDownloadGenerationCounter,- state: DownloadActorState<B>,- projection: PublicProjection,- progress_counters: ProgressCounters,- command_receiver: TokioMpscReceiver<TaskCommand>,- backend_event_receiver: TokioMpscReceiver<BackendEvent>,- pending_progress: Arc<TokioMutex<PendingProgressSlot>>,- progress_waker_receiver: TokioWatchReceiver<()>,- public_state_sender: TokioWatchSender<FileDownloadState>,- progress_sender: TokioBroadcastSender<FileDownloadState>,- terminal_sender: TokioWatchSender<TerminalOutcome>,- ) -> Self {- Self {- config,- context,- backend_event_sender,- generation_counter,- state,- projection,- progress_counters,- command_receiver,- backend_event_receiver,- pending_progress,- progress_waker_receiver,- public_state_sender,- progress_sender,- terminal_sender,- pending_terminal_outcome: None,- }- }-- pub async fn run(mut self) {- self.publish_current_state();-- let mut loop_exit = ActorLoopExit::PreserveArtifacts;- loop {- tokio::select! {- command = self.command_receiver.recv() => {- let Some(command) = command else {- break;- };- if !self.handle_command(command).await {- loop_exit = ActorLoopExit::AlreadyStopped;- break;- }- }- backend_event = self.backend_event_receiver.recv() => {- let Some(backend_event) = backend_event else {- break;- };- self.handle_backend_event(backend_event).await;- self.publish_current_state();- self.flush_terminal_outcome();- }- progress_wake_result = self.progress_waker_receiver.changed() => {- if progress_wake_result.is_err() {- break;- }- self.handle_pending_progress().await;- self.publish_current_state();- self.flush_terminal_outcome();- }- }- }-- if matches!(loop_exit, ActorLoopExit::PreserveArtifacts) {- self.stop_preserving_artifacts().await;- self.publish_current_state();- self.flush_terminal_outcome();- }- let _ = self.terminal_sender.send(TerminalOutcome::ActorStopped);- }-- async fn stop_preserving_artifacts(&mut self) {- let current_state = std::mem::replace(&mut self.state, DownloadActorState::NotDownloaded);- let from_state = current_state.name();- match current_state {- DownloadActorState::Downloading {- active_task,- destination_lease,- ..- } => match active_task.pause(&self.config.destination).await {- Ok(part_path) => {- let downloaded_bytes = B::read_resume_progress(&part_path).await.unwrap_or(0);- self.progress_counters = ProgressCounters {- downloaded_bytes,- total_bytes: self.config.expected_bytes.unwrap_or(downloaded_bytes),- };- release_destination_lease(destination_lease).await;- self.finish_transition(- from_state,- DownloadActorState::Paused {- part_path,- },- );- },- Err(error) => {- tracing::debug!("failed to preserve resume data while stopping download actor: {error}");- self.progress_counters = ProgressCounters::default();- release_destination_lease(destination_lease).await;- self.finish_transition(from_state, DownloadActorState::NotDownloaded);- },- },- state => {- self.state = state;- },- }-- let lock_path = lock_path_for_destination(&self.config.destination);- let _ = release_lock_if_owned(&lock_path, &self.config.manager_id, self.config.manager_instance_id).await;- }-- async fn handle_command(- &mut self,- command: TaskCommand,- ) -> bool {- match command {- TaskCommand::Download {- reply_sender,- } => {- let result = self.handle_download().await;- self.publish_current_state();- self.flush_terminal_outcome();- send_reply(reply_sender, result);- true- },- TaskCommand::Pause {- reply_sender,- } => {- let result = self.handle_pause().await;- self.publish_current_state();- self.flush_terminal_outcome();- send_reply(reply_sender, result);- true- },- TaskCommand::Cancel {- reply_sender,- } => {- let result = self.handle_cancel_or_remove().await;- self.publish_current_state();- self.flush_terminal_outcome();- send_reply(reply_sender, result);- true- },- TaskCommand::Remove {- reply_sender,- } => {- let result = self.handle_cancel_or_remove().await;- self.publish_current_state();- self.flush_terminal_outcome();- send_reply(reply_sender, result);- false- },- }- }-- async fn handle_download(&mut self) -> Result<(), DownloadError> {- match &self.state {- DownloadActorState::NotDownloaded => self.start_fresh_download().await,- DownloadActorState::Paused {- part_path,- } => self.resume_download(part_path.clone()).await,- DownloadActorState::Downloading {- ..- }- | DownloadActorState::Downloaded => Ok(()),- }- }-- async fn handle_pause(&mut self) -> Result<(), DownloadError> {- let current_state = std::mem::replace(&mut self.state, DownloadActorState::NotDownloaded);- let from_state = current_state.name();- match current_state {- DownloadActorState::Downloading {- active_task,- destination_lease,- ..- } => {- let pause_result = active_task.pause(&self.config.destination).await;- release_destination_lease(destination_lease).await;- match pause_result {- Ok(part_path) => {- let downloaded_bytes = B::read_resume_progress(&part_path).await.unwrap_or(0);- self.progress_counters = ProgressCounters {- downloaded_bytes,- total_bytes: self.config.expected_bytes.unwrap_or(downloaded_bytes),- };- self.finish_transition(- from_state,- DownloadActorState::Paused {- part_path,- },- );- Ok(())- },- Err(error) => {- let message = error.to_string();- self.projection = PublicProjection::StickyError(message.clone());- self.progress_counters = ProgressCounters::default();- self.pending_terminal_outcome = Some(TerminalOutcome::Error(message.clone()));- self.finish_transition(from_state, DownloadActorState::NotDownloaded);- Err(DownloadError::Backend(message))- },- }- },- DownloadActorState::Paused {- ..- } => {- self.state = current_state;- Ok(())- },- state => {- self.state = state;- Err(DownloadError::InvalidStateTransition)- },- }- }-- async fn handle_cancel_or_remove(&mut self) -> Result<(), DownloadError> {- let current_state = std::mem::replace(&mut self.state, DownloadActorState::NotDownloaded);- let from_state = current_state.name();- match current_state {- DownloadActorState::Downloading {- active_task,- destination_lease,- ..- } => {- let _ = active_task.cancel(&self.config.destination).await;- remove_resume_artifact(&self.config.destination).await;- self.progress_counters = ProgressCounters::default();- self.projection = PublicProjection::None;- release_destination_lease(destination_lease).await;- self.finish_transition(from_state, DownloadActorState::NotDownloaded);- Ok(())- },- DownloadActorState::Paused {- part_path,- } => {- remove_file(&part_path).await;- self.progress_counters = ProgressCounters::default();- self.projection = PublicProjection::None;- self.finish_transition(from_state, DownloadActorState::NotDownloaded);- Ok(())- },- state => {- self.state = state;- if matches!(self.projection, PublicProjection::StickyError(_)) {- self.projection = PublicProjection::None;- self.progress_counters = ProgressCounters::default();- }- Ok(())- },- }- }-- async fn handle_backend_event(- &mut self,- backend_event: BackendEvent,- ) {- match backend_event {- BackendEvent::Completed {- generation,- } => self.handle_backend_completed(generation).await,- BackendEvent::Error {- generation,- message,- } => self.handle_backend_error(generation, message).await,- }- }-- async fn handle_backend_completed(- &mut self,- completed_generation: ActiveDownloadGeneration,- ) {- let should_handle = matches!(- &self.state,- DownloadActorState::Downloading {- generation,- ..- } if *generation == completed_generation- );- if !should_handle {- return;- }-- let current_state = std::mem::replace(&mut self.state, DownloadActorState::NotDownloaded);- let from_state = current_state.name();- if let DownloadActorState::Downloading {- destination_lease,- ..- } = current_state- {- match validate_completed_file(&self.config).await {- Ok(total_bytes) => {- remove_resume_artifact(&self.config.destination).await;- self.progress_counters = ProgressCounters {- downloaded_bytes: total_bytes,- total_bytes,- };- self.projection = PublicProjection::None;- release_destination_lease(destination_lease).await;- self.finish_transition(from_state, DownloadActorState::Downloaded);- self.pending_terminal_outcome = Some(TerminalOutcome::Downloaded);- },- Err(message) => {- remove_file(&self.config.destination).await;- remove_resume_artifact(&self.config.destination).await;- remove_file(&crc_path_for_file(&self.config.destination)).await;- self.progress_counters = ProgressCounters::default();- self.projection = PublicProjection::StickyError(message.clone());- release_destination_lease(destination_lease).await;- self.finish_transition(from_state, DownloadActorState::NotDownloaded);- self.pending_terminal_outcome = Some(TerminalOutcome::Error(message));- },- }- }- }-- async fn handle_backend_error(- &mut self,- error_generation: ActiveDownloadGeneration,- message: String,- ) {- let should_handle = matches!(- &self.state,- DownloadActorState::Downloading {- generation,- ..- } if *generation == error_generation- );- if !should_handle {- return;- }-- let current_state = std::mem::replace(&mut self.state, DownloadActorState::NotDownloaded);- let from_state = current_state.name();- if let DownloadActorState::Downloading {- active_task,- destination_lease,- ..- } = current_state- {- let _ = active_task.cancel(&self.config.destination).await;- remove_resume_artifact(&self.config.destination).await;- self.projection = PublicProjection::StickyError(message.clone());- self.progress_counters = ProgressCounters::default();- release_destination_lease(destination_lease).await;- self.finish_transition(from_state, DownloadActorState::NotDownloaded);- self.pending_terminal_outcome = Some(TerminalOutcome::Error(message));- }- }-- async fn handle_pending_progress(&mut self) {- let progress = self.pending_progress.lock().await.take();- let Some(progress) = progress else {- return;- };-- if let DownloadActorState::Downloading {- generation,- ..- } = &self.state- && *generation == progress.generation- {- self.progress_counters = ProgressCounters {- downloaded_bytes: progress.downloaded_bytes,- total_bytes: progress.total_bytes.or(self.config.expected_bytes).unwrap_or(progress.downloaded_bytes),- };- }- }-- async fn start_fresh_download(&mut self) -> Result<(), DownloadError> {- let lease = self.acquire_destination_lease().await?;- let generation = self.generation_counter.allocate_next();- let active_task = match self- .context- .download(Arc::clone(&self.config), generation, self.backend_event_sender.clone(), &lease)- .await- {- Ok(active_task) => active_task,- Err(error) => {- release_destination_lease(lease).await;- return Err(DownloadError::Backend(error.to_string()));- },- };-- self.projection = PublicProjection::None;- self.progress_counters = ProgressCounters {- downloaded_bytes: 0,- total_bytes: self.config.expected_bytes.unwrap_or(0),- };- self.transition_to(DownloadActorState::Downloading {- active_task,- generation,- destination_lease: lease,- });- Ok(())- }-- async fn resume_download(- &mut self,- part_path: PathBuf,- ) -> Result<(), DownloadError> {- if !fs::asyn::try_exists(&part_path).await.unwrap_or(false) {- remove_file(&part_path).await;- return self.start_fresh_download().await;- }-- let lease = self.acquire_destination_lease().await?;- let generation = self.generation_counter.allocate_next();- let resume_bytes = B::read_resume_progress(&part_path).await.unwrap_or(0);- let active_task = match self- .context- .resume(Arc::clone(&self.config), generation, &part_path, self.backend_event_sender.clone(), &lease)- .await- {- Ok(active_task) => active_task,- Err(error) => {- release_destination_lease(lease).await;- remove_file(&part_path).await;- let message = error.to_string();- self.projection = PublicProjection::StickyError(message.clone());- self.progress_counters = ProgressCounters::default();- self.transition_to(DownloadActorState::NotDownloaded);- self.pending_terminal_outcome = Some(TerminalOutcome::Error(message.clone()));- return Err(DownloadError::Backend(message));- },- };-- self.projection = PublicProjection::None;- self.progress_counters = ProgressCounters {- downloaded_bytes: resume_bytes,- total_bytes: self.config.expected_bytes.unwrap_or(resume_bytes),- };- self.transition_to(DownloadActorState::Downloading {- active_task,- generation,- destination_lease: lease,- });- Ok(())- }-- async fn acquire_destination_lease(&mut self) -> Result<DestinationLockLease, DownloadError> {- let lock_path = lock_path_for_destination(&self.config.destination);- match check_lock_file(- &lock_path,- &self.config.manager_id,- self.config.manager_instance_id,- kiban::process::id(),- )- .await- {- LockFileState::OwnedByOtherApp(lock_file_info) => {- self.projection = PublicProjection::LockedByOther(lock_file_info.manager_id.clone());- Err(DownloadError::LockedByOther(lock_file_info.manager_id))- },- LockFileState::Missing- | LockFileState::OwnedByUs(_)- | LockFileState::OwnedBySameAppOldProcess(_)- | LockFileState::Stale(_)- | LockFileState::StaleUnparseable(_) => {- match DestinationLockLease::acquire(- &lock_path,- &self.config.manager_id,- self.config.manager_instance_id,- )- .await- {- Ok(lease) => Ok(lease),- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {- match check_lock_file(- &lock_path,- &self.config.manager_id,- self.config.manager_instance_id,- kiban::process::id(),- )- .await- {- LockFileState::OwnedByOtherApp(lock_file_info) => {- self.projection = PublicProjection::LockedByOther(lock_file_info.manager_id.clone());- Err(DownloadError::LockedByOther(lock_file_info.manager_id))- },- _ => Err(DownloadError::from(error)),- }- },- Err(error) => Err(DownloadError::from(error)),- }- },- }- }-- fn publish_current_state(&self) {- let public_state =- project_runtime_public_state(&self.state, &self.projection, self.progress_counters, &self.config);- let _ = self.public_state_sender.send(public_state.clone());- let _ = self.progress_sender.send(public_state);- }-- fn flush_terminal_outcome(&mut self) {- if let Some(terminal_outcome) = self.pending_terminal_outcome.take() {- let _ = self.terminal_sender.send(terminal_outcome);- }- }-- fn transition_to(- &mut self,- next_state: DownloadActorState<B>,- ) {- let from_state = self.state.name();- self.finish_transition(from_state, next_state);- }-- fn finish_transition(- &mut self,- from_state: &'static str,- next_state: DownloadActorState<B>,- ) {- let to_state = next_state.name();- self.state = next_state;- if from_state != to_state {- log(DownloadLogEvent::StateTransition {- download_id: self.config.download_id,- from: from_state,- to: to_state,- });- }- }-}--fn send_reply(- reply_sender: TokioOneshotSender<Result<(), DownloadError>>,- result: Result<(), DownloadError>,-) {- let _ = reply_sender.send(result);-}--async fn release_destination_lease(destination_lease: DestinationLockLease) {- let _ = destination_lease.release().await;-}--async fn remove_file(path: &Path) {- let _ = fs::asyn::remove_file(path).await;-}--async fn remove_resume_artifact(destination: &Path) {- remove_file(&destination.with_extension("part")).await;- remove_file(&destination.with_extension("resume_data")).await;-}--async fn validate_completed_file(config: &DownloadConfig) -> Result<u64, String> {- // After the backend reports completion the destination may not yet be fully- // visible on disk: metadata can lag, and on the copy/move fallback path the- // file briefly exists with fewer bytes than expected. Retry until it is- // present with the expected size (or the budget runs out) so a transient- // mismatch is not mistaken for a corrupt download. A genuinely truncated file- // has a stable size and still fails once the retries are exhausted.- for _ in 0..10 {- let is_ready = match fs::asyn::file_length(config.destination.as_path()).await {- Ok(dst_len) => match config.expected_bytes {- Some(expected_bytes) => dst_len == expected_bytes,- None => true,- },- Err(err) if err.kind() == ErrorKind::NotFound => false,- Err(err) => return Err(err.to_string()),- };- if is_ready {- break;- }-- kiban::time::sleep(Duration::from_millis(50)).await;- }-- let actual_bytes = fs::asyn::file_length(config.destination.as_path()).await.map_err(|err| err.to_string())?;- if let Some(expected_bytes) = config.expected_bytes- && expected_bytes != actual_bytes- {- return Err(format!("downloaded file is {actual_bytes} bytes but registry declared {expected_bytes}"));- }-- let total_bytes = config.expected_bytes.unwrap_or(actual_bytes);-- match &config.file_check {- FileCheck::None => Ok(total_bytes),- FileCheck::CRC(expected_crc) => {- let crc_result = calculate_and_verify_crc(&config.destination, expected_crc).await;- match crc_result {- Ok(true) => {- let destination = config.destination.clone();- let expected = expected_crc.clone();- let _ = save_crc_file(&destination, &expected).await;- Ok(total_bytes)- },- Ok(false) => Err("CRC verification failed".to_string()),- Err(error) => Err(format!("CRC verification error: {error}")),- }- },- }-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/generic_file_download_task.rs b/crates/legacy/download-manager/src/file_download_task_actor/generic_file_download_task.rsdeleted file mode 100644index 44b53aafb..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/generic_file_download_task.rs+++ /dev/null@@ -1,383 +0,0 @@-use std::{- fmt,- marker::PhantomData,- path::Path,- sync::{- Arc,- atomic::{AtomicBool, Ordering},- },-};--use kiban::{rt, rt::TaskJoinHandle};-use tokio::sync::{- Mutex as TokioMutex,- broadcast::{Sender as TokioBroadcastSender, channel as tokio_broadcast_channel},- mpsc::{Sender as TokioMpscSender, channel as tokio_mpsc_channel},- oneshot::channel as tokio_oneshot_channel,- watch::{Receiver as TokioWatchReceiver, channel as tokio_watch_channel},-};-use tokio_stream::{StreamExt as TokioStreamExt, wrappers::BroadcastStream as TokioBroadcastStream};--use crate::{- DownloadError, DownloadEventSender, DownloadId, FileCheck, FileDownloadEvent, FileDownloadPhase, FileDownloadState,- backends::common::{Backend, InitialTaskAttachment},- download_log_event::{DownloadLogEvent, log},- file_download_task::{FileDownloadTask, ManagedFileDownloadTask},- file_download_task_actor::{- DownloadActorState, DownloadTaskActor, PendingProgressSlot, ProgressCounters, PublicProjection, TaskCommand,- TerminalOutcome, project_runtime_public_state,- },- lock_manager::DestinationLockLease,- reducer::InitialLifecycleState,- traits::{ActiveDownloadGenerationCounter, BackendEventSender, DownloadBackend, DownloadConfig},-};--pub struct GenericFileDownloadTask<B: DownloadBackend> {- config: Arc<DownloadConfig>,- command_sender: TokioMpscSender<TaskCommand>,- public_state_receiver: TokioWatchReceiver<FileDownloadState>,- progress_sender: TokioBroadcastSender<FileDownloadState>,- terminal_receiver: TokioWatchReceiver<TerminalOutcome>,- listener_task: Arc<TokioMutex<Option<Box<dyn TaskJoinHandle<()>>>>>,- is_stopped: AtomicBool,- backend: PhantomData<B>,-}--impl<B: DownloadBackend> GenericFileDownloadTask<B> {- pub(crate) async fn spawn_with_initial_attachment(- config: Arc<DownloadConfig>,- context: Arc<B::Context>,- initial_lifecycle_state: InitialLifecycleState,- initial_projection: PublicProjection,- initial_progress: ProgressCounters,- mut startup_lease: Option<DestinationLockLease>,- ) -> Result<Self, DownloadError>- where- B: Backend,- {- let (command_sender, command_receiver) = tokio_mpsc_channel(64);- let (backend_event_sender, backend_event_receiver) = tokio_mpsc_channel(64);- let pending_progress = Arc::new(TokioMutex::new(PendingProgressSlot::default()));- let (progress_waker_sender, progress_waker_receiver) = tokio_watch_channel(());- let backend_event_sender = BackendEventSender::new(- config.download_id,- backend_event_sender,- Arc::clone(&pending_progress),- progress_waker_sender,- );- let (progress_sender, _) = tokio_broadcast_channel(64);- let (terminal_sender, terminal_receiver) = tokio_watch_channel(TerminalOutcome::Pending);-- let mut generation_counter = ActiveDownloadGenerationCounter::default();- let attachment_generation = generation_counter.allocate_next();- let attachment = if let Some(destination_lease) = startup_lease.as_ref() {- match B::initial_task_attachment(- context.as_ref(),- Arc::clone(&config),- attachment_generation,- backend_event_sender.clone(),- destination_lease,- )- .await- {- Ok(attachment) => attachment,- Err(error) => {- if let Some(lease) = startup_lease.take() {- let _ = lease.release().await;- }- return Err(error);- },- }- } else {- InitialTaskAttachment::None- };- let (lifecycle_state, progress_counters) = match (attachment, &initial_lifecycle_state) {- (InitialTaskAttachment::None, _) => (initial_lifecycle_state.into(), initial_progress),- (- InitialTaskAttachment::Downloading {- ..- },- InitialLifecycleState::Downloaded,- ) => (initial_lifecycle_state.into(), initial_progress),- (- InitialTaskAttachment::Downloading {- active_task,- initial_downloaded_bytes,- total_bytes,- },- _,- ) => {- let Some(destination_lease) = startup_lease.take() else {- return Err(DownloadError::Backend(- "backend returned an attached task without a startup lease".to_string(),- ));- };- (- DownloadActorState::Downloading {- active_task,- generation: attachment_generation,- destination_lease,- },- ProgressCounters {- downloaded_bytes: initial_downloaded_bytes,- total_bytes: total_bytes.or(config.expected_bytes).unwrap_or(initial_downloaded_bytes),- },- )- },- };-- if let Some(lease) = startup_lease.take() {- lease.release().await?;- }-- let initial_public_state =- project_runtime_public_state(&lifecycle_state, &initial_projection, progress_counters, &config);- let (public_state_sender, public_state_receiver) = tokio_watch_channel(initial_public_state);-- let actor = DownloadTaskActor::<B>::new(- Arc::clone(&config),- Arc::clone(&context),- backend_event_sender,- generation_counter,- lifecycle_state,- initial_projection,- progress_counters,- command_receiver,- backend_event_receiver,- pending_progress,- progress_waker_receiver,- public_state_sender,- progress_sender.clone(),- terminal_sender,- );- rt::spawn(actor.run());-- Ok(Self {- config,- command_sender,- public_state_receiver,- progress_sender,- terminal_receiver,- listener_task: Arc::new(TokioMutex::new(None)),- is_stopped: AtomicBool::new(false),- backend: PhantomData,- })- }-- async fn send_command(- &self,- command_builder: impl FnOnce(tokio::sync::oneshot::Sender<Result<(), DownloadError>>) -> TaskCommand,- ) -> Result<(), DownloadError> {- if self.is_stopped.load(Ordering::SeqCst) {- return Err(DownloadError::TaskStopped);- }- let (reply_sender, reply_receiver) = tokio_oneshot_channel();- self.command_sender.send(command_builder(reply_sender)).await.map_err(|_| DownloadError::ChannelClosed)?;- reply_receiver.await.unwrap_or(Err(DownloadError::TaskStopped))- }-- async fn wait_for_actor_stopped(&self) {- let mut terminal_receiver = self.terminal_receiver.clone();- loop {- if matches!(terminal_receiver.borrow().clone(), TerminalOutcome::ActorStopped) {- break;- }-- if terminal_receiver.changed().await.is_err() {- break;- }- }- }-}--impl<B: DownloadBackend> fmt::Debug for GenericFileDownloadTask<B> {- fn fmt(- &self,- formatter: &mut fmt::Formatter<'_>,- ) -> fmt::Result {- formatter- .debug_struct("GenericFileDownloadTask")- .field("download_id", &self.config.download_id)- .field("source_url", &self.config.source_url)- .field("destination", &self.config.destination)- .finish()- }-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-impl<B: DownloadBackend> crate::FileDownloadTask for GenericFileDownloadTask<B> {- fn download_id(&self) -> DownloadId {- self.config.download_id- }-- fn source_url(&self) -> &str {- &self.config.source_url- }-- fn destination(&self) -> &Path {- &self.config.destination- }-- fn file_check(&self) -> &FileCheck {- &self.config.file_check- }-- fn expected_bytes(&self) -> Option<u64> {- self.config.expected_bytes- }-- async fn download(&self) -> Result<(), DownloadError> {- self.send_command(|reply_sender| TaskCommand::Download {- reply_sender,- })- .await- }-- async fn pause(&self) -> Result<(), DownloadError> {- self.send_command(|reply_sender| TaskCommand::Pause {- reply_sender,- })- .await- }-- async fn cancel(&self) -> Result<(), DownloadError> {- self.send_command(|reply_sender| TaskCommand::Cancel {- reply_sender,- })- .await- }-- async fn state(&self) -> FileDownloadState {- self.public_state_receiver.borrow().clone()- }-- async fn progress(&self) -> Result<TokioBroadcastStream<FileDownloadState>, DownloadError> {- Ok(TokioBroadcastStream::new(self.progress_sender.subscribe()))- }-- async fn start_listening(- &self,- global_broadcast: DownloadEventSender,- ) {- let mut listener_task = self.listener_task.lock().await;- if listener_task.is_some() {- return;- }-- let download_id = self.config.download_id;- let destination = self.config.destination.clone();- let mut local_stream = TokioBroadcastStream::new(self.progress_sender.subscribe());- *listener_task = Some(rt::spawn(async move {- let mut last_downloaded_bytes = 0u64;-- while let Some(result) = local_stream.next().await {- let Ok(state) = result else {- continue;- };-- match state.phase {- FileDownloadPhase::Downloading => {- let bytes_written = state.downloaded_bytes.saturating_sub(last_downloaded_bytes);- last_downloaded_bytes = state.downloaded_bytes;- let event = FileDownloadEvent::ProgressUpdate {- bytes_written,- total_bytes_written: state.downloaded_bytes,- total_bytes_expected: state.total_bytes,- };- log(DownloadLogEvent::PublicEventEmitted {- download_id,- event: event.clone(),- });- let _ = global_broadcast.send((download_id, event));- },- FileDownloadPhase::Downloaded => {- let event = FileDownloadEvent::DownloadCompleted {- tmp_path: destination.clone(),- final_destination: destination.clone(),- };- log(DownloadLogEvent::PublicEventEmitted {- download_id,- event: event.clone(),- });- let _ = global_broadcast.send((download_id, event));- break;- },- FileDownloadPhase::Error(message) => {- let event = FileDownloadEvent::Error {- message,- };- log(DownloadLogEvent::PublicEventEmitted {- download_id,- event: event.clone(),- });- let _ = global_broadcast.send((download_id, event));- break;- },- FileDownloadPhase::NotDownloaded- | FileDownloadPhase::Paused- | FileDownloadPhase::LockedByOther(_) => {},- }- }- }));- }-- async fn stop_listening(&self) {- if let Some(listener_task) = self.listener_task.lock().await.take() {- listener_task.abort_and_join().await;- }- }-- async fn wait(&self) {- let mut terminal_receiver = self.terminal_receiver.clone();- loop {- match terminal_receiver.borrow().clone() {- TerminalOutcome::Pending => {},- TerminalOutcome::Downloaded | TerminalOutcome::Error(_) | TerminalOutcome::ActorStopped => break,- }-- if terminal_receiver.changed().await.is_err() {- break;- }- }- }-- fn broadcast_sender(&self) -> TokioBroadcastSender<FileDownloadState> {- self.progress_sender.clone()- }-}--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-impl<B: DownloadBackend> ManagedFileDownloadTask for GenericFileDownloadTask<B> {- async fn shutdown_for_removal(&self) -> Result<(), DownloadError> {- if self.is_stopped.swap(true, Ordering::SeqCst) {- self.wait_for_actor_stopped().await;- self.stop_listening().await;- return Ok(());- }-- let (reply_sender, reply_receiver) = tokio_oneshot_channel();- if self- .command_sender- .send(TaskCommand::Remove {- reply_sender,- })- .await- .is_err()- {- self.wait_for_actor_stopped().await;- self.stop_listening().await;- return Ok(());- }-- let result = reply_receiver.await.unwrap_or(Err(DownloadError::TaskStopped));- self.wait_for_actor_stopped().await;- self.stop_listening().await;- result- }-- fn is_stopped(&self) -> bool {- self.is_stopped.load(Ordering::SeqCst)- }-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/mod.rs b/crates/legacy/download-manager/src/file_download_task_actor/mod.rsdeleted file mode 100644index 534df13e2..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/mod.rs+++ /dev/null@@ -1,23 +0,0 @@-mod actor_state;-mod backend_event;-mod backend_progress;-mod download_task_actor;-mod generic_file_download_task;-mod pending_progress_slot;-mod progress_counters;-mod public_projection;-mod public_state_projector;-mod task_command;-mod terminal_outcome;--pub(crate) use actor_state::DownloadActorState;-pub use backend_event::BackendEvent;-pub use backend_progress::BackendProgress;-pub use download_task_actor::DownloadTaskActor;-pub use generic_file_download_task::GenericFileDownloadTask;-pub use pending_progress_slot::PendingProgressSlot;-pub use progress_counters::ProgressCounters;-pub use public_projection::PublicProjection;-pub use public_state_projector::project_runtime_public_state;-pub use task_command::TaskCommand;-pub use terminal_outcome::TerminalOutcome;diff --git a/crates/legacy/download-manager/src/file_download_task_actor/pending_progress_slot.rs b/crates/legacy/download-manager/src/file_download_task_actor/pending_progress_slot.rsdeleted file mode 100644index 2267d7c16..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/pending_progress_slot.rs+++ /dev/null@@ -1,12 +0,0 @@-use crate::file_download_task_actor::BackendProgress;--#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]-pub struct PendingProgressSlot {- pub progress: Option<BackendProgress>,-}--impl PendingProgressSlot {- pub fn take(&mut self) -> Option<BackendProgress> {- self.progress.take()- }-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/progress_counters.rs b/crates/legacy/download-manager/src/file_download_task_actor/progress_counters.rsdeleted file mode 100644index f762abfac..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/progress_counters.rs+++ /dev/null@@ -1,7 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-pub struct ProgressCounters {- pub downloaded_bytes: u64,- pub total_bytes: u64,-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/public_projection.rs b/crates/legacy/download-manager/src/file_download_task_actor/public_projection.rsdeleted file mode 100644index 464095e79..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/public_projection.rs+++ /dev/null@@ -1,9 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, Hash)]-pub enum PublicProjection {- #[default]- None,- LockedByOther(String),- StickyError(String),-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/public_state_projector.rs b/crates/legacy/download-manager/src/file_download_task_actor/public_state_projector.rsdeleted file mode 100644index 6c4247e29..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/public_state_projector.rs+++ /dev/null@@ -1,47 +0,0 @@-use crate::{- FileDownloadState,- file_download_task_actor::{DownloadActorState, ProgressCounters, PublicProjection},- traits::{DownloadBackend, DownloadConfig},-};--pub fn project_runtime_public_state<B: DownloadBackend>(- lifecycle_state: &DownloadActorState<B>,- projection: &PublicProjection,- progress_counters: ProgressCounters,- config: &DownloadConfig,-) -> FileDownloadState {- match projection {- PublicProjection::StickyError(message) => FileDownloadState::error(message.clone()),- PublicProjection::LockedByOther(manager_id) => FileDownloadState::locked_by_other(manager_id.clone()),- PublicProjection::None => match lifecycle_state {- DownloadActorState::NotDownloaded => FileDownloadState::not_downloaded(config.expected_bytes.unwrap_or(0)),- DownloadActorState::Paused {- ..- } => FileDownloadState::paused(- progress_counters.downloaded_bytes,- fallback_total_bytes(progress_counters, config.expected_bytes),- ),- DownloadActorState::Downloaded => {- let total_bytes = config.expected_bytes.unwrap_or(progress_counters.total_bytes);- FileDownloadState::downloaded(total_bytes)- },- DownloadActorState::Downloading {- ..- } => FileDownloadState::downloading(- progress_counters.downloaded_bytes,- fallback_total_bytes(progress_counters, config.expected_bytes),- ),- },- }-}--fn fallback_total_bytes(- progress_counters: ProgressCounters,- expected_bytes: Option<u64>,-) -> u64 {- if progress_counters.total_bytes == 0 {- expected_bytes.unwrap_or(0)- } else {- progress_counters.total_bytes- }-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/task_command.rs b/crates/legacy/download-manager/src/file_download_task_actor/task_command.rsdeleted file mode 100644index 14e232ac1..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/task_command.rs+++ /dev/null@@ -1,19 +0,0 @@-use tokio::sync::oneshot::Sender as TokioOneshotSender;--use crate::DownloadError;--#[derive(Debug)]-pub enum TaskCommand {- Download {- reply_sender: TokioOneshotSender<Result<(), DownloadError>>,- },- Pause {- reply_sender: TokioOneshotSender<Result<(), DownloadError>>,- },- Cancel {- reply_sender: TokioOneshotSender<Result<(), DownloadError>>,- },- Remove {- reply_sender: TokioOneshotSender<Result<(), DownloadError>>,- },-}diff --git a/crates/legacy/download-manager/src/file_download_task_actor/terminal_outcome.rs b/crates/legacy/download-manager/src/file_download_task_actor/terminal_outcome.rsdeleted file mode 100644index f1b176f3e..000000000--- a/crates/legacy/download-manager/src/file_download_task_actor/terminal_outcome.rs+++ /dev/null@@ -1,9 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum TerminalOutcome {- Pending,- Downloaded,- Error(String),- ActorStopped,-}diff --git a/crates/legacy/download-manager/src/file_state.rs b/crates/legacy/download-manager/src/file_state.rsdeleted file mode 100644index ac7a2916a..000000000--- a/crates/legacy/download-manager/src/file_state.rs+++ /dev/null@@ -1,7 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum FileState {- Exists,- Missing,-}diff --git a/crates/legacy/download-manager/src/group_download_task.rs b/crates/legacy/download-manager/src/group_download_task.rsnew file mode 100644index 000000000..867052a86--- /dev/null+++ b/crates/legacy/download-manager/src/group_download_task.rs@@ -0,0 +1,179 @@+use std::sync::{Arc, Mutex, PoisonError};++use futures_util::stream::{StreamExt, select_all};+use kiban::{rt, rt::TaskJoinHandle, stream::BoxStream};++use crate::{DownloadError, DownloadPhase, DownloadState, DownloadTask, DownloadTaskRequest, locks::LockError};++pub struct GroupDownloadTask {+ pub request: DownloadTaskRequest,+ children: Arc<[Arc<DownloadTask>]>,+ download_loop: Arc<Mutex<Option<Box<dyn TaskJoinHandle<()>>>>>,+}++impl GroupDownloadTask {+ pub fn new(+ request: DownloadTaskRequest,+ children: Vec<Arc<DownloadTask>>,+ ) -> Self {+ let group = Self {+ request,+ children: children.into(),+ download_loop: Arc::default(),+ };+ if group.state().phase == (DownloadPhase::Downloading {}) {+ group.start_download_loop();+ }+ group+ }++ pub fn subtasks(&self) -> &[Arc<DownloadTask>] {+ &self.children+ }++ pub fn state(&self) -> DownloadState {+ children_state(&self.children, &self.download_loop)+ }++ pub fn progress(&self) -> BoxStream<'static, DownloadState> {+ let children = Arc::clone(&self.children);+ let download_loop = Arc::clone(&self.download_loop);+ Box::pin(+ select_all(self.children.iter().map(|child| child.progress()))+ .map(move |_| children_state(&children, &download_loop)),+ )+ }++ pub async fn download(&self) -> Result<(), DownloadError> {+ self.stop_download_loop().await;+ let Some((current, state)) = self+ .children+ .iter()+ .map(|child| (child, child.state()))+ .find(|(_, state)| state.phase != (DownloadPhase::Downloaded {}))+ else {+ return Ok(());+ };+ if state.phase != (DownloadPhase::Downloading {}) {+ Box::pin(current.download()).await?;+ }+ self.start_download_loop();+ Ok(())+ }++ pub async fn pause(&self) -> Result<(), DownloadError> {+ self.stop_download_loop().await;+ let mut result = Ok(());+ for child in self.children.iter().filter(|child| child.state().is_in_progress()) {+ result = result.and(Box::pin(child.pause()).await);+ }+ result+ }++ pub async fn delete(&self) -> Result<(), DownloadError> {+ self.stop_download_loop().await;+ if let Some(manager_id) = self.foreign_owner().await {+ return Err(LockError::LockedByOther {+ manager_id,+ }+ .into());+ }+ let mut result = Ok(());+ for child in self.children.iter() {+ result = result.and(Box::pin(child.delete()).await);+ }+ result+ }++ pub async fn foreign_owner(&self) -> Option<String> {+ for child in self.children.iter() {+ if let Some(manager_id) = Box::pin(child.foreign_owner()).await {+ return Some(manager_id);+ }+ }+ None+ }++ fn start_download_loop(&self) {+ let children = Arc::clone(&self.children);+ let running = rt::spawn(async move { download_in_order(&children).await });+ if let Some(previous) = self.download_loop.lock().unwrap_or_else(PoisonError::into_inner).replace(running) {+ previous.abort();+ }+ }++ async fn stop_download_loop(&self) {+ let running = self.download_loop.lock().unwrap_or_else(PoisonError::into_inner).take();+ if let Some(running) = running {+ running.abort_and_join().await;+ }+ }+}++impl Drop for GroupDownloadTask {+ fn drop(&mut self) {+ if let Some(running) = self.download_loop.lock().unwrap_or_else(PoisonError::into_inner).take() {+ running.abort();+ }+ }+}++fn children_state(+ children: &[Arc<DownloadTask>],+ download_loop: &Mutex<Option<Box<dyn TaskJoinHandle<()>>>>,+) -> DownloadState {+ let download_loop_running = download_loop+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .as_ref()+ .is_some_and(|running| !running.is_finished());+ let mut total_bytes = 0;+ let mut downloaded_bytes = 0;+ let mut in_progress = None;+ let mut incomplete = None;+ for state in children.iter().map(|child| child.state()) {+ total_bytes += state.total_bytes;+ downloaded_bytes += state.downloaded_bytes;+ if state.phase.is_in_progress() {+ in_progress.get_or_insert(state.phase);+ } else if state.phase != (DownloadPhase::Downloaded {}) {+ incomplete.get_or_insert(state.phase);+ }+ }+ let phase = match (in_progress, incomplete) {+ (Some(phase), _) => phase,+ (None, None) => DownloadPhase::Downloaded {},+ (None, Some(DownloadPhase::NotDownloaded {} | DownloadPhase::Paused {})) if download_loop_running => {+ DownloadPhase::Downloading {}+ },+ (None, Some(DownloadPhase::NotDownloaded {})) if downloaded_bytes > 0 => DownloadPhase::Paused {},+ (None, Some(phase)) => phase,+ };+ DownloadState {+ total_bytes,+ downloaded_bytes,+ phase,+ }+}++async fn download_in_order(children: &[Arc<DownloadTask>]) {+ for child in children {+ let mut progress = child.progress();+ match child.state().phase {+ DownloadPhase::Downloaded {} => continue,+ DownloadPhase::Downloading {} => {},+ _ => {+ if child.download().await.is_err() {+ return;+ }+ },+ }+ while let Some(state) = progress.next().await {+ match state.phase {+ DownloadPhase::Downloaded {} => break,+ phase if phase.is_in_progress() => {},+ _ => return,+ }+ }+ }+}diff --git a/crates/legacy/download-manager/src/lib.rs b/crates/legacy/download-manager/src/lib.rsindex 844189b23..012a07fdf 100644--- a/crates/legacy/download-manager/src/lib.rs+++ b/crates/legacy/download-manager/src/lib.rs@@ -1,43 +1,36 @@-mod checked_file_state;-mod crc_utils;+#[cfg(feature = "bindings-uniffi")]+uniffi::setup_scaffolding!();++mod backends;+mod cached_download_task;+mod crc32c;+mod crc_receipt;mod download_error;-mod download_info;-mod download_log_event;+mod download_id;+mod download_manager;+mod download_manager_type;+mod download_phase;mod download_state;-mod file_check;-mod file_download_event;-mod file_download_manager;-mod file_download_phase;-mod file_download_state;-mod file_download_task;-mod file_state;-mod lock_file_info;-mod lock_file_state;-mod lock_manager;--pub(crate) mod backends;-pub(crate) mod file_download_task_actor;-pub(crate) mod reducer;-pub(crate) mod traits;+mod download_task;+mod download_task_kind;+mod download_task_request;+mod file_download;+mod group_download_task;+mod locks;-pub use checked_file_state::CheckedFileState;+#[cfg(target_vendor = "apple")]+pub use backends::AppleBackendError;+pub use backends::BackendError;+pub use crc32c::Crc32c;pub use download_error::DownloadError;-pub use download_info::DownloadInfo;+pub use download_id::DownloadId;+pub use download_manager::DownloadManager;+pub use download_manager_type::DownloadManagerType;+pub use download_phase::DownloadPhase;pub use download_state::DownloadState;-pub use file_check::FileCheck;-pub use file_download_event::FileDownloadEvent;-pub use file_download_manager::{- DownloadEvent, DownloadEventSender, FileDownloadManager, FileDownloadManagerType, SharedDownloadEventSender,-};-pub use file_download_phase::FileDownloadPhase;-pub use file_download_state::FileDownloadState;-pub use file_download_task::FileDownloadTask;-pub use file_state::FileState;-pub use lock_file_info::LockFileInfo;-pub use lock_file_state::LockFileState;-pub use lock_manager::{acquire_lock, check_lock_file, release_lock_if_owned, try_acquire_lock};--pub type DownloadId = uuid::Uuid;-pub fn compute_download_id(destination_path: &std::path::Path) -> DownloadId {- uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, destination_path.display().to_string().as_bytes())-}+pub use download_task::DownloadTask;+pub use download_task_kind::DownloadTaskKind;+pub use download_task_request::DownloadTaskRequest;+pub use file_download::{FileDownloadError, FileDownloadTask};+pub use group_download_task::GroupDownloadTask;+pub use locks::{DestinationLock, LockError, LockOwner};diff --git a/crates/legacy/download-manager/src/lock_file_info.rs b/crates/legacy/download-manager/src/lock_file_info.rsdeleted file mode 100644index 9b4654085..000000000--- a/crates/legacy/download-manager/src/lock_file_info.rs+++ /dev/null@@ -1,26 +0,0 @@-use serde::{Deserialize, Serialize};-use uuid::Uuid;--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub struct LockFileInfo {- pub manager_id: String,- #[serde(default)]- pub instance_id: Uuid,- pub acquired_at: chrono::DateTime<chrono::Utc>,- pub process_id: u32,-}--impl LockFileInfo {- pub fn new(- manager_id: String,- instance_id: Uuid,- process_id: u32,- ) -> Self {- Self {- manager_id,- instance_id,- acquired_at: chrono::Utc::now(),- process_id,- }- }-}diff --git a/crates/legacy/download-manager/src/lock_file_state.rs b/crates/legacy/download-manager/src/lock_file_state.rsdeleted file mode 100644index b3eb6909e..000000000--- a/crates/legacy/download-manager/src/lock_file_state.rs+++ /dev/null@@ -1,30 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::LockFileInfo;--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum LockFileState {- Missing,- OwnedByUs(LockFileInfo),- OwnedBySameAppOldProcess(LockFileInfo),- OwnedByOtherApp(LockFileInfo),- Stale(LockFileInfo),- StaleUnparseable(Vec<u8>),-}--impl LockFileState {- pub fn can_proceed(&self) -> bool {- matches!(- self,- Self::Missing- | Self::OwnedByUs(_)- | Self::OwnedBySameAppOldProcess(_)- | Self::Stale(_)- | Self::StaleUnparseable(_)- )- }-- pub fn is_conflict(&self) -> bool {- matches!(self, Self::OwnedByOtherApp(_))- }-}diff --git a/crates/legacy/download-manager/src/lock_manager.rs b/crates/legacy/download-manager/src/lock_manager.rsdeleted file mode 100644index dc1f0b52e..000000000--- a/crates/legacy/download-manager/src/lock_manager.rs+++ /dev/null@@ -1,377 +0,0 @@-use std::{- path::{Path, PathBuf},- time::Duration,-};--use kiban::{- fs,- process::{is_process_alive, proc_supported},- time::SystemTime,-};-use uuid::Uuid;--use crate::{LockFileInfo, LockFileState};--const LOCK_TIMEOUT_MINUTES: i64 = 30;--#[derive(Debug)]-pub(crate) struct DestinationLockLease {- lock_path: PathBuf,- manager_id: String,- instance_id: Uuid,-}--impl DestinationLockLease {- pub(crate) async fn acquire_for_destination(- destination_path: &Path,- manager_id: &str,- instance_id: Uuid,- ) -> Result<Self, std::io::Error> {- Self::acquire(&lock_path_for_destination(destination_path), manager_id, instance_id).await- }-- pub(crate) async fn acquire(- lock_path: &Path,- manager_id: &str,- instance_id: Uuid,- ) -> Result<Self, std::io::Error> {- acquire_lock(lock_path, manager_id, instance_id).await?;- Ok(Self {- lock_path: lock_path.to_path_buf(),- manager_id: manager_id.to_string(),- instance_id,- })- }-- pub(crate) async fn release(self) -> Result<bool, std::io::Error> {- release_lock_if_owned(&self.lock_path, &self.manager_id, self.instance_id).await- }-}--pub(crate) fn lock_path_for_destination(destination: &Path) -> PathBuf {- PathBuf::from(format!("{}.lock", destination.display()))-}--pub async fn check_lock_file(- lock_path: &Path,- our_manager_id: &str,- our_instance_id: Uuid,- our_process_id: u32,-) -> LockFileState {- let bytes = match fs::asyn::read(lock_path).await {- Ok(bytes) => bytes,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return LockFileState::Missing,- Err(_) => return classify_unparseable_lock(lock_path, Vec::new()).await,- };-- let lock_info = match serde_json::from_slice::<LockFileInfo>(&bytes) {- Ok(lock_info) => lock_info,- Err(_) => return classify_unparseable_lock(lock_path, bytes).await,- };-- if lock_info.manager_id == our_manager_id {- if proc_supported() {- if lock_info.process_id == our_process_id {- if lock_info.instance_id == our_instance_id {- return LockFileState::OwnedByUs(lock_info);- }- return LockFileState::OwnedByOtherApp(lock_info);- }-- if is_process_alive(lock_info.process_id).await {- return LockFileState::OwnedByOtherApp(lock_info);- }- } else {- return classify_same_manager_lock_without_process(lock_info, our_instance_id);- }-- return LockFileState::OwnedBySameAppOldProcess(lock_info);- }-- if is_process_alive(lock_info.process_id).await {- return LockFileState::OwnedByOtherApp(lock_info);- }-- if is_lock_stale(&lock_info) {- LockFileState::Stale(lock_info)- } else {- LockFileState::OwnedByOtherApp(lock_info)- }-}--pub async fn acquire_lock(- lock_path: &Path,- manager_id: &str,- instance_id: Uuid,-) -> Result<(), std::io::Error> {- let lock_info = LockFileInfo::new(manager_id.to_string(), instance_id, kiban::process::id());- let lock_contents = serde_json::to_string_pretty(&lock_info).map_err(std::io::Error::other)?;-- if let Some(parent) = lock_path.parent() {- fs::asyn::create_dir_all(parent).await?;- }-- match write_new_lock_file(lock_path, lock_contents.as_bytes()).await {- Ok(()) => Ok(()),- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {- match check_lock_file(lock_path, manager_id, instance_id, kiban::process::id()).await {- LockFileState::OwnedByUs(_) => Ok(()),- LockFileState::OwnedBySameAppOldProcess(observed) | LockFileState::Stale(observed) => {- match reclaim_stale_lock(lock_path, ReclaimExpectation::Matching(observed)).await? {- ReclaimOutcome::Reclaimed | ReclaimOutcome::Missing => {- Box::pin(acquire_lock(lock_path, manager_id, instance_id)).await- },- ReclaimOutcome::Changed => Err(std::io::Error::new(- std::io::ErrorKind::AlreadyExists,- "destination lock changed while reclaiming stale lock",- )),- }- },- LockFileState::StaleUnparseable(snapshot) => {- match reclaim_stale_lock(lock_path, ReclaimExpectation::UnparseableSnapshot(snapshot)).await? {- ReclaimOutcome::Reclaimed | ReclaimOutcome::Missing => {- Box::pin(acquire_lock(lock_path, manager_id, instance_id)).await- },- ReclaimOutcome::Changed => Err(std::io::Error::new(- std::io::ErrorKind::AlreadyExists,- "destination lock changed while reclaiming stale lock",- )),- }- },- LockFileState::OwnedByOtherApp(info) => Err(std::io::Error::new(- std::io::ErrorKind::AlreadyExists,- format!("destination locked by {}", info.manager_id),- )),- LockFileState::Missing => Box::pin(acquire_lock(lock_path, manager_id, instance_id)).await,- }- },- Err(error) => Err(error),- }-}--async fn write_new_lock_file(- lock_path: &Path,- lock_contents: &[u8],-) -> Result<(), std::io::Error> {- if !proc_supported() {- return write_new_lock_file_direct(lock_path, lock_contents).await;- }-- let temporary_lock_path = lock_path.with_extension(format!("lock-tmp-{}", Uuid::new_v4()));- let temporary_result = fs::asyn::write_with_sync_all(&temporary_lock_path, &lock_contents).await;- if let Err(error) = temporary_result {- let _ = fs::asyn::remove_file(&temporary_lock_path).await;- return Err(error);- }-- match fs::asyn::hard_link(&temporary_lock_path, lock_path).await {- Ok(()) => {- let _ = fs::asyn::remove_file(&temporary_lock_path).await;- Ok(())- },- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {- let _ = fs::asyn::remove_file(&temporary_lock_path).await;- Err(error)- },- Err(_) => {- let result = write_new_lock_file_direct(lock_path, lock_contents).await;- let _ = fs::asyn::remove_file(&temporary_lock_path).await;- result- },- }-}--async fn write_new_lock_file_direct(- lock_path: &Path,- lock_contents: &[u8],-) -> Result<(), std::io::Error> {- if let Err(err) = fs::asyn::write_with_sync_all(&lock_path, &lock_contents).await {- if err.kind() != std::io::ErrorKind::AlreadyExists {- let _ = fs::asyn::remove_file(&lock_path).await;- }- return Err(err);- }- Ok(())-}--#[derive(Clone, Debug)]-pub(crate) enum ReclaimExpectation {- Matching(LockFileInfo),- UnparseableSnapshot(Vec<u8>),-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(crate) enum ReclaimOutcome {- Reclaimed,- Missing,- Changed,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(crate) enum RestoreOutcome {- Restored,- DestinationAlreadyExists,-}--pub(crate) async fn reclaim_stale_lock(- lock_path: &Path,- expectation: ReclaimExpectation,-) -> Result<ReclaimOutcome, std::io::Error> {- let quarantine_path = lock_path.with_extension(format!("reclaim-{}", Uuid::new_v4()));- match fs::asyn::rename(lock_path, &quarantine_path).await {- Ok(()) => {},- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(ReclaimOutcome::Missing),- Err(error) => return Err(error),- }- let confirmed = match &expectation {- ReclaimExpectation::Matching(observed) => {- matches!(read_lock_file(&quarantine_path).await.ok(), Some(actual) if &actual == observed)- },- ReclaimExpectation::UnparseableSnapshot(snapshot) => {- matches!(fs::asyn::read(&quarantine_path).await.ok(), Some(bytes) if &bytes == snapshot)- },- };- if confirmed {- let _ = fs::asyn::remove_file(&quarantine_path).await;- return Ok(ReclaimOutcome::Reclaimed);- }- let _ = try_restore_quarantine(&quarantine_path, lock_path).await?;- Ok(ReclaimOutcome::Changed)-}--pub async fn release_lock_if_owned(- lock_path: &Path,- manager_id: &str,- instance_id: Uuid,-) -> Result<bool, std::io::Error> {- let observed = match check_lock_file(lock_path, manager_id, instance_id, kiban::process::id()).await {- LockFileState::OwnedByUs(info) => info,- _ => return Ok(false),- };- let quarantine_path = lock_path.with_extension(format!("release-{}", Uuid::new_v4()));- match fs::asyn::rename(lock_path, &quarantine_path).await {- Ok(()) => {},- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),- Err(error) => return Err(error),- }- let parsed = read_lock_file(&quarantine_path).await.ok();- let confirmed = matches!(parsed.as_ref(), Some(actual) if actual == &observed);- if confirmed {- let _ = fs::asyn::remove_file(&quarantine_path).await;- return Ok(true);- }- let _ = try_restore_quarantine(&quarantine_path, lock_path).await?;- Ok(false)-}--pub(crate) async fn try_restore_quarantine(- quarantine_path: &Path,- lock_path: &Path,-) -> Result<RestoreOutcome, std::io::Error> {- // Use atomic create-or-fail (hard_link, then create_new fallback) so a fresh lock- // installed by another owner during our quarantine isn't clobbered by `rename`.- match fs::asyn::hard_link(quarantine_path, lock_path).await {- Ok(()) => {- let _ = fs::asyn::remove_file(quarantine_path).await;- return Ok(RestoreOutcome::Restored);- },- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {- let _ = fs::asyn::remove_file(quarantine_path).await;- return Ok(RestoreOutcome::DestinationAlreadyExists);- },- Err(_) => {},- }-- let bytes = match fs::asyn::read(quarantine_path).await {- Ok(bytes) => bytes,- Err(error) => {- let _ = fs::asyn::remove_file(quarantine_path).await;- return Err(error);- },- };-- let lock_file_exists = matches!(fs::asyn::try_exists(lock_path).await, Ok(true));- if lock_file_exists {- let _ = fs::asyn::remove_file(quarantine_path).await;- return Ok(RestoreOutcome::DestinationAlreadyExists);- }-- if let Err(err) = fs::asyn::write_with_sync_all(&lock_path, &bytes).await {- let _ = fs::asyn::remove_file(quarantine_path).await;- if err.kind() == std::io::ErrorKind::AlreadyExists {- return Ok(RestoreOutcome::DestinationAlreadyExists);- }- let _ = fs::asyn::remove_file(lock_path).await;- return Err(err);- }- let _ = fs::asyn::remove_file(quarantine_path).await;-- Ok(RestoreOutcome::Restored)-}--pub async fn try_acquire_lock(- lock_path: &Path,- manager_id: &str,- instance_id: Uuid,-) -> Result<bool, std::io::Error> {- if check_lock_file(lock_path, manager_id, instance_id, kiban::process::id()).await.is_conflict() {- return Ok(false);- }-- acquire_lock(lock_path, manager_id, instance_id).await?;- Ok(true)-}--async fn read_lock_file(lock_path: &Path) -> Result<LockFileInfo, Box<dyn std::error::Error>> {- let file_content = fs::asyn::read_to_string(&lock_path).await?;- Ok(serde_json::from_str(&file_content)?)-}--pub(crate) fn classify_same_manager_lock_without_process(- lock_info: LockFileInfo,- our_instance_id: Uuid,-) -> LockFileState {- if lock_info.instance_id == our_instance_id {- return LockFileState::OwnedByUs(lock_info);- }-- if is_lock_stale(&lock_info) {- LockFileState::Stale(lock_info)- } else {- LockFileState::OwnedByOtherApp(lock_info)- }-}--async fn classify_unparseable_lock(- lock_path: &Path,- snapshot: Vec<u8>,-) -> LockFileState {- let stale_duration = Duration::from_secs((LOCK_TIMEOUT_MINUTES * 60) as u64);- let mtime = match fs::asyn::file_modified(lock_path).await {- Ok(mtime) => mtime,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return LockFileState::Missing,- Err(_) => {- return LockFileState::OwnedByOtherApp(LockFileInfo {- manager_id: "unknown".to_string(),- instance_id: Uuid::nil(),- acquired_at: chrono::Utc::now(),- process_id: 0,- });- },- };- let age = SystemTime::now().duration_since(mtime).ok();- if matches!(age, Some(age) if age >= stale_duration) {- LockFileState::StaleUnparseable(snapshot)- } else {- LockFileState::OwnedByOtherApp(LockFileInfo {- manager_id: "unknown".to_string(),- instance_id: Uuid::nil(),- acquired_at: chrono::Utc::now(),- process_id: 0,- })- }-}--fn is_lock_stale(lock_info: &LockFileInfo) -> bool {- chrono::Utc::now() - lock_info.acquired_at > chrono::Duration::minutes(LOCK_TIMEOUT_MINUTES)-}diff --git a/crates/legacy/download-manager/src/locks/destination_lock.rs b/crates/legacy/download-manager/src/locks/destination_lock.rsnew file mode 100644index 000000000..1733dc33d--- /dev/null+++ b/crates/legacy/download-manager/src/locks/destination_lock.rs@@ -0,0 +1,68 @@+use std::path::{Path, PathBuf};++use kiban::fs::{self, FileLock};+use uuid::Uuid;++use crate::locks::{LockError, LockOwner};++pub struct DestinationLock {+ path: PathBuf,+ _lock: FileLock,+}++impl DestinationLock {+ pub async fn acquire(+ destination: &Path,+ owner: &LockOwner,+ ) -> Result<Self, LockError> {+ let path = Self::path_for(destination);+ let Some(lock) = FileLock::try_acquire(&path).await? else {+ return Err(LockError::LockedByOther {+ manager_id: Self::owner(destination).await.manager_id,+ });+ };+ lock.write(&serde_json::to_vec(owner).map_err(std::io::Error::other)?).await?;+ Ok(Self {+ path,+ _lock: lock,+ })+ }++ pub async fn foreign_owner(+ destination: &Path,+ owner: &LockOwner,+ ) -> Option<String> {+ let path = Self::path_for(destination);+ if !fs::asyn::try_exists(&path).await.unwrap_or(false) {+ return None;+ }+ match FileLock::try_acquire(&path).await {+ Ok(None) => {+ let holder = Self::owner(destination).await;+ (holder != *owner).then_some(holder.manager_id)+ },+ Ok(Some(_)) | Err(_) => None,+ }+ }++ pub async fn owner(destination: &Path) -> LockOwner {+ fs::asyn::read_to_string(Self::path_for(destination))+ .await+ .ok()+ .and_then(|contents| serde_json::from_str(&contents).ok())+ .unwrap_or_else(|| LockOwner {+ manager_id: "unknown".to_string(),+ instance_id: Uuid::nil(),+ })+ }++ fn path_for(destination: &Path) -> PathBuf {+ PathBuf::from(format!("{}.lock", destination.display()))+ }+}++impl Drop for DestinationLock {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.path);+ }+}diff --git a/crates/legacy/download-manager/src/locks/lock_error.rs b/crates/legacy/download-manager/src/locks/lock_error.rsnew file mode 100644index 000000000..c70fbd59a--- /dev/null+++ b/crates/legacy/download-manager/src/locks/lock_error.rs@@ -0,0 +1,9 @@+#[derive(Debug, thiserror::Error)]+pub enum LockError {+ #[error("destination locked by another manager: {manager_id}")]+ LockedByOther {+ manager_id: String,+ },+ #[error(transparent)]+ Io(#[from] std::io::Error),+}diff --git a/crates/legacy/download-manager/src/locks/lock_owner.rs b/crates/legacy/download-manager/src/locks/lock_owner.rsnew file mode 100644index 000000000..24c711c95--- /dev/null+++ b/crates/legacy/download-manager/src/locks/lock_owner.rs@@ -0,0 +1,8 @@+use serde::{Deserialize, Serialize};+use uuid::Uuid;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct LockOwner {+ pub manager_id: String,+ pub instance_id: Uuid,+}diff --git a/crates/legacy/download-manager/src/locks/mod.rs b/crates/legacy/download-manager/src/locks/mod.rsnew file mode 100644index 000000000..26da9793d--- /dev/null+++ b/crates/legacy/download-manager/src/locks/mod.rs@@ -0,0 +1,7 @@+mod destination_lock;+mod lock_error;+mod lock_owner;++pub use destination_lock::DestinationLock;+pub use lock_error::LockError;+pub use lock_owner::LockOwner;diff --git a/crates/legacy/download-manager/src/reducer/action.rs b/crates/legacy/download-manager/src/reducer/action.rsdeleted file mode 100644index e2421db93..000000000--- a/crates/legacy/download-manager/src/reducer/action.rs+++ /dev/null@@ -1,20 +0,0 @@-use std::path::PathBuf;--use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum Action {- DeleteFile {- path: PathBuf,- },- DeleteCrcCache {- path: PathBuf,- },- DeleteResumeArtifact {- path: PathBuf,- },- SaveCrcCache {- destination: PathBuf,- crc: String,- },-}diff --git a/crates/legacy/download-manager/src/reducer/action_plan.rs b/crates/legacy/download-manager/src/reducer/action_plan.rsdeleted file mode 100644index f4432ee74..000000000--- a/crates/legacy/download-manager/src/reducer/action_plan.rs+++ /dev/null@@ -1,40 +0,0 @@-use crate::reducer::Action;--#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]-pub struct ActionPlan {- actions: Box<[Action]>,-}--impl ActionPlan {- pub fn empty() -> Self {- Self::default()- }-- pub fn from_ordered_actions(actions: impl IntoIterator<Item = Action>) -> Self {- let mut ordered_actions = Vec::new();-- for action in actions {- if !ordered_actions.contains(&action) {- ordered_actions.push(action);- }- }-- Self {- actions: ordered_actions.into_boxed_slice(),- }- }-- pub fn merge_in_order(action_plans: impl IntoIterator<Item = ActionPlan>) -> Self {- Self::from_ordered_actions(- action_plans.into_iter().flat_map(|action_plan| Vec::from(action_plan.actions).into_iter()),- )- }-- pub fn as_slice(&self) -> &[Action] {- &self.actions- }-- pub fn is_empty(&self) -> bool {- self.actions.is_empty()- }-}diff --git a/crates/legacy/download-manager/src/reducer/decision.rs b/crates/legacy/download-manager/src/reducer/decision.rsdeleted file mode 100644index a6acae665..000000000--- a/crates/legacy/download-manager/src/reducer/decision.rs+++ /dev/null@@ -1,109 +0,0 @@-use crate::{- CheckedFileState, FileState, LockFileState,- file_download_task_actor::{ProgressCounters, PublicProjection},- reducer::{Action, ActionPlan, DiskObservation, InitialLifecycleState, LockObservation, ValidationOutcome},-};--#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub struct Decision {- pub initial_lifecycle_state: InitialLifecycleState,- pub initial_projection: PublicProjection,- pub initial_progress: ProgressCounters,- pub action_plan: ActionPlan,-}--pub fn decide(- observation: &DiskObservation,- lock_observation: &LockObservation,- validation: &ValidationOutcome,-) -> Decision {- let action_plan = if lock_observation.state.is_conflict() {- ActionPlan::empty()- } else {- let decision_action_plan = decide_actions(observation, validation);- ActionPlan::merge_in_order([validation.action_plan.clone(), decision_action_plan])- };-- let initial_lifecycle_state = match validation.checked {- CheckedFileState::Valid => InitialLifecycleState::Downloaded,- CheckedFileState::Invalid | CheckedFileState::Missing if observation.resume_state == FileState::Exists => {- InitialLifecycleState::Paused {- part_path: observation- .resume_artifact_path- .clone()- .unwrap_or_else(|| observation.destination_path.with_extension("part")),- }- },- CheckedFileState::Invalid | CheckedFileState::Missing => InitialLifecycleState::NotDownloaded,- };-- // Don't surface `LockedByOther` when the file is already on disk; ownership-sensitive- // callers use `FileDownloadManager::destination_foreign_lock` directly.- let initial_projection = match (&lock_observation.state, &initial_lifecycle_state) {- (LockFileState::OwnedByOtherApp(lock_file_info), state)- if !matches!(state, InitialLifecycleState::Downloaded) =>- {- PublicProjection::LockedByOther(lock_file_info.manager_id.clone())- },- _ => PublicProjection::None,- };-- let initial_progress = match &initial_lifecycle_state {- InitialLifecycleState::Paused {- ..- } => ProgressCounters {- downloaded_bytes: observation.resume_size.unwrap_or(0),- total_bytes: observation.expected_bytes.or(observation.resume_size).unwrap_or(0),- },- InitialLifecycleState::Downloaded => {- let total_bytes = observation.expected_bytes.or(observation.destination_size).unwrap_or(0);- ProgressCounters {- downloaded_bytes: total_bytes,- total_bytes,- }- },- InitialLifecycleState::NotDownloaded => ProgressCounters {- downloaded_bytes: 0,- total_bytes: observation.expected_bytes.unwrap_or(0),- },- };-- Decision {- initial_lifecycle_state,- initial_projection,- initial_progress,- action_plan,- }-}--fn decide_actions(- observation: &DiskObservation,- validation: &ValidationOutcome,-) -> ActionPlan {- let mut actions = Vec::new();-- if validation.checked == CheckedFileState::Valid- && observation.resume_state == FileState::Exists- && let Some(path) = observation.resume_artifact_path.clone()- {- actions.push(Action::DeleteResumeArtifact {- path,- });- }-- if validation.checked == CheckedFileState::Invalid {- actions.push(Action::DeleteFile {- path: observation.destination_path.clone(),- });-- if observation.crc_state == FileState::Exists- && let Some(path) = observation.crc_path.clone()- {- actions.push(Action::DeleteCrcCache {- path,- });- }- }-- ActionPlan::from_ordered_actions(actions)-}diff --git a/crates/legacy/download-manager/src/reducer/disk_observation.rs b/crates/legacy/download-manager/src/reducer/disk_observation.rsdeleted file mode 100644index ac75f6693..000000000--- a/crates/legacy/download-manager/src/reducer/disk_observation.rs+++ /dev/null@@ -1,19 +0,0 @@-use std::path::PathBuf;--use serde::{Deserialize, Serialize};--use crate::FileState;--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub struct DiskObservation {- pub destination_state: FileState,- pub crc_state: FileState,- pub resume_state: FileState,- pub destination_size: Option<u64>,- pub resume_size: Option<u64>,- pub expected_crc: Option<String>,- pub expected_bytes: Option<u64>,- pub destination_path: PathBuf,- pub crc_path: Option<PathBuf>,- pub resume_artifact_path: Option<PathBuf>,-}diff --git a/crates/legacy/download-manager/src/reducer/initial_lifecycle_state.rs b/crates/legacy/download-manager/src/reducer/initial_lifecycle_state.rsdeleted file mode 100644index 6970b7ead..000000000--- a/crates/legacy/download-manager/src/reducer/initial_lifecycle_state.rs+++ /dev/null@@ -1,24 +0,0 @@-use std::path::PathBuf;--use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub enum InitialLifecycleState {- NotDownloaded,- Paused {- part_path: PathBuf,- },- Downloaded,-}--impl InitialLifecycleState {- pub fn name(&self) -> &'static str {- match self {- Self::NotDownloaded => "NotDownloaded",- Self::Paused {- ..- } => "Paused",- Self::Downloaded => "Downloaded",- }- }-}diff --git a/crates/legacy/download-manager/src/reducer/lock_observation.rs b/crates/legacy/download-manager/src/reducer/lock_observation.rsdeleted file mode 100644index cab355a35..000000000--- a/crates/legacy/download-manager/src/reducer/lock_observation.rs+++ /dev/null@@ -1,8 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::LockFileState;--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub struct LockObservation {- pub state: LockFileState,-}diff --git a/crates/legacy/download-manager/src/reducer/mod.rs b/crates/legacy/download-manager/src/reducer/mod.rsdeleted file mode 100644index ee0049927..000000000--- a/crates/legacy/download-manager/src/reducer/mod.rs+++ /dev/null@@ -1,15 +0,0 @@-mod action;-mod action_plan;-mod decision;-mod disk_observation;-mod initial_lifecycle_state;-mod lock_observation;-mod validation_outcome;--pub use action::Action;-pub use action_plan::ActionPlan;-pub use decision::decide;-pub use disk_observation::DiskObservation;-pub use initial_lifecycle_state::InitialLifecycleState;-pub use lock_observation::LockObservation;-pub use validation_outcome::{ValidationOutcome, validate};diff --git a/crates/legacy/download-manager/src/reducer/validation_outcome.rs b/crates/legacy/download-manager/src/reducer/validation_outcome.rsdeleted file mode 100644index fba6749ab..000000000--- a/crates/legacy/download-manager/src/reducer/validation_outcome.rs+++ /dev/null@@ -1,65 +0,0 @@-use crate::{- CheckedFileState, FileState,- crc_utils::{calculate_and_verify_crc, crc_cache_matches},- reducer::{Action, ActionPlan, DiskObservation},-};--#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub struct ValidationOutcome {- pub checked: CheckedFileState,- pub action_plan: ActionPlan,-}--pub async fn validate(observation: &DiskObservation) -> ValidationOutcome {- let length_matches = match (observation.destination_size, observation.expected_bytes) {- (Some(actual), Some(expected)) => actual == expected,- _ => true,- };-- let (checked, mut actions) = match (observation.destination_state, observation.expected_crc.as_deref()) {- (FileState::Missing, _) => (CheckedFileState::Missing, Vec::new()),- (FileState::Exists, _) if !length_matches => (CheckedFileState::Invalid, Vec::new()),- (FileState::Exists, None) => (CheckedFileState::Valid, Vec::new()),- (FileState::Exists, Some(expected_crc)) => validate_crc_with_cache(observation, expected_crc).await,- };-- if checked == CheckedFileState::Missing- && observation.crc_state == FileState::Exists- && let Some(path) = observation.crc_path.clone()- {- actions.push(Action::DeleteCrcCache {- path,- });- }-- let action_plan = ActionPlan::from_ordered_actions(actions);-- ValidationOutcome {- checked,- action_plan,- }-}--async fn validate_crc_with_cache(- observation: &DiskObservation,- expected_crc: &str,-) -> (CheckedFileState, Vec<Action>) {- if observation.crc_state == FileState::Exists- && crc_cache_matches(&observation.destination_path, expected_crc).await- {- return (CheckedFileState::Valid, Vec::new());- }-- let crc_check = calculate_and_verify_crc(&observation.destination_path, expected_crc).await.ok();-- match crc_check {- Some(true) => (- CheckedFileState::Valid,- vec![Action::SaveCrcCache {- destination: observation.destination_path.clone(),- crc: expected_crc.to_string(),- }],- ),- _ => (CheckedFileState::Invalid, Vec::new()),- }-}diff --git a/crates/legacy/download-manager/src/traits/active_download_generation.rs b/crates/legacy/download-manager/src/traits/active_download_generation.rsdeleted file mode 100644index 12bdb7d32..000000000--- a/crates/legacy/download-manager/src/traits/active_download_generation.rs+++ /dev/null@@ -1,10 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub struct ActiveDownloadGeneration(u64);--impl ActiveDownloadGeneration {- pub fn new(value: u64) -> Self {- Self(value)- }-}diff --git a/crates/legacy/download-manager/src/traits/active_download_generation_counter.rs b/crates/legacy/download-manager/src/traits/active_download_generation_counter.rsdeleted file mode 100644index dd30ddf82..000000000--- a/crates/legacy/download-manager/src/traits/active_download_generation_counter.rs+++ /dev/null@@ -1,14 +0,0 @@-use crate::traits::ActiveDownloadGeneration;--#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]-pub struct ActiveDownloadGenerationCounter {- next_value: u64,-}--impl ActiveDownloadGenerationCounter {- pub fn allocate_next(&mut self) -> ActiveDownloadGeneration {- let generation = ActiveDownloadGeneration::new(self.next_value);- self.next_value = self.next_value.saturating_add(1);- generation- }-}diff --git a/crates/legacy/download-manager/src/traits/active_task.rs b/crates/legacy/download-manager/src/traits/active_task.rsdeleted file mode 100644index c2c52e54e..000000000--- a/crates/legacy/download-manager/src/traits/active_task.rs+++ /dev/null@@ -1,19 +0,0 @@-use std::path::{Path, PathBuf};--use crate::traits::{CancelOutcome, DownloadBackend};--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-pub trait ActiveTask: Send + Sync + Sized {- type Backend: DownloadBackend<ActiveTask = Self>;-- async fn pause(- self,- destination: &Path,- ) -> Result<PathBuf, <Self::Backend as DownloadBackend>::Error>;-- async fn cancel(- self,- destination: &Path,- ) -> CancelOutcome;-}diff --git a/crates/legacy/download-manager/src/traits/backend_context.rs b/crates/legacy/download-manager/src/traits/backend_context.rsdeleted file mode 100644index dc0732f7e..000000000--- a/crates/legacy/download-manager/src/traits/backend_context.rs+++ /dev/null@@ -1,29 +0,0 @@-use std::{path::Path, sync::Arc};--use crate::{- lock_manager::DestinationLockLease,- traits::{ActiveDownloadGeneration, BackendEventSender, DownloadBackend, DownloadConfig},-};--#[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)]-#[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))]-pub trait BackendContext: Send + Sync + Sized {- type Backend: DownloadBackend<Context = Self>;-- async fn download(- &self,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- backend_event_sender: BackendEventSender,- destination_lease: &DestinationLockLease,- ) -> Result<<Self::Backend as DownloadBackend>::ActiveTask, <Self::Backend as DownloadBackend>::Error>;-- async fn resume(- &self,- config: Arc<DownloadConfig>,- generation: ActiveDownloadGeneration,- resume_artifact_path: &Path,- backend_event_sender: BackendEventSender,- destination_lease: &DestinationLockLease,- ) -> Result<<Self::Backend as DownloadBackend>::ActiveTask, <Self::Backend as DownloadBackend>::Error>;-}diff --git a/crates/legacy/download-manager/src/traits/backend_event_sender.rs b/crates/legacy/download-manager/src/traits/backend_event_sender.rsdeleted file mode 100644index 1d44aee45..000000000--- a/crates/legacy/download-manager/src/traits/backend_event_sender.rs+++ /dev/null@@ -1,73 +0,0 @@-use std::sync::Arc;--use tokio::sync::{Mutex as TokioMutex, mpsc::Sender as TokioMpscSender, watch::Sender as TokioWatchSender};--use crate::{- DownloadId,- download_log_event::{DownloadLogEvent, log},- file_download_task_actor::{BackendEvent, BackendProgress, PendingProgressSlot},- traits::ActiveDownloadGeneration,-};--#[derive(Clone, Debug)]-pub struct BackendEventSender {- download_id: DownloadId,- terminal_event_sender: TokioMpscSender<BackendEvent>,- progress_coalescer: SharedProgressCoalescer,-}--impl BackendEventSender {- pub fn new(- download_id: DownloadId,- terminal_event_sender: TokioMpscSender<BackendEvent>,- pending_progress: Arc<TokioMutex<PendingProgressSlot>>,- actor_waker: TokioWatchSender<()>,- ) -> Self {- Self {- download_id,- terminal_event_sender,- progress_coalescer: SharedProgressCoalescer {- pending_progress,- actor_waker,- },- }- }-- pub async fn send_terminal(- &self,- event: BackendEvent,- ) -> Result<(), BackendEvent> {- log(DownloadLogEvent::BackendTerminal {- download_id: self.download_id,- event: event.clone(),- });- self.terminal_event_sender.send(event).await.map_err(|error| error.0)- }-- pub async fn send_progress(- &self,- generation: ActiveDownloadGeneration,- downloaded_bytes: u64,- total_bytes: Option<u64>,- ) {- log(DownloadLogEvent::BackendProgress {- download_id: self.download_id,- generation,- downloaded_bytes,- total_bytes,- });- let mut pending_progress = self.progress_coalescer.pending_progress.lock().await;- pending_progress.progress = Some(BackendProgress {- generation,- downloaded_bytes,- total_bytes,- });- let _ = self.progress_coalescer.actor_waker.send(());- }-}--#[derive(Clone, Debug)]-struct SharedProgressCoalescer {- pending_progress: Arc<TokioMutex<PendingProgressSlot>>,- actor_waker: TokioWatchSender<()>,-}diff --git a/crates/legacy/download-manager/src/traits/cancel_outcome.rs b/crates/legacy/download-manager/src/traits/cancel_outcome.rsdeleted file mode 100644index ab310fa3e..000000000--- a/crates/legacy/download-manager/src/traits/cancel_outcome.rs+++ /dev/null@@ -1,8 +0,0 @@-use serde::{Deserialize, Serialize};--#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum CancelOutcome {- Confirmed,- TimedOut,- BestEffort,-}diff --git a/crates/legacy/download-manager/src/traits/download_backend.rs b/crates/legacy/download-manager/src/traits/download_backend.rsdeleted file mode 100644index 35de4e90c..000000000--- a/crates/legacy/download-manager/src/traits/download_backend.rs+++ /dev/null@@ -1,17 +0,0 @@-use std::{fmt::Debug, future::Future, path::Path};--use kiban::{fs, maybe::MaybeSend};--use crate::traits::{ActiveTask, BackendContext};--pub trait DownloadBackend: Debug + Clone + Send + Sync + 'static {- type Context: BackendContext<Backend = Self>;- type ActiveTask: ActiveTask<Backend = Self>;- type Error: std::error::Error + Send + Sync + 'static;-- // Default = file size (correct for `.part`-style artifacts). Apple must override:- // `.resume_data` is a small metadata blob, not the downloaded bytes.- fn read_resume_progress(part_path: &Path) -> impl Future<Output = Option<u64>> + MaybeSend {- async move { fs::asyn::file_length(part_path).await.ok() }- }-}diff --git a/crates/legacy/download-manager/src/traits/download_config.rs b/crates/legacy/download-manager/src/traits/download_config.rsdeleted file mode 100644index 041d50a7e..000000000--- a/crates/legacy/download-manager/src/traits/download_config.rs+++ /dev/null@@ -1,17 +0,0 @@-use std::path::PathBuf;--use serde::{Deserialize, Serialize};-use uuid::Uuid;--use crate::{DownloadId, FileCheck};--#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]-pub struct DownloadConfig {- pub download_id: DownloadId,- pub source_url: String,- pub destination: PathBuf,- pub file_check: FileCheck,- pub expected_bytes: Option<u64>,- pub manager_id: String,- pub manager_instance_id: Uuid,-}diff --git a/crates/legacy/download-manager/src/traits/mod.rs b/crates/legacy/download-manager/src/traits/mod.rsdeleted file mode 100644index 007ea3a41..000000000--- a/crates/legacy/download-manager/src/traits/mod.rs+++ /dev/null@@ -1,17 +0,0 @@-mod active_download_generation;-mod active_download_generation_counter;-mod active_task;-mod backend_context;-mod backend_event_sender;-mod cancel_outcome;-mod download_backend;-mod download_config;--pub use active_download_generation::ActiveDownloadGeneration;-pub use active_download_generation_counter::ActiveDownloadGenerationCounter;-pub use active_task::ActiveTask;-pub use backend_context::BackendContext;-pub use backend_event_sender::BackendEventSender;-pub use cancel_outcome::CancelOutcome;-pub use download_backend::DownloadBackend;-pub use download_config::DownloadConfig;diff --git a/crates/legacy/download-manager/tests/common/helpers.rs b/crates/legacy/download-manager/tests/common/helpers.rsnew file mode 100644index 000000000..e4301ad4d--- /dev/null+++ b/crates/legacy/download-manager/tests/common/helpers.rs@@ -0,0 +1,69 @@+use std::{path::Path, time::Duration};++use download_manager::{DestinationLock, DownloadState, DownloadTask, DownloadTaskRequest, LockOwner};+use kiban::stream::BoxStream;+use mock_registry::MockRegistry;+use tokio::time::timeout;+use tokio_stream::StreamExt;+use uuid::Uuid;++pub fn file_request(+ source_url: &str,+ destination: &Path,+ expected_crc32c: Option<String>,+ expected_bytes: Option<u64>,+) -> DownloadTaskRequest {+ DownloadTaskRequest::file()+ .destination(destination)+ .source_url(source_url)+ .maybe_expected_crc32c(expected_crc32c)+ .maybe_expected_bytes(expected_bytes)+ .build()+}++pub fn model_request(+ registry: &MockRegistry,+ directory: &Path,+) -> Result<DownloadTaskRequest, Box<dyn std::error::Error>> {+ let mut files = Vec::new();+ for served in registry.files.iter() {+ files.push(+ DownloadTaskRequest::file()+ .destination(&served.file.name)+ .source_url(&served.file.url)+ .expected_crc32c(served.crc32c()?)+ .expected_bytes(served.file.size as u64)+ .build(),+ );+ }+ Ok(DownloadTaskRequest::group().destination(directory).subrequests(files).build())+}++pub async fn wait_for_state(+ task: &DownloadTask,+ progress: &mut BoxStream<'static, DownloadState>,+ mut is_expected: impl FnMut(&DownloadState) -> bool,+) -> DownloadState {+ timeout(Duration::from_secs(30), async {+ let state = task.state();+ if is_expected(&state) {+ return state;+ }+ while let Some(state) = progress.next().await {+ if is_expected(&state) {+ return state;+ }+ }+ panic!("progress stream ended before the expected state");+ })+ .await+ .expect("timed out waiting for download state")+}++pub async fn foreign_lock(destination: &Path) -> DestinationLock {+ let owner = LockOwner {+ manager_id: "foreign-manager".to_string(),+ instance_id: Uuid::new_v4(),+ };+ DestinationLock::acquire(destination, &owner).await.expect("foreign lock")+}diff --git a/crates/legacy/download-manager/tests/common/mod.rs b/crates/legacy/download-manager/tests/common/mod.rsindex 132da97cc..125f5c280 100644--- a/crates/legacy/download-manager/tests/common/mod.rs+++ b/crates/legacy/download-manager/tests/common/mod.rs@@ -1,39 +1,4 @@-#![allow(dead_code, unused_imports)]+mod helpers;-use std::{sync::Arc, time::Duration};--use download_manager::{FileDownloadPhase, FileDownloadState, FileDownloadTask};-pub use mock_registry::{Behavior, MockRegistry};-use tokio::time::timeout;-use tokio_stream::{StreamExt, wrappers::BroadcastStream};--pub async fn wait_for_phase(- task: &Arc<dyn FileDownloadTask>,- progress_stream: &mut BroadcastStream<FileDownloadState>,- mut is_expected_phase: impl FnMut(&FileDownloadPhase) -> bool,-) -> FileDownloadState {- timeout(Duration::from_secs(15), async {- let state = task.state().await;- if is_expected_phase(&state.phase) {- return state;- }-- while let Some(result) = progress_stream.next().await {- let state = result.expect("download progress stream must not lag");- if is_expected_phase(&state.phase) {- return state;- }- }-- panic!("download progress stream ended before expected phase");- })- .await- .expect("timed out waiting for file download phase")-}--pub fn error_message(state: FileDownloadState) -> String {- let FileDownloadPhase::Error(message) = state.phase else {- unreachable!("state must be an error")- };- message-}+pub use helpers::*;+pub use mock_registry::{Behavior, MockRegistry, artifact_path};diff --git a/crates/legacy/download-manager/tests/download_manager.rs b/crates/legacy/download-manager/tests/download_manager.rsnew file mode 100644index 000000000..e0e80a97d--- /dev/null+++ b/crates/legacy/download-manager/tests/download_manager.rs@@ -0,0 +1,438 @@+mod common;++use std::{path::Path, sync::Arc, time::Duration};++use download_manager::{+ DestinationLock, DownloadError, DownloadManager, DownloadManagerType, DownloadPhase, DownloadState, DownloadTask,+ DownloadTaskRequest, LockError, LockOwner,+};+use kiban::rt::RuntimeHandle;+use rstest::rstest;+use tokio::time::timeout;+use uuid::Uuid;+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{method, path},+};++use crate::common::{Behavior, MockRegistry, artifact_path, file_request, foreign_lock, model_request, wait_for_state};++fn manager(kind: DownloadManagerType) -> DownloadManager {+ DownloadManager::new(kind, RuntimeHandle::current())+}++fn assert_sequential(+ task: &DownloadTask,+ state: &DownloadState,+ last_downloaded_bytes: &mut i64,+) {+ let downloading =+ task.subtasks().iter().filter(|child| matches!(child.state().phase, DownloadPhase::Downloading {})).count();+ assert!(downloading <= 1, "{downloading} files downloading at once");+ assert!(state.downloaded_bytes >= *last_downloaded_bytes, "downloaded bytes went backwards");+ *last_downloaded_bytes = state.downloaded_bytes;+}++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;+ let directory = tempfile::tempdir()?;+ let manager = manager(kind);+ let request = model_request(®istry, directory.path())?;+ let total_bytes: i64 = registry.files.iter().map(|served| served.file.size).sum();+ let mut last_downloaded_bytes = 0;++ let model = manager.download_task(request.clone()).await?;+ assert!(Arc::ptr_eq(&model, &manager.download_task(request.clone()).await?));+ let bundle_request = DownloadTaskRequest::group()+ .destination(directory.path().join("bundle"))+ .subrequests(vec![request.clone()])+ .build();+ let bundle = manager.download_task(bundle_request).await?;+ assert!(Arc::ptr_eq(&bundle.subtasks()[0], &model));+ assert_eq!(model.state().total_bytes, total_bytes);+ assert_eq!(bundle.state().total_bytes, total_bytes);+ assert_eq!(model.state().phase, DownloadPhase::NotDownloaded {});++ let mut progress = model.progress();+ model.download().await?;+ wait_for_state(&model, &mut progress, |state| {+ assert_sequential(&model, state, &mut last_downloaded_bytes);+ matches!(state.phase, DownloadPhase::Downloading {}) && state.downloaded_bytes >= total_bytes / 4+ })+ .await;++ model.pause().await?;+ let paused = wait_for_state(&model, &mut progress, |state| matches!(state.phase, DownloadPhase::Paused {})).await;+ assert!(paused.downloaded_bytes >= total_bytes / 4);+ assert_eq!(bundle.state().phase, DownloadPhase::Paused {});++ drop(progress);+ drop(bundle);+ drop(model);+ let model = manager.download_task(request).await?;+ assert_eq!(model.state().phase, DownloadPhase::Paused {});+ assert_eq!(model.state().downloaded_bytes, paused.downloaded_bytes);++ let mut progress = model.progress();+ model.download().await?;+ let downloaded = wait_for_state(&model, &mut progress, |state| {+ assert_sequential(&model, state, &mut last_downloaded_bytes);+ matches!(state.phase, DownloadPhase::Downloaded {})+ })+ .await;+ assert_eq!(downloaded.downloaded_bytes, total_bytes);+ assert_eq!(downloaded.total_bytes, total_bytes);+ for served in registry.files.iter() {+ let destination = directory.path().join(&served.file.name);+ assert_eq!(tokio::fs::read(&destination).await?, served.bytes.to_vec());+ assert!(artifact_path(&destination, "crc").is_file());+ }++ model.delete().await?;+ assert_eq!(model.state().phase, DownloadPhase::NotDownloaded {});+ assert_eq!(model.state().downloaded_bytes, 0);+ for served in registry.files.iter() {+ let destination = directory.path().join(&served.file.name);+ assert!(!destination.exists());+ assert!(!artifact_path(&destination, "crc").exists());+ assert!(!artifact_path(&destination, "lock").exists());+ }++ let first = registry.files.first().expect("mock registry serves files");+ let destination = directory.path().join(&first.file.name);+ let expected_bytes = Some(first.file.size as u64);+ let conflicting_url =+ manager.download_task(file_request("http://example.invalid/other", &destination, None, expected_bytes)).await;+ assert!(matches!(conflicting_url, Err(DownloadError::ConflictingConfig(_))));+ let conflicting_size =+ manager.download_task(file_request(&first.file.url, &destination, Some(first.crc32c()?), Some(1))).await;+ assert!(matches!(conflicting_size, Err(DownloadError::ConflictingConfig(_))));+ let same = file_request(&first.file.url, &destination, Some(first.crc32c()?), expected_bytes);+ let (task_a, task_b) = tokio::join!(manager.download_task(same.clone()), manager.download_task(same));+ assert!(Arc::ptr_eq(&task_a?, &task_b?));+ Ok(())+}++#[rstest]+#[case::universal(DownloadManagerType::Universal, "part")]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native, "resume_data"))]+#[tokio::test(flavor = "multi_thread")]+async fn startup_reconciliation(+ #[case] kind: DownloadManagerType,+ #[case] resume_artifact_extension: &str,+) -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start().await?;+ let served = registry.file("config.json")?;+ let crc = served.crc32c()?;+ let size = Some(served.file.size as u64);+ let manager = manager(kind);+ let request = |destination: &Path| file_request(&served.file.url, destination, Some(crc.clone()), size);++ let valid = tempfile::tempdir()?;+ let destination = valid.path().join(&served.file.name);+ let artifact = artifact_path(&destination, resume_artifact_extension);+ tokio::fs::write(&destination, served.bytes.as_ref()).await?;+ tokio::fs::write(&artifact, b"partial").await?;+ let task = manager.download_task(request(&destination)).await?;+ assert_eq!(task.state().phase, DownloadPhase::Downloaded {});+ assert!(!artifact.exists());+ let receipt: serde_json::Value =+ serde_json::from_str(&tokio::fs::read_to_string(artifact_path(&destination, "crc")).await?)?;+ assert_eq!(receipt["version"].as_u64(), Some(1));+ assert_eq!(receipt["crc"].as_str(), Some(crc.as_str()));+ assert_eq!(receipt["file_size"].as_u64(), size);++ let mut changed_bytes = served.bytes.to_vec();+ changed_bytes[0] = changed_bytes[0].wrapping_add(1);+ let stale_receipt = serde_json::to_vec(&serde_json::json!({+ "version": 1,+ "crc": crc.clone(),+ "file_size": served.file.size,+ "modified_unix_seconds": 0,+ "modified_nanos": 0,+ }))?;+ for cache in [crc.clone().into_bytes(), stale_receipt] {+ let stale = tempfile::tempdir()?;+ let destination = stale.path().join(&served.file.name);+ tokio::fs::write(&destination, &changed_bytes).await?;+ tokio::fs::write(artifact_path(&destination, "crc"), cache).await?;+ let task = manager.download_task(request(&destination)).await?;+ assert_eq!(task.state().phase, DownloadPhase::NotDownloaded {});+ assert!(!destination.exists());+ }++ let folder = tempfile::tempdir()?;+ let destination = folder.path().join(&served.file.name);+ tokio::fs::create_dir(&destination).await?;+ let task = manager.download_task(file_request(&served.file.url, &destination, None, None)).await?;+ assert_eq!(task.state().phase, DownloadPhase::NotDownloaded {});++ let locked = tempfile::tempdir()?;+ let destination = locked.path().join(&served.file.name);+ let artifact = artifact_path(&destination, resume_artifact_extension);+ tokio::fs::write(&destination, b"corrupt").await?;+ tokio::fs::write(artifact_path(&destination, "crc"), &crc).await?;+ tokio::fs::write(&artifact, b"partial").await?;+ let lock = foreign_lock(&destination).await;+ let group = manager+ .download_task(+ DownloadTaskRequest::group()+ .destination(locked.path())+ .subrequests(vec![file_request(+ &served.file.url,+ Path::new(&served.file.name),+ Some(crc.clone()),+ size,+ )])+ .build(),+ )+ .await?;+ assert!(matches!(group.state().phase, DownloadPhase::Locked { .. }));+ assert!(matches!(group.delete().await, Err(DownloadError::Lock(LockError::LockedByOther { .. }))));+ assert!(destination.exists());+ assert!(artifact_path(&destination, "crc").exists());+ assert!(artifact.exists());+ let mut progress = group.progress();+ if kind == DownloadManagerType::Universal {+ tokio::fs::write(&artifact, b"partial-and-more").await?;+ wait_for_state(&group, &mut progress, |state| state.downloaded_bytes == b"partial-and-more".len() as i64).await;+ }+ drop(lock);+ wait_for_state(&group, &mut progress, |state| matches!(state.phase, DownloadPhase::Paused {})).await;+ assert!(!destination.exists());+ assert!(artifact.exists());++ let paused = tempfile::tempdir()?;+ let destination = paused.path().join(&served.file.name);+ let artifact = artifact_path(&destination, resume_artifact_extension);+ tokio::fs::write(&artifact, b"partial").await?;+ let task = manager.download_task(request(&destination)).await?;+ assert_eq!(task.state().phase, DownloadPhase::Paused {});+ task.delete().await?;+ assert_eq!(task.state().phase, DownloadPhase::NotDownloaded {});+ assert!(!artifact.exists());++ let empty = tempfile::tempdir()?;+ let destination = empty.path().join(&served.file.name);+ tokio::fs::write(artifact_path(&destination, resume_artifact_extension), b"").await?;+ let task = manager.download_task(request(&destination)).await?;+ assert_eq!(task.state().phase, DownloadPhase::Paused {});+ let mut progress = task.progress();+ task.download().await?;+ wait_for_state(&task, &mut progress, |state| matches!(state.phase, DownloadPhase::Downloaded {})).await;+ assert_eq!(tokio::fs::read(&destination).await?, served.bytes.to_vec());+ Ok(())+}++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn failures(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let manager = manager(kind);++ let corrupt = MockRegistry::start_with(Behavior::CORRUPT_BODY).await?;+ let served = corrupt.file("tokenizer.json")?;+ let directory = tempfile::tempdir()?;+ let destination = directory.path().join(&served.file.name);+ let task = manager+ .download_task(file_request(+ &served.file.url,+ &destination,+ Some(served.crc32c()?),+ Some(served.file.size as u64),+ ))+ .await?;+ let mut progress = task.progress();+ task.download().await?;+ let state = wait_for_state(&task, &mut progress, |state| matches!(state.phase, DownloadPhase::Error { .. })).await;+ let DownloadPhase::Error {+ message,+ } = state.phase+ else {+ panic!("expected an error phase, got {:?}", state.phase)+ };+ assert!(message.contains("CRC"), "unexpected error: {message}");+ task.delete().await?;+ assert_eq!(task.state().phase, DownloadPhase::NotDownloaded {});++ let truncated = MockRegistry::start_with(Behavior::TRUNCATE_BODY).await?;+ let served = truncated.file("config.json")?;+ let destination = directory.path().join(&served.file.name);+ let task = manager+ .download_task(file_request(&served.file.url, &destination, None, Some(served.file.size as u64)))+ .await?;+ let mut progress = task.progress();+ task.download().await?;+ let state = wait_for_state(&task, &mut progress, |state| {+ matches!(state.phase, DownloadPhase::Downloaded {} | DownloadPhase::Error { .. })+ })+ .await;+ assert!(+ matches!(state.phase, DownloadPhase::Error { .. }),+ "truncated body must surface as Error, got {:?}",+ state.phase+ );+ Ok(())+}++#[rstest]+#[case::universal(DownloadManagerType::Universal, "part")]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native, "resume_data"))]+#[tokio::test(flavor = "multi_thread")]+async fn shutdown_and_locks(+ #[case] kind: DownloadManagerType,+ #[case] resume_artifact_extension: &str,+) -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;+ let served = registry.file("tokenizer.json")?;+ let directory = tempfile::tempdir()?;+ let destination = directory.path().join(&served.file.name);+ let lock = artifact_path(&destination, "lock");+ let artifact = artifact_path(&destination, resume_artifact_extension);+ let request = || {+ file_request(&served.file.url, &destination, Some(served.crc32c().expect("crc")), Some(served.file.size as u64))+ };++ let manager_a = manager(kind);+ let task_a = manager_a.download_task(request()).await?;+ let mut progress_a = task_a.progress();+ task_a.download().await?;+ wait_for_state(&task_a, &mut progress_a, |state| {+ matches!(state.phase, DownloadPhase::Downloading {}) && state.downloaded_bytes > 0+ })+ .await;+ assert!(lock.exists());++ let manager_b = manager(kind);+ let task_b = manager_b.download_task(request()).await?;+ assert!(matches!(task_b.state().phase, DownloadPhase::Locked { .. }));+ drop(task_b);+ drop(manager_b);+ assert_eq!(task_a.state().phase, DownloadPhase::Downloading {});++ drop(progress_a);+ drop(task_a);+ drop(manager_a);+ timeout(Duration::from_secs(2), async {+ let probe = LockOwner {+ manager_id: "probe".to_string(),+ instance_id: Uuid::new_v4(),+ };+ while DestinationLock::foreign_owner(&destination, &probe).await.is_some() {+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+ })+ .await?;+ assert!(artifact.exists());+ let size_at_release = artifact.metadata()?.len();+ tokio::time::sleep(Duration::from_millis(200)).await;+ assert_eq!(artifact.metadata()?.len(), size_at_release);+ Ok(())+}++#[tokio::test(flavor = "multi_thread")]+async fn universal_resume() -> Result<(), Box<dyn std::error::Error>> {+ let manager = manager(DownloadManagerType::Universal);+ let full_bytes: &[u8] = b"abcdefghij";+ let partial_bytes: &[u8] = b"abcde";++ let ignoring_range = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/model.bin"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(full_bytes))+ .mount(&ignoring_range)+ .await;+ let directory = tempfile::tempdir()?;+ let destination = directory.path().join("model.bin");+ tokio::fs::write(artifact_path(&destination, "part"), partial_bytes).await?;+ let task = manager+ .download_task(file_request(+ &format!("{}/model.bin", ignoring_range.uri()),+ &destination,+ None,+ Some(full_bytes.len() as u64),+ ))+ .await?;+ assert_eq!(task.state().phase, DownloadPhase::Paused {});+ let mut progress = task.progress();+ task.download().await?;+ wait_for_state(&task, &mut progress, |state| matches!(state.phase, DownloadPhase::Downloaded {})).await;+ assert_eq!(tokio::fs::read(&destination).await?, full_bytes);++ let misaligned = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/model.bin"))+ .respond_with(+ ResponseTemplate::new(206)+ .set_body_bytes(partial_bytes)+ .insert_header("Content-Range", format!("bytes 0-{}/{}", full_bytes.len() - 1, full_bytes.len())),+ )+ .mount(&misaligned)+ .await;+ let directory = tempfile::tempdir()?;+ let destination = directory.path().join("model.bin");+ tokio::fs::write(artifact_path(&destination, "part"), partial_bytes).await?;+ let task = manager+ .download_task(file_request(+ &format!("{}/model.bin", misaligned.uri()),+ &destination,+ None,+ Some(full_bytes.len() as u64),+ ))+ .await?;+ assert_eq!(task.state().phase, DownloadPhase::Paused {});+ let mut progress = task.progress();+ task.download().await?;+ let state = wait_for_state(&task, &mut progress, |state| matches!(state.phase, DownloadPhase::Error { .. })).await;+ let DownloadPhase::Error {+ message,+ } = state.phase+ else {+ panic!("expected an error phase, got {:?}", state.phase)+ };+ assert!(message.contains("starting at"), "unexpected error: {message}");+ assert!(!destination.exists());+ Ok(())+}++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn locked_takeover(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start().await?;+ let directory = tempfile::tempdir()?;+ let manager = manager(kind);+ let first = registry.files.first().ok_or("mock registry must include files")?;+ let lock = foreign_lock(&directory.path().join(&first.file.name)).await;+ let group = manager.download_task(model_request(®istry, directory.path())?).await?;+ let mut progress = group.progress();+ group.download().await?;+ assert!(matches!(group.state().phase, DownloadPhase::Locked { .. }));+ drop(lock);+ wait_for_state(&group, &mut progress, |state| matches!(state.phase, DownloadPhase::Downloaded {})).await;+ for served in registry.files.iter() {+ assert_eq!(tokio::fs::read(directory.path().join(&served.file.name)).await?, served.bytes.to_vec());+ }+ Ok(())+}++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn ancestor_destination_rejected(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let directory = tempfile::tempdir()?;+ let request = DownloadTaskRequest::group()+ .destination(directory.path())+ .subrequests(vec![file_request("http://127.0.0.1/unused", directory.path(), None, None)])+ .build();+ let result = timeout(Duration::from_secs(5), manager(kind).download_task(request)).await?;+ assert!(matches!(result, Err(DownloadError::ConflictingConfig(_))));+ Ok(())+}diff --git a/crates/legacy/download-manager/tests/locks.rs b/crates/legacy/download-manager/tests/locks.rsnew file mode 100644index 000000000..ae51908ec--- /dev/null+++ b/crates/legacy/download-manager/tests/locks.rs@@ -0,0 +1,31 @@+use download_manager::{DestinationLock, LockError, LockOwner};+use uuid::Uuid;++#[tokio::test(flavor = "multi_thread")]+async fn lock_rules() -> Result<(), Box<dyn std::error::Error>> {+ let temp = tempfile::tempdir()?;+ let destination = temp.path().join("nested").join("destination");+ let owner_a = LockOwner {+ manager_id: "manager-a".to_string(),+ instance_id: Uuid::new_v4(),+ };+ let owner_b = LockOwner {+ manager_id: "manager-b".to_string(),+ instance_id: Uuid::new_v4(),+ };+ assert_eq!(DestinationLock::foreign_owner(&destination, &owner_a).await, None);++ let lock = DestinationLock::acquire(&destination, &owner_a).await?;+ assert_eq!(DestinationLock::owner(&destination).await, owner_a);+ assert_eq!(DestinationLock::foreign_owner(&destination, &owner_a).await, None);+ assert_eq!(DestinationLock::foreign_owner(&destination, &owner_b).await, Some("manager-a".to_string()));+ assert!(matches!(+ DestinationLock::acquire(&destination, &owner_b).await,+ Err(LockError::LockedByOther { manager_id }) if manager_id == "manager-a"+ ));++ drop(lock);+ assert_eq!(DestinationLock::foreign_owner(&destination, &owner_b).await, None);+ DestinationLock::acquire(&destination, &owner_b).await?;+ Ok(())+}diff --git a/crates/legacy/download-manager/tests/unit/backends/apple/mod.rs b/crates/legacy/download-manager/tests/unit/backends/apple/mod.rsdeleted file mode 100644index 4c9d08011..000000000--- a/crates/legacy/download-manager/tests/unit/backends/apple/mod.rs+++ /dev/null@@ -1 +0,0 @@-mod test_context;diff --git a/crates/legacy/download-manager/tests/unit/backends/apple/test_context.rs b/crates/legacy/download-manager/tests/unit/backends/apple/test_context.rsdeleted file mode 100644index 47ecbc516..000000000--- a/crates/legacy/download-manager/tests/unit/backends/apple/test_context.rs+++ /dev/null@@ -1,246 +0,0 @@-use std::sync::Arc;--use kiban::rt::RuntimeHandle;-use mock_registry::{Behavior, MockRegistry};-use tokio::sync::{- Mutex as TokioMutex,- mpsc::{Receiver as TokioMpscReceiver, channel as tokio_mpsc_channel},- watch::channel as tokio_watch_channel,-};-use uuid::Uuid;--use crate::{- FileCheck,- backends::apple::AppleBackendContext,- compute_download_id,- file_download_task_actor::{BackendEvent, PendingProgressSlot},- lock_manager::DestinationLockLease,- traits::{ActiveDownloadGeneration, BackendContext, BackendEventSender, DownloadConfig},-};--fn backend_event_sender() -> (BackendEventSender, TokioMpscReceiver<BackendEvent>) {- let (backend_event_sender, backend_event_receiver) = tokio_mpsc_channel(64);- let pending_progress = Arc::new(TokioMutex::new(PendingProgressSlot::default()));- let (progress_waker_sender, _progress_waker_receiver) = tokio_watch_channel(());- (- BackendEventSender::new(Uuid::new_v4(), backend_event_sender, pending_progress, progress_waker_sender),- backend_event_receiver,- )-}--#[tokio::test(flavor = "multi_thread")]-async fn test_apple_resume_empty_resume_data_starts_fresh_download() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let served_file = registry.file("config.json")?;- let temporary_directory = tempfile::tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- let resume_artifact_path = destination.with_extension("resume_data");- tokio::fs::write(&resume_artifact_path, b"").await?;-- let context = AppleBackendContext::new(RuntimeHandle::current());- let config = Arc::new(DownloadConfig {- download_id: compute_download_id(&destination),- source_url: served_file.file.url.clone(),- destination: destination.clone(),- file_check: FileCheck::None,- expected_bytes: Some(served_file.file.size as u64),- manager_id: "test-manager".to_string(),- manager_instance_id: Uuid::new_v4(),- });- let destination_lease = DestinationLockLease::acquire_for_destination(- &config.destination,- &config.manager_id,- config.manager_instance_id,- )- .await?;- let generation = ActiveDownloadGeneration::new(0);- let (backend_event_sender, mut backend_event_receiver) = backend_event_sender();-- let active_task = context- .resume(Arc::clone(&config), generation, &resume_artifact_path, backend_event_sender, &destination_lease)- .await?;- let event = tokio::time::timeout(std::time::Duration::from_secs(5), backend_event_receiver.recv())- .await?- .ok_or_else(|| {- std::io::Error::new(- std::io::ErrorKind::UnexpectedEof,- "backend event channel closed before empty resume-data fallback completed",- )- })?;-- assert_eq!(event, BackendEvent::completed(generation));- assert_eq!(tokio::fs::read(&destination).await?, served_file.bytes.to_vec());-- drop(active_task);- destination_lease.release().await?;- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn dropping_apple_active_task_unregisters_event_sink() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let served_file = registry.file("config.json")?;- let temporary_directory = tempfile::tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);-- let context = AppleBackendContext::new(RuntimeHandle::current());- let download_id = compute_download_id(&destination);- let config = Arc::new(DownloadConfig {- download_id,- source_url: served_file.file.url.clone(),- destination,- file_check: FileCheck::None,- expected_bytes: Some(served_file.file.size as u64),- manager_id: "test-manager".to_string(),- manager_instance_id: Uuid::new_v4(),- });- let destination_lease = DestinationLockLease::acquire_for_destination(- &config.destination,- &config.manager_id,- config.manager_instance_id,- )- .await?;-- let (backend_event_sender, _backend_event_receiver) = backend_event_sender();- let active_task = context- .download(Arc::clone(&config), ActiveDownloadGeneration::new(0), backend_event_sender, &destination_lease)- .await?;- assert_eq!(- context.event_sink_count_for_download(download_id),- 1,- "precondition: exactly one event sink should be registered for download_id after starting download",- );-- drop(active_task);- destination_lease.release().await?;-- assert_eq!(- context.event_sink_count_for_download(download_id),- 0,- "dropping AppleActiveTask must unregister its event sink",- );- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn registry_distinguishes_generations_for_same_download_id() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let served_file = registry.file("config.json")?;- let temporary_directory = tempfile::tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- let download_id = compute_download_id(&destination);-- let context = AppleBackendContext::new(RuntimeHandle::current());- let config = Arc::new(DownloadConfig {- download_id,- source_url: served_file.file.url.clone(),- destination,- file_check: FileCheck::None,- expected_bytes: Some(served_file.file.size as u64),- manager_id: "test-manager".to_string(),- manager_instance_id: Uuid::new_v4(),- });- let destination_lease = DestinationLockLease::acquire_for_destination(- &config.destination,- &config.manager_id,- config.manager_instance_id,- )- .await?;-- let (backend_event_sender_first, _backend_event_receiver_first) = backend_event_sender();- let first_task = context- .download(Arc::clone(&config), ActiveDownloadGeneration::new(0), backend_event_sender_first, &destination_lease)- .await?;- assert_eq!(- context.event_sink_task_identifiers_for_download(download_id).len(),- 1,- "first generation must register a sink",- );-- let (backend_event_sender_second, _backend_event_receiver_second) = backend_event_sender();- let second_task = context- .download(- Arc::clone(&config),- ActiveDownloadGeneration::new(1),- backend_event_sender_second,- &destination_lease,- )- .await?;-- let both_keys = context.event_sink_task_identifiers_for_download(download_id);- assert_eq!(both_keys.len(), 2, "second generation must not overwrite the first sink; got keys: {both_keys:?}");- assert_ne!(both_keys[0], both_keys[1], "the two generations must have distinct task identifiers");-- drop(first_task);- drop(second_task);- destination_lease.release().await?;- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn claim_cancels_mismatched_task() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let served_file = registry.file("tokenizer.json")?;- let temporary_directory = tempfile::tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- let download_id = compute_download_id(&destination);-- let context = AppleBackendContext::new(RuntimeHandle::current());- let original_config = Arc::new(DownloadConfig {- download_id,- source_url: served_file.file.url.clone(),- destination: destination.clone(),- file_check: FileCheck::None,- expected_bytes: Some(served_file.file.size as u64),- manager_id: "test-manager".to_string(),- manager_instance_id: Uuid::new_v4(),- });- let destination_lease = DestinationLockLease::acquire_for_destination(- &original_config.destination,- &original_config.manager_id,- original_config.manager_instance_id,- )- .await?;-- let (backend_event_sender, _backend_event_receiver) = backend_event_sender();- let original_task = context- .download(- Arc::clone(&original_config),- ActiveDownloadGeneration::new(0),- backend_event_sender,- &destination_lease,- )- .await?;-- assert!(- context.claim_matching_download_task(&original_config).await?.is_some(),- "precondition: original task should be visible before the mismatched claim",- );-- let mismatched_config = DownloadConfig {- source_url: "http://example.invalid/different-url".to_string(),- ..(*original_config).clone()- };- assert!(- context.has_download_task_to_claim(&mismatched_config).await?,- "manager startup must take the claim path for a live same-destination task with mismatched metadata",- );- assert!(context.claim_matching_download_task(&mismatched_config).await?.is_none());-- let mut cancelled = false;- for _attempt in 0..50 {- if context.claim_matching_download_task(&original_config).await?.is_none() {- cancelled = true;- break;- }- tokio::time::sleep(std::time::Duration::from_millis(20)).await;- }-- assert!(- cancelled,- "claiming a same-destination task with mismatched metadata must cancel the stale URLSession task",- );- drop(original_task);- destination_lease.release().await?;- Ok(())-}diff --git a/crates/legacy/download-manager/tests/unit/backends/common/mod.rs b/crates/legacy/download-manager/tests/unit/backends/common/mod.rsdeleted file mode 100644index 6dfc229bb..000000000--- a/crates/legacy/download-manager/tests/unit/backends/common/mod.rs+++ /dev/null@@ -1,6 +0,0 @@-mod test_actor_task_drop;-mod test_corrupt_body;-mod test_lifecycle;-mod test_manager_startup;-mod test_state_and_lock_regression;-mod test_truncated_body;diff --git a/crates/legacy/download-manager/tests/unit/backends/common/test_actor_task_drop.rs b/crates/legacy/download-manager/tests/unit/backends/common/test_actor_task_drop.rsdeleted file mode 100644index ef2deb6a3..000000000--- a/crates/legacy/download-manager/tests/unit/backends/common/test_actor_task_drop.rs+++ /dev/null@@ -1,96 +0,0 @@-use std::{path::PathBuf, sync::Arc};--use download_manager::{DownloadError, FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use rstest::rstest;--use crate::common::{Behavior, MockRegistry, wait_for_phase};--#[rstest]-#[case::universal(FileDownloadManagerType::Universal, "part")]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple, "resume_data"))]-#[tokio::test(flavor = "multi_thread")]-async fn remove_paused_task_deletes_resume_artifact(- #[case] download_manager_type: FileDownloadManagerType,- #[case] resume_artifact_extension: &str,-) -> Result<(), Box<dyn std::error::Error>> {- let temporary_directory = tempfile::tempdir()?;- let destination = temporary_directory.path().join("model.bin");- let resume_artifact = destination.with_extension(resume_artifact_extension);- tokio::fs::write(&resume_artifact, b"partial").await?;-- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await?;- let task = manager- .file_download_task("http://example.invalid/model.bin", &destination, FileCheck::None, Some(100))- .await?;-- assert!(matches!(task.state().await.phase, FileDownloadPhase::Paused));-- manager.remove_file_task(task.download_id()).await?;-- assert!(!resume_artifact.exists());- assert!(matches!(task.download().await, Err(DownloadError::TaskStopped)));- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal, "part")]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple, "resume_data"))]-#[tokio::test(flavor = "multi_thread")]-async fn dropping_active_download_cancels_backend_before_releasing_lock(- #[case] download_manager_type: FileDownloadManagerType,- #[case] resume_artifact_extension: &str,-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let tokenizer = registry.file("tokenizer.json")?;- let temp_dir = tempfile::tempdir()?;- let destination = temp_dir.path().join(&tokenizer.file.name);- let lock_path = PathBuf::from(format!("{}.lock", destination.display()));- let resume_artifact = destination.with_extension(resume_artifact_extension);- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();- let task = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();- let mut progress = task.progress().await.unwrap();- task.download().await.unwrap();- wait_for_phase(&task, &mut progress, |phase| matches!(phase, FileDownloadPhase::Downloading)).await;- assert!(lock_path.exists());-- manager.remove_file_task(task.download_id()).await.unwrap();-- assert!(matches!(task.download().await, Err(DownloadError::TaskStopped)));- let replacement_task = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();- assert!(!Arc::ptr_eq(&task, &replacement_task));- drop(replacement_task);-- let mut lock_released = false;- for _ in 0..100 {- if !lock_path.exists() {- lock_released = true;- break;- }- tokio::time::sleep(std::time::Duration::from_millis(20)).await;- }- assert!(lock_released);- assert!(!resume_artifact.exists());-- let destination_size_at_release = destination.metadata().map(|m| m.len()).unwrap_or(0);- tokio::time::sleep(std::time::Duration::from_millis(200)).await;- let destination_size_after = destination.metadata().map(|m| m.len()).unwrap_or(0);- assert_eq!(destination_size_at_release, destination_size_after);- Ok(())-}diff --git a/crates/legacy/download-manager/tests/unit/backends/common/test_corrupt_body.rs b/crates/legacy/download-manager/tests/unit/backends/common/test_corrupt_body.rsdeleted file mode 100644index a036eb5ab..000000000--- a/crates/legacy/download-manager/tests/unit/backends/common/test_corrupt_body.rs+++ /dev/null@@ -1,65 +0,0 @@-use download_manager::{FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use rstest::rstest;--use crate::common::{Behavior, MockRegistry, error_message, wait_for_phase};--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_corrupt_body_fails_crc(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::CORRUPT_BODY).await?;- let tokenizer = registry.file("tokenizer.json")?;- let temp_dir = tempfile::tempdir().unwrap();- let destination = temp_dir.path().join(&tokenizer.file.name);- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();- let task = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();- let mut progress = task.progress().await.unwrap();-- task.download().await.unwrap();- let state = wait_for_phase(&task, &mut progress, |phase| matches!(phase, FileDownloadPhase::Error(_))).await;- let message = error_message(state);- assert!(message.contains("CRC") || message.contains("checksum"), "unexpected error: {message}");- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_corrupt_body_cancel_resets_error_state(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::CORRUPT_BODY).await?;- let tokenizer = registry.file("tokenizer.json")?;- let temporary_directory = tempfile::tempdir()?;- let destination = temporary_directory.path().join(&tokenizer.file.name);- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await?;- let task = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await?;- let mut progress = task.progress().await?;-- task.download().await?;- wait_for_phase(&task, &mut progress, |phase| matches!(phase, FileDownloadPhase::Error(_))).await;- task.cancel().await?;-- assert!(matches!(task.state().await.phase, FileDownloadPhase::NotDownloaded));- Ok(())-}diff --git a/crates/legacy/download-manager/tests/unit/backends/common/test_lifecycle.rs b/crates/legacy/download-manager/tests/unit/backends/common/test_lifecycle.rsdeleted file mode 100644index 8edeff37c..000000000--- a/crates/legacy/download-manager/tests/unit/backends/common/test_lifecycle.rs+++ /dev/null@@ -1,39 +0,0 @@-use download_manager::{FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use rstest::rstest;--use crate::common::{MockRegistry, wait_for_phase};--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_download_fresh_completes(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let tokenizer = registry.file("tokenizer.json")?;- let temp_dir = tempfile::tempdir().unwrap();- let destination = temp_dir.path().join(&tokenizer.file.name);-- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();- let task = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();- let mut progress = task.progress().await.unwrap();-- task.download().await.unwrap();- let state = wait_for_phase(&task, &mut progress, |phase| matches!(phase, FileDownloadPhase::Downloaded)).await;-- assert_eq!(state.downloaded_bytes, tokenizer.file.size as u64);- assert_eq!(state.total_bytes, tokenizer.file.size as u64);- assert_eq!(tokio::fs::read(&destination).await.unwrap(), tokenizer.bytes.to_vec());- assert!(std::path::PathBuf::from(format!("{}.crc", destination.display())).is_file());- Ok(())-}diff --git a/crates/legacy/download-manager/tests/unit/backends/common/test_manager_startup.rs b/crates/legacy/download-manager/tests/unit/backends/common/test_manager_startup.rsdeleted file mode 100644index ae2c29040..000000000--- a/crates/legacy/download-manager/tests/unit/backends/common/test_manager_startup.rs+++ /dev/null@@ -1,160 +0,0 @@-use chrono::Utc;-use download_manager::{FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use tempfile::tempdir;--use crate::common::MockRegistry;--#[tokio::test(flavor = "multi_thread")]-async fn test_manager_startup_valid_existing_file_is_downloaded() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let served_file = registry.file("config.json")?;- let expected_crc = served_file.crc32c()?;- let temporary_directory = tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- let crc_path = std::path::PathBuf::from(format!("{}.crc", destination.display()));- let resume_artifact = destination.with_extension("part");- tokio::fs::write(&destination, served_file.bytes.as_ref()).await?;- tokio::fs::write(&resume_artifact, b"partial").await?;-- let task = manager_task(- &served_file.file.url,- &destination,- FileCheck::CRC(expected_crc.clone()),- Some(served_file.file.size as u64),- )- .await?;-- assert_eq!(task.state().await.phase, FileDownloadPhase::Downloaded);- assert!(!resume_artifact.exists());- let crc_receipt: serde_json::Value = serde_json::from_str(&tokio::fs::read_to_string(crc_path).await?)?;- assert_eq!(crc_receipt["version"].as_u64(), Some(1));- assert_eq!(crc_receipt["crc"].as_str(), Some(expected_crc.as_str()));- assert_eq!(crc_receipt["file_size"].as_u64(), Some(served_file.file.size as u64));- assert!(crc_receipt["modified_unix_seconds"].as_u64().is_some());- assert!(crc_receipt["modified_nanos"].as_u64().is_some());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_manager_startup_rejects_legacy_crc_cache_after_file_changes() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let served_file = registry.file("config.json")?;- let expected_crc = served_file.crc32c()?;- let temporary_directory = tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- let crc_path = std::path::PathBuf::from(format!("{}.crc", destination.display()));- let mut stale_destination_bytes = served_file.bytes.to_vec();- stale_destination_bytes[0] = stale_destination_bytes[0].wrapping_add(1);- tokio::fs::write(&destination, stale_destination_bytes).await?;- tokio::fs::write(&crc_path, &expected_crc).await?;-- let task = manager_task(- &served_file.file.url,- &destination,- FileCheck::CRC(expected_crc),- Some(served_file.file.size as u64),- )- .await?;-- assert_eq!(task.state().await.phase, FileDownloadPhase::NotDownloaded);- assert!(!destination.exists());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_manager_startup_revalidates_stale_metadata_crc_cache() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let served_file = registry.file("config.json")?;- let expected_crc = served_file.crc32c()?;- let temporary_directory = tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- let crc_path = std::path::PathBuf::from(format!("{}.crc", destination.display()));- let mut stale_destination_bytes = served_file.bytes.to_vec();- stale_destination_bytes[0] = stale_destination_bytes[0].wrapping_add(1);- tokio::fs::write(&destination, stale_destination_bytes).await?;- tokio::fs::write(- &crc_path,- serde_json::to_vec(&serde_json::json!({- "version": 1,- "crc": expected_crc.clone(),- "file_size": served_file.file.size,- "modified_unix_seconds": 0,- "modified_nanos": 0,- }))?,- )- .await?;-- let task = manager_task(- &served_file.file.url,- &destination,- FileCheck::CRC(expected_crc),- Some(served_file.file.size as u64),- )- .await?;-- assert_eq!(task.state().await.phase, FileDownloadPhase::NotDownloaded);- assert!(!destination.exists());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_manager_startup_directory_destination_is_not_downloaded() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let served_file = registry.file("config.json")?;- let temporary_directory = tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- tokio::fs::create_dir(&destination).await?;-- let task = manager_task(&served_file.file.url, &destination, FileCheck::None, None).await?;-- assert_eq!(task.state().await.phase, FileDownloadPhase::NotDownloaded);- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn test_manager_startup_foreign_lock_preserves_files() -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let served_file = registry.file("config.json")?;- let temporary_directory = tempdir()?;- let destination = temporary_directory.path().join(&served_file.file.name);- let crc_path = std::path::PathBuf::from(format!("{}.crc", destination.display()));- let resume_artifact = destination.with_extension("part");- let lock_path = std::path::PathBuf::from(format!("{}.lock", destination.display()));- tokio::fs::write(&destination, b"corrupt").await?;- tokio::fs::write(&crc_path, served_file.crc32c()?).await?;- tokio::fs::write(&resume_artifact, b"partial").await?;- tokio::fs::write(- &lock_path,- serde_json::to_vec(&serde_json::json!({- "manager_id": "foreign-manager",- "acquired_at": Utc::now(),- "process_id": std::process::id(),- }))?,- )- .await?;-- let task = manager_task(- &served_file.file.url,- &destination,- FileCheck::CRC(served_file.crc32c()?),- Some(served_file.file.size as u64),- )- .await?;-- assert!(matches!(task.state().await.phase, FileDownloadPhase::LockedByOther(_)));- assert!(destination.exists());- assert!(crc_path.exists());- assert!(resume_artifact.exists());- Ok(())-}--async fn manager_task(- source_url: &str,- destination: &std::path::Path,- file_check: FileCheck,- expected_bytes: Option<u64>,-) -> Result<std::sync::Arc<dyn download_manager::FileDownloadTask>, download_manager::DownloadError> {- let manager = <dyn FileDownloadManager>::new(FileDownloadManagerType::Universal, RuntimeHandle::current()).await?;- manager.file_download_task(source_url, destination, file_check, expected_bytes).await-}diff --git a/crates/legacy/download-manager/tests/unit/backends/common/test_state_and_lock_regression.rs b/crates/legacy/download-manager/tests/unit/backends/common/test_state_and_lock_regression.rsdeleted file mode 100644index d5d486054..000000000--- a/crates/legacy/download-manager/tests/unit/backends/common/test_state_and_lock_regression.rs+++ /dev/null@@ -1,158 +0,0 @@-use std::sync::Arc;--use download_manager::{DownloadError, FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use rstest::rstest;--use crate::common::{Behavior, MockRegistry, wait_for_phase};--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_concurrent_task_creation_returns_same_task(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let tokenizer = registry.file("tokenizer.json")?;- let temp_dir = tempfile::tempdir().unwrap();- let destination = temp_dir.path().join(&tokenizer.file.name);- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();-- let (first, second) = tokio::join!(- manager.file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- ),- manager.file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- ),- );- let first = first.unwrap();- let second = second.unwrap();-- assert!(Arc::ptr_eq(&first, &second));- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn different_urls_targeting_same_destination_are_rejected(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let tokenizer = registry.file("tokenizer.json")?;- let temp_dir = tempfile::tempdir().unwrap();- let destination = temp_dir.path().join(&tokenizer.file.name);- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();-- let _first = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();- let second = manager- .file_download_task(- "http://example.invalid/different-url",- &destination,- FileCheck::None,- Some(tokenizer.file.size as u64),- )- .await;-- assert!(matches!(second, Err(DownloadError::ConflictingConfig(_))));- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn different_expected_bytes_targeting_same_destination_are_rejected(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start().await?;- let tokenizer = registry.file("tokenizer.json")?;- let temp_dir = tempfile::tempdir().unwrap();- let destination = temp_dir.path().join(&tokenizer.file.name);- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();-- let _first = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();- let second = manager- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64 + 1),- )- .await;-- assert!(matches!(second, Err(DownloadError::ConflictingConfig(_))));- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn separate_managers_in_same_process_cannot_share_destination_lock(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let tokenizer = registry.file("tokenizer.json")?;- let temp_dir = tempfile::tempdir().unwrap();- let destination = temp_dir.path().join(&tokenizer.file.name);-- let manager_a = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();- let task_a = manager_a- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();- let mut progress_a = task_a.progress().await.unwrap();- task_a.download().await.unwrap();- wait_for_phase(&task_a, &mut progress_a, |phase| matches!(phase, FileDownloadPhase::Downloading)).await;-- let manager_b = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();- let task_b = manager_b- .file_download_task(- &tokenizer.file.url,- &destination,- FileCheck::CRC(tokenizer.crc32c()?),- Some(tokenizer.file.size as u64),- )- .await- .unwrap();-- assert!(matches!(task_b.state().await.phase, FileDownloadPhase::LockedByOther(_)));-- drop(task_b);- drop(manager_b);-- let progress_a_after_b_dropped = task_a.state().await.phase;- assert!(!matches!(progress_a_after_b_dropped, FileDownloadPhase::Error(_)));- Ok(())-}diff --git a/crates/legacy/download-manager/tests/unit/backends/common/test_truncated_body.rs b/crates/legacy/download-manager/tests/unit/backends/common/test_truncated_body.rsdeleted file mode 100644index a33df50cf..000000000--- a/crates/legacy/download-manager/tests/unit/backends/common/test_truncated_body.rs+++ /dev/null@@ -1,38 +0,0 @@-use download_manager::{FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use rstest::rstest;--use crate::common::{Behavior, MockRegistry, wait_for_phase};--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn truncated_body_without_crc_fails_length_check(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- let registry = MockRegistry::start_with(Behavior::TRUNCATE_BODY).await?;- let served_file = registry.file("config.json")?;- let temp_dir = tempfile::tempdir().unwrap();- let destination = temp_dir.path().join(&served_file.file.name);-- let manager = <dyn FileDownloadManager>::new(download_manager_type, RuntimeHandle::current()).await.unwrap();- let task = manager- .file_download_task(&served_file.file.url, &destination, FileCheck::None, Some(served_file.file.size as u64))- .await- .unwrap();- let mut progress = task.progress().await.unwrap();-- task.download().await.unwrap();- let state = wait_for_phase(&task, &mut progress, |phase| {- matches!(phase, FileDownloadPhase::Downloaded | FileDownloadPhase::Error(_))- })- .await;-- assert!(- matches!(state.phase, FileDownloadPhase::Error(_)),- "truncated body must surface as Error, got {:?}",- state.phase,- );- Ok(())-}diff --git a/crates/legacy/download-manager/tests/unit/backends/mod.rs b/crates/legacy/download-manager/tests/unit/backends/mod.rsdeleted file mode 100644index ddd4277f2..000000000--- a/crates/legacy/download-manager/tests/unit/backends/mod.rs+++ /dev/null@@ -1,4 +0,0 @@-#[cfg(target_vendor = "apple")]-mod apple;-mod common;-mod universal;diff --git a/crates/legacy/download-manager/tests/unit/backends/universal/mod.rs b/crates/legacy/download-manager/tests/unit/backends/universal/mod.rsdeleted file mode 100644index 522185cd3..000000000--- a/crates/legacy/download-manager/tests/unit/backends/universal/mod.rs+++ /dev/null@@ -1,2 +0,0 @@-mod test_resume;-mod test_resume_content_range_validation;diff --git a/crates/legacy/download-manager/tests/unit/backends/universal/test_resume.rs b/crates/legacy/download-manager/tests/unit/backends/universal/test_resume.rsdeleted file mode 100644index 6a47c2f51..000000000--- a/crates/legacy/download-manager/tests/unit/backends/universal/test_resume.rs+++ /dev/null@@ -1,44 +0,0 @@-use std::time::Duration;--use download_manager::{FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use tempfile::tempdir;-use tokio::time::timeout;-use wiremock::{- Mock, MockServer, ResponseTemplate,- matchers::{method, path},-};--#[tokio::test(flavor = "multi_thread")]-async fn test_universal_resume_restarts_when_server_ignores_range() -> Result<(), Box<dyn std::error::Error>> {- let bytes = b"complete file body";- let server = MockServer::start().await;- Mock::given(method("GET"))- .and(path("/model.bin"))- .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.as_slice()))- .mount(&server)- .await;-- let temporary_directory = tempdir().unwrap();- let destination = temporary_directory.path().join("model.bin");- let part_path = destination.with_extension("part");- tokio::fs::write(&part_path, b"partial").await?;-- let manager = <dyn FileDownloadManager>::new(FileDownloadManagerType::Universal, RuntimeHandle::current()).await?;- let task = manager- .file_download_task(- &format!("{}/model.bin", server.uri()),- &destination,- FileCheck::None,- Some(bytes.len() as u64),- )- .await?;-- assert_eq!(task.state().await.phase, FileDownloadPhase::Paused);- task.download().await?;- timeout(Duration::from_secs(10), task.wait()).await?;-- assert_eq!(task.state().await.phase, FileDownloadPhase::Downloaded);- assert_eq!(tokio::fs::read(&destination).await?, bytes);- Ok(())-}diff --git a/crates/legacy/download-manager/tests/unit/backends/universal/test_resume_content_range_validation.rs b/crates/legacy/download-manager/tests/unit/backends/universal/test_resume_content_range_validation.rsdeleted file mode 100644index b5de0614f..000000000--- a/crates/legacy/download-manager/tests/unit/backends/universal/test_resume_content_range_validation.rs+++ /dev/null@@ -1,56 +0,0 @@-use std::time::Duration;--use download_manager::{FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase};-use kiban::rt::RuntimeHandle;-use tempfile::tempdir;-use tokio::time::timeout;-use wiremock::{- Mock, MockServer, ResponseTemplate,- matchers::{method, path},-};--#[tokio::test(flavor = "multi_thread")]-async fn resume_rejects_206_when_content_range_offset_mismatches_request() -> Result<(), Box<dyn std::error::Error>> {- let full_bytes: &[u8] = b"abcdefghij";- let partial_bytes: &[u8] = b"abcde";- let total = full_bytes.len();-- let server = MockServer::start().await;- Mock::given(method("GET"))- .and(path("/model.bin"))- .respond_with(- ResponseTemplate::new(206)- .set_body_bytes(partial_bytes)- .insert_header("Content-Range", format!("bytes 0-{}/{}", total - 1, total)),- )- .mount(&server)- .await;-- let temporary_directory = tempdir().unwrap();- let destination = temporary_directory.path().join("model.bin");- let part_path = destination.with_extension("part");- tokio::fs::write(&part_path, partial_bytes).await?;-- let manager = <dyn FileDownloadManager>::new(FileDownloadManagerType::Universal, RuntimeHandle::current()).await?;- let task = manager- .file_download_task(&format!("{}/model.bin", server.uri()), &destination, FileCheck::None, Some(total as u64))- .await?;-- assert_eq!(task.state().await.phase, FileDownloadPhase::Paused);- task.download().await?;- timeout(Duration::from_secs(10), task.wait()).await?;-- let final_phase = task.state().await.phase;- match &final_phase {- FileDownloadPhase::Error(_) => Ok(()),- FileDownloadPhase::Downloaded => {- assert_eq!(- tokio::fs::read(&destination).await?,- full_bytes,- "phase reached Downloaded but file content was corrupted by accepting a misaligned Content-Range",- );- Ok(())- },- other => panic!("unexpected final phase: {:?}", other),- }-}diff --git a/crates/legacy/download-manager/tests/unit/mod.rs b/crates/legacy/download-manager/tests/unit/mod.rsdeleted file mode 100644index 0637eea96..000000000--- a/crates/legacy/download-manager/tests/unit/mod.rs+++ /dev/null@@ -1,2 +0,0 @@-mod backends;-mod test_lock_manager;diff --git a/crates/legacy/download-manager/tests/unit/test_entry.rs b/crates/legacy/download-manager/tests/unit/test_entry.rsdeleted file mode 100644index b2d060b3d..000000000--- a/crates/legacy/download-manager/tests/unit/test_entry.rs+++ /dev/null@@ -1,10 +0,0 @@-extern crate self as download_manager;--include!("../../src/lib.rs");--#[path = "../common/mod.rs"]-mod common;--mod unit_tests {- include!("mod.rs");-}diff --git a/crates/legacy/download-manager/tests/unit/test_lock_manager.rs b/crates/legacy/download-manager/tests/unit/test_lock_manager.rsdeleted file mode 100644index a71d0f5ff..000000000--- a/crates/legacy/download-manager/tests/unit/test_lock_manager.rs+++ /dev/null@@ -1,259 +0,0 @@-use std::path::PathBuf;--use chrono::{Duration as ChronoDuration, Utc};-use download_manager::{LockFileInfo, LockFileState, acquire_lock, release_lock_if_owned};-use uuid::Uuid;--use crate::lock_manager::{- ReclaimExpectation, ReclaimOutcome, RestoreOutcome, classify_same_manager_lock_without_process, reclaim_stale_lock,- try_restore_quarantine,-};--fn lock_path(temp: &tempfile::TempDir) -> PathBuf {- temp.path().join("destination.lock")-}--#[tokio::test(flavor = "multi_thread")]-async fn acquire_lock_does_not_overwrite_other_managers_lock() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- acquire_lock(&path, "manager-a", Uuid::new_v4()).await?;- let acquired_by_b = acquire_lock(&path, "manager-b", Uuid::new_v4()).await;-- assert!(acquired_by_b.is_err());-- let info: LockFileInfo = serde_json::from_str(&std::fs::read_to_string(&path)?)?;- assert_eq!(info.manager_id, "manager-a");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn acquire_lock_reclaims_stale_locks() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- let stale_info = LockFileInfo {- manager_id: "manager-a".to_string(),- instance_id: Uuid::new_v4(),- acquired_at: Utc::now() - ChronoDuration::hours(2),- process_id: 999_999,- };- std::fs::write(&path, serde_json::to_string(&stale_info)?)?;-- acquire_lock(&path, "manager-b", Uuid::new_v4()).await?;-- let info: LockFileInfo = serde_json::from_str(&std::fs::read_to_string(&path)?)?;- assert_eq!(info.manager_id, "manager-b");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn acquire_lock_is_idempotent_for_same_owner() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);- let instance_id = Uuid::new_v4();-- acquire_lock(&path, "manager-a", instance_id).await?;- acquire_lock(&path, "manager-a", instance_id).await?;-- let info: LockFileInfo = serde_json::from_str(&std::fs::read_to_string(&path)?)?;- assert_eq!(info.manager_id, "manager-a");- assert_eq!(info.process_id, std::process::id());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn acquire_lock_reclaims_old_unparseable_lock() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- std::fs::write(&path, b"this is not valid json")?;- let two_hours_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 60 * 60);- let times = std::fs::FileTimes::new().set_modified(two_hours_ago).set_accessed(two_hours_ago);- let lock_handle = std::fs::OpenOptions::new().write(true).open(&path)?;- lock_handle.set_times(times)?;- drop(lock_handle);-- acquire_lock(&path, "manager-b", Uuid::new_v4()).await?;-- let info: LockFileInfo = serde_json::from_str(&std::fs::read_to_string(&path)?)?;- assert_eq!(info.manager_id, "manager-b");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn acquire_lock_does_not_steal_a_recent_unparseable_lock() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- std::fs::write(&path, b"")?;-- let result = acquire_lock(&path, "manager-b", Uuid::new_v4()).await;-- assert!(result.is_err());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn acquire_lock_blocks_same_manager_id_with_different_instance_id() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- acquire_lock(&path, "manager-a", Uuid::new_v4()).await?;- let result = acquire_lock(&path, "manager-a", Uuid::new_v4()).await;-- assert!(result.is_err());- Ok(())-}--#[test]-fn same_manager_lock_without_process_blocks_different_recent_instance() {- let other_instance_id = Uuid::new_v4();- let lock_info = LockFileInfo {- manager_id: "manager-a".to_string(),- instance_id: other_instance_id,- acquired_at: Utc::now(),- process_id: 0,- };-- let state = classify_same_manager_lock_without_process(lock_info, Uuid::new_v4());-- assert!(matches!(state, LockFileState::OwnedByOtherApp(info) if info.instance_id == other_instance_id));-}--#[test]-fn same_manager_lock_without_process_reclaims_only_after_stale() {- let other_instance_id = Uuid::new_v4();- let lock_info = LockFileInfo {- manager_id: "manager-a".to_string(),- instance_id: other_instance_id,- acquired_at: Utc::now() - ChronoDuration::hours(2),- process_id: 0,- };-- let state = classify_same_manager_lock_without_process(lock_info, Uuid::new_v4());-- assert!(matches!(state, LockFileState::Stale(info) if info.instance_id == other_instance_id));-}--#[tokio::test(flavor = "multi_thread")]-async fn check_lock_file_treats_disappearing_lock_as_missing() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- let result = acquire_lock(&path, "self-manager", Uuid::new_v4()).await;-- assert!(result.is_ok());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn release_lock_if_owned_leaves_other_owners_lock_intact() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- let other_owner = LockFileInfo {- manager_id: "other-manager".to_string(),- instance_id: Uuid::new_v4(),- acquired_at: Utc::now(),- process_id: std::process::id(),- };- std::fs::write(&path, serde_json::to_string(&other_owner)?)?;-- let released = release_lock_if_owned(&path, "self-manager", Uuid::new_v4()).await?;-- assert!(!released);- let info: LockFileInfo = serde_json::from_str(&std::fs::read_to_string(&path)?)?;- assert_eq!(info.manager_id, "other-manager");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn release_lock_if_owned_removes_our_own_lock() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);- let instance_id = Uuid::new_v4();-- acquire_lock(&path, "self-manager", instance_id).await?;- let released = release_lock_if_owned(&path, "self-manager", instance_id).await?;-- assert!(released);- assert!(!path.exists());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn acquire_lock_does_not_steal_live_lock_from_other_manager() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);-- let live_owner = LockFileInfo {- manager_id: "other-manager".to_string(),- instance_id: Uuid::new_v4(),- acquired_at: Utc::now() - ChronoDuration::hours(2),- process_id: std::process::id(),- };- std::fs::write(&path, serde_json::to_string(&live_owner)?)?;-- let result = acquire_lock(&path, "manager-b", Uuid::new_v4()).await;-- assert!(result.is_err());- let info: LockFileInfo = serde_json::from_str(&std::fs::read_to_string(&path)?)?;- assert_eq!(info.manager_id, "other-manager");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn reclaim_unparseable_snapshot_refuses_when_bytes_changed() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);- std::fs::write(&path, b"different bytes than the original snapshot")?;-- let stale_snapshot = b"old garbage that was observed earlier".to_vec();- let reclaimed = reclaim_stale_lock(&path, ReclaimExpectation::UnparseableSnapshot(stale_snapshot)).await?;-- assert!(matches!(reclaimed, ReclaimOutcome::Changed));- let restored = std::fs::read(&path)?;- assert_eq!(restored, b"different bytes than the original snapshot");- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn reclaim_unparseable_snapshot_succeeds_when_bytes_match() -> Result<(), Box<dyn std::error::Error>> {- let temp = tempfile::tempdir()?;- let path = lock_path(&temp);- let snapshot = b"identical garbage".to_vec();- std::fs::write(&path, &snapshot)?;-- let reclaimed = reclaim_stale_lock(&path, ReclaimExpectation::UnparseableSnapshot(snapshot)).await?;-- assert_eq!(reclaimed, ReclaimOutcome::Reclaimed);- assert!(!path.exists());- Ok(())-}--#[tokio::test(flavor = "multi_thread")]-async fn try_restore_quarantine_does_not_overwrite_a_new_lock_at_destination() -> Result<(), Box<dyn std::error::Error>>-{- let temp = tempfile::tempdir()?;- let lock_target = lock_path(&temp);- let quarantine = lock_target.with_extension("reclaim-test");- std::fs::write(&quarantine, b"quarantined-stale-content")?;-- let new_owner = LockFileInfo {- manager_id: "new-owner".to_string(),- instance_id: Uuid::new_v4(),- acquired_at: Utc::now(),- process_id: std::process::id(),- };- std::fs::write(&lock_target, serde_json::to_string(&new_owner)?)?;-- let restore_outcome = try_restore_quarantine(&quarantine, &lock_target).await?;-- assert_eq!(restore_outcome, RestoreOutcome::DestinationAlreadyExists);- assert!(!quarantine.exists());- let intact: LockFileInfo = serde_json::from_str(&std::fs::read_to_string(&lock_target)?)?;- assert_eq!(intact.manager_id, "new-owner");- Ok(())-}diff --git a/crates/legacy/download-manager/uniffi.toml b/crates/legacy/download-manager/uniffi.tomlnew file mode 100644index 000000000..7f3df2ee1--- /dev/null+++ b/crates/legacy/download-manager/uniffi.toml@@ -0,0 +1,2 @@+[bindings.swift]+generate_codable_conformance = truediff --git a/crates/legacy/kiban/Cargo.toml b/crates/legacy/kiban/Cargo.tomlindex ab6074e2e..c569ca74f 100644--- a/crates/legacy/kiban/Cargo.toml+++ b/crates/legacy/kiban/Cargo.toml@@ -13,9 +13,6 @@ license.workspace = trueasync-trait.workspace = truefutures-util.workspace = true-[target.'cfg(unix)'.dependencies]-libc.workspace = true-[target.'cfg(target_family = "wasm")'.dependencies]tokio = { workspace = true, features = ["sync", "time"] }wasm-bindgen.workspace = truediff --git a/crates/legacy/kiban/src/fs/asyn_opfs.rs b/crates/legacy/kiban/src/fs/asyn_opfs.rsindex 4a7b4e433..cf4bbc3ba 100644--- a/crates/legacy/kiban/src/fs/asyn_opfs.rs+++ b/crates/legacy/kiban/src/fs/asyn_opfs.rs@@ -12,7 +12,7 @@ use web_sys::{js_sys::Reflect, wasm_bindgen::JsValue};use super::opfs::{self, WriteCommandType, WriteParams};use crate::time::SystemTime;-pub(crate) async fn dir_create_all(path: &str) -> Result<(), io::Error> {+pub async fn dir_create_all(path: &str) -> Result<(), io::Error> {let mut root = get_root_dir().await?;for segment in normalized_segments(path)? {root = get_dir_handle(&root, &segment, true).await?;@@ -20,7 +20,7 @@ pub(crate) async fn dir_create_all(path: &str) -> Result<(), io::Error> {Ok(())}-pub(crate) async fn exists(path: &str) -> Result<bool, io::Error> {+pub async fn exists(path: &str) -> Result<bool, io::Error> {let root = get_root_dir().await?;let (parent, name) = match resolve_parent(&root, path).await {Ok(path) => path,@@ -40,7 +40,7 @@ pub(crate) async fn exists(path: &str) -> Result<bool, io::Error> {}}-pub(crate) async fn file_copy(+pub async fn file_copy(src_path: &str,dst_path: &str,) -> Result<(), io::Error> {@@ -89,7 +89,7 @@ pub(crate) async fn file_copy(Ok(())}-pub(crate) async fn file_copy_if_absent(+pub async fn file_copy_if_absent(src_path: &str,dst_path: &str,) -> Result<(), io::Error> {@@ -100,25 +100,25 @@ pub(crate) async fn file_copy_if_absent(file_copy(src_path, dst_path).await}-pub(crate) async fn file_length(path: &str) -> Result<u64, io::Error> {+pub async fn file_length(path: &str) -> Result<u64, io::Error> {let file = get_file_handle_root(path, false).await?;let size = file.size().await.map_err(|err| js_value_to_io_error(&err, ErrorKind::Other))?;Ok(size)}-pub(crate) async fn file_modified(path: &str) -> Result<SystemTime, io::Error> {+pub async fn file_modified(path: &str) -> Result<SystemTime, io::Error> {let file_handle = get_file_handle_root(path, false).await?;let file = file_handle.get_file().await.map_err(|err| js_value_to_io_error(&err, ErrorKind::InvalidInput))?;Ok(file.last_modified())}-pub(crate) async fn file_read(path: &str) -> Result<Vec<u8>, io::Error> {+pub async fn file_read(path: &str) -> Result<Vec<u8>, io::Error> {let file = get_file_handle_root(path, false).await?;let result = file.read().await.map_err(|err| js_value_to_io_error(&err, ErrorKind::Other))?;Ok(result)}-pub(crate) async fn file_read_range(+pub async fn file_read_range(path: &str,range: impl RangeBounds<u64>,) -> Result<Vec<u8>, io::Error> {@@ -127,7 +127,7 @@ pub(crate) async fn file_read_range(Ok(result)}-pub(crate) async fn file_remove(path: &str) -> Result<(), io::Error> {+pub async fn file_remove(path: &str) -> Result<(), io::Error> {let root = get_root_dir().await?;let (parent, name) = resolve_parent(&root, path).await?;let _ = get_file_handle(parent.clone(), &name, false).await?;@@ -135,7 +135,7 @@ pub(crate) async fn file_remove(path: &str) -> Result<(), io::Error> {Ok(())}-pub(crate) async fn file_rename(+pub async fn file_rename(src_path: &str,dst_path: &str,) -> Result<(), io::Error> {@@ -148,7 +148,7 @@ pub(crate) async fn file_rename(file_remove(src_path).await}-pub(crate) async fn file_write(+pub async fn file_write(path: &str,contents: &[u8],) -> Result<(), io::Error> {@@ -159,7 +159,7 @@ pub(crate) async fn file_write(Ok(())}-pub(crate) async fn file_write_if_absent(+pub async fn file_write_if_absent(path: &str,contents: &[u8],) -> Result<(), io::Error> {@@ -170,11 +170,11 @@ pub(crate) async fn file_write_if_absent(file_write(path, contents).await}-pub(crate) async fn is_file(path: &str) -> bool {+pub async fn is_file(path: &str) -> bool {get_file_handle_root(path, false).await.is_ok()}-pub(crate) async fn get_dir_handle(+pub async fn get_dir_handle(dir: &opfs::DirectoryHandle,path: &str,create: bool,@@ -182,7 +182,7 @@ pub(crate) async fn get_dir_handle(dir.get_directory_handle(path, create).await.map_err(|err| js_value_to_io_error(&err, ErrorKind::Other))}-pub(crate) async fn get_file_handle(+pub async fn get_file_handle(dir_handle: opfs::DirectoryHandle,path: &str,create: bool,@@ -190,7 +190,7 @@ pub(crate) async fn get_file_handle(dir_handle.get_file_handle(path, create).await.map_err(|err| js_value_to_io_error(&err, ErrorKind::Other))}-pub(crate) async fn get_file_handle_root(+pub async fn get_file_handle_root(path: &str,create: bool,) -> Result<opfs::FileHandle, io::Error> {@@ -199,11 +199,11 @@ pub(crate) async fn get_file_handle_root(get_file_handle(parent, &name, create).await}-pub(crate) async fn get_root_dir() -> Result<opfs::DirectoryHandle, io::Error> {+pub async fn get_root_dir() -> Result<opfs::DirectoryHandle, io::Error> {opfs::get_storage_root().await.map_err(|err| js_value_to_io_error(&err, ErrorKind::Other))}-pub(crate) async fn resolve_parent(+pub async fn resolve_parent(root: &opfs::DirectoryHandle,path: &str,) -> Result<(opfs::DirectoryHandle, String), io::Error> {@@ -259,7 +259,7 @@ fn create_if_absent_lock() -> &'static Mutex<()> {CREATE_IF_ABSENT_LOCK.get_or_init(|| Mutex::new(()))}-pub(crate) fn js_value_to_io_error(+pub fn js_value_to_io_error(value: &JsValue,kind: ErrorKind,) -> io::Error {diff --git a/crates/legacy/kiban/src/fs/file_lock.rs b/crates/legacy/kiban/src/fs/file_lock.rsnew file mode 100644index 000000000..c5cf5962f--- /dev/null+++ b/crates/legacy/kiban/src/fs/file_lock.rs@@ -0,0 +1,104 @@+use std::{io, path::Path};++pub struct FileLock {+ #[cfg(not(target_family = "wasm"))]+ file: std::fs::File,+ #[cfg(target_family = "wasm")]+ path: std::path::PathBuf,+ #[cfg(target_family = "wasm")]+ release: web_sys::js_sys::Function,+}++impl FileLock {+ pub async fn try_acquire(path: &Path) -> Result<Option<Self>, io::Error> {+ if let Some(parent) = path.parent() {+ super::asyn::create_dir_all(parent).await?;+ }++ #[cfg(target_family = "wasm")]+ {+ use std::io::ErrorKind;++ use futures_util::future::{Either, select};+ use wasm_bindgen_futures::JsFuture;+ use web_sys::{+ js_sys::{Function, Object, Promise, Reflect},+ wasm_bindgen::{JsCast, JsValue, closure::Closure},+ };++ use super::asyn_opfs::js_value_to_io_error;++ let to_io = |value: JsValue| js_value_to_io_error(&value, ErrorKind::Other);+ let navigator =+ web_sys::window().ok_or_else(|| io::Error::other("no window object available"))?.navigator();+ let locks = Reflect::get(&navigator, &JsValue::from_str("locks")).map_err(to_io)?;+ let request = Reflect::get(&locks, &JsValue::from_str("request"))+ .map_err(to_io)?+ .dyn_into::<Function>()+ .map_err(to_io)?;+ let options = Object::new();+ Reflect::set(&options, &JsValue::from_str("ifAvailable"), &JsValue::TRUE).map_err(to_io)?;+ let (granted_sender, granted_receiver) = tokio::sync::oneshot::channel();+ let callback = Closure::once_into_js(move |lock: JsValue| -> JsValue {+ if lock.is_null() {+ let _ = granted_sender.send(None);+ return JsValue::UNDEFINED;+ }+ let mut release = None;+ let held = Promise::new(&mut |resolve, _reject| release = Some(resolve));+ let _ = granted_sender.send(release);+ held.into()+ });+ let requested = request+ .call3(&locks, &JsValue::from_str(&path.to_string_lossy()), &options, &callback)+ .map_err(to_io)?;+ let release = match select(granted_receiver, JsFuture::from(Promise::from(requested))).await {+ Either::Left((Ok(release), _)) => release,+ Either::Left((Err(_), _)) | Either::Right((Ok(_), _)) => None,+ Either::Right((Err(error), _)) => return Err(to_io(error)),+ };+ Ok(release.map(|release| Self {+ path: path.to_path_buf(),+ release,+ }))+ }++ #[cfg(not(target_family = "wasm"))]+ {+ let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(path)?;+ match file.try_lock() {+ Ok(()) => Ok(Some(Self {+ file,+ })),+ Err(std::fs::TryLockError::WouldBlock) => Ok(None),+ Err(std::fs::TryLockError::Error(error)) => Err(error),+ }+ }+ }++ pub async fn write(+ &self,+ contents: &[u8],+ ) -> Result<(), io::Error> {+ #[cfg(target_family = "wasm")]+ {+ super::asyn::write(&self.path, contents).await+ }++ #[cfg(not(target_family = "wasm"))]+ {+ use std::io::{Seek, SeekFrom, Write};++ self.file.set_len(0)?;+ (&self.file).seek(SeekFrom::Start(0))?;+ (&self.file).write_all(contents)+ }+ }+}++#[cfg(target_family = "wasm")]+impl Drop for FileLock {+ fn drop(&mut self) {+ let _ = self.release.call0(&web_sys::wasm_bindgen::JsValue::NULL);+ }+}diff --git a/crates/legacy/kiban/src/fs/mod.rs b/crates/legacy/kiban/src/fs/mod.rsindex 6273abbaf..b5120a36c 100644--- a/crates/legacy/kiban/src/fs/mod.rs+++ b/crates/legacy/kiban/src/fs/mod.rs@@ -1,9 +1,11 @@#[cfg(target_family = "wasm")]mod asyn_opfs;+mod file_lock;#[cfg(target_family = "wasm")]mod opfs;mod part_file;pub mod asyn;+pub use file_lock::FileLock;pub use part_file::PartFile;diff --git a/crates/legacy/kiban/src/lib.rs b/crates/legacy/kiban/src/lib.rsindex c929b2dec..ed9ec7b3a 100644--- a/crates/legacy/kiban/src/lib.rs+++ b/crates/legacy/kiban/src/lib.rs@@ -2,8 +2,8 @@pub mod fs;pub mod maybe;-pub mod process;pub mod rt;+pub mod stream;pub mod time;#[cfg(target_family = "wasm")]diff --git a/crates/legacy/kiban/src/process.rs b/crates/legacy/kiban/src/process.rsdeleted file mode 100644index 25da8cbf1..000000000--- a/crates/legacy/kiban/src/process.rs+++ /dev/null@@ -1,45 +0,0 @@-#[cfg(unix)]-pub async fn is_process_alive(process_id: u32) -> bool {- // SAFETY: `kill(pid, 0)` is a probe with no signal delivery. Direct syscall is required- // because sandboxed macOS apps can't exec `/bin/kill`.- let result = unsafe { libc::kill(process_id as libc::pid_t, 0) };- if result == 0 {- return true;- }- // EPERM = exists but we can't signal it; ESRCH = gone.- std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)-}--#[cfg(windows)]-pub async fn is_process_alive(process_id: u32) -> bool {- tokio::task::spawn_blocking(move || {- std::process::Command::new("tasklist")- .args(["/FI", &format!("PID eq {process_id}")])- .output()- .map(|output| String::from_utf8_lossy(&output.stdout).contains(&process_id.to_string()))- .unwrap_or(false)- })- .await- .unwrap_or(false)-}--#[cfg(target_family = "wasm")]-pub async fn is_process_alive(_process_id: u32) -> bool {- false-}--pub fn id() -> u32 {- if proc_supported() {- std::process::id()- } else {- 0- }-}--pub fn proc_supported() -> bool {- #[cfg(not(target_family = "wasm"))]- return true;-- #[cfg(target_family = "wasm")]- false-}diff --git a/crates/legacy/kiban/src/rt/mod.rs b/crates/legacy/kiban/src/rt/mod.rsindex a1300915f..7ecd018c5 100644--- a/crates/legacy/kiban/src/rt/mod.rs+++ b/crates/legacy/kiban/src/rt/mod.rs@@ -18,6 +18,9 @@ pub trait TaskJoinHandle<T>: Send + Sync {/// Abort the task and wait for it to finish winding down.async fn abort_and_join(self: Box<Self>);++ /// Whether the task has stopped running, by completion or abort.+ fn is_finished(&self) -> bool;}pub fn spawn<F: Future<Output: MaybeSend + 'static> + MaybeSend + 'static>(diff --git a/crates/legacy/kiban/src/rt/tokio.rs b/crates/legacy/kiban/src/rt/tokio.rsindex 55c0dedc6..3b05130a2 100644--- a/crates/legacy/kiban/src/rt/tokio.rs+++ b/crates/legacy/kiban/src/rt/tokio.rs@@ -40,6 +40,10 @@ impl<T: Send + 'static> TaskJoinHandle<T> for JoinHandle<T> {self.abort();let _ = (*self).await;}++ fn is_finished(&self) -> bool {+ JoinHandle::is_finished(self)+ }}pub fn spawn<F: Future<Output: Send + 'static> + Send + 'static>(future: F) -> Box<dyn TaskJoinHandle<F::Output>> {diff --git a/crates/legacy/kiban/src/rt/wasm.rs b/crates/legacy/kiban/src/rt/wasm.rsindex 9b0957169..6f8aed92a 100644--- a/crates/legacy/kiban/src/rt/wasm.rs+++ b/crates/legacy/kiban/src/rt/wasm.rs@@ -40,6 +40,10 @@ impl<T> TaskJoinHandle<T> for WasmTaskJoinHandle {self.abort_handle.abort();let _ = self.completion.await;}++ fn is_finished(&self) -> bool {+ !self.completion.is_empty()+ }}pub fn spawn<F: Future<Output: 'static> + 'static>(future: F) -> Box<dyn TaskJoinHandle<F::Output>> {diff --git a/crates/legacy/kiban/src/stream/box_stream.rs b/crates/legacy/kiban/src/stream/box_stream.rsnew file mode 100644index 000000000..2280181ba--- /dev/null+++ b/crates/legacy/kiban/src/stream/box_stream.rs@@ -0,0 +1,6 @@+#[cfg(not(target_family = "wasm"))]+use futures_util::stream::BoxStream as PlatformBoxStream;+#[cfg(target_family = "wasm")]+use futures_util::stream::LocalBoxStream as PlatformBoxStream;++pub type BoxStream<'a, T> = PlatformBoxStream<'a, T>;diff --git a/crates/legacy/kiban/src/stream/mod.rs b/crates/legacy/kiban/src/stream/mod.rsnew file mode 100644index 000000000..554319703--- /dev/null+++ b/crates/legacy/kiban/src/stream/mod.rs@@ -0,0 +1,3 @@+mod box_stream;++pub use box_stream::BoxStream;diff --git a/crates/legacy/kiban/src/time/sleep_wasm.rs b/crates/legacy/kiban/src/time/sleep_wasm.rsindex 61774fa45..585cd090a 100644--- a/crates/legacy/kiban/src/time/sleep_wasm.rs+++ b/crates/legacy/kiban/src/time/sleep_wasm.rs@@ -16,7 +16,7 @@ struct SleepState {waker: Option<Waker>,}-pub(crate) struct Sleep {+pub struct Sleep {state: Rc<RefCell<SleepState>>,timeout_id: i32,_done: Closure<dyn FnMut()>,diff --git a/crates/legacy/mock-registry/src/artifact_path.rs b/crates/legacy/mock-registry/src/artifact_path.rsnew file mode 100644index 000000000..dc94095e9--- /dev/null+++ b/crates/legacy/mock-registry/src/artifact_path.rs@@ -0,0 +1,8 @@+use std::path::{Path, PathBuf};++pub fn artifact_path(+ destination: &Path,+ extension: &str,+) -> PathBuf {+ PathBuf::from(format!("{}.{extension}", destination.display()))+}diff --git a/crates/legacy/mock-registry/src/lib.rs b/crates/legacy/mock-registry/src/lib.rsindex c787707fa..17ee7d72d 100644--- a/crates/legacy/mock-registry/src/lib.rs+++ b/crates/legacy/mock-registry/src/lib.rs@@ -1,3 +1,4 @@+mod artifact_path;mod behavior;mod bytes;mod error;@@ -8,6 +9,7 @@ mod mock_registry;mod model;mod served_file;+pub use artifact_path::artifact_path;pub use behavior::Behavior;pub use error::{Error, Result};pub use mock_registry::MockRegistry;diff --git a/crates/legacy/shoji/src/traits/registry.rs b/crates/legacy/shoji/src/traits/registry.rsindex 4a2c64064..f5bf35ecb 100644--- a/crates/legacy/shoji/src/traits/registry.rs+++ b/crates/legacy/shoji/src/traits/registry.rs@@ -1,19 +1,19 @@use std::{error::Error, future::Future, pin::Pin};-use crate::types::model::Model;+use crate::types::model::{Model, ModelIdentifier};pub trait Registry: Send + Sync {type Error: Error;- fn indentifier(&self) -> String;+ fn identifier(&self) -> String;fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, Self::Error>> + Send + '_>>;fn model_by_identifier(&self,- identifier: &str,+ identifier: &ModelIdentifier,) -> Pin<Box<dyn Future<Output = Result<Option<Model>, Self::Error>> + Send + '_>> {- let identifier = identifier.to_string();+ let identifier = identifier.clone();Box::pin(async move {let models = self.models().await?;let model = models.iter().find(|model| model.identifier == identifier).cloned();diff --git a/crates/legacy/shoji/src/types/model/mod.rs b/crates/legacy/shoji/src/types/model/mod.rsindex a30a19526..7170b59ad 100644--- a/crates/legacy/shoji/src/types/model/mod.rs+++ b/crates/legacy/shoji/src/types/model/mod.rs@@ -2,6 +2,7 @@ mod accessibility;mod backend;mod family;mod model;+mod model_identifier;mod properties;mod quantization;mod reference;@@ -13,6 +14,7 @@ pub use accessibility::ModelAccessibility;pub use backend::ModelBackend;pub use family::ModelFamily;pub use model::Model;+pub use model_identifier::ModelIdentifier;pub use properties::ModelProperties;pub use quantization::ModelQuantization;pub use reference::ModelReference;diff --git a/crates/legacy/shoji/src/types/model/model.rs b/crates/legacy/shoji/src/types/model/model.rsindex 31fa14c3a..4bdcb4e94 100644--- a/crates/legacy/shoji/src/types/model/model.rs+++ b/crates/legacy/shoji/src/types/model/model.rs@@ -3,8 +3,8 @@ use serde::{Deserialize, Serialize};use crate::types::{basic::{Metadata, Value},model::{- ModelAccessibility, ModelBackend, ModelFamily, ModelProperties, ModelQuantization, ModelReference,- ModelRegistry, ModelSpecialization,+ ModelAccessibility, ModelBackend, ModelFamily, ModelIdentifier, ModelProperties, ModelQuantization,+ ModelReference, ModelRegistry, ModelSpecialization,},};@@ -13,7 +13,7 @@ use crate::types::{#[serde(rename_all = "snake_case")]pub struct Model {#[serde(rename = "id")]- pub identifier: String,+ pub identifier: ModelIdentifier,pub registry: ModelRegistry,pub backends: Vec<ModelBackend>,pub family: Option<ModelFamily>,@@ -178,7 +178,7 @@ impl Model {impl Model {#[bindings::export(Method(Factory))]pub fn external(- identifier: String,+ identifier: ModelIdentifier,registry_identifier: String,registry_name: String,backend_identifier: String,diff --git a/crates/legacy/shoji/src/types/model/model_identifier.rs b/crates/legacy/shoji/src/types/model/model_identifier.rsnew file mode 100644index 000000000..9ce11ee31--- /dev/null+++ b/crates/legacy/shoji/src/types/model/model_identifier.rs@@ -0,0 +1,2 @@+#[bindings::export(Alias)]+pub type ModelIdentifier = String;diff --git a/crates/legacy/uzu/Cargo.toml b/crates/legacy/uzu/Cargo.tomlindex 38440cec3..48f86359f 100644--- a/crates/legacy/uzu/Cargo.toml+++ b/crates/legacy/uzu/Cargo.toml@@ -28,12 +28,14 @@ bindings-uniffi = ["bindings-types/bindings-uniffi","shoji/bindings-uniffi","nagare/bindings-uniffi",+ "download-manager/bindings-uniffi","dep:uniffi",]bindings-napi = ["bindings-types/bindings-napi","shoji/bindings-napi","nagare/bindings-napi",+ "download-manager/bindings-napi","dep:napi","dep:napi-derive","dep:napi-build",@@ -42,6 +44,7 @@ bindings-pyo3 = ["bindings-types/bindings-pyo3","shoji/bindings-pyo3","nagare/bindings-pyo3",+ "download-manager/bindings-pyo3","dep:pyo3","dep:pyo3-build-config","dep:pyo3-async-runtimes",@@ -52,6 +55,7 @@ bindings-wasm = ["bindings-types/bindings-wasm","shoji/bindings-wasm","nagare/bindings-wasm",+ "download-manager/bindings-wasm","dep:wasm-bindgen","dep:serde-wasm-bindgen","dep:wasm-bindgen-futures",@@ -65,7 +69,6 @@ uzu-engine.workspace = truekiban.workspace = trueshoji.workspace = trueanyhow.workspace = true-bitflags.workspace = trueuniffi = { workspace = true, optional = true }napi = { workspace = true, optional = true }napi-derive = { workspace = true, optional = true }@@ -113,7 +116,6 @@ chrono.workspace = true[target.'cfg(target_vendor = "apple")'.dependencies]objc2.workspace = trueobjc2-foundation.workspace = true-objc2-security.workspace = true[target.'cfg(target_os = "macos")'.dependencies]apple-native-keyring-store = { workspace = true, features = [@@ -125,8 +127,6 @@ apple-native-keyring-store = { workspace = true, features = [apple-native-keyring-store = { workspace = true, features = ["protected"] }[dev-dependencies]-tracing-subscriber.workspace = true-tracing-appender.workspace = truetempfile.workspace = trueindicatif.workspace = truedotenvy.workspace = true@@ -139,10 +139,6 @@ rstest.workspace = truename = "tool"path = "tests/tool/mod.rs"-[[test]]-name = "unit"-path = "tests/unit/test_entry.rs"-[build-dependencies]napi-build = { workspace = true, optional = true }pyo3-build-config = { workspace = true, optional = true }diff --git a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi b/crates/legacy/uzu/bindings/python/uzu/__init__.pyiindex 95c6d64c3..fee31c7a1 100644--- a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi+++ b/crates/legacy/uzu/bindings/python/uzu/__init__.pyi@@ -5,6 +5,7 @@ import builtinsimport collections.abcimport enumimport typing+from typing import TypeAliasfrom uzu._tool import UzuToolFunction, uzu_tool_function__all__ = ["CancelToken",@@ -42,7 +43,6 @@ __all__ = ["DownloadState","Downloader","DownloaderStream",- "DownloaderStreamUpdate","Engine","EngineCallback","EngineConfig",@@ -59,6 +59,7 @@ __all__ = ["ModelAccessibility","ModelBackend","ModelFamily",+ "ModelIdentifier","ModelProperties","ModelQuantization","ModelReference",@@ -92,6 +93,7 @@ __all__ = ["uzu_tool_function",]+ModelIdentifier: TypeAlias = builtins.str@typing.finalclass CancelToken:@property@@ -631,8 +633,10 @@ class DownloadPhase:@typing.finalclass Locked(DownloadPhase):- __match_args__ = ()- def __new__(cls) -> DownloadPhase.Locked: ...+ __match_args__ = ("manager_id",)+ @property+ def manager_id(self) -> builtins.str: ...+ def __new__(cls, manager_id: builtins.str) -> DownloadPhase.Locked: ...@typing.finalclass Error(DownloadPhase):@@ -673,21 +677,11 @@ class Downloader:@typing.finalclass DownloaderStream:- def next(self) -> collections.abc.Awaitable[DownloaderStreamUpdate | None]: ...+ def next(self) -> collections.abc.Awaitable[DownloadState | None]: ...def __aiter__(self) -> DownloaderStream: ...- def __anext__(self) -> collections.abc.Awaitable[DownloaderStreamUpdate]: ...+ def __anext__(self) -> collections.abc.Awaitable[DownloadState]: ...def iterator(self) -> DownloaderStream: ...-class DownloaderStreamUpdate:- @property- def bytes_total(self) -> builtins.int: ...- @property- def bytes_downloaded(self) -> builtins.int: ...- @property- def progress(self) -> builtins.float: ...- def __new__(cls, bytes_total: builtins.int, bytes_downloaded: builtins.int) -> DownloaderStreamUpdate: ...-@typing.finalclass Engine:@staticmethod@@ -717,7 +711,7 @@ class Engine:def downloader(self, model: Model) -> Downloader: ...def download(self, model: Model) -> collections.abc.Awaitable[DownloaderStream]: ...def download_state(self, model: Model) -> collections.abc.Awaitable[DownloadState | None]: ...- def download_states(self) -> collections.abc.Awaitable[builtins.dict[builtins.str, DownloadState]]: ...+ def download_states(self) -> collections.abc.Awaitable[builtins.dict[ModelIdentifier, DownloadState]]: ...def chat(self, model: Model, config: ChatConfig) -> collections.abc.Awaitable[ChatSession]: ...def chat_instance(self, model: Model, config: ChatConfig) -> collections.abc.Awaitable[ChatInstance]: ...def chat_with_instance(self, instance: ChatInstance) -> collections.abc.Awaitable[ChatSession]: ...diff --git a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/Extensions.swift b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/Extensions.swiftindex ad030d6ae..4f261b000 100644--- a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/Extensions.swift+++ b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/Extensions.swift@@ -1,5 +1,11 @@// Auto-generated by cli-tools — do not edit.+public typealias ModelIdentifier = String++public typealias TokenId = UInt32++public typealias TokenValue = String+extension CancelToken {public static func create() -> CancelToken {cancelTokenCreate()@@ -91,7 +97,7 @@ extension Metadata {}extension Model {- public static func external(identifier: String, registryIdentifier: String, registryName: String, backendIdentifier: String, backendName: String, backendVersion: String, specializations: [ModelSpecialization], accessibility: ModelAccessibility, encoding: Value?) -> Model {+ public static func external(identifier: ModelIdentifier, registryIdentifier: String, registryName: String, backendIdentifier: String, backendName: String, backendVersion: String, specializations: [ModelSpecialization], accessibility: ModelAccessibility, encoding: Value?) -> Model {modelExternal(identifier: identifier, registryIdentifier: registryIdentifier, registryName: registryName, backendIdentifier: backendIdentifier, backendName: backendName, backendVersion: backendVersion, specializations: specializations, accessibility: accessibility, encoding: encoding)}}@@ -144,8 +150,8 @@ extension ChatSessionStream {}extension DownloaderStream {- public func iterator() -> AsyncThrowingStream<DownloaderStreamUpdate, Swift.Error> {- AsyncThrowingStream<DownloaderStreamUpdate, Swift.Error> { continuation in+ public func iterator() -> AsyncThrowingStream<DownloadState, Swift.Error> {+ AsyncThrowingStream<DownloadState, Swift.Error> { continuation inlet task = Task {while !Task.isCancelled {let item = await self.next()diff --git a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/download_manager.swift b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/download_manager.swiftnew file mode 100644index 000000000..d58420db1--- /dev/null+++ b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/download_manager.swift@@ -0,0 +1,814 @@+// This file was autogenerated by some hot garbage in the `uniffi` crate.+// Trust me, you don't want to mess with it!++// swiftlint:disable all+import Foundation++// Depending on the consumer's build setup, the low-level FFI code+// might be in a separate module, or it might be compiled inline into+// this module. This is a bit of light hackery to work with both.+#if canImport(download_managerFFI)+import download_managerFFI+#endif++fileprivate extension RustBuffer {+ // Allocate a new buffer, copying the contents of a `UInt8` array.+ init(bytes: [UInt8]) {+ let rbuf = bytes.withUnsafeBufferPointer { ptr in+ RustBuffer.from(ptr)+ }+ self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)+ }++ static func empty() -> RustBuffer {+ RustBuffer(capacity: 0, len:0, data: nil)+ }++ static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {+ try! rustCall { ffi_download_manager_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }+ }++ // Frees the buffer in place.+ // The buffer must not be used after this is called.+ func deallocate() {+ try! rustCall { ffi_download_manager_rustbuffer_free(self, $0) }+ }+}++fileprivate extension ForeignBytes {+ init(bufferPointer: UnsafeBufferPointer<UInt8>) {+ self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)+ }+}++// For every type used in the interface, we provide helper methods for conveniently+// lifting and lowering that type from C-compatible data, and for reading and writing+// values of that type in a buffer.++// Helper classes/extensions that don't change.+// Someday, this will be in a library of its own.++fileprivate extension Data {+ init(rustBuffer: RustBuffer) {+ self.init(+ bytesNoCopy: rustBuffer.data!,+ count: Int(rustBuffer.len),+ deallocator: .none+ )+ }+}++// Define reader functionality. Normally this would be defined in a class or+// struct, but we use standalone functions instead in order to make external+// types work.+//+// With external types, one swift source file needs to be able to call the read+// method on another source file's FfiConverter, but then what visibility+// should Reader have?+// - If Reader is fileprivate, then this means the read() must also+// be fileprivate, which doesn't work with external types.+// - If Reader is internal/public, we'll get compile errors since both source+// files will try define the same type.+//+// Instead, the read() method and these helper functions input a tuple of data++fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {+ (data: data, offset: 0)+}++// Reads an integer at the current offset, in big-endian order, and advances+// the offset on success. Throws if reading the integer would move the+// offset past the end of the buffer.+fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {+ let range = reader.offset..<reader.offset + MemoryLayout<T>.size+ guard reader.data.count >= range.upperBound else {+ throw UniffiInternalError.bufferOverflow+ }+ if T.self == UInt8.self {+ let value = reader.data[reader.offset]+ reader.offset += 1+ return value as! T+ }+ var value: T = 0+ let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})+ reader.offset = range.upperBound+ return value.bigEndian+}++// Reads an arbitrary number of bytes, to be used to read+// raw bytes, this is useful when lifting strings+fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {+ let range = reader.offset..<(reader.offset+count)+ guard reader.data.count >= range.upperBound else {+ throw UniffiInternalError.bufferOverflow+ }+ var value = [UInt8](repeating: 0, count: count)+ value.withUnsafeMutableBufferPointer({ buffer in+ reader.data.copyBytes(to: buffer, from: range)+ })+ reader.offset = range.upperBound+ return value+}++// Reads a float at the current offset.+fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {+ return Float(bitPattern: try readInt(&reader))+}++// Reads a float at the current offset.+fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {+ return Double(bitPattern: try readInt(&reader))+}++// Indicates if the offset has reached the end of the buffer.+fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {+ return reader.offset < reader.data.count+}++// Define writer functionality. Normally this would be defined in a class or+// struct, but we use standalone functions instead in order to make external+// types work. See the above discussion on Readers for details.++fileprivate func createWriter() -> [UInt8] {+ return []+}++fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {+ writer.append(contentsOf: byteArr)+}++// Writes an integer in big-endian order.+//+// Warning: make sure what you are trying to write+// is in the correct type!+fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {+ var value = value.bigEndian+ withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }+}++fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {+ writeInt(&writer, value.bitPattern)+}++fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {+ writeInt(&writer, value.bitPattern)+}++// Protocol for types that transfer other types across the FFI. This is+// analogous to the Rust trait of the same name.+fileprivate protocol FfiConverter {+ associatedtype FfiType+ associatedtype SwiftType++ static func lift(_ value: FfiType) throws -> SwiftType+ static func lower(_ value: SwiftType) -> FfiType+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType+ static func write(_ value: SwiftType, into buf: inout [UInt8])+}++// Types conforming to `Primitive` pass themselves directly over the FFI.+fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }++extension FfiConverterPrimitive {+#if swift(>=5.8)+ @_documentation(visibility: private)+#endif+ public static func lift(_ value: FfiType) throws -> SwiftType {+ return value+ }++#if swift(>=5.8)+ @_documentation(visibility: private)+#endif+ public static func lower(_ value: SwiftType) -> FfiType {+ return value+ }+}++// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.+// Used for complex types where it's hard to write a custom lift/lower.+fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}++extension FfiConverterRustBuffer {+#if swift(>=5.8)+ @_documentation(visibility: private)+#endif+ public static func lift(_ buf: RustBuffer) throws -> SwiftType {+ var reader = createReader(data: Data(rustBuffer: buf))+ let value = try read(from: &reader)+ if hasRemaining(reader) {+ throw UniffiInternalError.incompleteData+ }+ buf.deallocate()+ return value+ }++#if swift(>=5.8)+ @_documentation(visibility: private)+#endif+ public static func lower(_ value: SwiftType) -> RustBuffer {+ var writer = createWriter()+ write(value, into: &writer)+ return RustBuffer(bytes: writer)+ }+}+// An error type for FFI errors. These errors occur at the UniFFI level, not+// the library level.+fileprivate enum UniffiInternalError: LocalizedError {+ case bufferOverflow+ case incompleteData+ case unexpectedOptionalTag+ case unexpectedEnumCase+ case unexpectedNullPointer+ case unexpectedRustCallStatusCode+ case unexpectedRustCallError+ case unexpectedStaleHandle+ case rustPanic(_ message: String)++ public var errorDescription: String? {+ switch self {+ case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"+ case .incompleteData: return "The buffer still has data after lifting its containing value"+ case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"+ case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"+ case .unexpectedNullPointer: return "Raw pointer value was null"+ case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"+ case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"+ case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"+ case let .rustPanic(message): return message+ }+ }+}++fileprivate extension NSLock {+ func withLock<T>(f: () throws -> T) rethrows -> T {+ self.lock()+ defer { self.unlock() }+ return try f()+ }+}++fileprivate let CALL_SUCCESS: Int8 = 0+fileprivate let CALL_ERROR: Int8 = 1+fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2+fileprivate let CALL_CANCELLED: Int8 = 3++fileprivate extension RustCallStatus {+ init() {+ self.init(+ code: CALL_SUCCESS,+ errorBuf: RustBuffer.init(+ capacity: 0,+ len: 0,+ data: nil+ )+ )+ }+}++private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {+ let neverThrow: ((RustBuffer) throws -> Never)? = nil+ return try makeRustCall(callback, errorHandler: neverThrow)+}++private func rustCallWithError<T, E: Swift.Error>(+ _ errorHandler: @escaping (RustBuffer) throws -> E,+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {+ try makeRustCall(callback, errorHandler: errorHandler)+}++private func makeRustCall<T, E: Swift.Error>(+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,+ errorHandler: ((RustBuffer) throws -> E)?+) throws -> T {+ uniffiEnsureDownloadManagerInitialized()+ var callStatus = RustCallStatus.init()+ let returnedVal = callback(&callStatus)+ try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)+ return returnedVal+}++private func uniffiCheckCallStatus<E: Swift.Error>(+ callStatus: RustCallStatus,+ errorHandler: ((RustBuffer) throws -> E)?+) throws {+ switch callStatus.code {+ case CALL_SUCCESS:+ return++ case CALL_ERROR:+ if let errorHandler = errorHandler {+ throw try errorHandler(callStatus.errorBuf)+ } else {+ callStatus.errorBuf.deallocate()+ throw UniffiInternalError.unexpectedRustCallError+ }++ case CALL_UNEXPECTED_ERROR:+ // When the rust code sees a panic, it tries to construct a RustBuffer+ // with the message. But if that code panics, then it just sends back+ // an empty buffer.+ if callStatus.errorBuf.len > 0 {+ throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))+ } else {+ callStatus.errorBuf.deallocate()+ throw UniffiInternalError.rustPanic("Rust panic")+ }++ case CALL_CANCELLED:+ fatalError("Cancellation not supported yet")++ default:+ throw UniffiInternalError.unexpectedRustCallStatusCode+ }+}++private func uniffiTraitInterfaceCall<T>(+ callStatus: UnsafeMutablePointer<RustCallStatus>,+ makeCall: () throws -> T,+ writeReturn: (T) -> ()+) {+ do {+ try writeReturn(makeCall())+ } catch let error {+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))+ }+}++private func uniffiTraitInterfaceCallWithError<T, E>(+ callStatus: UnsafeMutablePointer<RustCallStatus>,+ makeCall: () throws -> T,+ writeReturn: (T) -> (),+ lowerError: (E) -> RustBuffer+) {+ do {+ try writeReturn(makeCall())+ } catch let error as E {+ callStatus.pointee.code = CALL_ERROR+ callStatus.pointee.errorBuf = lowerError(error)+ } catch {+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))+ }+}+// Initial value and increment amount for handles.+// These ensure that SWIFT handles always have the lowest bit set+fileprivate let UNIFFI_HANDLEMAP_INITIAL: UInt64 = 1+fileprivate let UNIFFI_HANDLEMAP_DELTA: UInt64 = 2++fileprivate final class UniffiHandleMap<T>: @unchecked Sendable {+ // All mutation happens with this lock held, which is why we implement @unchecked Sendable.+ private let lock = NSLock()+ private var map: [UInt64: T] = [:]+ private var currentHandle: UInt64 = UNIFFI_HANDLEMAP_INITIAL++ func insert(obj: T) -> UInt64 {+ lock.withLock {+ return doInsert(obj)+ }+ }++ // Low-level insert function, this assumes `lock` is held.+ private func doInsert(_ obj: T) -> UInt64 {+ let handle = currentHandle+ currentHandle += UNIFFI_HANDLEMAP_DELTA+ map[handle] = obj+ return handle+ }++ func get(handle: UInt64) throws -> T {+ try lock.withLock {+ guard let obj = map[handle] else {+ throw UniffiInternalError.unexpectedStaleHandle+ }+ return obj+ }+ }++ func clone(handle: UInt64) throws -> UInt64 {+ try lock.withLock {+ guard let obj = map[handle] else {+ throw UniffiInternalError.unexpectedStaleHandle+ }+ return doInsert(obj)+ }+ }++ @discardableResult+ func remove(handle: UInt64) throws -> T {+ try lock.withLock {+ guard let obj = map.removeValue(forKey: handle) else {+ throw UniffiInternalError.unexpectedStaleHandle+ }+ return obj+ }+ }++ var count: Int {+ get {+ map.count+ }+ }+}+++// Public interface members begin here.+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterInt64: FfiConverterPrimitive {+ typealias FfiType = Int64+ typealias SwiftType = Int64++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Int64 {+ return try lift(readInt(&buf))+ }++ public static func write(_ value: Int64, into buf: inout [UInt8]) {+ writeInt(&buf, lower(value))+ }+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterFloat: FfiConverterPrimitive {+ typealias FfiType = Float+ typealias SwiftType = Float++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Float {+ return try lift(readFloat(&buf))+ }++ public static func write(_ value: Float, into buf: inout [UInt8]) {+ writeFloat(&buf, lower(value))+ }+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterBool : FfiConverter {+ typealias FfiType = Int8+ typealias SwiftType = Bool++ public static func lift(_ value: Int8) throws -> Bool {+ return value != 0+ }++ public static func lower(_ value: Bool) -> Int8 {+ return value ? 1 : 0+ }++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {+ return try lift(readInt(&buf))+ }++ public static func write(_ value: Bool, into buf: inout [UInt8]) {+ writeInt(&buf, lower(value))+ }+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+fileprivate struct FfiConverterString: FfiConverter {+ typealias SwiftType = String+ typealias FfiType = RustBuffer++ public static func lift(_ value: RustBuffer) throws -> String {+ defer {+ value.deallocate()+ }+ if value.data == nil {+ return String()+ }+ let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))+ return String(bytes: bytes, encoding: String.Encoding.utf8)!+ }++ public static func lower(_ value: String) -> RustBuffer {+ return value.utf8CString.withUnsafeBufferPointer { ptr in+ // The swift string gives us int8_t, we want uint8_t.+ ptr.withMemoryRebound(to: UInt8.self) { ptr in+ // The swift string gives us a trailing null byte, we don't want it.+ let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))+ return RustBuffer.from(buf)+ }+ }+ }++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {+ let len: Int32 = try readInt(&buf)+ return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!+ }++ public static func write(_ value: String, into buf: inout [UInt8]) {+ let len = Int32(value.utf8.count)+ writeInt(&buf, len)+ writeBytes(&buf, value.utf8)+ }+}+++public struct DownloadState: Equatable, Hashable, Codable {+ public var totalBytes: Int64+ public var downloadedBytes: Int64+ public var phase: DownloadPhase++ // Default memberwise initializers are never public by default, so we+ // declare one manually.+ public init(totalBytes: Int64, downloadedBytes: Int64, phase: DownloadPhase) {+ self.totalBytes = totalBytes+ self.downloadedBytes = downloadedBytes+ self.phase = phase+ }+++public func canDelete() -> Bool {+ return try! FfiConverterBool.lift(try! rustCall() {+ uniffi_download_manager_fn_method_downloadstate_can_delete(+ FfiConverterTypeDownloadState_lower(self),$0+ )+})+}++public func canPause() -> Bool {+ return try! FfiConverterBool.lift(try! rustCall() {+ uniffi_download_manager_fn_method_downloadstate_can_pause(+ FfiConverterTypeDownloadState_lower(self),$0+ )+})+}++public func isInProgress() -> Bool {+ return try! FfiConverterBool.lift(try! rustCall() {+ uniffi_download_manager_fn_method_downloadstate_is_in_progress(+ FfiConverterTypeDownloadState_lower(self),$0+ )+})+}++public func name() -> String {+ return try! FfiConverterString.lift(try! rustCall() {+ uniffi_download_manager_fn_method_downloadstate_name(+ FfiConverterTypeDownloadState_lower(self),$0+ )+})+}++public func progress() -> Float {+ return try! FfiConverterFloat.lift(try! rustCall() {+ uniffi_download_manager_fn_method_downloadstate_progress(+ FfiConverterTypeDownloadState_lower(self),$0+ )+})+}++++}++#if compiler(>=6)+extension DownloadState: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeDownloadState: FfiConverterRustBuffer {+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadState {+ return+ try DownloadState(+ totalBytes: FfiConverterInt64.read(from: &buf),+ downloadedBytes: FfiConverterInt64.read(from: &buf),+ phase: FfiConverterTypeDownloadPhase.read(from: &buf)+ )+ }++ public static func write(_ value: DownloadState, into buf: inout [UInt8]) {+ FfiConverterInt64.write(value.totalBytes, into: &buf)+ FfiConverterInt64.write(value.downloadedBytes, into: &buf)+ FfiConverterTypeDownloadPhase.write(value.phase, into: &buf)+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeDownloadState_lift(_ buf: RustBuffer) throws -> DownloadState {+ return try FfiConverterTypeDownloadState.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeDownloadState_lower(_ value: DownloadState) -> RustBuffer {+ return FfiConverterTypeDownloadState.lower(value)+}++// Note that we don't yet support `indirect` for enums.+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.++public enum DownloadManagerType: Equatable, Hashable, Codable {++ case native+ case universal++++++}++#if compiler(>=6)+extension DownloadManagerType: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeDownloadManagerType: FfiConverterRustBuffer {+ typealias SwiftType = DownloadManagerType++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadManagerType {+ let variant: Int32 = try readInt(&buf)+ switch variant {++ case 1: return .native++ case 2: return .universal++ default: throw UniffiInternalError.unexpectedEnumCase+ }+ }++ public static func write(_ value: DownloadManagerType, into buf: inout [UInt8]) {+ switch value {+++ case .native:+ writeInt(&buf, Int32(1))+++ case .universal:+ writeInt(&buf, Int32(2))++ }+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeDownloadManagerType_lift(_ buf: RustBuffer) throws -> DownloadManagerType {+ return try FfiConverterTypeDownloadManagerType.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeDownloadManagerType_lower(_ value: DownloadManagerType) -> RustBuffer {+ return FfiConverterTypeDownloadManagerType.lower(value)+}+++// Note that we don't yet support `indirect` for enums.+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.++public enum DownloadPhase: Equatable, Hashable, Codable {++ case notDownloaded+ case downloading+ case paused+ case downloaded+ case locked(managerId: String+ )+ case error(message: String+ )++++++}++#if compiler(>=6)+extension DownloadPhase: Sendable {}+#endif++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public struct FfiConverterTypeDownloadPhase: FfiConverterRustBuffer {+ typealias SwiftType = DownloadPhase++ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadPhase {+ let variant: Int32 = try readInt(&buf)+ switch variant {++ case 1: return .notDownloaded++ case 2: return .downloading++ case 3: return .paused++ case 4: return .downloaded++ case 5: return .locked(managerId: try FfiConverterString.read(from: &buf)+ )++ case 6: return .error(message: try FfiConverterString.read(from: &buf)+ )++ default: throw UniffiInternalError.unexpectedEnumCase+ }+ }++ public static func write(_ value: DownloadPhase, into buf: inout [UInt8]) {+ switch value {+++ case .notDownloaded:+ writeInt(&buf, Int32(1))+++ case .downloading:+ writeInt(&buf, Int32(2))+++ case .paused:+ writeInt(&buf, Int32(3))+++ case .downloaded:+ writeInt(&buf, Int32(4))+++ case let .locked(managerId):+ writeInt(&buf, Int32(5))+ FfiConverterString.write(managerId, into: &buf)+++ case let .error(message):+ writeInt(&buf, Int32(6))+ FfiConverterString.write(message, into: &buf)++ }+ }+}+++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeDownloadPhase_lift(_ buf: RustBuffer) throws -> DownloadPhase {+ return try FfiConverterTypeDownloadPhase.lift(buf)+}++#if swift(>=5.8)+@_documentation(visibility: private)+#endif+public func FfiConverterTypeDownloadPhase_lower(_ value: DownloadPhase) -> RustBuffer {+ return FfiConverterTypeDownloadPhase.lower(value)+}+++private enum InitializationResult {+ case ok+ case contractVersionMismatch+ case apiChecksumMismatch+}+// Use a global variable to perform the versioning checks. Swift ensures that+// the code inside is only computed once.+private let initializationResult: InitializationResult = {+ // Get the bindings contract version from our ComponentInterface+ let bindings_contract_version = 30+ // Get the scaffolding contract version by calling the into the dylib+ let scaffolding_contract_version = ffi_download_manager_uniffi_contract_version()+ if bindings_contract_version != scaffolding_contract_version {+ return InitializationResult.contractVersionMismatch+ }++ return InitializationResult.ok+}()++// Make the ensure init function public so that other modules which have external type references to+// our types can call it.+public func uniffiEnsureDownloadManagerInitialized() {+ switch initializationResult {+ case .ok:+ break+ case .contractVersionMismatch:+ fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")+ case .apiChecksumMismatch:+ fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }+}++// swiftlint:enable all\ No newline at end of filediff --git a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swiftindex fea4d4fbe..e9f0f13ed 100644--- a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift+++ b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift@@ -438,22 +438,6 @@ fileprivate struct FfiConverterInt64: FfiConverterPrimitive {}}-#if swift(>=5.8)-@_documentation(visibility: private)-#endif-fileprivate struct FfiConverterFloat: FfiConverterPrimitive {- typealias FfiType = Float- typealias SwiftType = Float-- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Float {- return try lift(readFloat(&buf))- }-- public static func write(_ value: Float, into buf: inout [UInt8]) {- writeFloat(&buf, lower(value))- }-}-#if swift(>=5.8)@_documentation(visibility: private)#endif@@ -726,7 +710,7 @@ public func FfiConverterTypeDownloader_lower(_ value: Downloader) -> UInt64 {public protocol DownloaderStreamProtocol: AnyObject, Sendable {- func next() async -> DownloaderStreamUpdate?+ func next() async -> DownloadState?}open class DownloaderStream: DownloaderStreamProtocol, @unchecked Sendable {@@ -782,7 +766,7 @@ open class DownloaderStream: DownloaderStreamProtocol, @unchecked Sendable {-open func next()async -> DownloaderStreamUpdate? {+open func next()async -> DownloadState? {returntry! await uniffiRustCallAsync(rustFutureFunc: {@@ -794,7 +778,7 @@ open func next()async -> DownloaderStreamUpdate? {pollFunc: ffi_uzu_rust_future_poll_rust_buffer,completeFunc: ffi_uzu_rust_future_complete_rust_buffer,freeFunc: ffi_uzu_rust_future_free_rust_buffer,- liftFunc: FfiConverterOptionTypeDownloaderStreamUpdate.lift,+ liftFunc: FfiConverterOptionTypeDownloadState.lift,errorHandler: nil)@@ -1998,166 +1982,6 @@ public func FfiConverterTypeDevice_lower(_ value: Device) -> RustBuffer {}-public struct DownloadState: Equatable, Hashable, Codable {- public var totalBytes: Int64- public var downloadedBytes: Int64- public var phase: DownloadPhase-- // Default memberwise initializers are never public by default, so we- // declare one manually.- public init(totalBytes: Int64, downloadedBytes: Int64, phase: DownloadPhase) {- self.totalBytes = totalBytes- self.downloadedBytes = downloadedBytes- self.phase = phase- }---public func canDelete() -> Bool {- return try! FfiConverterBool.lift(try! rustCall() {- uniffi_uzu_fn_method_downloadstate_can_delete(- FfiConverterTypeDownloadState_lower(self),$0- )-})-}--public func canPause() -> Bool {- return try! FfiConverterBool.lift(try! rustCall() {- uniffi_uzu_fn_method_downloadstate_can_pause(- FfiConverterTypeDownloadState_lower(self),$0- )-})-}--public func isInProgress() -> Bool {- return try! FfiConverterBool.lift(try! rustCall() {- uniffi_uzu_fn_method_downloadstate_is_in_progress(- FfiConverterTypeDownloadState_lower(self),$0- )-})-}--public func name() -> String {- return try! FfiConverterString.lift(try! rustCall() {- uniffi_uzu_fn_method_downloadstate_name(- FfiConverterTypeDownloadState_lower(self),$0- )-})-}--public func progress() -> Float {- return try! FfiConverterFloat.lift(try! rustCall() {- uniffi_uzu_fn_method_downloadstate_progress(- FfiConverterTypeDownloadState_lower(self),$0- )-})-}----}--#if compiler(>=6)-extension DownloadState: Sendable {}-#endif--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public struct FfiConverterTypeDownloadState: FfiConverterRustBuffer {- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadState {- return- try DownloadState(- totalBytes: FfiConverterInt64.read(from: &buf),- downloadedBytes: FfiConverterInt64.read(from: &buf),- phase: FfiConverterTypeDownloadPhase.read(from: &buf)- )- }-- public static func write(_ value: DownloadState, into buf: inout [UInt8]) {- FfiConverterInt64.write(value.totalBytes, into: &buf)- FfiConverterInt64.write(value.downloadedBytes, into: &buf)- FfiConverterTypeDownloadPhase.write(value.phase, into: &buf)- }-}---#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloadState_lift(_ buf: RustBuffer) throws -> DownloadState {- return try FfiConverterTypeDownloadState.lift(buf)-}--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloadState_lower(_ value: DownloadState) -> RustBuffer {- return FfiConverterTypeDownloadState.lower(value)-}---public struct DownloaderStreamUpdate: Equatable, Hashable, Codable {- public var bytesTotal: Int64- public var bytesDownloaded: Int64-- // Default memberwise initializers are never public by default, so we- // declare one manually.- public init(bytesTotal: Int64, bytesDownloaded: Int64) {- self.bytesTotal = bytesTotal- self.bytesDownloaded = bytesDownloaded- }---public func progress() -> Float {- return try! FfiConverterFloat.lift(try! rustCall() {- uniffi_uzu_fn_method_downloaderstreamupdate_progress(- FfiConverterTypeDownloaderStreamUpdate_lower(self),$0- )-})-}----}--#if compiler(>=6)-extension DownloaderStreamUpdate: Sendable {}-#endif--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public struct FfiConverterTypeDownloaderStreamUpdate: FfiConverterRustBuffer {- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloaderStreamUpdate {- return- try DownloaderStreamUpdate(- bytesTotal: FfiConverterInt64.read(from: &buf),- bytesDownloaded: FfiConverterInt64.read(from: &buf)- )- }-- public static func write(_ value: DownloaderStreamUpdate, into buf: inout [UInt8]) {- FfiConverterInt64.write(value.bytesTotal, into: &buf)- FfiConverterInt64.write(value.bytesDownloaded, into: &buf)- }-}---#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloaderStreamUpdate_lift(_ buf: RustBuffer) throws -> DownloaderStreamUpdate {- return try FfiConverterTypeDownloaderStreamUpdate.lift(buf)-}--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloaderStreamUpdate_lower(_ value: DownloaderStreamUpdate) -> RustBuffer {- return FfiConverterTypeDownloaderStreamUpdate.lower(value)-}--public struct EngineConfig: Equatable, Hashable, Codable {public var applicationIdentifier: String?public var miraiApiKey: String?@@ -2455,171 +2279,6 @@ public func FfiConverterTypeDeviceError_lower(_ value: DeviceError) -> RustBuffereturn FfiConverterTypeDeviceError.lower(value)}-// Note that we don't yet support `indirect` for enums.-// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.--public enum DownloadManagerType: Equatable, Hashable, Codable {-- case native- case universal------}--#if compiler(>=6)-extension DownloadManagerType: Sendable {}-#endif--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public struct FfiConverterTypeDownloadManagerType: FfiConverterRustBuffer {- typealias SwiftType = DownloadManagerType-- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadManagerType {- let variant: Int32 = try readInt(&buf)- switch variant {-- case 1: return .native-- case 2: return .universal-- default: throw UniffiInternalError.unexpectedEnumCase- }- }-- public static func write(_ value: DownloadManagerType, into buf: inout [UInt8]) {- switch value {--- case .native:- writeInt(&buf, Int32(1))--- case .universal:- writeInt(&buf, Int32(2))-- }- }-}---#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloadManagerType_lift(_ buf: RustBuffer) throws -> DownloadManagerType {- return try FfiConverterTypeDownloadManagerType.lift(buf)-}--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloadManagerType_lower(_ value: DownloadManagerType) -> RustBuffer {- return FfiConverterTypeDownloadManagerType.lower(value)-}---// Note that we don't yet support `indirect` for enums.-// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.--public enum DownloadPhase: Equatable, Hashable, Codable {-- case notDownloaded- case downloading- case paused- case downloaded- case locked- case error(message: String- )------}--#if compiler(>=6)-extension DownloadPhase: Sendable {}-#endif--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public struct FfiConverterTypeDownloadPhase: FfiConverterRustBuffer {- typealias SwiftType = DownloadPhase-- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadPhase {- let variant: Int32 = try readInt(&buf)- switch variant {-- case 1: return .notDownloaded-- case 2: return .downloading-- case 3: return .paused-- case 4: return .downloaded-- case 5: return .locked-- case 6: return .error(message: try FfiConverterString.read(from: &buf)- )-- default: throw UniffiInternalError.unexpectedEnumCase- }- }-- public static func write(_ value: DownloadPhase, into buf: inout [UInt8]) {- switch value {--- case .notDownloaded:- writeInt(&buf, Int32(1))--- case .downloading:- writeInt(&buf, Int32(2))--- case .paused:- writeInt(&buf, Int32(3))--- case .downloaded:- writeInt(&buf, Int32(4))--- case .locked:- writeInt(&buf, Int32(5))--- case let .error(message):- writeInt(&buf, Int32(6))- FfiConverterString.write(message, into: &buf)-- }- }-}---#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloadPhase_lift(_ buf: RustBuffer) throws -> DownloadPhase {- return try FfiConverterTypeDownloadPhase.lift(buf)-}--#if swift(>=5.8)-@_documentation(visibility: private)-#endif-public func FfiConverterTypeDownloadPhase_lower(_ value: DownloadPhase) -> RustBuffer {- return FfiConverterTypeDownloadPhase.lower(value)-}--public enum EngineError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {@@ -2637,7 +2296,6 @@ public enum EngineError: Swift.Error, Equatable, Hashable, Codable, Foundation.L)case UnableToCreateBackendcase BackendNotFound- case UnableToGetDownloaderProgressStreamcase ChatSession(ChatSessionError)case ClassificationSession(ClassificationSessionError@@ -2691,17 +2349,16 @@ public struct FfiConverterTypeEngineError: FfiConverterRustBuffer {)case 6: return .UnableToCreateBackendcase 7: return .BackendNotFound- case 8: return .UnableToGetDownloaderProgressStream- case 9: return .ChatSession(+ case 8: return .ChatSession(try FfiConverterTypeChatSessionError.read(from: &buf))- case 10: return .ClassificationSession(+ case 9: return .ClassificationSession(try FfiConverterTypeClassificationSessionError.read(from: &buf))- case 11: return .TextToSpeechSession(+ case 10: return .TextToSpeechSession(try FfiConverterTypeTextToSpeechSessionError.read(from: &buf))- case 12: return .SettingsNotAvailable+ case 11: return .SettingsNotAvailabledefault: throw UniffiInternalError.unexpectedEnumCase}@@ -2747,27 +2404,23 @@ public struct FfiConverterTypeEngineError: FfiConverterRustBuffer {writeInt(&buf, Int32(7))- case .UnableToGetDownloaderProgressStream:- writeInt(&buf, Int32(8))--case let .ChatSession(v1):- writeInt(&buf, Int32(9))+ writeInt(&buf, Int32(8))FfiConverterTypeChatSessionError.write(v1, into: &buf)case let .ClassificationSession(v1):- writeInt(&buf, Int32(10))+ writeInt(&buf, Int32(9))FfiConverterTypeClassificationSessionError.write(v1, into: &buf)case let .TextToSpeechSession(v1):- writeInt(&buf, Int32(11))+ writeInt(&buf, Int32(10))FfiConverterTypeTextToSpeechSessionError.write(v1, into: &buf)case .SettingsNotAvailable:- writeInt(&buf, Int32(12))+ writeInt(&buf, Int32(11))}}@@ -3114,21 +2767,13 @@ public enum StorageError: Swift.Error, Equatable, Hashable, Codable, Foundation.case UnableToCreateDirectory(path: String)- case UnableToCreateDownloadManager(message: String- )case DownloadManager(message: String)case HashNotFound(identifier: String, name: String)- case InvalidStateTransition(from: DownloadPhase, to: DownloadPhase- )- case Io(message: String- )- case ItemNotFound(identifier: String- )- case Registry(RegistryError+ case ModelNotFound(identifier: String)- case UnsupportedItem(identifier: String+ case UnsupportedModel(identifier: String)@@ -3162,30 +2807,17 @@ public struct FfiConverterTypeStorageError: FfiConverterRustBuffer {case 1: return .UnableToCreateDirectory(path: try FfiConverterString.read(from: &buf))- case 2: return .UnableToCreateDownloadManager(+ case 2: return .DownloadManager(message: try FfiConverterString.read(from: &buf))- case 3: return .DownloadManager(- message: try FfiConverterString.read(from: &buf)- )- case 4: return .HashNotFound(+ case 3: return .HashNotFound(identifier: try FfiConverterString.read(from: &buf),name: try FfiConverterString.read(from: &buf))- case 5: return .InvalidStateTransition(- from: try FfiConverterTypeDownloadPhase.read(from: &buf),- to: try FfiConverterTypeDownloadPhase.read(from: &buf)- )- case 6: return .Io(- message: try FfiConverterString.read(from: &buf)- )- case 7: return .ItemNotFound(+ case 4: return .ModelNotFound(identifier: try FfiConverterString.read(from: &buf))- case 8: return .Registry(- try FfiConverterTypeRegistryError.read(from: &buf)- )- case 9: return .UnsupportedItem(+ case 5: return .UnsupportedModel(identifier: try FfiConverterString.read(from: &buf))@@ -3205,45 +2837,24 @@ public struct FfiConverterTypeStorageError: FfiConverterRustBuffer {FfiConverterString.write(path, into: &buf)- case let .UnableToCreateDownloadManager(message):- writeInt(&buf, Int32(2))- FfiConverterString.write(message, into: &buf)--case let .DownloadManager(message):- writeInt(&buf, Int32(3))+ writeInt(&buf, Int32(2))FfiConverterString.write(message, into: &buf)case let .HashNotFound(identifier,name):- writeInt(&buf, Int32(4))+ writeInt(&buf, Int32(3))FfiConverterString.write(identifier, into: &buf)FfiConverterString.write(name, into: &buf)- case let .InvalidStateTransition(from,to):- writeInt(&buf, Int32(5))- FfiConverterTypeDownloadPhase.write(from, into: &buf)- FfiConverterTypeDownloadPhase.write(to, into: &buf)--- case let .Io(message):- writeInt(&buf, Int32(6))- FfiConverterString.write(message, into: &buf)--- case let .ItemNotFound(identifier):- writeInt(&buf, Int32(7))+ case let .ModelNotFound(identifier):+ writeInt(&buf, Int32(4))FfiConverterString.write(identifier, into: &buf)- case let .Registry(v1):- writeInt(&buf, Int32(8))- FfiConverterTypeRegistryError.write(v1, into: &buf)--- case let .UnsupportedItem(identifier):- writeInt(&buf, Int32(9))+ case let .UnsupportedModel(identifier):+ writeInt(&buf, Int32(5))FfiConverterString.write(identifier, into: &buf)}@@ -3411,30 +3022,6 @@ fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {}}-#if swift(>=5.8)-@_documentation(visibility: private)-#endif-fileprivate struct FfiConverterOptionTypeModel: FfiConverterRustBuffer {- typealias SwiftType = Model?-- public static func write(_ value: SwiftType, into buf: inout [UInt8]) {- guard let value = value else {- writeInt(&buf, Int8(0))- return- }- writeInt(&buf, Int8(1))- FfiConverterTypeModel.write(value, into: &buf)- }-- public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {- switch try readInt(&buf) as Int8 {- case 0: return nil- case 1: return try FfiConverterTypeModel.read(from: &buf)- default: throw UniffiInternalError.unexpectedOptionalTag- }- }-}-#if swift(>=5.8)@_documentation(visibility: private)#endif@@ -3462,8 +3049,8 @@ fileprivate struct FfiConverterOptionTypeDownloadState: FfiConverterRustBuffer {#if swift(>=5.8)@_documentation(visibility: private)#endif-fileprivate struct FfiConverterOptionTypeDownloaderStreamUpdate: FfiConverterRustBuffer {- typealias SwiftType = DownloaderStreamUpdate?+fileprivate struct FfiConverterOptionTypeModel: FfiConverterRustBuffer {+ typealias SwiftType = Model?public static func write(_ value: SwiftType, into buf: inout [UInt8]) {guard let value = value else {@@ -3471,13 +3058,13 @@ fileprivate struct FfiConverterOptionTypeDownloaderStreamUpdate: FfiConverterRusreturn}writeInt(&buf, Int8(1))- FfiConverterTypeDownloaderStreamUpdate.write(value, into: &buf)+ FfiConverterTypeModel.write(value, into: &buf)}public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {switch try readInt(&buf) as Int8 {case 0: return nil- case 1: return try FfiConverterTypeDownloaderStreamUpdate.read(from: &buf)+ case 1: return try FfiConverterTypeModel.read(from: &buf)default: throw UniffiInternalError.unexpectedOptionalTag}}@@ -3736,13 +3323,13 @@ private let initializationResult: InitializationResult = {if (uniffi_uzu_checksum_method_engine_classification() != 6465) {return InitializationResult.apiChecksumMismatch}- if (uniffi_uzu_checksum_method_engine_download() != 25329) {+ if (uniffi_uzu_checksum_method_engine_download() != 31558) {return InitializationResult.apiChecksumMismatch}- if (uniffi_uzu_checksum_method_engine_download_state() != 15736) {+ if (uniffi_uzu_checksum_method_engine_download_state() != 36334) {return InitializationResult.apiChecksumMismatch}- if (uniffi_uzu_checksum_method_engine_download_states() != 7129) {+ if (uniffi_uzu_checksum_method_engine_download_states() != 6598) {return InitializationResult.apiChecksumMismatch}if (uniffi_uzu_checksum_method_engine_downloader() != 59345) {@@ -3826,16 +3413,16 @@ private let initializationResult: InitializationResult = {if (uniffi_uzu_checksum_method_downloader_pause() != 36380) {return InitializationResult.apiChecksumMismatch}- if (uniffi_uzu_checksum_method_downloader_progress() != 21048) {+ if (uniffi_uzu_checksum_method_downloader_progress() != 28865) {return InitializationResult.apiChecksumMismatch}if (uniffi_uzu_checksum_method_downloader_resume() != 13815) {return InitializationResult.apiChecksumMismatch}- if (uniffi_uzu_checksum_method_downloader_state() != 23876) {+ if (uniffi_uzu_checksum_method_downloader_state() != 51713) {return InitializationResult.apiChecksumMismatch}- if (uniffi_uzu_checksum_method_downloaderstream_next() != 54036) {+ if (uniffi_uzu_checksum_method_downloaderstream_next() != 51573) {return InitializationResult.apiChecksumMismatch}if (uniffi_uzu_checksum_method_player_append_pcm_batch() != 29421) {@@ -3861,6 +3448,7 @@ private let initializationResult: InitializationResult = {}uniffiCallbackInitEngineCallbackHandler()+ uniffiEnsureDownloadManagerInitialized()uniffiEnsureNagareInitialized()uniffiEnsureShojiInitialized()return InitializationResult.okdiff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mtsindex 96d38b508..5134aa10d 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts@@ -1,5 +1,54 @@/* auto-generated by NAPI-RS *//* eslint-disable */+export declare class DownloadPhaseDownloaded {++ constructor()+}++export declare class DownloadPhaseDownloading {++ constructor()+}++export declare class DownloadPhaseError {+ message: string+ constructor(message: string)+}++export declare class DownloadPhaseLocked {+ managerId: string+ constructor(managerId: string)+}++export declare class DownloadPhaseNotDownloaded {++ constructor()+}++export declare class DownloadPhasePaused {++ constructor()+}++export declare class DownloadState {+ totalBytes: number+ downloadedBytes: number+ phase: DownloadPhase+ constructor(totalBytes: number, downloadedBytes: number, phase: DownloadPhase)+ get progress(): number+ get isInProgress(): boolean+ get canPause(): boolean+ get canDelete(): boolean+ get name(): string+}++export declare const enum DownloadManagerType {+ Native = 'Native',+ Universal = 'Universal'+}++export type DownloadPhase =+ DownloadPhaseNotDownloaded | DownloadPhaseDownloading | DownloadPhasePaused | DownloadPhaseDownloaded | DownloadPhaseLocked | DownloadPhaseError/*** A loaded chat backend instance (model weights, tokenizer, configuration).* Cloning is cheap and shares the underlying instance, so multiple [`ChatSession`]s@@ -481,7 +530,7 @@ export declare class Metadata {}export declare class Model {- identifier: string+ identifier: ModelIdentifierregistry: ModelRegistrybackends: Array<ModelBackend>family?: ModelFamily@@ -490,7 +539,7 @@ export declare class Model {specializations: Array<ModelSpecialization>accessibility: ModelAccessibilityencoding?: any- constructor(identifier: string, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any)+ constructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any)get name(): stringget isLocal(): booleanget isRemote(): boolean@@ -502,7 +551,7 @@ export declare class Model {get referenceName(): string | nullget checkpointVersion(): string | null- static external(identifier: string, registryIdentifier: string, registryName: string, backendIdentifier: string, backendName: string, backendVersion: string, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any | undefined | null): Model+ static external(identifier: ModelIdentifier, registryIdentifier: string, registryName: string, backendIdentifier: string, backendName: string, backendVersion: string, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any | undefined | null): Modelget isChatCapable(): booleanget isClassificationCapable(): booleanget isTextToSpeechCapable(): boolean@@ -818,6 +867,9 @@ export declare const enum ImageTheme {export type ModelAccessibility =ModelAccessibilityLocal | ModelAccessibilityRemote+export type ModelIdentifier =+ string+export type ModelReference =ModelReferenceMirai | ModelReferenceHuggingFace | ModelReferenceLocal@@ -881,57 +933,8 @@ export declare class Downloader {* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols*/export declare class DownloaderStream {- next(): Promise<DownloaderStreamUpdate | null>- [Symbol.asyncIterator](): AsyncGenerator<DownloaderStreamUpdate, void, undefined>-}--export declare class DownloaderStreamUpdate {- bytesTotal: number- bytesDownloaded: number- constructor(bytesTotal: number, bytesDownloaded: number)- get progress(): number-}--export declare class DownloadPhaseDownloaded {-- constructor()-}--export declare class DownloadPhaseDownloading {-- constructor()-}--export declare class DownloadPhaseError {- message: string- constructor(message: string)-}--export declare class DownloadPhaseLocked {-- constructor()-}--export declare class DownloadPhaseNotDownloaded {-- constructor()-}--export declare class DownloadPhasePaused {-- constructor()-}--export declare class DownloadState {- totalBytes: number- downloadedBytes: number- phase: DownloadPhase- constructor(totalBytes: number, downloadedBytes: number, phase: DownloadPhase)- get progress(): number- get isInProgress(): boolean- get canPause(): boolean- get canDelete(): boolean- get name(): string+ next(): Promise<DownloadState | null>+ [Symbol.asyncIterator](): AsyncGenerator<DownloadState, void, undefined>}export declare class Engine {@@ -954,14 +957,14 @@ export declare class Engine {get modelFamilies(): Promise<Array<ModelFamily>>modelsByFamily(familyIdentifier: string): Promise<Array<Model>>model(identifier: string): Promise<Model | null>- modelByIdentifier(identifier: string): Promise<Model | null>+ modelByIdentifier(identifier: ModelIdentifier): Promise<Model | null>modelByRepoId(repoId: string): Promise<Model | null>modelByPath(path: string): Promise<Model | null>modelPath(model: Model): Promise<string | null>downloader(model: Model): Downloaderdownload(model: Model): Promise<DownloaderStream>downloadState(model: Model): Promise<DownloadState | null>- get downloadStates(): Promise<Record<string, DownloadState>>+ get downloadStates(): Promise<Record<ModelIdentifier, DownloadState>>chat(model: Model, config: ChatConfig): Promise<ChatSession>chatInstance(model: Model, config: ChatConfig): Promise<ChatInstance>chatWithInstance(instance: ChatInstance): Promise<ChatSession>@@ -1023,14 +1026,6 @@ export declare class Settings {export type DeviceError =| { type: 'UnsupportedDevice' }-export declare const enum DownloadManagerType {- Native = 'Native',- Universal = 'Universal'-}--export type DownloadPhase =- DownloadPhaseNotDownloaded | DownloadPhaseDownloading | DownloadPhasePaused | DownloadPhaseDownloaded | DownloadPhaseLocked | DownloadPhaseError-export type EngineError =| { type: 'TokioError', message: string }| { type: 'Device', field0: DeviceError }@@ -1039,7 +1034,6 @@ export type EngineError =| { type: 'Registry', field0: RegistryError }| { type: 'UnableToCreateBackend' }| { type: 'BackendNotFound' }- | { type: 'UnableToGetDownloaderProgressStream' }| { type: 'ChatSession', field0: ChatSessionError }| { type: 'ClassificationSession', field0: ClassificationSessionError }| { type: 'TextToSpeechSession', field0: TextToSpeechSessionError }@@ -1064,11 +1058,7 @@ export type SettingsError =export type StorageError =| { type: 'UnableToCreateDirectory', path: string }- | { type: 'UnableToCreateDownloadManager', message: string }| { type: 'DownloadManager', message: string }- | { type: 'HashNotFound', identifier: string, name: string }- | { type: 'InvalidStateTransition', from: DownloadPhase, to: DownloadPhase }- | { type: 'IO', message: string }- | { type: 'ItemNotFound', identifier: string }- | { type: 'Registry', field0: RegistryError }- | { type: 'UnsupportedItem', identifier: string }+ | { type: 'HashNotFound', identifier: ModelIdentifier, name: string }+ | { type: 'ModelNotFound', identifier: ModelIdentifier }+ | { type: 'UnsupportedModel', identifier: ModelIdentifier }diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.tsindex 96d38b508..5134aa10d 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts@@ -1,5 +1,54 @@/* auto-generated by NAPI-RS *//* eslint-disable */+export declare class DownloadPhaseDownloaded {++ constructor()+}++export declare class DownloadPhaseDownloading {++ constructor()+}++export declare class DownloadPhaseError {+ message: string+ constructor(message: string)+}++export declare class DownloadPhaseLocked {+ managerId: string+ constructor(managerId: string)+}++export declare class DownloadPhaseNotDownloaded {++ constructor()+}++export declare class DownloadPhasePaused {++ constructor()+}++export declare class DownloadState {+ totalBytes: number+ downloadedBytes: number+ phase: DownloadPhase+ constructor(totalBytes: number, downloadedBytes: number, phase: DownloadPhase)+ get progress(): number+ get isInProgress(): boolean+ get canPause(): boolean+ get canDelete(): boolean+ get name(): string+}++export declare const enum DownloadManagerType {+ Native = 'Native',+ Universal = 'Universal'+}++export type DownloadPhase =+ DownloadPhaseNotDownloaded | DownloadPhaseDownloading | DownloadPhasePaused | DownloadPhaseDownloaded | DownloadPhaseLocked | DownloadPhaseError/*** A loaded chat backend instance (model weights, tokenizer, configuration).* Cloning is cheap and shares the underlying instance, so multiple [`ChatSession`]s@@ -481,7 +530,7 @@ export declare class Metadata {}export declare class Model {- identifier: string+ identifier: ModelIdentifierregistry: ModelRegistrybackends: Array<ModelBackend>family?: ModelFamily@@ -490,7 +539,7 @@ export declare class Model {specializations: Array<ModelSpecialization>accessibility: ModelAccessibilityencoding?: any- constructor(identifier: string, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any)+ constructor(identifier: ModelIdentifier, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any)get name(): stringget isLocal(): booleanget isRemote(): boolean@@ -502,7 +551,7 @@ export declare class Model {get referenceName(): string | nullget checkpointVersion(): string | null- static external(identifier: string, registryIdentifier: string, registryName: string, backendIdentifier: string, backendName: string, backendVersion: string, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any | undefined | null): Model+ static external(identifier: ModelIdentifier, registryIdentifier: string, registryName: string, backendIdentifier: string, backendName: string, backendVersion: string, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility, encoding?: any | undefined | null): Modelget isChatCapable(): booleanget isClassificationCapable(): booleanget isTextToSpeechCapable(): boolean@@ -818,6 +867,9 @@ export declare const enum ImageTheme {export type ModelAccessibility =ModelAccessibilityLocal | ModelAccessibilityRemote+export type ModelIdentifier =+ string+export type ModelReference =ModelReferenceMirai | ModelReferenceHuggingFace | ModelReferenceLocal@@ -881,57 +933,8 @@ export declare class Downloader {* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols*/export declare class DownloaderStream {- next(): Promise<DownloaderStreamUpdate | null>- [Symbol.asyncIterator](): AsyncGenerator<DownloaderStreamUpdate, void, undefined>-}--export declare class DownloaderStreamUpdate {- bytesTotal: number- bytesDownloaded: number- constructor(bytesTotal: number, bytesDownloaded: number)- get progress(): number-}--export declare class DownloadPhaseDownloaded {-- constructor()-}--export declare class DownloadPhaseDownloading {-- constructor()-}--export declare class DownloadPhaseError {- message: string- constructor(message: string)-}--export declare class DownloadPhaseLocked {-- constructor()-}--export declare class DownloadPhaseNotDownloaded {-- constructor()-}--export declare class DownloadPhasePaused {-- constructor()-}--export declare class DownloadState {- totalBytes: number- downloadedBytes: number- phase: DownloadPhase- constructor(totalBytes: number, downloadedBytes: number, phase: DownloadPhase)- get progress(): number- get isInProgress(): boolean- get canPause(): boolean- get canDelete(): boolean- get name(): string+ next(): Promise<DownloadState | null>+ [Symbol.asyncIterator](): AsyncGenerator<DownloadState, void, undefined>}export declare class Engine {@@ -954,14 +957,14 @@ export declare class Engine {get modelFamilies(): Promise<Array<ModelFamily>>modelsByFamily(familyIdentifier: string): Promise<Array<Model>>model(identifier: string): Promise<Model | null>- modelByIdentifier(identifier: string): Promise<Model | null>+ modelByIdentifier(identifier: ModelIdentifier): Promise<Model | null>modelByRepoId(repoId: string): Promise<Model | null>modelByPath(path: string): Promise<Model | null>modelPath(model: Model): Promise<string | null>downloader(model: Model): Downloaderdownload(model: Model): Promise<DownloaderStream>downloadState(model: Model): Promise<DownloadState | null>- get downloadStates(): Promise<Record<string, DownloadState>>+ get downloadStates(): Promise<Record<ModelIdentifier, DownloadState>>chat(model: Model, config: ChatConfig): Promise<ChatSession>chatInstance(model: Model, config: ChatConfig): Promise<ChatInstance>chatWithInstance(instance: ChatInstance): Promise<ChatSession>@@ -1023,14 +1026,6 @@ export declare class Settings {export type DeviceError =| { type: 'UnsupportedDevice' }-export declare const enum DownloadManagerType {- Native = 'Native',- Universal = 'Universal'-}--export type DownloadPhase =- DownloadPhaseNotDownloaded | DownloadPhaseDownloading | DownloadPhasePaused | DownloadPhaseDownloaded | DownloadPhaseLocked | DownloadPhaseError-export type EngineError =| { type: 'TokioError', message: string }| { type: 'Device', field0: DeviceError }@@ -1039,7 +1034,6 @@ export type EngineError =| { type: 'Registry', field0: RegistryError }| { type: 'UnableToCreateBackend' }| { type: 'BackendNotFound' }- | { type: 'UnableToGetDownloaderProgressStream' }| { type: 'ChatSession', field0: ChatSessionError }| { type: 'ClassificationSession', field0: ClassificationSessionError }| { type: 'TextToSpeechSession', field0: TextToSpeechSessionError }@@ -1064,11 +1058,7 @@ export type SettingsError =export type StorageError =| { type: 'UnableToCreateDirectory', path: string }- | { type: 'UnableToCreateDownloadManager', message: string }| { type: 'DownloadManager', message: string }- | { type: 'HashNotFound', identifier: string, name: string }- | { type: 'InvalidStateTransition', from: DownloadPhase, to: DownloadPhase }- | { type: 'IO', message: string }- | { type: 'ItemNotFound', identifier: string }- | { type: 'Registry', field0: RegistryError }- | { type: 'UnsupportedItem', identifier: string }+ | { type: 'HashNotFound', identifier: ModelIdentifier, name: string }+ | { type: 'ModelNotFound', identifier: ModelIdentifier }+ | { type: 'UnsupportedModel', identifier: ModelIdentifier }diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.js b/crates/legacy/uzu/bindings/typescript/src/napi/index.jsindex 8cca77c77..898f39cf7 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.js+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.js@@ -508,6 +508,14 @@ if (!nativeBinding) {}module.exports = nativeBinding+module.exports.DownloadPhaseDownloaded = nativeBinding.DownloadPhaseDownloaded+module.exports.DownloadPhaseDownloading = nativeBinding.DownloadPhaseDownloading+module.exports.DownloadPhaseError = nativeBinding.DownloadPhaseError+module.exports.DownloadPhaseLocked = nativeBinding.DownloadPhaseLocked+module.exports.DownloadPhaseNotDownloaded = nativeBinding.DownloadPhaseNotDownloaded+module.exports.DownloadPhasePaused = nativeBinding.DownloadPhasePaused+module.exports.DownloadState = nativeBinding.DownloadState+module.exports.DownloadManagerType = nativeBinding.DownloadManagerTypemodule.exports.ChatInstance = nativeBinding.ChatInstancemodule.exports.ChatSession = nativeBinding.ChatSessionmodule.exports.ChatSessionStream = nativeBinding.ChatSessionStream@@ -618,18 +626,9 @@ module.exports.ReasoningEffort = nativeBinding.ReasoningEffortmodule.exports.Device = nativeBinding.Devicemodule.exports.Downloader = nativeBinding.Downloadermodule.exports.DownloaderStream = nativeBinding.DownloaderStream-module.exports.DownloaderStreamUpdate = nativeBinding.DownloaderStreamUpdate-module.exports.DownloadPhaseDownloaded = nativeBinding.DownloadPhaseDownloaded-module.exports.DownloadPhaseDownloading = nativeBinding.DownloadPhaseDownloading-module.exports.DownloadPhaseError = nativeBinding.DownloadPhaseError-module.exports.DownloadPhaseLocked = nativeBinding.DownloadPhaseLocked-module.exports.DownloadPhaseNotDownloaded = nativeBinding.DownloadPhaseNotDownloaded-module.exports.DownloadPhasePaused = nativeBinding.DownloadPhasePaused-module.exports.DownloadState = nativeBinding.DownloadStatemodule.exports.Engine = nativeBinding.Enginemodule.exports.EngineCallback = nativeBinding.EngineCallbackmodule.exports.EngineConfig = nativeBinding.EngineConfigmodule.exports.Player = nativeBinding.Playermodule.exports.Settings = nativeBinding.Settings-module.exports.DownloadManagerType = nativeBinding.DownloadManagerTypemodule.exports.SettingKind = nativeBinding.SettingKinddiff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.mjs b/crates/legacy/uzu/bindings/typescript/src/napi/index.mjsindex 624762937..ca539a656 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.mjs+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.mjs@@ -5,6 +5,14 @@ import cjs from './index.js';export default cjs;+export const DownloadPhaseDownloaded = cjs.DownloadPhaseDownloaded;+export const DownloadPhaseDownloading = cjs.DownloadPhaseDownloading;+export const DownloadPhaseError = cjs.DownloadPhaseError;+export const DownloadPhaseLocked = cjs.DownloadPhaseLocked;+export const DownloadPhaseNotDownloaded = cjs.DownloadPhaseNotDownloaded;+export const DownloadPhasePaused = cjs.DownloadPhasePaused;+export const DownloadState = cjs.DownloadState;+export const DownloadManagerType = cjs.DownloadManagerType;export const ChatInstance = cjs.ChatInstance;export const ChatSession = cjs.ChatSession;export const ChatSessionStream = cjs.ChatSessionStream;@@ -115,18 +123,9 @@ export const ReasoningEffort = cjs.ReasoningEffort;export const Device = cjs.Device;export const Downloader = cjs.Downloader;export const DownloaderStream = cjs.DownloaderStream;-export const DownloaderStreamUpdate = cjs.DownloaderStreamUpdate;-export const DownloadPhaseDownloaded = cjs.DownloadPhaseDownloaded;-export const DownloadPhaseDownloading = cjs.DownloadPhaseDownloading;-export const DownloadPhaseError = cjs.DownloadPhaseError;-export const DownloadPhaseLocked = cjs.DownloadPhaseLocked;-export const DownloadPhaseNotDownloaded = cjs.DownloadPhaseNotDownloaded;-export const DownloadPhasePaused = cjs.DownloadPhasePaused;-export const DownloadState = cjs.DownloadState;export const Engine = cjs.Engine;export const EngineCallback = cjs.EngineCallback;export const EngineConfig = cjs.EngineConfig;export const Player = cjs.Player;export const Settings = cjs.Settings;-export const DownloadManagerType = cjs.DownloadManagerType;export const SettingKind = cjs.SettingKind;diff --git a/crates/legacy/uzu/src/engine/config.rs b/crates/legacy/uzu/src/engine/config.rsindex 4c63aec0e..7fa559993 100644--- a/crates/legacy/uzu/src/engine/config.rs+++ b/crates/legacy/uzu/src/engine/config.rs@@ -3,8 +3,8 @@ use std::env;use serde::{Deserialize, Serialize};use crate::{- engine::DownloadManagerType,settings::{SettingKind, Settings, SettingsError},+ storage::DownloadManagerType,};pub const KEY_MIRAI_API_KEY: &str = "MIRAI_API_KEY";diff --git a/crates/legacy/uzu/src/engine/download_manager.rs b/crates/legacy/uzu/src/engine/download_manager.rsdeleted file mode 100644index beb91b546..000000000--- a/crates/legacy/uzu/src/engine/download_manager.rs+++ /dev/null@@ -1,30 +0,0 @@-use download_manager::FileDownloadManagerType;-use serde::{Deserialize, Serialize};--#[bindings::export(Enumeration)]-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]-#[serde(rename_all = "snake_case")]-pub enum DownloadManagerType {- #[cfg(target_vendor = "apple")]- Native,- Universal,-}--impl Default for DownloadManagerType {- #[allow(unreachable_code)]- fn default() -> Self {- #[cfg(target_vendor = "apple")]- return Self::Native;- Self::Universal- }-}--impl From<DownloadManagerType> for FileDownloadManagerType {- fn from(value: DownloadManagerType) -> Self {- match value {- #[cfg(target_vendor = "apple")]- DownloadManagerType::Native => Self::Apple,- DownloadManagerType::Universal => Self::Universal,- }- }-}diff --git a/crates/legacy/uzu/src/engine/downloader.rs b/crates/legacy/uzu/src/engine/downloader.rsindex feb6c2214..3e6cc3bb6 100644--- a/crates/legacy/uzu/src/engine/downloader.rs+++ b/crates/legacy/uzu/src/engine/downloader.rs@@ -1,242 +1,60 @@-use serde::{Deserialize, Serialize};-use tokio_stream::{StreamExt, wrappers::BroadcastStream};+use std::sync::Arc;++use shoji::types::model::ModelIdentifier;use crate::{- engine::EngineError,- helpers::SharedAccess,- storage::{- Storage, StorageError,- types::{DownloadPhase, DownloadState},- },+ engine::{DownloaderStream, EngineError},+ storage::{DownloadState, Storage},};#[bindings::export(Class)]#[derive(Clone)]pub struct Downloader {- identifier: String,- storage: SharedAccess<Storage>,+ identifier: ModelIdentifier,+ storage: Arc<Storage>,}impl Downloader {pub fn new(- identifier: String,- storage: SharedAccess<Storage>,+ identifier: ModelIdentifier,+ storage: Arc<Storage>,) -> Self {Self {identifier,storage,}}-- async fn wait_for_resume_to_be_observable(- &self,- mut stream: BroadcastStream<(String, DownloadState)>,- ) -> Result<(), EngineError> {- if self.state().await.is_some_and(|state| Self::is_resume_observable_phase(&state.phase)) {- return Ok(());- }-- while let Some(result) = stream.next().await {- match result {- Ok((identifier, state)) if identifier == self.identifier => {- if Self::is_resume_observable_phase(&state.phase) {- return Ok(());- }- },- Ok(_) => {},- Err(error) => {- tracing::warn!(- identifier = self.identifier,- ?error,- "downloader resume stream lagged; some updates were dropped"- );- },- }- }-- Err(EngineError::UnableToGetDownloaderProgressStream {})- }-- fn is_progress_streaming_phase(phase: &DownloadPhase) -> bool {- matches!(phase, DownloadPhase::Downloading {})- }-- fn is_resume_observable_phase(phase: &DownloadPhase) -> bool {- matches!(phase, DownloadPhase::Downloading {} | DownloadPhase::Downloaded {} | DownloadPhase::Error { .. })- }}#[bindings::export(Implementation)]impl Downloader {#[bindings::export(Method(Getter))]pub async fn state(&self) -> Option<DownloadState> {- self.storage.lock().await.state(&self.identifier).await+ self.storage.state(&self.identifier).await.ok()}#[bindings::export(Method)]pub async fn resume(&self) -> Result<(), EngineError> {- let state = self.state().await.ok_or(StorageError::ItemNotFound {- identifier: self.identifier.clone(),- })?;-- match state.phase {- DownloadPhase::Downloading {} | DownloadPhase::Downloaded {} => Ok(()),- DownloadPhase::NotDownloaded {} | DownloadPhase::Paused {} | DownloadPhase::Locked {} => {- let stream = self.storage.lock().await.subscribe();- self.storage.lock().await.download(&self.identifier).await?;- self.wait_for_resume_to_be_observable(stream).await- },- DownloadPhase::Error {- ..- } => {- let stream = self.storage.lock().await.subscribe();- let storage = self.storage.lock().await;- storage.delete(&self.identifier).await?;- storage.download(&self.identifier).await?;- drop(storage);- self.wait_for_resume_to_be_observable(stream).await- },- }+ Ok(self.storage.download(&self.identifier).await?)}#[bindings::export(Method)]pub async fn pause(&self) -> Result<(), EngineError> {- Ok(self.storage.lock().await.pause(&self.identifier).await?)+ Ok(self.storage.pause(&self.identifier).await?)}#[bindings::export(Method)]pub async fn delete(&self) -> Result<(), EngineError> {- Ok(self.storage.lock().await.delete(&self.identifier).await?)+ Ok(self.storage.delete(&self.identifier).await?)}#[bindings::export(Method)]pub async fn progress(&self) -> Result<DownloaderStream, EngineError> {- let Some(state) = self.state().await else {- return Err(EngineError::UnableToGetDownloaderProgressStream {});- };- if !Self::is_progress_streaming_phase(&state.phase) {+ let events = self.storage.subscribe();+ let state = self.storage.state(&self.identifier).await?;+ if !state.is_in_progress() {return Ok(DownloaderStream::empty(self.identifier.clone()));}- let stream = self.storage.lock().await.subscribe();- Ok(DownloaderStream::new(self.identifier.clone(), stream, self.storage.clone()))- }-}--#[bindings::export(Class(Stream))]-#[derive(Clone)]-pub struct DownloaderStream {- identifier: String,- stream: SharedAccess<Option<BroadcastStream<(String, DownloadState)>>>,- storage: Option<SharedAccess<Storage>>,-}--impl DownloaderStream {- pub(crate) fn new(- identifier: String,- stream: BroadcastStream<(String, DownloadState)>,- storage: SharedAccess<Storage>,- ) -> Self {- Self {- identifier,- stream: SharedAccess::new(Some(stream)),- storage: Some(storage),- }- }-- pub(crate) fn empty(identifier: String) -> Self {- Self {- identifier,- stream: SharedAccess::new(None),- storage: None,- }- }-- /// A transient non-`Downloading` phase (for example a momentary `Paused`- /// while a download is being resumed) is superseded by `Downloading` almost- /// immediately, whereas a real pause/stop persists. Poll the canonical state- /// briefly to tell them apart so a blip does not permanently end the stream.- async fn download_has_settled(&self) -> bool {- let Some(storage) = self.storage.as_ref() else {- return true;- };- for _ in 0..10 {- match storage.lock().await.state(&self.identifier).await {- Some(state) if matches!(state.phase, DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}) => {- return false;- },- Some(_) => {},- None => return true,- }- tokio::time::sleep(std::time::Duration::from_millis(20)).await;- }- true- }-}--#[bindings::export(Implementation)]-impl DownloaderStream {- #[bindings::export(Method(StreamNext))]- pub async fn next(&self) -> Option<DownloaderStreamUpdate> {- let mut stream_guard = self.stream.lock().await;- let stream = stream_guard.as_mut()?;- while let Some(result) = stream.next().await {- match result {- Ok((identifier, state)) => {- if identifier == self.identifier {- let update = DownloaderStreamUpdate {- bytes_total: state.total_bytes,- bytes_downloaded: state.downloaded_bytes,- };- let stream_ended = match state.phase {- // Still actively downloading: keep streaming.- DownloadPhase::Downloading {} => false,- // Terminal: the download is over either way.- DownloadPhase::Downloaded {}- | DownloadPhase::Error {- ..- } => true,- // Possibly a transient blip while (re)starting. End the- // stream only if the model has genuinely stopped, so a- // momentary state change does not cut off progress for a- // download that is still on its way to completion.- DownloadPhase::Paused {} | DownloadPhase::NotDownloaded {} | DownloadPhase::Locked {} => {- self.download_has_settled().await- },- };- if stream_ended {- *stream_guard = None;- }- return Some(update);- }- },- Err(error) => {- tracing::warn!(- identifier = self.identifier,- ?error,- "downloader progress stream lagged; some updates were dropped"- );- },- }- }- None- }-}--#[bindings::export(Structure(Class))]-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]-pub struct DownloaderStreamUpdate {- pub bytes_total: i64,- pub bytes_downloaded: i64,-}--#[bindings::export(Implementation)]-impl DownloaderStreamUpdate {- #[bindings::export(Method(Getter))]- pub fn progress(&self) -> f32 {- if self.bytes_total == 0 {- 0.0- } else {- self.bytes_downloaded as f32 / self.bytes_total as f32- }+ Ok(DownloaderStream::new(self.identifier.clone(), events))}}diff --git a/crates/legacy/uzu/src/engine/downloader_stream.rs b/crates/legacy/uzu/src/engine/downloader_stream.rsnew file mode 100644index 000000000..894654b9a--- /dev/null+++ b/crates/legacy/uzu/src/engine/downloader_stream.rs@@ -0,0 +1,59 @@+use shoji::types::model::ModelIdentifier;+use tokio_stream::{StreamExt, wrappers::BroadcastStream};++use crate::{helpers::SharedAccess, storage::DownloadState};++#[bindings::export(Class(Stream))]+#[derive(Clone)]+pub struct DownloaderStream {+ identifier: ModelIdentifier,+ stream: SharedAccess<Option<BroadcastStream<(ModelIdentifier, DownloadState)>>>,+}++impl DownloaderStream {+ pub fn new(+ identifier: ModelIdentifier,+ stream: BroadcastStream<(ModelIdentifier, DownloadState)>,+ ) -> Self {+ Self {+ identifier,+ stream: SharedAccess::new(Some(stream)),+ }+ }++ pub fn empty(identifier: ModelIdentifier) -> Self {+ Self {+ identifier,+ stream: SharedAccess::new(None),+ }+ }+}++#[bindings::export(Implementation)]+impl DownloaderStream {+ #[bindings::export(Method(StreamNext))]+ pub async fn next(&self) -> Option<DownloadState> {+ let mut stream_guard = self.stream.lock().await;+ let stream = stream_guard.as_mut()?;+ while let Some(result) = stream.next().await {+ match result {+ Ok((identifier, state)) => {+ if identifier == self.identifier {+ if !state.is_in_progress() {+ *stream_guard = None;+ }+ return Some(state);+ }+ },+ Err(error) => {+ tracing::warn!(+ identifier = self.identifier,+ ?error,+ "downloader progress stream lagged; some updates were dropped"+ );+ },+ }+ }+ None+ }+}diff --git a/crates/legacy/uzu/src/engine/error.rs b/crates/legacy/uzu/src/engine/error.rsindex 844726a8c..51175fd74 100644--- a/crates/legacy/uzu/src/engine/error.rs+++ b/crates/legacy/uzu/src/engine/error.rs@@ -18,8 +18,6 @@ pub enum EngineError {UnableToCreateBackend {},#[error("Backend not found")]BackendNotFound {},- #[error("Unable to get downloader progress stream")]- UnableToGetDownloaderProgressStream {},#[error(transparent)]ChatSession(#[from] nagare::chat::ChatSessionError),#[error(transparent)]diff --git a/crates/legacy/uzu/src/engine/mod.rs b/crates/legacy/uzu/src/engine/mod.rsindex 0cb58de75..8fa794e2e 100644--- a/crates/legacy/uzu/src/engine/mod.rs+++ b/crates/legacy/uzu/src/engine/mod.rs@@ -1,8 +1,8 @@pub mod bridge;mod callback;pub mod config;-mod download_manager;mod downloader;+mod downloader_stream;mod error;use std::{collections::HashMap, sync::Arc};@@ -10,8 +10,8 @@ use std::{collections::HashMap, sync::Arc};use backend_remote::openai::Backend as OpenAIBackend;pub use callback::{EngineCallback, EngineCallbackType};pub use config::EngineConfig;-pub use download_manager::DownloadManagerType;-pub use downloader::{Downloader, DownloaderStream, DownloaderStreamUpdate};+pub use downloader::Downloader;+pub use downloader_stream::DownloaderStream;pub use error::EngineError;use indexmap::IndexSet;use kiban::rt::RuntimeHandle;@@ -24,7 +24,7 @@ use nagare::{use shoji::{traits::{Backend, Registry},types::{- model::{Model, ModelFamily, ModelRegistry, ModelVendor},+ model::{Model, ModelFamily, ModelIdentifier, ModelRegistry, ModelVendor},session::chat::ChatConfig,},};@@ -42,10 +42,7 @@ use crate::{openai::{Config as OpenAIConfig, Registry as OpenAIRegistry},},settings::Settings,- storage::{- Config as StorageConfig, Storage,- types::{DownloadPhase, DownloadState},- },+ storage::{Config as StorageConfig, DownloadPhase, DownloadState, Storage},};#[bindings::export(Class)]@@ -53,7 +50,7 @@ use crate::{pub struct Engine {settings: SharedAccess<Option<Settings>>,registry: SharedAccess<MergedRegistry>,- storage: SharedAccess<Storage>,+ storage: Arc<Storage>,backends: SharedAccess<HashMap<String, Arc<dyn Backend>>>,callback: SharedAccess<Option<Arc<EngineCallback>>>,telemetry: SharedAccess<Telemetry>,@@ -92,12 +89,11 @@ impl Engine {});let registry = SharedAccess::new(MergedRegistry::new(vec![]));- let storage_config = StorageConfig::new(device.clone(), None, "mirai".to_string())- .with_download_manager_type(config.download_manager_type.into());- let storage_cache_path = storage_config.cache_path();- logs::start(storage_config.cache_path(), &storage_config.log_name(), false);-- let storage = SharedAccess::new(Storage::new(runtime_handle, storage_config).await?);+ let storage_config =+ StorageConfig::new(device.clone(), None, "mirai".to_string(), config.download_manager_type);+ let storage_cache_path = Storage::cache_path(&storage_config);+ logs::start(storage_cache_path.clone(), &format!("{}.log", storage_config.name), false);+ let storage = Arc::new(Storage::new(runtime_handle, storage_config).await?);let engine = Self {settings: SharedAccess::new(settings),@@ -382,7 +378,7 @@ impl Engine {#[bindings::export(Method)]pub async fn model_by_identifier(&self,- identifier: String,+ identifier: ModelIdentifier,) -> Result<Option<Model>, EngineError> {self.registry.lock().await.model_by_identifier(&identifier).await.map_err(EngineError::from)}@@ -423,20 +419,11 @@ impl Engine {if let Some(local_external_path) = model.local_external_path() {return Some(local_external_path);}- let storage = self.storage.lock().await;- let state = storage.state(&model.identifier).await?;- match state.phase {- DownloadPhase::Downloaded {} => {- storage.config.cache_model_path(model).map(|path| path.to_string_lossy().to_string())- },- DownloadPhase::NotDownloaded {}- | DownloadPhase::Downloading {}- | DownloadPhase::Paused {}- | DownloadPhase::Locked {}- | DownloadPhase::Error {- ..- } => None,+ let state = self.storage.state(&model.identifier).await.ok()?;+ if !matches!(state.phase, DownloadPhase::Downloaded {}) {+ return None;}+ self.storage.cache_model_path(model).map(|path| path.to_string_lossy().to_string())}#[bindings::export(Method)]@@ -444,7 +431,7 @@ impl Engine {&self,model: &Model,) -> Downloader {- Downloader::new(model.identifier.clone(), self.storage.clone())+ Downloader::new(model.identifier.clone(), Arc::clone(&self.storage))}#[bindings::export(Method)]@@ -457,12 +444,6 @@ impl Engine {}let downloader = self.downloader(model);- let Some(state) = downloader.state().await else {- return Err(EngineError::UnableToGetDownloaderProgressStream {});- };- if matches!(state.phase, DownloadPhase::Downloaded {}) {- return Ok(DownloaderStream::empty(model.identifier.clone()));- }downloader.resume().await?;downloader.progress().await}@@ -476,8 +457,8 @@ impl Engine {}#[bindings::export(Method(Getter))]- pub async fn download_states(&self) -> HashMap<String, DownloadState> {- self.storage.lock().await.states().await+ pub async fn download_states(&self) -> HashMap<ModelIdentifier, DownloadState> {+ self.storage.states().await}}@@ -561,13 +542,13 @@ impl Engine {}impl Engine {- pub async fn storage_subscribe(&self) -> BroadcastStream<(String, DownloadState)> {- self.storage.lock().await.subscribe()+ pub fn storage_subscribe(&self) -> BroadcastStream<(ModelIdentifier, DownloadState)> {+ self.storage.subscribe()}async fn handle_registry_refresh(&self) -> Result<(), EngineError> {let models = self.registry.lock().await.models().await?;- self.storage.lock().await.refresh(models).await?;+ self.storage.refresh(&models).await?;if let Some(callback) = self.callback.lock().await.as_ref().cloned() {callback.on_event();};@@ -575,11 +556,11 @@ impl Engine {}async fn spawn_storage_listener(&self) {- let mut stream = self.storage_subscribe().await;+ let mut stream = self.storage_subscribe();let callback = self.callback.clone();let telemetry = self.telemetry.lock().await.clone();- tokio::spawn(async move {- let mut last_phase: HashMap<String, DownloadPhase> = HashMap::new();+ kiban::rt::spawn(async move {+ let mut last_phase: HashMap<ModelIdentifier, DownloadPhase> = HashMap::new();while let Some(update) = stream.next().await {let Ok((id, state)) = update else {continue;diff --git a/crates/legacy/uzu/src/lib.rs b/crates/legacy/uzu/src/lib.rsindex 6db09af94..3d632e5f7 100644--- a/crates/legacy/uzu/src/lib.rs+++ b/crates/legacy/uzu/src/lib.rs@@ -31,6 +31,16 @@ pyo3_stub_gen::define_stub_info_gatherer!(pyo3_bindings_annotations);#[cfg(feature = "bindings-pyo3")]pyo3_stub_gen::reexport_module_members!("uzu" from "uzu._tool"; "UzuToolFunction", "uzu_tool_function");+#[cfg(feature = "bindings-pyo3")]+inventory::submit! {+ pyo3_stub_gen::type_info::TypeAliasInfo {+ name: "ModelIdentifier",+ module: "uzu",+ r#type: <String as pyo3_stub_gen::PyStubType>::type_output,+ doc: "",+ }+}+#[cfg(not(target_family = "wasm"))]pub mod device;#[cfg(not(target_family = "wasm"))]diff --git a/crates/legacy/uzu/src/registry/cached.rs b/crates/legacy/uzu/src/registry/cached.rsindex 3f60d544b..7120dbff3 100644--- a/crates/legacy/uzu/src/registry/cached.rs+++ b/crates/legacy/uzu/src/registry/cached.rs@@ -17,18 +17,13 @@ impl CachedRegistry {models: Mutex::new(None),}}-- pub async fn clear(&self) {- let mut cached_models = self.models.lock().await;- *cached_models = None;- }}impl Registry for CachedRegistry {type Error = RegistryError;- fn indentifier(&self) -> String {- self.registry.indentifier()+ fn identifier(&self) -> String {+ self.registry.identifier()}fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {diff --git a/crates/legacy/uzu/src/registry/fixed.rs b/crates/legacy/uzu/src/registry/fixed.rsdeleted file mode 100644index c777b1890..000000000--- a/crates/legacy/uzu/src/registry/fixed.rs+++ /dev/null@@ -1,37 +0,0 @@-use std::{future::Future, pin::Pin};--use shoji::{traits::Registry, types::model::Model};-use tokio::sync::Mutex;--use crate::registry::RegistryError;--pub struct FixedRegistry {- identifier: String,- models: Mutex<Vec<Model>>,-}--impl FixedRegistry {- pub fn new(- identifier: String,- models: Vec<Model>,- ) -> Self {- Self {- identifier,- models: Mutex::new(models),- }- }-}--impl Registry for FixedRegistry {- type Error = RegistryError;-- fn indentifier(&self) -> String {- self.identifier.clone()- }-- fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {- Box::pin(async {- return Ok(self.models.lock().await.clone());- })- }-}diff --git a/crates/legacy/uzu/src/registry/local/mod.rs b/crates/legacy/uzu/src/registry/local/mod.rsindex 15c0842c2..1c52548db 100644--- a/crates/legacy/uzu/src/registry/local/mod.rs+++ b/crates/legacy/uzu/src/registry/local/mod.rs@@ -29,7 +29,7 @@ impl Registry {impl RegistryTrait for Registry {type Error = RegistryError;- fn indentifier(&self) -> String {+ fn identifier(&self) -> String {self.config.identifier.clone()}diff --git a/crates/legacy/uzu/src/registry/merged.rs b/crates/legacy/uzu/src/registry/merged.rsindex 57aa502ac..eb801c233 100644--- a/crates/legacy/uzu/src/registry/merged.rs+++ b/crates/legacy/uzu/src/registry/merged.rs@@ -19,9 +19,9 @@ impl MergedRegistry {&mut self,registry: Box<dyn Registry<Error = RegistryError>>,) -> Result<(), RegistryError> {- if self.registries.iter().any(|current_registry| current_registry.indentifier() == registry.indentifier()) {+ if self.registries.iter().any(|current_registry| current_registry.identifier() == registry.identifier()) {return Err(RegistryError::UnableToAddRegistry {- identifier: registry.indentifier(),+ identifier: registry.identifier(),});}self.registries.push(registry);@@ -32,7 +32,7 @@ impl MergedRegistry {&mut self,identifier: &str,) -> Result<(), RegistryError> {- self.registries.retain(|registry| registry.indentifier() != identifier);+ self.registries.retain(|registry| registry.identifier() != identifier);Ok(())}}@@ -40,8 +40,8 @@ impl MergedRegistry {impl Registry for MergedRegistry {type Error = RegistryError;- fn indentifier(&self) -> String {- self.registries.iter().map(|registry| registry.indentifier()).collect::<Vec<String>>().join(":")+ fn identifier(&self) -> String {+ self.registries.iter().map(|registry| registry.identifier()).collect::<Vec<String>>().join(":")}fn models(&self) -> Pin<Box<dyn Future<Output = Result<Vec<Model>, RegistryError>> + Send + '_>> {@@ -53,7 +53,7 @@ impl Registry for MergedRegistry {match result {Ok(registry_models) => models.extend(registry_models),Err(error) => {- tracing::warn!(?error, registry = %registry.indentifier(), "skipping registry that failed to list models");+ tracing::warn!(?error, registry = %registry.identifier(), "skipping registry that failed to list models");},}}diff --git a/crates/legacy/uzu/src/registry/mirai/registry.rs b/crates/legacy/uzu/src/registry/mirai/registry.rsindex 09809db46..2d4dabdd0 100644--- a/crates/legacy/uzu/src/registry/mirai/registry.rs+++ b/crates/legacy/uzu/src/registry/mirai/registry.rs@@ -1,6 +1,7 @@use std::{fs::{read_to_string, write},future::Future,+ io,path::PathBuf,pin::Pin,};@@ -49,7 +50,7 @@ impl Registry {impl RegistryTrait for Registry {type Error = RegistryError;- fn indentifier(&self) -> String {+ fn identifier(&self) -> String {"mirai".to_string()}@@ -57,7 +58,10 @@ impl RegistryTrait for Registry {Box::pin(async {match self.fetch_models().await {Ok(models) => {- if let Err(error) = self.save_registry(&models) {+ let saved = serde_json::to_vec_pretty(&models)+ .map_err(io::Error::other)+ .and_then(|contents| write(self.registry_path(), contents));+ if let Err(error) = saved {tracing::warn!(?error, "failed to save Mirai registry");}Ok(models)@@ -94,18 +98,6 @@ impl Registry {self.cache_path.join("registry.json")}- fn save_registry(- &self,- models: &[Model],- ) -> Result<(), RegistryError> {- let contents = serde_json::to_vec_pretty(models).map_err(|error| RegistryError::UnableToGetModels {- message: format!("Unable to serialize registry: {}", error),- })?;- write(self.registry_path(), contents).map_err(|error| RegistryError::UnableToGetModels {- message: format!("Unable to write registry: {}", error),- })- }-fn load_registry(&self) -> Result<Vec<Model>, RegistryError> {let contents = read_to_string(self.registry_path()).map_err(|error| RegistryError::UnableToGetModels {message: format!("Unable to read registry: {}", error),diff --git a/crates/legacy/uzu/src/registry/mod.rs b/crates/legacy/uzu/src/registry/mod.rsindex 25e91a452..e634651b9 100644--- a/crates/legacy/uzu/src/registry/mod.rs+++ b/crates/legacy/uzu/src/registry/mod.rs@@ -1,6 +1,5 @@mod cached;mod error;-mod fixed;pub mod local;mod merged;pub mod mirai;@@ -8,5 +7,4 @@ pub mod openai;pub use cached::CachedRegistry;pub use error::RegistryError;-pub use fixed::FixedRegistry;pub use merged::MergedRegistry;diff --git a/crates/legacy/uzu/src/registry/openai/mod.rs b/crates/legacy/uzu/src/registry/openai/mod.rsindex dbd74293f..e0bb1353b 100644--- a/crates/legacy/uzu/src/registry/openai/mod.rs+++ b/crates/legacy/uzu/src/registry/openai/mod.rs@@ -68,7 +68,7 @@ impl Registry {impl RegistryTrait for Registry {type Error = RegistryError;- fn indentifier(&self) -> String {+ fn identifier(&self) -> String {self.config.identifier.clone()}diff --git a/crates/legacy/uzu/src/storage/config.rs b/crates/legacy/uzu/src/storage/config.rsindex 450ef69c9..f07bfad04 100644--- a/crates/legacy/uzu/src/storage/config.rs+++ b/crates/legacy/uzu/src/storage/config.rs@@ -1,10 +1,8 @@use std::path::PathBuf;-use download_manager::FileDownloadManagerType;+use download_manager::DownloadManagerType;use serde::{Deserialize, Serialize};-use shoji::types::model::Model;-use super::download_contents::DownloadContents;use crate::device::Device;#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]@@ -14,9 +12,7 @@ pub struct Config {pub base_path: Option<PathBuf>,pub name: String,#[serde(default)]- pub download_manager_type: FileDownloadManagerType,- #[serde(skip)]- pub download_contents: DownloadContents,+ pub download_manager_type: DownloadManagerType,}impl Config {@@ -24,54 +20,13 @@ impl Config {device: Device,base_path: Option<PathBuf>,name: String,+ download_manager_type: DownloadManagerType,) -> Self {Self {device,base_path,name,- download_manager_type: FileDownloadManagerType::default(),- download_contents: DownloadContents::default(),- }- }-- pub fn cache_path(&self) -> PathBuf {- self.base_path.clone().unwrap_or(PathBuf::from(self.device.home_path.clone())).join(".cache").join(&self.name)- }-- pub fn cache_models_path(&self) -> PathBuf {- self.cache_path().join("models")- }-- pub fn cache_model_path(- &self,- model: &Model,- ) -> Option<PathBuf> {- let reference_name = model.reference_name()?;- let checkpoint_version = model.checkpoint_version()?;- Some(self.cache_models_path().join(reference_name).join(model.cache_identifier()).join(checkpoint_version))- }-- pub fn log_name(&self) -> String {- format!("{}.log", self.name)- }-- pub fn with_download_manager_type(- &self,- download_manager_type: FileDownloadManagerType,- ) -> Self {- Self {download_manager_type,- ..self.clone()- }- }-- pub fn with_download_contents(- &self,- download_contents: DownloadContents,- ) -> Self {- Self {- download_contents,- ..self.clone()}}}diff --git a/crates/legacy/uzu/src/storage/download_contents.rs b/crates/legacy/uzu/src/storage/download_contents.rsdeleted file mode 100644index 7fb0ca1fb..000000000--- a/crates/legacy/uzu/src/storage/download_contents.rs+++ /dev/null@@ -1,33 +0,0 @@-use bitflags::bitflags;--bitflags! {- #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]- pub struct DownloadContents: u8 {- const CONFIG = 0b0000_0001;- const TOKENIZER = 0b0000_0010;- const WEIGHTS = 0b0000_0100;- const TRACES = 0b0000_1000;- }-}--impl Default for DownloadContents {- fn default() -> Self {- Self::all()- }-}--impl DownloadContents {- pub fn includes_file(- &self,- file_name: &str,- ) -> bool {- let flag = match file_name {- "config.json" => Self::CONFIG,- "tokenizer.json" => Self::TOKENIZER,- "traces.safetensors" => Self::TRACES,- name if name.ends_with(".safetensors") => Self::WEIGHTS,- _ => Self::CONFIG,- };- self.contains(flag)- }-}diff --git a/crates/legacy/uzu/src/storage/error.rs b/crates/legacy/uzu/src/storage/error.rsindex cd04057e2..97aabfd4c 100644--- a/crates/legacy/uzu/src/storage/error.rs+++ b/crates/legacy/uzu/src/storage/error.rs@@ -1,4 +1,5 @@-use crate::{registry::RegistryError, storage::types::DownloadPhase};+use download_manager::DownloadError;+use shoji::types::model::ModelIdentifier;#[bindings::export(Error)]#[derive(Debug, Clone, PartialEq, thiserror::Error)]@@ -8,36 +9,29 @@ pub enum StorageError {UnableToCreateDirectory {path: String,},- #[error("Unable to create download manager: {message}")]- UnableToCreateDownloadManager {- message: String,- },#[error("Download manager error: {message}")]DownloadManager {message: String,},#[error("Hash not found for file: {identifier}/{name}")]HashNotFound {- identifier: String,+ identifier: ModelIdentifier,name: String,},- #[error("Invalid state transition from {from:?} to {to:?}")]- InvalidStateTransition {- from: DownloadPhase,- to: DownloadPhase,- },- #[error("IO error: {message}")]- IO {- message: String,+ #[error("Model not found: {identifier}")]+ ModelNotFound {+ identifier: ModelIdentifier,},- #[error("Item not found: {identifier}")]- ItemNotFound {- identifier: String,- },- #[error(transparent)]- Registry(#[from] RegistryError),- #[error("Unsupported item: {identifier}")]- UnsupportedItem {- identifier: String,+ #[error("Unsupported model: {identifier}")]+ UnsupportedModel {+ identifier: ModelIdentifier,},}++impl From<DownloadError> for StorageError {+ fn from(error: DownloadError) -> Self {+ Self::DownloadManager {+ message: error.to_string(),+ }+ }+}diff --git a/crates/legacy/uzu/src/storage/mod.rs b/crates/legacy/uzu/src/storage/mod.rsindex 121686e36..7ab896c32 100644--- a/crates/legacy/uzu/src/storage/mod.rs+++ b/crates/legacy/uzu/src/storage/mod.rs@@ -1,296 +1,9 @@mod config;-mod download_contents;mod error;-pub mod types;--use std::{- collections::{HashMap, HashSet},- fs::{create_dir_all, read_dir, remove_dir_all},- sync::Arc,-};+mod model_tasks;+mod storage;pub use config::Config;-pub use download_contents::DownloadContents;-use download_manager::{FileCheck, FileDownloadManager, FileDownloadPhase};+pub use download_manager::{DownloadManagerType, DownloadPhase, DownloadState};pub use error::StorageError;-use futures_util::future::join_all;-use kiban::rt::RuntimeHandle;-use shoji::types::{- basic::File,- model::{Model, ModelAccessibility, ModelReference},-};-use tokio::sync::broadcast::channel as tokio_broadcast_channel;--use crate::{- helpers::SharedAccess,- storage::types::{DownloadPhase, DownloadState, Item, StorageDownloadEventSender, StorageDownloadEventStream},-};--pub struct Storage {- pub config: Config,-- download_manager: SharedAccess<Arc<dyn FileDownloadManager>>,- items: SharedAccess<HashMap<String, Item>>,- items_broadcast_sender: StorageDownloadEventSender,- handle: RuntimeHandle,-}--impl Storage {- pub async fn new(- runtime_handle: RuntimeHandle,- config: Config,- ) -> Result<Self, StorageError> {- create_dir_all(config.cache_path()).map_err(|_| StorageError::UnableToCreateDirectory {- path: config.cache_path().to_string_lossy().to_string(),- })?;-- let download_manager = SharedAccess::new(Arc::from(- <dyn FileDownloadManager>::new(config.download_manager_type, runtime_handle.clone()).await.map_err(- |error| StorageError::DownloadManager {- message: error.to_string(),- },- )?,- ));-- let items = SharedAccess::new(HashMap::new());-- let (items_broadcast_sender, _) = tokio_broadcast_channel(256);-- let storage = Self {- config,- download_manager,- items,- items_broadcast_sender,- handle: runtime_handle,- };- Ok(storage)- }-}--impl Storage {- pub async fn refresh(- &self,- models: Vec<Model>,- ) -> Result<(), StorageError> {- let models = models.into_iter().filter(|model| model.is_downloadable()).collect::<Vec<_>>();- let actual_model_identifiers: HashSet<String> = models.iter().map(|model| model.identifier.clone()).collect();-- let download_manager = { self.download_manager.lock().await.clone() };-- let existing_file_tasks =- download_manager.get_all_file_tasks().await.map_err(|error| StorageError::DownloadManager {- message: error.to_string(),- })?;- let mut active_file_tasks = Vec::with_capacity(existing_file_tasks.len());- for task in existing_file_tasks {- let task_state = task.state().await;- if matches!(task_state.phase, FileDownloadPhase::Error(_)) {- let download_id = task.download_id();- let _ = task.cancel().await;- let _ = download_manager.remove_file_task(download_id).await;- } else {- active_file_tasks.push(task);- }- }-- let mut items = self.items.lock().await;- let stale_model_identifiers: Vec<String> = items- .keys()- .filter(|identifier| !actual_model_identifiers.contains(identifier.as_str()))- .cloned()- .collect();- for identifier in stale_model_identifiers {- if let Some(item) = items.remove(&identifier) {- if let Err(error) = item.detach_active_downloads().await {- tracing::warn!(?error, identifier, "failed to detach stale model file tasks");- }- item.stop_listening().await;- }- }-- for model in models {- let identifier = model.identifier.clone();- if items.contains_key(&identifier) {- continue;- }-- let files = self.resolve_model_files(&model)?;- let total_bytes: u64 = files.iter().map(|file| file.size as u64).sum();-- let cache_path = self.config.cache_model_path(&model).ok_or(StorageError::UnsupportedItem {- identifier: identifier.clone(),- })?;-- let has_files_on_disk = cache_path.exists();- let has_active_tasks = files.iter().any(|file| {- let file_path = cache_path.join(&file.name);- active_file_tasks.iter().any(|task| task.destination() == file_path)- });-- let item = if has_files_on_disk || has_active_tasks {- let mut file_tasks = Vec::new();- for file in &files {- let file_path = cache_path.join(&file.name);- let file_check = FileCheck::CRC(file.crc32c().ok_or(StorageError::HashNotFound {- identifier: identifier.clone(),- name: file.name.clone(),- })?);-- let file_task = download_manager- .file_download_task(&file.url, &file_path, file_check, Some(file.size as u64))- .await- .map_err(|error| StorageError::DownloadManager {- message: error.to_string(),- })?;-- file_tasks.push(file_task);- }-- let item = Item::new(- identifier.clone(),- files.into(),- cache_path.clone(),- DownloadState::not_downloaded(total_bytes as i64),- download_manager.clone(),- file_tasks,- self.handle.clone(),- self.items_broadcast_sender.clone(),- );-- item.start_listening().await;- let _ = item.reconcile().await;- let item_state = item.state().await;-- if matches!(item_state.phase, DownloadPhase::NotDownloaded {})- && cache_path.exists()- && let Ok(entries) = read_dir(&cache_path)- {- let has_real_files = entries.flatten().any(|entry| {- entry- .file_name()- .to_str()- .is_some_and(|name| !name.ends_with(".resume_data") && !name.starts_with('.'))- });- if !has_real_files {- let _ = remove_dir_all(&cache_path);- }- }-- item- } else {- Item::new(- identifier.clone(),- files.into(),- cache_path.clone(),- DownloadState::not_downloaded(total_bytes as i64),- download_manager.clone(),- Vec::new(),- self.handle.clone(),- self.items_broadcast_sender.clone(),- )- };-- items.insert(identifier, item);- }-- Ok(())- }-- pub fn subscribe(&self) -> StorageDownloadEventStream {- StorageDownloadEventStream::new(self.items_broadcast_sender.subscribe())- }-- pub async fn get(- &self,- model_identifier: &String,- ) -> Option<Item> {- let items = self.items.lock().await;- items.get(model_identifier).cloned()- }-- pub async fn state(- &self,- model_identifier: &String,- ) -> Option<DownloadState> {- let item = self.get(model_identifier).await?;- let state = item.state().await;- Some(state)- }-- pub async fn states(&self) -> HashMap<String, DownloadState> {- let items = self.items.lock().await;- let state_futures = items.iter().map(|(identifier, item)| {- let identifier = identifier.clone();- async move { (identifier, item.state().await) }- });- join_all(state_futures).await.into_iter().collect()- }-- pub async fn download(- &self,- model_identifier: &String,- ) -> Result<(), StorageError> {- let item = self.get(model_identifier).await.ok_or_else(|| StorageError::ItemNotFound {- identifier: model_identifier.clone(),- })?;- item.download().await- }-- pub async fn pause(- &self,- model_identifier: &String,- ) -> Result<(), StorageError> {- let item = self.get(model_identifier).await.ok_or_else(|| StorageError::ItemNotFound {- identifier: model_identifier.clone(),- })?;- item.pause().await- }-- pub async fn delete(- &self,- model_identifier: &String,- ) -> Result<(), StorageError> {- let item = self.get(model_identifier).await.ok_or_else(|| StorageError::ItemNotFound {- identifier: model_identifier.clone(),- })?;- item.cancel().await- }-}--impl Storage {- fn resolve_model_files(- &self,- model: &Model,- ) -> Result<Vec<File>, StorageError> {- match &model.accessibility {- ModelAccessibility::Local {- reference,- ..- } => match &reference {- ModelReference::Mirai {- files,- ..- } => Ok(files- .iter()- .filter(|file| self.config.download_contents.includes_file(&file.name))- .cloned()- .collect()),- ModelReference::HuggingFace {- ..- } => Err(StorageError::UnsupportedItem {- identifier: model.identifier.clone(),- }),- ModelReference::Local {- ..- } => Err(StorageError::UnsupportedItem {- identifier: model.identifier.clone(),- }),- },- ModelAccessibility::Remote {- ..- } => Err(StorageError::UnsupportedItem {- identifier: model.identifier.clone(),- }),- }- }-}+pub use storage::Storage;diff --git a/crates/legacy/uzu/src/storage/model_tasks.rs b/crates/legacy/uzu/src/storage/model_tasks.rsnew file mode 100644index 000000000..bcf555d04--- /dev/null+++ b/crates/legacy/uzu/src/storage/model_tasks.rs@@ -0,0 +1,7 @@+use std::{collections::HashMap, sync::Arc};++use download_manager::DownloadTask;+use kiban::rt::TaskJoinHandle;+use shoji::types::model::ModelIdentifier;++pub type ModelTasks = HashMap<ModelIdentifier, (Arc<DownloadTask>, Box<dyn TaskJoinHandle<()>>)>;diff --git a/crates/legacy/uzu/src/storage/storage.rs b/crates/legacy/uzu/src/storage/storage.rsnew file mode 100644index 000000000..2bbb47e1e--- /dev/null+++ b/crates/legacy/uzu/src/storage/storage.rs@@ -0,0 +1,187 @@+use std::{collections::HashMap, path::PathBuf, sync::Arc};++use download_manager::{DownloadManager, DownloadState, DownloadTask, DownloadTaskRequest};+use futures_util::future::join_all;+use kiban::{fs, rt::RuntimeHandle};+use shoji::types::{+ basic::File,+ model::{Model, ModelAccessibility, ModelIdentifier, ModelReference},+};+use tokio::sync::{+ Mutex as TokioMutex,+ broadcast::{Sender as TokioBroadcastSender, channel as tokio_broadcast_channel},+};+use tokio_stream::{StreamExt, wrappers::BroadcastStream};++use crate::storage::{Config, StorageError, model_tasks::ModelTasks};++pub struct Storage {+ config: Config,+ download_manager: DownloadManager,+ tasks: TokioMutex<ModelTasks>,+ events: TokioBroadcastSender<(ModelIdentifier, DownloadState)>,+}++impl Storage {+ pub async fn new(+ runtime_handle: RuntimeHandle,+ config: Config,+ ) -> Result<Self, StorageError> {+ let cache_path = Self::cache_path(&config);+ fs::asyn::create_dir_all(&cache_path).await.map_err(|_| StorageError::UnableToCreateDirectory {+ path: cache_path.to_string_lossy().to_string(),+ })?;+ let (events, _) = tokio_broadcast_channel(256);+ Ok(Self {+ download_manager: DownloadManager::new(config.download_manager_type, runtime_handle),+ config,+ tasks: TokioMutex::new(ModelTasks::new()),+ events,+ })+ }++ pub fn cache_path(config: &Config) -> PathBuf {+ let home_path = PathBuf::from(config.device.home_path.clone());+ config.base_path.clone().unwrap_or(home_path).join(".cache").join(&config.name)+ }++ pub fn cache_model_path(+ &self,+ model: &Model,+ ) -> Option<PathBuf> {+ let reference_name = model.reference_name()?;+ let checkpoint_version = model.checkpoint_version()?;+ Some(+ Self::cache_path(&self.config)+ .join("models")+ .join(reference_name)+ .join(model.cache_identifier())+ .join(checkpoint_version),+ )+ }++ pub async fn refresh(+ &self,+ models: &[Model],+ ) -> Result<(), StorageError> {+ let mut requests = HashMap::new();+ for model in models {+ let ModelAccessibility::Local {+ reference: ModelReference::Mirai {+ files,+ ..+ },+ } = &model.accessibility+ else {+ continue;+ };+ requests.entry(model.identifier.clone()).or_insert(self.request(model, files)?);+ }+ let missing: Vec<(ModelIdentifier, DownloadTaskRequest)> = {+ let mut tasks = self.tasks.lock().await;+ tasks.retain(|identifier, (task, forwarder)| {+ let keep = requests.get(identifier).is_some_and(|request| task.request() == request);+ if !keep {+ forwarder.abort();+ }+ keep+ });+ requests.into_iter().filter(|(identifier, _)| !tasks.contains_key(identifier)).collect()+ };+ let created = join_all(missing.into_iter().map(|(identifier, request)| async move {+ (identifier, self.download_manager.download_task(request).await)+ }))+ .await;+ let mut tasks = self.tasks.lock().await;+ for (identifier, task) in created {+ let task = task?;+ let events = self.events.clone();+ let mut progress = task.progress();+ let forwarder = kiban::rt::spawn({+ let identifier = identifier.clone();+ async move {+ while let Some(state) = progress.next().await {+ let _ = events.send((identifier.clone(), state));+ }+ }+ });+ if let Some((_, replaced)) = tasks.insert(identifier, (task, forwarder)) {+ replaced.abort();+ }+ }+ Ok(())+ }++ pub fn subscribe(&self) -> BroadcastStream<(ModelIdentifier, DownloadState)> {+ BroadcastStream::new(self.events.subscribe())+ }++ pub async fn state(+ &self,+ identifier: &ModelIdentifier,+ ) -> Result<DownloadState, StorageError> {+ Ok(self.model(identifier).await?.state())+ }++ pub async fn states(&self) -> HashMap<ModelIdentifier, DownloadState> {+ self.tasks.lock().await.iter().map(|(identifier, (task, _))| (identifier.clone(), task.state())).collect()+ }++ pub async fn download(+ &self,+ identifier: &ModelIdentifier,+ ) -> Result<(), StorageError> {+ Ok(self.model(identifier).await?.download().await?)+ }++ pub async fn pause(+ &self,+ identifier: &ModelIdentifier,+ ) -> Result<(), StorageError> {+ Ok(self.model(identifier).await?.pause().await?)+ }++ pub async fn delete(+ &self,+ identifier: &ModelIdentifier,+ ) -> Result<(), StorageError> {+ Ok(self.model(identifier).await?.delete().await?)+ }++ async fn model(+ &self,+ identifier: &ModelIdentifier,+ ) -> Result<Arc<DownloadTask>, StorageError> {+ self.tasks.lock().await.get(identifier).map(|(task, _)| Arc::clone(task)).ok_or_else(|| {+ StorageError::ModelNotFound {+ identifier: identifier.clone(),+ }+ })+ }++ fn request(+ &self,+ model: &Model,+ files: &[File],+ ) -> Result<DownloadTaskRequest, StorageError> {+ let cache_path = self.cache_model_path(model).ok_or_else(|| StorageError::UnsupportedModel {+ identifier: model.identifier.clone(),+ })?;+ let subrequests = files+ .iter()+ .map(|file| {+ let crc32c = file.crc32c().ok_or_else(|| StorageError::HashNotFound {+ identifier: model.identifier.clone(),+ name: file.name.clone(),+ })?;+ Ok(DownloadTaskRequest::file()+ .destination(&file.name)+ .source_url(&file.url)+ .expected_crc32c(crc32c)+ .maybe_expected_bytes(u64::try_from(file.size).ok())+ .build())+ })+ .collect::<Result<Vec<_>, StorageError>>()?;+ Ok(DownloadTaskRequest::group().destination(cache_path).subrequests(subrequests).build())+ }+}diff --git a/crates/legacy/uzu/src/storage/types/download_state.rs b/crates/legacy/uzu/src/storage/types/download_state.rsdeleted file mode 100644index e626418e4..000000000--- a/crates/legacy/uzu/src/storage/types/download_state.rs+++ /dev/null@@ -1,159 +0,0 @@-use download_manager::{FileDownloadPhase, FileDownloadState};-use serde::{Deserialize, Serialize};--use crate::storage::types::DownloadPhase;--#[bindings::export(Structure(Class))]-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]-pub struct DownloadState {- pub total_bytes: i64,- pub downloaded_bytes: i64,- pub phase: DownloadPhase,-}--impl DownloadState {- pub fn not_downloaded(total_bytes: i64) -> Self {- Self {- total_bytes,- downloaded_bytes: 0,- phase: DownloadPhase::NotDownloaded {},- }- }-- pub fn downloading(- downloaded_bytes: i64,- total_bytes: i64,- ) -> Self {- Self {- total_bytes,- downloaded_bytes,- phase: DownloadPhase::Downloading {},- }- }-- pub fn paused(- downloaded_bytes: i64,- total_bytes: i64,- ) -> Self {- Self {- total_bytes,- downloaded_bytes,- phase: DownloadPhase::Paused {},- }- }-- pub fn downloaded(total_bytes: i64) -> Self {- Self {- total_bytes,- downloaded_bytes: total_bytes,- phase: DownloadPhase::Downloaded {},- }- }-- pub fn locked(- downloaded_bytes: i64,- total_bytes: i64,- ) -> Self {- Self {- total_bytes,- downloaded_bytes,- phase: DownloadPhase::Locked {},- }- }-- pub fn error(error_message: String) -> Self {- Self {- total_bytes: 0,- downloaded_bytes: 0,- phase: DownloadPhase::Error {- message: error_message,- },- }- }-}--#[bindings::export(Implementation)]-impl DownloadState {- #[bindings::export(Method(Getter))]- pub fn progress(&self) -> f32 {- if self.total_bytes == 0 {- 0.0- } else {- self.downloaded_bytes as f32 / self.total_bytes as f32- }- }-- #[bindings::export(Method(Getter))]- pub fn is_in_progress(&self) -> bool {- self.phase.is_in_progress()- }-- #[bindings::export(Method(Getter))]- pub fn can_pause(&self) -> bool {- self.phase.can_pause()- }-- #[bindings::export(Method(Getter))]- pub fn can_delete(&self) -> bool {- self.phase.can_delete()- }-- #[bindings::export(Method(Getter))]- pub fn name(&self) -> String {- match &self.phase {- DownloadPhase::NotDownloaded {} => "Not Downloaded".to_string(),- DownloadPhase::Downloading {} => "Downloading".to_string(),- DownloadPhase::Paused {} => "Paused".to_string(),- DownloadPhase::Downloaded {} => "Downloaded".to_string(),- DownloadPhase::Locked {} => "Locked".to_string(),- DownloadPhase::Error {- ..- } => "Error".to_string(),- }- }-}--pub fn reduce_file_download_states(file_states: &[FileDownloadState]) -> DownloadState {- if file_states.is_empty() {- return DownloadState::not_downloaded(0);- }-- let total_bytes: u64 = file_states.iter().map(|f| f.total_bytes).sum();- let downloaded_bytes: u64 = file_states.iter().map(|f| f.downloaded_bytes).sum();-- let all_downloaded = file_states.iter().all(|f| matches!(f.phase, FileDownloadPhase::Downloaded));- let any_downloaded = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::Downloaded));- let any_downloading = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::Downloading));- let any_paused = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::Paused));- let any_locked = file_states.iter().any(|f| matches!(f.phase, FileDownloadPhase::LockedByOther(_)));-- if all_downloaded {- return DownloadState::downloaded(total_bytes as i64);- }-- if let Some(error_state) = file_states.iter().find(|f| matches!(f.phase, FileDownloadPhase::Error(_)))- && let FileDownloadPhase::Error(err) = &error_state.phase- {- return DownloadState::error(err.clone());- }-- if any_locked {- return DownloadState::locked(downloaded_bytes as i64, total_bytes as i64);- }-- if any_downloading {- return DownloadState::downloading(downloaded_bytes as i64, total_bytes as i64);- }-- if any_paused {- return DownloadState::paused(downloaded_bytes as i64, total_bytes as i64);- }-- // If some files are downloaded but not all, and nothing is actively- // downloading, treat as paused (partial progress, can resume)- if any_downloaded && downloaded_bytes > 0 {- return DownloadState::paused(downloaded_bytes as i64, total_bytes as i64);- }-- DownloadState::not_downloaded(total_bytes as i64)-}diff --git a/crates/legacy/uzu/src/storage/types/item.rs b/crates/legacy/uzu/src/storage/types/item.rsdeleted file mode 100644index 619ee4060..000000000--- a/crates/legacy/uzu/src/storage/types/item.rs+++ /dev/null@@ -1,679 +0,0 @@-use std::{- fs::{create_dir_all, remove_dir_all},- path::PathBuf,- sync::Arc,-};--use download_manager::{DownloadError, FileDownloadManager, FileDownloadPhase, FileDownloadState, FileDownloadTask};-use futures_util::future::join_all;-use kiban::rt::{RuntimeHandle, TaskJoinHandle};-use shoji::types::basic::File;-use tokio::sync::{- broadcast::{Sender as TokioBroadcastSender, channel as tokio_broadcast_channel},- mpsc::channel as tokio_mpsc_channel,-};-use tokio_stream::wrappers::BroadcastStream;--use crate::{- helpers::SharedAccess,- storage::{- StorageError,- types::{DownloadPhase, DownloadState, StorageDownloadEventSender, reduce_file_download_states},- },-};--pub struct Item {- pub identifier: String,- pub files: Arc<Vec<File>>,- pub cache_path: PathBuf,-- download_state: SharedAccess<DownloadState>,- file_download_manager: Arc<dyn FileDownloadManager>,- file_download_tasks: SharedAccess<Vec<Arc<dyn FileDownloadTask>>>,- file_download_states: SharedAccess<Vec<FileDownloadState>>,-- runtime_handle: RuntimeHandle,- broadcast_sender: TokioBroadcastSender<DownloadState>,- storage_broadcast_sender: StorageDownloadEventSender,- listener_task: SharedAccess<Option<Box<dyn TaskJoinHandle<()>>>>,-}--impl std::fmt::Debug for Item {- fn fmt(- &self,- f: &mut std::fmt::Formatter<'_>,- ) -> std::fmt::Result {- f.debug_struct("Item").field("identifier", &self.identifier).field("cache_path", &self.cache_path).finish()- }-}--impl Clone for Item {- fn clone(&self) -> Self {- Self {- identifier: self.identifier.clone(),- files: self.files.clone(),- cache_path: self.cache_path.clone(),- download_state: self.download_state.clone(),- file_download_manager: self.file_download_manager.clone(),- file_download_tasks: self.file_download_tasks.clone(),- file_download_states: self.file_download_states.clone(),- runtime_handle: self.runtime_handle.clone(),- broadcast_sender: self.broadcast_sender.clone(),- storage_broadcast_sender: self.storage_broadcast_sender.clone(),- listener_task: self.listener_task.clone(),- }- }-}--impl Item {- pub fn new(- identifier: String,- files: Arc<Vec<File>>,- cache_path: PathBuf,- download_state: DownloadState,- file_download_manager: Arc<dyn FileDownloadManager>,- file_download_tasks: Vec<Arc<dyn FileDownloadTask>>,- runtime_handle: RuntimeHandle,- storage_broadcast_sender: StorageDownloadEventSender,- ) -> Self {- let (broadcast_sender, _) = tokio_broadcast_channel(64);- let file_download_states = SharedAccess::new(Vec::new());- Self {- identifier,- files,- cache_path,- download_state: SharedAccess::new(download_state),- file_download_manager,- file_download_tasks: SharedAccess::new(file_download_tasks),- file_download_states,- runtime_handle,- broadcast_sender,- storage_broadcast_sender,- listener_task: SharedAccess::new(None),- }- }-- pub async fn state(&self) -> DownloadState {- self.download_state.lock().await.clone()- }-- async fn get_file_download_states(&self) -> Vec<FileDownloadState> {- let file_tasks_guard = self.file_download_tasks.lock().await;- let num_file_tasks = file_tasks_guard.len();- drop(file_tasks_guard);-- // Use cached states from broadcasts - more reliable than querying- let cache_guard = self.file_download_states.lock().await;-- // Validate cache is properly sized before using it- if !cache_guard.is_empty() && cache_guard.len() == num_file_tasks {- let mut states = cache_guard.clone();- for (i, state) in states.iter_mut().enumerate() {- if state.total_bytes == 0- && let Some(file_info) = self.files.get(i)- && file_info.size > 0- {- state.total_bytes = file_info.size as u64;- }- }- return states;- }-- // If cache exists but size mismatched, fall back to direct query- if !cache_guard.is_empty() && cache_guard.len() != num_file_tasks {- tracing::warn!(- "[MODEL] Cache size mismatch: cache={}, tasks={}, model={}. Falling back to direct query.",- cache_guard.len(),- num_file_tasks,- self.identifier- );- }-- drop(cache_guard);-- // Fall back to querying if cache not initialized or size mismatch- let file_tasks_guard = self.file_download_tasks.lock().await;- let mut states = Vec::new();- for file_task in file_tasks_guard.iter() {- states.push(file_task.state().await);- }-- // Patch total_bytes from registry if missing (safety net)- for (i, state) in states.iter_mut().enumerate() {- if state.total_bytes == 0- && let Some(file_info) = self.files.get(i)- && file_info.size > 0- {- state.total_bytes = file_info.size as u64;- }- }-- states- }-- pub async fn reduce_state(&self) -> DownloadState {- let file_download_states = self.get_file_download_states().await;-- tracing::debug!(- "[MODEL] reduce_state: model={}, file_states count={}",- self.identifier,- file_download_states.len()- );- for (i, state) in file_download_states.iter().enumerate() {- tracing::debug!(- "[MODEL] File {} - phase={:?}, downloaded={}/{} bytes",- i,- state.phase,- state.downloaded_bytes,- state.total_bytes- );- }-- let result = reduce_file_download_states(&file_download_states);-- tracing::debug!(- "[MODEL] reduce_state result: phase={:?}, bytes={}/{}, progress={:.1}%",- result.phase,- result.downloaded_bytes,- result.total_bytes,- result.progress() * 100.0- );-- result- }-- pub async fn update_state_and_broadcast(- &self,- new_state: DownloadState,- ) {- tracing::debug!(- "[MODEL] Broadcasting state: id={}, phase={:?}, progress={:.1}%",- self.identifier,- new_state.phase,- new_state.progress() * 100.0- );-- let mut state_guard = self.download_state.lock().await;- *state_guard = new_state.clone();- drop(state_guard);-- let own_receiver_count = self.broadcast_sender.receiver_count();- let storage_receiver_count = self.storage_broadcast_sender.receiver_count();-- if own_receiver_count == 0 && storage_receiver_count == 0 {- tracing::debug!("[MODEL] No receivers active, skipping broadcasts (likely shutdown)");- return;- }-- if own_receiver_count > 0 {- let own_result = self.broadcast_sender.send(new_state.clone());-- match own_result {- Ok(count) => tracing::debug!("[MODEL] ✓ Own broadcast sent to {} receiver(s)", count),- Err(_) => {- tracing::trace!("[MODEL] Own broadcast skipped (no receivers)")- },- }- } else {- tracing::trace!("[MODEL] Skipping own broadcast (no receivers)");- }-- if storage_receiver_count > 0 {- let storage_result = self.storage_broadcast_sender.send((self.identifier.clone(), new_state));-- match storage_result {- Ok(count) => tracing::debug!("[MODEL] ✓ Storage broadcast sent to {} receiver(s)", count),- Err(_) => tracing::debug!("[MODEL] ⚠️ Storage broadcast failed (no receivers)"),- }- } else {- tracing::trace!("[MODEL] Skipping storage broadcast (no receivers)");- }- }-- pub async fn file_task_by_download_id(- &self,- download_id: uuid::Uuid,- ) -> Option<Arc<dyn FileDownloadTask>> {- let file_tasks_guard = self.file_download_tasks.lock().await;- file_tasks_guard.iter().find(|task| task.download_id() == download_id).cloned()- }-- pub async fn reconcile(&self) -> Result<(), StorageError> {- // Reconciliation is now handled by FileDownloadTask- // Just update our broadcast with current state- let calculated_state = self.reduce_state().await;- self.update_state_and_broadcast(calculated_state).await;- Ok(())- }-- async fn ensure_file_tasks(&self) -> Result<bool, StorageError> {- let mut file_tasks_guard = self.file_download_tasks.lock().await;-- // If file tasks already exist, skip creation- if !file_tasks_guard.is_empty() {- return Ok(false);- }-- // Initialize file download tasks- let mut new_file_tasks = Vec::new();- for file_info in self.files.iter() {- let file_path = self.cache_path.join(&file_info.name);- let file_check =- download_manager::FileCheck::CRC(file_info.crc32c().ok_or(StorageError::HashNotFound {- identifier: self.identifier.clone(),- name: file_info.name.clone(),- })?);-- let file_task = self- .file_download_manager- .file_download_task(&file_info.url, &file_path, file_check, Some(file_info.size as u64))- .await- .map_err(|error| StorageError::DownloadManager {- message: error.to_string(),- })?;-- // Start listening to global broadcast- file_task.start_listening((*self.file_download_manager.global_broadcast_sender()).clone()).await;-- new_file_tasks.push(file_task);- }-- *file_tasks_guard = new_file_tasks;- Ok(true)- }-- pub async fn download(&self) -> Result<(), StorageError> {- tracing::debug!("[MODEL] download() called for model: {}", self.identifier);-- let tasks_were_created = self.ensure_file_tasks().await?;- if tasks_were_created {- tracing::debug!("[MODEL] Restarting listener for model: {} (file tasks created)", self.identifier);- self.stop_listening().await;- self.start_listening().await;- }-- let current_state = self.reduce_state().await;- if !Self::can_transition_to_downloading(¤t_state.phase) {- return Err(StorageError::InvalidStateTransition {- from: current_state.phase.clone(),- to: DownloadPhase::Downloading {},- });- }-- tracing::debug!("[MODEL] Calling ensure_downloading");- self.ensure_downloading().await?;-- self.stop_listening().await;- self.start_listening().await;-- let downloading_state = self.reduce_state().await;- self.update_state_and_broadcast(downloading_state).await;-- tracing::debug!("[MODEL] download() completed for model: {}", self.identifier);- Ok(())- }-- pub async fn pause(&self) -> Result<(), StorageError> {- tracing::debug!("[MODEL] pause() called for model: {}", self.identifier);-- let tasks_were_created = self.ensure_file_tasks().await?;- if tasks_were_created {- tracing::debug!("[MODEL] Restarting listener for model: {} (file tasks created)", self.identifier);- self.stop_listening().await;- self.start_listening().await;- }-- let current_state = self.reduce_state().await;- if !current_state.can_pause() {- return Err(StorageError::InvalidStateTransition {- from: current_state.phase.clone(),- to: DownloadPhase::Paused {},- });- }-- tracing::debug!("[MODEL] Calling ensure_paused");- self.ensure_paused().await?;-- let file_tasks_guard = self.file_download_tasks.lock().await;- let mut file_download_states = Vec::with_capacity(file_tasks_guard.len());- for file_task in file_tasks_guard.iter() {- file_download_states.push(file_task.state().await);- }- drop(file_tasks_guard);-- *self.file_download_states.lock().await = file_download_states;- let paused_state = self.reduce_state().await;- self.update_state_and_broadcast(paused_state).await;-- tracing::debug!("[MODEL] pause() completed for model: {}", self.identifier);- Ok(())- }-- pub async fn cancel(&self) -> Result<(), StorageError> {- let tasks_were_created = self.ensure_file_tasks().await?;- if tasks_were_created {- tracing::debug!("[MODEL] Restarting listener for model: {} (file tasks created)", self.identifier);- self.stop_listening().await;- self.start_listening().await;- }-- for file_info in self.files.iter() {- let destination = self.cache_path.join(&file_info.name);- if let Some(owner) = self.file_download_manager.destination_foreign_lock(&destination).await {- tracing::info!(?destination, %owner, "refusing to cancel: destination is locked by another manager");- return Err(StorageError::InvalidStateTransition {- from: DownloadPhase::Locked {},- to: DownloadPhase::NotDownloaded {},- });- }- }-- let current_state = self.reduce_state().await;- if matches!(current_state.phase, DownloadPhase::Locked {}) {- return Err(StorageError::InvalidStateTransition {- from: current_state.phase,- to: DownloadPhase::NotDownloaded {},- });- }-- self.cancel_and_remove_active_file_tasks().await?;-- self.stop_listening().await;- *self.file_download_tasks.lock().await = Vec::new();- *self.file_download_states.lock().await = Vec::new();-- if self.cache_path.exists() {- let _ = remove_dir_all(&self.cache_path);- }-- let total_bytes: u64 = self.files.iter().map(|f| f.size as u64).sum();- let not_downloaded_state = DownloadState::not_downloaded(total_bytes as i64);- self.update_state_and_broadcast(not_downloaded_state).await;- Ok(())- }-- pub async fn progress(&self) -> Result<BroadcastStream<DownloadState>, StorageError> {- Ok(BroadcastStream::new(self.broadcast_sender.subscribe()))- }-- pub async fn detach_active_downloads(&self) -> Result<(), StorageError> {- self.cancel_and_remove_active_file_tasks().await?;- *self.file_download_tasks.lock().await = Vec::new();- *self.file_download_states.lock().await = Vec::new();- Ok(())- }-- async fn cancel_and_remove_active_file_tasks(&self) -> Result<(), StorageError> {- let file_tasks = self.file_download_tasks.lock().await.clone();- let cancel_futures = file_tasks.iter().map(|file_task| {- let file_task = file_task.clone();- let manager = self.file_download_manager.clone();- async move {- let download_id = file_task.download_id();- file_task.cancel().await?;- manager.remove_file_task(download_id).await?;- Ok::<(), download_manager::DownloadError>(())- }- });- let first_error = join_all(cancel_futures).await.into_iter().find_map(Result::err);-- match first_error {- Some(error) => Err(StorageError::DownloadManager {- message: error.to_string(),- }),- None => Ok(()),- }- }-- /// Handle file task state update- /// Called by ModelStorage listener when a file task broadcasts a state change- pub async fn handle_file_task_update(&self) {- tracing::debug!("[MODEL] handle_file_task_update: Computing new state for model: {}", self.identifier);-- let new_state = self.reduce_state().await;-- tracing::debug!(- "[MODEL] handle_file_task_update: New state computed: phase={:?}, bytes={}/{}, progress={:.1}%",- new_state.phase,- new_state.downloaded_bytes,- new_state.total_bytes,- new_state.progress() * 100.0- );-- self.update_state_and_broadcast(new_state).await;- }-- async fn ensure_downloading(&self) -> Result<(), StorageError> {- tracing::debug!("[MODEL] ensure_downloading: model={}", self.identifier);-- create_dir_all(&self.cache_path).map_err(|error| StorageError::IO {- message: error.to_string(),- })?;-- let file_tasks_guard = self.file_download_tasks.lock().await;- let download_futures = file_tasks_guard.iter().map(|file_task| {- let file_task = file_task.clone();- async move { file_task.download().await }- });- let first_error = join_all(download_futures).await.into_iter().find_map(Result::err);- drop(file_tasks_guard);-- if let Some(error) = first_error {- return Err(StorageError::DownloadManager {- message: error.to_string(),- });- }-- tracing::debug!("[MODEL] ensure_downloading: All file downloads initiated");- Ok(())- }-- async fn ensure_paused(&self) -> Result<(), StorageError> {- tracing::debug!("[MODEL] ensure_paused: model={}", self.identifier);- let file_tasks_guard = self.file_download_tasks.lock().await;- let pause_futures = file_tasks_guard.iter().map(|file_task| {- let file_task = file_task.clone();- async move {- if matches!(file_task.state().await.phase, FileDownloadPhase::Downloading) {- match file_task.pause().await {- Ok(()) => Ok(()),- Err(DownloadError::InvalidStateTransition)- if !matches!(file_task.state().await.phase, FileDownloadPhase::Downloading) =>- {- Ok(())- },- Err(error) => Err(error),- }- } else {- Ok(())- }- }- });- let first_error = join_all(pause_futures).await.into_iter().find_map(Result::err);- drop(file_tasks_guard);-- if let Some(error) = first_error {- return Err(StorageError::DownloadManager {- message: error.to_string(),- });- }-- tracing::debug!("[MODEL] ensure_paused: All file tasks paused");- Ok(())- }-- /// Start listening to file task broadcasts- pub async fn start_listening(&self) {- // Check if already listening- let mut listener_guard = self.listener_task.lock().await;- if listener_guard.is_some() {- tracing::debug!("[MODEL] start_listening: Already listening for model: {}", self.identifier);- return;- }-- // Collect all file task broadcast streams and initialize cache- let file_tasks_guard = self.file_download_tasks.lock().await;- let num_files = file_tasks_guard.len();- let mut streams = Vec::new();- let mut initial_states = Vec::new();- for (idx, file_task) in file_tasks_guard.iter().enumerate() {- let sender = file_task.broadcast_sender();- let receiver_count_before = sender.receiver_count();- let stream = BroadcastStream::new(sender.subscribe());- tracing::info!(- "[MODEL] Subscribed to file task {}: model={}, receivers_before={}, receivers_after={}",- idx,- self.identifier,- receiver_count_before,- sender.receiver_count()- );- streams.push((idx, stream));-- let mut state = file_task.state().await;- if state.total_bytes == 0- && let Some(file_info) = self.files.get(idx)- && file_info.size > 0- {- state.total_bytes = file_info.size as u64;- }- initial_states.push(state);- }- drop(file_tasks_guard);-- if streams.is_empty() {- tracing::debug!("[MODEL] start_listening: No file tasks yet for model: {}", self.identifier);- return;- }-- // Pre-allocate cache with correct size BEFORE starting listener- // This ensures all updates will have valid indices- {- let mut cache_guard = self.file_download_states.lock().await;- *cache_guard = initial_states;-- debug_assert_eq!(cache_guard.len(), num_files, "Cache size must match number of file tasks");-- tracing::debug!(- "[MODEL] Cache initialized with {} entries for model: {}",- cache_guard.len(),- self.identifier- );- }-- tracing::debug!(- "[MODEL] start_listening: Starting listener for model: {} ({} streams)",- self.identifier,- streams.len()- );-- let model = self.clone();- tracing::debug!("[MODEL] Spawning listener task for model: {}", self.identifier);- let handle = self.runtime_handle.spawn(async move {- tracing::debug!("[MODEL] Listener task started for model: {}", model.identifier);- use tokio_stream::StreamExt as TokioStreamExt;-- // Fan-in: per-stream forwarders into a single bounded channel- let num_streams = streams.len();- let (tx, mut rx) = tokio_mpsc_channel::<(usize, FileDownloadState)>(1024);- let mut forwarder_handles = Vec::with_capacity(num_streams);-- for (idx, mut stream) in streams {- let tx = tx.clone();- let forwarder_handle = model.runtime_handle.spawn(async move {- while let Some(item) = stream.next().await {- match item {- Ok(state) => {- // Forward latest state; drop if aggregator has gone away- let _ = tx.send((idx, state)).await;- },- Err(_e) => {- // Lag on a single stream isn't fatal- },- }- }- });- forwarder_handles.push(forwarder_handle);- }- let _forwarder_handles = ListenerForwarderHandles {- handles: forwarder_handles,- };- drop(tx); // close when all forwarders end-- // Aggregator: coalesce bursts, keep only latest state per task- let mut pending: Vec<Option<FileDownloadState>> = vec![None; num_streams];-- while let Some((idx, state)) = rx.recv().await {- pending[idx] = Some(state);-- // Drain quickly to coalesce into latest-only- while let Ok((i, s)) = rx.try_recv() {- pending[i] = Some(s);- }-- // Apply all latest states atomically, then notify once- {- let mut cache_guard = model.file_download_states.lock().await;- for (i, slot) in pending.iter_mut().enumerate() {- if let Some(mut s) = slot.take() {- if i < cache_guard.len() {- // Patch total bytes if 0 in incoming update- if s.total_bytes == 0- && let Some(file_info) = model.files.get(i)- && file_info.size > 0- {- s.total_bytes = file_info.size as u64;- }- cache_guard[i] = s;- } else {- tracing::error!(- "[MODEL] CRITICAL: File task index {} out of bounds (cache size: {}), model={}",- i,- cache_guard.len(),- model.identifier- );- }- }- }- }-- model.handle_file_task_update().await;- }-- tracing::debug!("[MODEL] All streams ended for model: {}", model.identifier);-- tracing::debug!("[MODEL] Listener task ended for model: {}", model.identifier);- });-- *listener_guard = Some(handle);- }-- /// Stop listening to file task broadcasts- pub async fn stop_listening(&self) {- let mut listener_guard = self.listener_task.lock().await;- if let Some(handle) = listener_guard.take() {- handle.abort_and_join().await;- }- }-- fn can_transition_to_downloading(from: &DownloadPhase) -> bool {- matches!(- from,- DownloadPhase::NotDownloaded {}- | DownloadPhase::Downloading {}- | DownloadPhase::Paused {}- | DownloadPhase::Error { .. }- )- }-}--struct ListenerForwarderHandles {- handles: Vec<Box<dyn TaskJoinHandle<()>>>,-}--impl Drop for ListenerForwarderHandles {- fn drop(&mut self) {- for handle in &self.handles {- handle.abort();- }- }-}diff --git a/crates/legacy/uzu/src/storage/types/mod.rs b/crates/legacy/uzu/src/storage/types/mod.rsdeleted file mode 100644index 30dae366c..000000000--- a/crates/legacy/uzu/src/storage/types/mod.rs+++ /dev/null@@ -1,13 +0,0 @@-mod download_phase;-mod download_state;-mod item;--pub use download_phase::DownloadPhase;-pub use download_state::{DownloadState, reduce_file_download_states};-pub use item::Item;-use tokio::sync::broadcast::Sender as TokioBroadcastSender;-use tokio_stream::wrappers::BroadcastStream as TokioBroadcastStream;--pub type StorageDownloadEvent = (String, DownloadState);-pub type StorageDownloadEventSender = TokioBroadcastSender<StorageDownloadEvent>;-pub type StorageDownloadEventStream = TokioBroadcastStream<StorageDownloadEvent>;diff --git a/crates/legacy/uzu/tests/common/mod.rs b/crates/legacy/uzu/tests/common/mod.rsindex 62e95933c..0c3bac348 100644--- a/crates/legacy/uzu/tests/common/mod.rs+++ b/crates/legacy/uzu/tests/common/mod.rs@@ -1,2 +1,3 @@-pub mod test_storage;-pub mod tracing_setup;+mod test_storage;++pub use test_storage::TestStorage;diff --git a/crates/legacy/uzu/tests/common/test_storage.rs b/crates/legacy/uzu/tests/common/test_storage.rsindex 56a958be3..8345c8f1c 100644--- a/crates/legacy/uzu/tests/common/test_storage.rs+++ b/crates/legacy/uzu/tests/common/test_storage.rs@@ -1,50 +1,34 @@-#![allow(dead_code)]+use std::sync::Arc;-use std::path::PathBuf;--use download_manager::FileDownloadManagerType;use kiban::rt::RuntimeHandle;use shoji::types::model::Model;use uzu::{device::Device,- registry::FixedRegistry,- storage::{Config, Storage},+ storage::{Config, DownloadManagerType, Storage},};pub struct TestStorage {- pub config: Config,- pub registry: FixedRegistry,- pub storage: Storage,- pub base_path: PathBuf,+ pub storage: Arc<Storage>,_temp_dir_guard: tempfile::TempDir,}impl TestStorage {- pub async fn with_models(- tokio_handle: RuntimeHandle,- models: Vec<Model>,- ) -> Result<Self, Box<dyn std::error::Error>> {- Self::with_models_and_manager(tokio_handle, models, FileDownloadManagerType::default()).await- }-- pub async fn with_models_and_manager(+ pub async fn new(tokio_handle: RuntimeHandle,models: Vec<Model>,- download_manager_type: FileDownloadManagerType,+ download_manager_type: DownloadManagerType,) -> Result<Self, Box<dyn std::error::Error>> {let temp_dir_guard = tempfile::tempdir()?;- let base_path = temp_dir_guard.path().to_path_buf();- let registry = FixedRegistry::new("test_registry".to_string(), models.clone());- let device = Device::new()?;- let config = Config::new(device, Some(base_path.clone()), "test_storage".to_string())- .with_download_manager_type(download_manager_type);- let storage = Storage::new(tokio_handle, config.clone()).await?;- storage.refresh(models).await?;+ let config = Config::new(+ Device::new()?,+ Some(temp_dir_guard.path().to_path_buf()),+ "test_storage".to_string(),+ download_manager_type,+ );+ let storage = Storage::new(tokio_handle, config).await?;+ storage.refresh(&models).await?;Ok(Self {- config,- registry,- storage,- base_path,+ storage: Arc::new(storage),_temp_dir_guard: temp_dir_guard,})}diff --git a/crates/legacy/uzu/tests/common/tracing_setup.rs b/crates/legacy/uzu/tests/common/tracing_setup.rsdeleted file mode 100644index 8b73a0249..000000000--- a/crates/legacy/uzu/tests/common/tracing_setup.rs+++ /dev/null@@ -1,30 +0,0 @@-#![allow(dead_code)]--use std::sync::Once;--use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};--static INIT: Once = Once::new();--pub fn init_test_tracing() {- INIT.call_once(|| {- let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");- let log_dir = std::env::temp_dir().join("uzu-storage-test-logs");- std::fs::create_dir_all(&log_dir).ok();-- let file_appender = tracing_appender::rolling::never(&log_dir, format!("storage_{}.log", timestamp));-- let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);-- // Keep guard alive for entire test run- std::mem::forget(guard);-- tracing_subscriber::registry()- .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")))- .with(fmt::layer().with_writer(non_blocking).with_ansi(false))- .with(fmt::layer().with_test_writer())- .init();-- tracing::info!("Test logging initialized, writing to test_logs/");- });-}diff --git a/crates/legacy/uzu/tests/storage.rs b/crates/legacy/uzu/tests/storage.rsnew file mode 100644index 000000000..6e14447a1--- /dev/null+++ b/crates/legacy/uzu/tests/storage.rs@@ -0,0 +1,162 @@+#![cfg(not(target_family = "wasm"))]++mod common;++use std::{sync::Arc, time::Duration};++use download_manager::{DestinationLock, LockOwner};+use kiban::rt::RuntimeHandle;+use mock_registry::{Behavior, MockRegistry, artifact_path};+use rstest::rstest;+use tokio::time::timeout;+use tokio_stream::{StreamExt, wrappers::BroadcastStream};+use uuid::Uuid;+use uzu::{+ engine::Downloader,+ storage::{DownloadManagerType, DownloadPhase, DownloadState, Storage},+ types::model::{ModelAccessibility, ModelIdentifier, ModelReference},+};++use crate::common::TestStorage;++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn model_lifecycle(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;+ let model = registry.models.first().ok_or("mock registry must include a model")?;+ let test_storage = TestStorage::new(RuntimeHandle::current(), vec![model.clone()], kind).await?;+ let storage = &test_storage.storage;+ let identifier = model.identifier.clone();+ let cache_path = storage.cache_model_path(model).ok_or("model must have a cache path")?;+ let mut events = storage.subscribe();+ let total_bytes = storage.state(&identifier).await?.total_bytes;++ storage.download(&identifier).await?;+ let downloading = wait_for(storage, &identifier, &mut events, |state| {+ state.total_bytes > 0 && state.downloaded_bytes >= state.total_bytes / 4+ })+ .await;+ assert!(matches!(downloading.phase, DownloadPhase::Downloading {}), "got {:?}", downloading.phase);++ storage.pause(&identifier).await?;+ let paused =+ wait_for(storage, &identifier, &mut events, |state| matches!(state.phase, DownloadPhase::Paused {})).await;+ assert!(paused.downloaded_bytes >= total_bytes / 4);++ storage.download(&identifier).await?;+ let downloaded =+ wait_for(storage, &identifier, &mut events, |state| matches!(state.phase, DownloadPhase::Downloaded {})).await;+ assert_eq!(downloaded.downloaded_bytes, total_bytes);+ for served in registry.files.iter() {+ let destination = cache_path.join(&served.file.name);+ assert_eq!(tokio::fs::read(&destination).await?, served.bytes.to_vec());+ assert!(artifact_path(&destination, "crc").is_file());+ }++ storage.delete(&identifier).await?;+ let deleted = storage.state(&identifier).await?;+ assert!(matches!(deleted.phase, DownloadPhase::NotDownloaded {}));+ assert_eq!(deleted.downloaded_bytes, 0);+ for served in registry.files.iter() {+ let destination = cache_path.join(&served.file.name);+ assert!(!destination.exists());+ assert!(!artifact_path(&destination, "crc").exists());+ }++ let served = registry.files.first().ok_or("mock registry must include files")?;+ let destination = cache_path.join(&served.file.name);+ tokio::fs::create_dir_all(&cache_path).await?;+ tokio::fs::write(&destination, served.bytes.as_ref()).await?;+ let _lock = DestinationLock::acquire(+ &destination,+ &LockOwner {+ manager_id: "foreign-manager".to_string(),+ instance_id: Uuid::new_v4(),+ },+ )+ .await?;+ let refused = storage.delete(&identifier).await.expect_err("delete must be refused while locked");+ assert!(refused.to_string().contains("foreign-manager"), "unexpected error: {refused}");+ assert!(destination.exists());++ let mut changed = model.clone();+ if let ModelAccessibility::Local {+ reference: ModelReference::Mirai {+ files,+ ..+ },+ } = &mut changed.accessibility+ {+ files.truncate(1);+ }+ storage.refresh(&[changed.clone()]).await?;+ assert_eq!(storage.state(&identifier).await?.total_bytes, served.file.size);+ storage.refresh(&[model.clone(), changed.clone()]).await?;+ assert_eq!(storage.state(&identifier).await?.total_bytes, total_bytes);+ storage.refresh(&[changed, model.clone()]).await?;+ assert_eq!(storage.state(&identifier).await?.total_bytes, served.file.size);+ Ok(())+}++#[rstest]+#[case::universal(DownloadManagerType::Universal)]+#[cfg_attr(target_vendor = "apple", case::native(DownloadManagerType::Native))]+#[tokio::test(flavor = "multi_thread")]+async fn downloader_streams(#[case] kind: DownloadManagerType) -> Result<(), Box<dyn std::error::Error>> {+ let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;+ let model = registry.models.first().ok_or("mock registry must include a model")?;+ let test_storage = TestStorage::new(RuntimeHandle::current(), vec![model.clone()], kind).await?;+ let storage = Arc::clone(&test_storage.storage);+ let identifier = model.identifier.clone();+ let downloader = Downloader::new(identifier.clone(), Arc::clone(&storage));+ let mut events = storage.subscribe();++ downloader.resume().await?;+ let progress = downloader.progress().await?;+ wait_for(&storage, &identifier, &mut events, |state| matches!(state.phase, DownloadPhase::Downloading {})).await;+ downloader.pause().await?;+ timeout(Duration::from_secs(10), async { while progress.next().await.is_some() {} }).await?;+ let paused =+ wait_for(&storage, &identifier, &mut events, |state| matches!(state.phase, DownloadPhase::Paused {})).await;+ assert!(!paused.is_in_progress());+ assert!(!paused.can_pause());++ downloader.resume().await?;+ let progress = downloader.progress().await?;+ let last = timeout(Duration::from_secs(30), async {+ let mut last = None;+ while let Some(state) = progress.next().await {+ last = Some(state);+ }+ last+ })+ .await?;+ assert!(matches!(last.map(|state| state.phase), Some(DownloadPhase::Downloaded {})));+ assert!(downloader.progress().await?.next().await.is_none());+ Ok(())+}++async fn wait_for(+ storage: &Storage,+ identifier: &ModelIdentifier,+ events: &mut BroadcastStream<(ModelIdentifier, DownloadState)>,+ mut is_expected: impl FnMut(&DownloadState) -> bool,+) -> DownloadState {+ timeout(Duration::from_secs(30), async {+ let state = storage.state(identifier).await.expect("model state must exist");+ if is_expected(&state) {+ return state;+ }+ while let Some(result) = events.next().await {+ let (event_identifier, state) = result.expect("storage event stream must not lag");+ if &event_identifier == identifier && is_expected(&state) {+ return state;+ }+ }+ panic!("storage event stream ended before the expected state");+ })+ .await+ .expect("timed out waiting for storage state")+}diff --git a/crates/legacy/uzu/tests/unit/mod.rs b/crates/legacy/uzu/tests/unit/mod.rsdeleted file mode 100644index 80aaac2ba..000000000--- a/crates/legacy/uzu/tests/unit/mod.rs+++ /dev/null@@ -1 +0,0 @@-mod storage;diff --git a/crates/legacy/uzu/tests/unit/storage/lifecycle_mock_registry_model_test.rs b/crates/legacy/uzu/tests/unit/storage/lifecycle_mock_registry_model_test.rsdeleted file mode 100644index b3f9d7fc3..000000000--- a/crates/legacy/uzu/tests/unit/storage/lifecycle_mock_registry_model_test.rs+++ /dev/null@@ -1,330 +0,0 @@-use std::sync::Arc;--use chrono::Utc;-use download_manager::FileDownloadManagerType;-use kiban::rt::RuntimeHandle;-use mock_registry::{Behavior, MockRegistry};-use rstest::rstest;-use tokio::time::{Duration, timeout};-use tokio_stream::{StreamExt, wrappers::BroadcastStream};-use uzu::{- engine::Downloader,- helpers::SharedAccess,- storage::types::{DownloadPhase, DownloadState, Item},-};--use crate::common::{test_storage::TestStorage, tracing_setup::init_test_tracing};--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_mock_registry_model_download_lifecycle(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- init_test_tracing();- tracing::info!("starting storage mock registry lifecycle test");- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let model = registry.models.first().ok_or_else(|| std::io::Error::other("mock registry must include a model"))?;- tracing::info!(model_identifier = %model.identifier, "loaded mock registry model");- let test_storage =- TestStorage::with_models_and_manager(RuntimeHandle::current(), vec![model.clone()], download_manager_type)- .await?;- let model_identifier = model.identifier.clone();- let item = Arc::new(- test_storage- .storage- .get(&model_identifier)- .await- .ok_or_else(|| format!("model not found: {model_identifier}"))?,- );- let mut progress = item.progress().await?;- let total_bytes = item.state().await.total_bytes;-- tracing::info!(total_bytes, "starting first download");- item.download().await?;- let pre_pause_state = wait_for_item_state(&item, &mut progress, "first download reaches 25%", |state| {- has_reached_fraction(state, 1, 4)- })- .await;- assert!(- matches!(pre_pause_state.phase, DownloadPhase::Downloading {}),- "must pause while download is still active to exercise pause/resume; got {:?}",- pre_pause_state.phase- );-- tracing::info!("pausing storage item");- item.pause().await?;- item.reconcile().await?;- let paused_state = wait_for_item_state(&item, &mut progress, "pause transitions to Paused", |state| {- matches!(state.phase, DownloadPhase::Paused {})- })- .await;- tracing::info!(?paused_state, "observed paused state");-- tracing::info!("resuming storage item");- item.download().await?;- let post_resume_state = wait_for_item_state(&item, &mut progress, "resumed download reaches 50%", |state| {- has_reached_fraction(state, 1, 2) || matches!(state.phase, DownloadPhase::Downloaded {})- })- .await;- assert!(- matches!(post_resume_state.phase, DownloadPhase::Downloading {} | DownloadPhase::Downloaded {}),- "resumed model must transition through Downloading and reach Downloaded; got {:?}",- post_resume_state.phase- );-- tracing::info!("cancelling storage item");- item.cancel().await?;- let cancelled_state = item.state().await;- tracing::info!(?cancelled_state, "observed cancelled state");- assert!(matches!(cancelled_state.phase, DownloadPhase::NotDownloaded {}));- assert_eq!(cancelled_state.downloaded_bytes, 0);-- tracing::info!("starting final download");- item.download().await?;- let final_state = wait_for_item_state(&item, &mut progress, "final download completes", |state| {- matches!(state.phase, DownloadPhase::Downloaded {})- })- .await;- tracing::info!(?final_state, "observed final downloaded state");-- assert_eq!(final_state.downloaded_bytes, total_bytes);- assert_eq!(final_state.total_bytes, total_bytes);- for served_file in registry.files {- let destination = item.cache_path.join(&served_file.file.name);- assert_eq!(tokio::fs::read(&destination).await?, served_file.bytes.to_vec());- assert!(std::path::PathBuf::from(format!("{}.crc", destination.display())).is_file());- }-- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_storage_cancel_does_not_delete_locked_files(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- init_test_tracing();- let registry = MockRegistry::start().await?;- let model = registry.models.first().ok_or_else(|| std::io::Error::other("mock registry must include a model"))?;- let test_storage =- TestStorage::with_models_and_manager(RuntimeHandle::current(), vec![model.clone()], download_manager_type)- .await?;- let item = test_storage- .storage- .get(&model.identifier)- .await- .ok_or_else(|| format!("model not found: {}", model.identifier))?;- let served_file =- registry.files.first().ok_or_else(|| std::io::Error::other("mock registry must include files"))?;- let destination = item.cache_path.join(&served_file.file.name);- if let Some(parent) = destination.parent() {- tokio::fs::create_dir_all(parent).await?;- }- tokio::fs::write(&destination, served_file.bytes.as_ref()).await?;- tokio::fs::write(- std::path::PathBuf::from(format!("{}.lock", destination.display())),- serde_json::to_vec(&serde_json::json!({- "manager_id": "foreign-manager",- "acquired_at": Utc::now(),- "process_id": std::process::id(),- }))?,- )- .await?;-- let result = item.cancel().await;-- assert!(result.is_err());- assert!(destination.exists());- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_downloader_progress_stream_closes_after_pause(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- init_test_tracing();- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let model = registry.models.first().ok_or_else(|| std::io::Error::other("mock registry must include a model"))?;- let test_storage =- TestStorage::with_models_and_manager(RuntimeHandle::current(), vec![model.clone()], download_manager_type)- .await?;- let downloader = Downloader::new(model.identifier.clone(), SharedAccess::new(test_storage.storage));-- downloader.resume().await?;- let progress = downloader.progress().await?;- timeout(Duration::from_secs(30), async {- loop {- let state = downloader.state().await.expect("model state must exist");- if matches!(state.phase, DownloadPhase::Downloading {}) {- break;- }- tokio::time::sleep(Duration::from_millis(20)).await;- }- })- .await?;-- downloader.pause().await?;- timeout(Duration::from_secs(10), async { while progress.next().await.is_some() {} }).await?;-- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_downloader_pause_updates_public_state(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- init_test_tracing();- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let model = registry.models.first().ok_or_else(|| std::io::Error::other("mock registry must include a model"))?;- let test_storage =- TestStorage::with_models_and_manager(RuntimeHandle::current(), vec![model.clone()], download_manager_type)- .await?;- let downloader = Downloader::new(model.identifier.clone(), SharedAccess::new(test_storage.storage));-- downloader.resume().await?;- wait_for_downloader_state(&downloader, "downloader reaches Downloading", |state| {- matches!(state.phase, DownloadPhase::Downloading {})- })- .await;-- downloader.pause().await?;- let paused_state = wait_for_downloader_state(&downloader, "downloader reaches Paused", |state| {- matches!(state.phase, DownloadPhase::Paused {})- })- .await;-- assert!(!paused_state.is_in_progress());- assert!(!paused_state.can_pause());- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_downloader_progress_after_resuming_paused_model_reaches_downloaded(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- init_test_tracing();- let registry = MockRegistry::start_with(Behavior::THROTTLED).await?;- let model = registry.models.first().ok_or_else(|| std::io::Error::other("mock registry must include a model"))?;- let test_storage =- TestStorage::with_models_and_manager(RuntimeHandle::current(), vec![model.clone()], download_manager_type)- .await?;- let downloader = Downloader::new(model.identifier.clone(), SharedAccess::new(test_storage.storage));-- downloader.resume().await?;- wait_for_downloader_state(&downloader, "downloader reaches Downloading before pause", |state| {- matches!(state.phase, DownloadPhase::Downloading {})- })- .await;- downloader.pause().await?;- wait_for_downloader_state(&downloader, "downloader reaches Paused before resume", |state| {- matches!(state.phase, DownloadPhase::Paused {})- })- .await;-- downloader.resume().await?;- let progress = downloader.progress().await?;- timeout(Duration::from_secs(30), async {- loop {- let state = downloader.state().await.expect("model state must exist");- if matches!(state.phase, DownloadPhase::Downloaded {}) {- return;- }- assert!(progress.next().await.is_some(), "progress stream ended before the resumed model downloaded");- }- })- .await?;- Ok(())-}--#[rstest]-#[case::universal(FileDownloadManagerType::Universal)]-#[cfg_attr(target_vendor = "apple", case::apple(FileDownloadManagerType::Apple))]-#[tokio::test(flavor = "multi_thread")]-async fn test_downloader_progress_for_downloaded_model_is_empty(- #[case] download_manager_type: FileDownloadManagerType-) -> Result<(), Box<dyn std::error::Error>> {- init_test_tracing();- let registry = MockRegistry::start().await?;- let model = registry.models.first().ok_or_else(|| std::io::Error::other("mock registry must include a model"))?;- let test_storage =- TestStorage::with_models_and_manager(RuntimeHandle::current(), vec![model.clone()], download_manager_type)- .await?;- let downloader = Downloader::new(model.identifier.clone(), SharedAccess::new(test_storage.storage));-- downloader.resume().await?;- wait_for_downloader_state(&downloader, "downloader reaches Downloaded", |state| {- matches!(state.phase, DownloadPhase::Downloaded {})- })- .await;-- let downloaded_progress = downloader.progress().await?;- assert!(downloaded_progress.next().await.is_none());- Ok(())-}--async fn wait_for_item_state(- item: &Arc<Item>,- progress: &mut BroadcastStream<DownloadState>,- label: &'static str,- mut is_expected_state: impl FnMut(&DownloadState) -> bool,-) -> DownloadState {- timeout(Duration::from_secs(30), async {- tracing::info!(label, "waiting for storage download state");- let current_state = item.state().await;- tracing::debug!(label, ?current_state, "observed initial storage download state");- if is_expected_state(¤t_state) {- return current_state;- }-- while let Some(result) = progress.next().await {- let state = result.expect("storage progress stream must not lag");- tracing::debug!(label, ?state, "observed storage progress state");- if is_expected_state(&state) {- return state;- }- }-- panic!("storage progress stream ended before expected state");- })- .await- .unwrap_or_else(|_| panic!("timed out waiting for storage download state: {label}"))-}--async fn wait_for_downloader_state(- downloader: &Downloader,- label: &'static str,- mut is_expected_state: impl FnMut(&DownloadState) -> bool,-) -> DownloadState {- timeout(Duration::from_secs(30), async {- loop {- let state = downloader.state().await.expect("model state must exist");- if is_expected_state(&state) {- return state;- }- tokio::time::sleep(Duration::from_millis(20)).await;- }- })- .await- .unwrap_or_else(|_| panic!("timed out waiting for downloader state: {label}"))-}--fn has_reached_fraction(- state: &DownloadState,- numerator: i64,- denominator: i64,-) -> bool {- state.total_bytes > 0 && state.downloaded_bytes >= state.total_bytes * numerator / denominator-}diff --git a/crates/legacy/uzu/tests/unit/storage/mod.rs b/crates/legacy/uzu/tests/unit/storage/mod.rsdeleted file mode 100644index 3ae7e42c9..000000000--- a/crates/legacy/uzu/tests/unit/storage/mod.rs+++ /dev/null@@ -1 +0,0 @@-mod lifecycle_mock_registry_model_test;diff --git a/crates/legacy/uzu/tests/unit/test_entry.rs b/crates/legacy/uzu/tests/unit/test_entry.rsdeleted file mode 100644index c0d36c57c..000000000--- a/crates/legacy/uzu/tests/unit/test_entry.rs+++ /dev/null@@ -1,4 +0,0 @@-#[path = "../common/mod.rs"]-mod common;--include!("mod.rs");diff --git a/crates/uzu-engine/unit/common/path.rs b/crates/uzu-engine/unit/common/path.rsindex b0fa6cace..b59a3fcbf 100644--- a/crates/uzu-engine/unit/common/path.rs+++ b/crates/uzu-engine/unit/common/path.rs@@ -15,7 +15,7 @@ pub fn get_test_weights_path() -> PathBuf {fn resolve_test_model_path() -> PathBuf {use uzu::{engine::{Engine, EngineConfig},- storage::types::DownloadPhase,+ storage::DownloadPhase,};const TEST_MODEL_REPO_ID: &str = "meta-llama/Llama-3.2-1B-Instruct";