π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Support concurrent asset downloads
Manav Rathid0f40585d5f1
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.ktindex f68981e1f7..b39d62be11 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.kt@@ -19,7 +19,7 @@ import androidx.core.app.NotificationManagerCompatclass AssetDownloadJobService : JobService() {override fun onStartJob(params: JobParameters): Boolean {synchronized(lock) {- if (!downloadActive) return false+ if (cancellations.isEmpty()) return falserunningJob = thisrunningParams = params}@@ -33,14 +33,15 @@ class AssetDownloadJobService : JobService() {}override fun onStopJob(params: JobParameters): Boolean {- val cancel: (() -> Unit)?- synchronized(lock) {+ val callbacks = synchronized(lock) {if (runningParams !== params) return falserunningJob = nullrunningParams = null- cancel = onCancel+ val callbacks = cancellations.values.toList()+ cancellations.clear()+ callbacks}- cancel?.invoke()+ callbacks.forEach { it() }return false}@@ -52,9 +53,9 @@ class AssetDownloadJobService : JobService() {private const val NOTIFY_INTERVAL_MS = 1000Lprivate val lock = Any()+ private val cancellations = mutableMapOf<Long, () -> Unit>()private lateinit var appContext: Context- private var onCancel: (() -> Unit)? = null- private var downloadActive = false+ private var nextId = 0Lprivate var lastNotifyMs = 0Lprivate var runningJob: AssetDownloadJobService? = nullprivate var runningParams: JobParameters? = null@@ -63,17 +64,20 @@ class AssetDownloadJobService : JobService() {appContext = context.applicationContext}- fun begin(onCancelled: () -> Unit) {- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return- synchronized(lock) {- onCancel = onCancelled- downloadActive = true- lastNotifyMs = 0L+ fun begin(onCancelled: () -> Unit): Long {+ val (id, first) = synchronized(lock) {+ val id = nextId+++ val first = cancellations.isEmpty()+ cancellations[id] = onCancelled+ if (first) lastNotifyMs = 0L+ id to first}+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return id+ if (!first) return idval scheduler = appContext.getSystemService(JobScheduler::class.java)if (scheduler == null) {Log.w(TAG, "JobScheduler unavailable")- return+ return id}val job = JobInfo.Builder(JOB_ID, ComponentName(appContext, AssetDownloadJobService::class.java)).setUserInitiated(true)@@ -81,45 +85,49 @@ class AssetDownloadJobService : JobService() {.build()val result = runCatching { scheduler.schedule(job) }.getOrElse { error ->Log.w(TAG, "Download job schedule failed", error)- return+ return id}if (result != JobScheduler.RESULT_SUCCESS) {Log.w(TAG, "Download job not scheduled")}+ return id}- fun update(percent: Int, indeterminate: Boolean) {+ fun update(id: Long, percent: Int, indeterminate: Boolean) {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) returnval job: AssetDownloadJobServiceval params: JobParameters+ val shownPercent: Int+ val shownIndeterminate: Booleansynchronized(lock) {- if (!downloadActive) return+ if (id !in cancellations) returnjob = runningJob ?: returnparams = runningParams ?: returnval now = SystemClock.elapsedRealtime()if (now - lastNotifyMs < NOTIFY_INTERVAL_MS) returnlastNotifyMs = now+ shownPercent = if (cancellations.size == 1) percent else 0+ shownIndeterminate = cancellations.size != 1 || indeterminate}job.setNotification(params,NOTIFICATION_ID,- buildNotification(appContext, percent, indeterminate),+ buildNotification(appContext, shownPercent, shownIndeterminate),JOB_END_NOTIFICATION_POLICY_REMOVE)}- fun end() {- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return- val job: AssetDownloadJobService?- val params: JobParameters?- synchronized(lock) {- downloadActive = false- onCancel = null- job = runningJob- params = runningParams+ fun end(id: Long) {+ val state = synchronized(lock) {+ if (cancellations.remove(id) == null) return+ if (cancellations.isNotEmpty()) return+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return+ val state = runningJob to runningParamsrunningJob = nullrunningParams = null+ state}+ val (job, params) = stateif (job != null && params != null) {job.jobFinished(params, false)} else {diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.ktindex 73ab0b8db6..48b10b3f00 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.kt@@ -20,7 +20,6 @@ import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.asyncimport kotlinx.coroutines.coroutineScope-import kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.withContextclass AssetStore(context: Context) {@@ -29,7 +28,6 @@ class AssetStore(context: Context) {private val legacyLlmDir = appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.let { File(it, "llm") }private val legacyTranscriptionDir = File(appContext.dataDir, "app_ensu_transcription_models")- private val downloadMutex = Mutex()private val core: AssetStoreCoreinit {@@ -55,8 +53,6 @@ class AssetStore(context: Context) {mmprojUrl = mmprojUrl)- val isDownloadActive: Boolean get() = core.isDownloadActive()-fun assetDir(asset: Asset): File = File(core.assetDir(asset))fun llmModelPath(asset: Asset): File? =@@ -85,22 +81,10 @@ class AssetStore(context: Context) {assets: List<Asset>,onProgress: (AssetDownloadProgress) -> Unit): Unit = withContext(Dispatchers.IO) {- if (!downloadMutex.tryLock()) throw DownloadAlreadyActiveException()- try {- downloadLocked(assets, onProgress)- } finally {- downloadMutex.unlock()- }- }-- private suspend fun downloadLocked(- assets: List<Asset>,- onProgress: (AssetDownloadProgress) -> Unit- ) {- if (assets.all { core.isDownloaded(it) }) return+ if (assets.all { core.isDownloaded(it) }) return@withContextval token = CancellationToken()- AssetDownloadJobService.begin { token.cancel() }+ val lease = AssetDownloadJobService.begin { token.cancel() }try {coroutineScope {val download = async {@@ -110,6 +94,7 @@ class AssetStore(context: Context) {override fun onProgress(progress: AssetDownloadProgress) {progress.logLine?.let { Log.i("AssetStore", it) }AssetDownloadJobService.update(+ lease,progress.percentage.toInt(),progress.totalBytes == null)@@ -127,9 +112,7 @@ class AssetStore(context: Context) {}}} finally {- AssetDownloadJobService.end()+ AssetDownloadJobService.end(lease)}}}--private class DownloadAlreadyActiveException : Exception("An asset download is already active")diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.ktindex 84177f186a..3df30be935 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt@@ -22,6 +22,7 @@ import io.ente.ensu.device.AndroidDeviceCapabilityProviderimport io.ente.ensu.device.requireChatSupportedimport io.ente.ensu.settings.IS_ENSU_PACKS_ENABLEDimport java.io.File+import java.util.concurrent.atomic.AtomicIntegerimport kotlin.math.maximport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.sync.Mutex@@ -51,6 +52,7 @@ class LlmProvider(@Volatile private var currentJobId: Long? = nullprivate var backendInitialized = falseprivate val modelLoadMutex = Mutex()+ private val activeDownloads = AtomicInteger()private val embeddingAsset = knowledgeEmbeddingModelAsset()class EmbeddingAssetInvalid : Exception("Embedding model asset is invalid")@@ -68,7 +70,7 @@ class LlmProvider(assetStore.estimateDownloadSize(chatAsset(selection))val isDownloadActive: Boolean- get() = assetStore.isDownloadActive+ get() = activeDownloads.get() > 0suspend fun ensureModelReady(selection: LlmModelSelection,@@ -327,13 +329,18 @@ class LlmProvider(assets: List<Asset>,onProgress: (DownloadProgress) -> Unit) {- assetStore.download(assets) { progress ->- onProgress(- DownloadProgress(- progress.percentage.toInt().coerceIn(0, 99),- progress.status+ activeDownloads.incrementAndGet()+ try {+ assetStore.download(assets) { progress ->+ onProgress(+ DownloadProgress(+ progress.percentage.toInt().coerceIn(0, 99),+ progress.status+ ))- )+ }+ } finally {+ activeDownloads.decrementAndGet()}}diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/AssetStore.swift b/mobile/native/apple/apps/ensu/Ensu/Services/AssetStore.swiftindex a0ae8b69cc..6b7f832866 100644--- a/mobile/native/apple/apps/ensu/Ensu/Services/AssetStore.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Services/AssetStore.swift@@ -5,8 +5,6 @@ private let logger = EnsuLogging.shared.logger("AssetStore")final class AssetStore: @unchecked Sendable {private let core: AssetStoreCore- private let activeLock = NSLock()- private var downloadActive = false@MainActorinit() {@@ -93,27 +91,22 @@ final class AssetStore: @unchecked Sendable {onProgress: @escaping (AssetDownloadProgress) -> Void) async throws {let token = CancellationToken()- let started = activeLock.withLock { () -> Bool in- if downloadActive { return false }- downloadActive = true- return true- }- guard started else { throw DownloadAlreadyActiveError() }- defer { activeLock.withLock { downloadActive = false } }-if assets.allSatisfy({ self.core.isDownloaded(asset: $0) }) {return}+ let leaseId: UUID?if #available(iOS 26.0, *) {- AssetDownloadBackgroundTask.begin {+ leaseId = AssetDownloadBackgroundTask.begin {token.cancel()}+ } else {+ leaseId = nil}var succeeded = falsedefer {- if #available(iOS 26.0, *) {- AssetDownloadBackgroundTask.end(success: succeeded)+ if #available(iOS 26.0, *), let leaseId {+ AssetDownloadBackgroundTask.end(id: leaseId, success: succeeded)}}@@ -124,8 +117,9 @@ final class AssetStore: @unchecked Sendable {if let line = progress.logLine {logger.info(line)}- if #available(iOS 26.0, *) {+ if #available(iOS 26.0, *), let leaseId {AssetDownloadBackgroundTask.update(+ id: leaseId,downloadedBytes: progress.downloadedBytes,totalBytes: progress.totalBytes)@@ -145,8 +139,6 @@ final class AssetStore: @unchecked Sendable {}}-private struct DownloadAlreadyActiveError: Error {}-private final class AssetDownloadCallbackSink: AssetDownloadCallback, @unchecked Sendable {private let onProgressHandler: (AssetDownloadProgress) -> Void@@ -164,8 +156,8 @@ private enum AssetDownloadBackgroundTask {private static let identifier = "io.ente.ensu.asset-download"private static let lock = NSLock()private static var task: BGContinuedProcessingTask?- private static var onExpiration: (() -> Void)?- private static var downloadActive = false+ private static var cancellations: [UUID: () -> Void] = [:]+ private static var allSucceeded = truestatic func register() {BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil) { bgTask in@@ -177,11 +169,15 @@ private enum AssetDownloadBackgroundTask {}}- static func begin(onExpiration: @escaping () -> Void) {- lock.lock()- downloadActive = true- Self.onExpiration = onExpiration- lock.unlock()+ static func begin(onExpiration: @escaping () -> Void) -> UUID {+ let id = UUID()+ let first = lock.withLock {+ let first = cancellations.isEmpty+ if first { allSucceeded = true }+ cancellations[id] = onExpiration+ return first+ }+ guard first else { return id }let request = BGContinuedProcessingTaskRequest(identifier: identifier,@@ -194,49 +190,61 @@ private enum AssetDownloadBackgroundTask {} catch {logger.warning("Background download task not scheduled", details: "\(error)")}+ return id}- static func update(downloadedBytes: Int64, totalBytes: Int64?) {- lock.lock()- let task = task- lock.unlock()- guard let task, let totalBytes, totalBytes > 0 else { return }+ static func update(id: UUID, downloadedBytes: Int64, totalBytes: Int64?) {+ let state: (task: BGContinuedProcessingTask?, activeCount: Int)? = lock.withLock {+ guard cancellations[id] != nil else { return nil }+ return (task, cancellations.count)+ }+ guard let state, let task = state.task else { return }+ guard state.activeCount == 1, let totalBytes, totalBytes > 0 else {+ task.progress.totalUnitCount = -1+ task.progress.completedUnitCount = 0+ return+ }task.progress.totalUnitCount = totalBytestask.progress.completedUnitCount = min(downloadedBytes, totalBytes)}- static func end(success: Bool) {- lock.lock()- downloadActive = false- onExpiration = nil- let task = task- Self.task = nil- lock.unlock()- task?.setTaskCompleted(success: success)+ static func end(id: UUID, success: Bool) {+ let completion: (BGContinuedProcessingTask?, Bool)? = lock.withLock {+ guard cancellations.removeValue(forKey: id) != nil else { return nil }+ allSucceeded = allSucceeded && success+ guard cancellations.isEmpty else { return nil }+ let completed = (task, allSucceeded)+ task = nil+ return completed+ }+ if let completion {+ completion.0?.setTaskCompleted(success: completion.1)+ }}private static func adopt(_ bgTask: BGContinuedProcessingTask) {- lock.lock()- guard downloadActive else {- lock.unlock()+ let adopted = lock.withLock {+ guard !cancellations.isEmpty else { return false }+ task = bgTask+ return true+ }+ guard adopted else {bgTask.setTaskCompleted(success: true)return}- task = bgTask- lock.unlock()bgTask.expirationHandler = {- lock.lock()- let expired = task === bgTask- let handler = onExpiration- if expired {+ let callbacks = lock.withLock {+ guard task === bgTask else { return [() -> Void]() }task = nil+ let callbacks = Array(cancellations.values)+ cancellations.removeAll()+ return callbacks}- lock.unlock()- if expired {- handler?()- bgTask.setTaskCompleted(success: false)- }+ guard !callbacks.isEmpty else { return }+ callbacks.forEach { $0() }+ bgTask.setTaskCompleted(success: false)}}+}diff --git a/rust/apps/ensu/src-tauri/src/commands/llm.rs b/rust/apps/ensu/src-tauri/src/commands/llm.rsindex 31fdc7017a..6ea3c29d56 100644--- a/rust/apps/ensu/src-tauri/src/commands/llm.rs+++ b/rust/apps/ensu/src-tauri/src/commands/llm.rs@@ -307,9 +307,9 @@ pub async fn llm_download_model(};let result = store.download(- &asset,+ std::slice::from_ref(&asset),|progress| {- let progress = ente_ensu::model::display_progress(progress);+ let progress = ente_ensu::model::display_progress(&progress);if let Some(line) = &progress.log_line {logging::log("LLMDownload", line.clone());}diff --git a/rust/bindings/uniffi/ensu/src/assets.rs b/rust/bindings/uniffi/ensu/src/assets.rsindex f1ce142241..8d7f7e7b08 100644--- a/rust/bindings/uniffi/ensu/src/assets.rs+++ b/rust/bindings/uniffi/ensu/src/assets.rs@@ -1,17 +1,16 @@use std::path::PathBuf;-use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, OnceLock};-use ente_assets::{Asset as RustAsset, AssetStore as RustAssetStore, download};+use ente_assets::download;use thiserror::Error;#[derive(uniffi::Object)]pub struct Asset {- pub(crate) inner: RustAsset,+ pub(crate) inner: ente_assets::Asset,}impl Asset {- pub(crate) fn new(inner: RustAsset) -> Arc<Self> {+ pub(crate) fn new(inner: ente_assets::Asset) -> Arc<Self> {Arc::new(Self { inner })}}@@ -20,22 +19,22 @@ impl Asset {pub enum AssetDownloadError {#[error("download cancelled")]Cancelled,- #[error("{message}")]- Validation { message: String },+ #[error("{detail}")]+ Validation { detail: String },#[error("HTTP {status}")]Http { status: u16 },- #[error("network: {message}")]- Network { message: String },+ #[error("network: {detail}")]+ Network { detail: String },#[error("size mismatch: expected {expected} bytes, got {actual}")]SizeMismatch { expected: u64, actual: u64 },- #[error("range protocol violation: {message}")]- Protocol { message: String },- #[error("invalid download target: {message}")]- InvalidTarget { message: String },+ #[error("range protocol violation: {detail}")]+ Protocol { detail: String },+ #[error("invalid download target: {detail}")]+ InvalidTarget { detail: String },#[error("not enough storage space")]StorageFull,- #[error("{message}")]- Io { message: String },+ #[error("{detail}")]+ Io { detail: String },}impl From<download::Error> for AssetDownloadError {@@ -44,20 +43,20 @@ impl From<download::Error> for AssetDownloadError {download::Error::Cancelled => Self::Cancelled,download::Error::Target { source, .. } => Self::from(*source),download::Error::Fallback { single, .. } => Self::from(*single),- download::Error::Validation(message) => Self::Validation { message },+ download::Error::Validation(detail) => Self::Validation { detail },download::Error::Http(status) => Self::Http { status },- download::Error::Network(message) => Self::Network { message },+ download::Error::Network(detail) => Self::Network { detail },download::Error::SizeMismatch { expected, actual } => {Self::SizeMismatch { expected, actual }}- download::Error::Protocol(message) => Self::Protocol { message },- download::Error::InvalidTarget(message) => Self::InvalidTarget { message },+ download::Error::Protocol(detail) => Self::Protocol { detail },+ download::Error::InvalidTarget(detail) => Self::InvalidTarget { detail },download::Error::StorageFull => Self::StorageFull,download::Error::Io(error) => Self::Io {- message: error.to_string(),+ detail: error.to_string(),},download::Error::Json(error) => Self::Io {- message: error.to_string(),+ detail: error.to_string(),},}}@@ -93,11 +92,11 @@ pub struct AssetDownloadProgress {pub log_line: Option<String>,}-impl From<ente_assets::download::Progress> for AssetDownloadProgress {- fn from(value: ente_assets::download::Progress) -> Self {- let display = ente_ensu::model::display_progress(value.clone());+impl From<ente_assets::AssetDownloadProgress> for AssetDownloadProgress {+ fn from(value: ente_assets::AssetDownloadProgress) -> Self {+ let display = ente_ensu::model::display_progress(&value);Self {- label: value.label,+ label: value.asset_progress.label,downloaded_bytes: i64::try_from(value.downloaded_bytes).unwrap_or(i64::MAX),total_bytes: value.total_bytes@@ -149,9 +148,8 @@ pub fn migrate_ensu_assets(assets_dir: String, legacy: LegacyAssets) -> Option<S#[derive(uniffi::Object)]pub struct AssetStoreCore {- inner: RustAssetStore,+ inner: ente_assets::AssetStore,runtime: OnceLock<tokio::runtime::Runtime>,- active_downloads: AtomicUsize,}#[uniffi::export]@@ -159,9 +157,8 @@ impl AssetStoreCore {#[uniffi::constructor]pub fn new(assets_dir: String) -> Arc<Self> {Arc::new(Self {- inner: RustAssetStore::new(assets_dir),+ inner: ente_assets::AssetStore::new(assets_dir),runtime: OnceLock::new(),- active_downloads: AtomicUsize::new(0),})}@@ -189,14 +186,13 @@ impl AssetStoreCore {self.inner.is_downloaded(&asset.inner)}- pub fn is_download_active(&self) -> bool {- self.active_downloads.load(Ordering::SeqCst) > 0- }-pub fn estimated_download_size(&self, asset: Arc<Asset>) -> Option<i64> {self.runtime().ok()?- .block_on(self.inner.estimated_download_size(&asset.inner))+ .block_on(+ self.inner+ .estimated_download_size(std::slice::from_ref(&asset.inner)),+ ).map(|size| i64::try_from(size).unwrap_or(i64::MAX))}@@ -214,28 +210,25 @@ impl AssetStoreCore {callback: Box<dyn AssetDownloadCallback>,cancellation: Arc<CancellationToken>,) -> Result<(), AssetDownloadError> {- self.active_downloads.fetch_add(1, Ordering::SeqCst);- let result = self.runtime().and_then(|runtime| {- runtime.block_on(async {- for asset in assets {- self.inner- .download(- &asset.inner,- |progress| callback.on_progress(progress.into()),- cancellation.inner.clone(),- )- .await?;- }- Ok(())- })- });- self.active_downloads.fetch_sub(1, Ordering::SeqCst);- result.map_err(Into::into)+ let assets = assets+ .into_iter()+ .map(|asset| asset.inner.clone())+ .collect::<Vec<_>>();+ match self.runtime() {+ Ok(runtime) => runtime+ .block_on(self.inner.download(+ &assets,+ |progress| callback.on_progress(progress.into()),+ cancellation.inner.clone(),+ ))+ .map_err(AssetDownloadError::from),+ Err(error) => Err(AssetDownloadError::from(error)),+ }}}impl AssetStoreCore {- pub(crate) fn store(&self) -> &RustAssetStore {+ pub(crate) fn store(&self) -> &ente_assets::AssetStore {&self.inner}diff --git a/rust/crates/assets/Cargo.toml b/rust/crates/assets/Cargo.tomlindex 0c1cf76068..819f9c64b1 100644--- a/rust/crates/assets/Cargo.toml+++ b/rust/crates/assets/Cargo.toml@@ -11,7 +11,7 @@ serde_json.workspace = truesha2 = "0.11.0"tar = "0.4.46"thiserror.workspace = true-tokio = { version = "1", features = ["sync"] }+tokio = { version = "1", features = ["macros", "sync"] }[dev-dependencies]-tokio = { version = "1", features = ["macros", "rt"] }+tokio = { version = "1", features = ["rt"] }diff --git a/rust/crates/assets/src/download.rs b/rust/crates/assets/src/download.rsindex 35268e3b56..1c3937065f 100644--- a/rust/crates/assets/src/download.rs+++ b/rust/crates/assets/src/download.rs@@ -10,6 +10,7 @@ use reqwest::header::{ACCEPT_RANGES, CONTENT_RANGE, ETAG, IF_RANGE, LAST_MODIFIEuse reqwest::{Client, Response, StatusCode};use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};+use tokio::sync::Notify;const MIN_RANGE_DOWNLOAD_BYTES: u64 = 1024 * 1024;const MAX_ATTEMPTS: usize = 3;@@ -89,9 +90,15 @@ pub struct Progress {pub complete: bool,}+#[derive(Default)]+struct CancellationState {+ cancelled: AtomicBool,+ changed: Notify,+}+#[derive(Clone, Default)]pub struct CancellationToken {- cancelled: Arc<AtomicBool>,+ state: Arc<CancellationState>,}impl CancellationToken {@@ -100,11 +107,26 @@ impl CancellationToken {}pub fn cancel(&self) {- self.cancelled.store(true, Ordering::SeqCst);+ if !self.state.cancelled.swap(true, Ordering::SeqCst) {+ self.state.changed.notify_waiters();+ }}pub fn is_cancelled(&self) -> bool {- self.cancelled.load(Ordering::SeqCst)+ self.state.cancelled.load(Ordering::SeqCst)+ }++ pub(crate) async fn cancelled(&self) {+ if self.is_cancelled() {+ return;+ }+ let changed = self.state.changed.notified();+ tokio::pin!(changed);+ changed.as_mut().enable();+ if self.is_cancelled() {+ return;+ }+ changed.await;}}diff --git a/rust/crates/assets/src/lib.rs b/rust/crates/assets/src/lib.rsindex a4db6103d2..6f04c806e1 100644--- a/rust/crates/assets/src/lib.rs+++ b/rust/crates/assets/src/lib.rs@@ -2,4 +2,4 @@ mod archive;pub mod download;mod store;-pub use store::{Asset, AssetFile, AssetStore};+pub use store::{Asset, AssetDownloadProgress, AssetFile, AssetStore, AssetStoreError};diff --git a/rust/crates/assets/src/store.rs b/rust/crates/assets/src/store.rsindex 420dd9f465..69252d8b55 100644--- a/rust/crates/assets/src/store.rs+++ b/rust/crates/assets/src/store.rs@@ -1,9 +1,10 @@-use std::collections::HashSet;+use std::collections::{HashMap, HashSet};use std::fs;use std::path::{Path, PathBuf};-use std::sync::OnceLock;+use std::sync::{Arc, OnceLock};-use tokio::sync::Mutex;+use futures_util::future::join_all;+use tokio::sync::{Mutex, Semaphore};use crate::archive;use crate::download::{self, CancellationToken, DownloadTarget, Downloader, Error, Progress};@@ -11,6 +12,7 @@ use crate::download::{self, CancellationToken, DownloadTarget, Downloader, Errorconst STAGING_DIR: &str = ".staging";const ARCHIVE_FILE: &str = ".archive.tar.gz";const EXTRACTION_DIR: &str = ".extracted";+const ASSET_CONCURRENCY: usize = 2;#[derive(Debug, Clone, PartialEq, Eq)]pub struct Asset {@@ -31,6 +33,22 @@ pub struct AssetFile {pub sha256: String,}+#[derive(Debug, Clone)]+pub struct AssetDownloadProgress {+ pub asset_progress: Progress,+ pub downloaded_bytes: u64,+ pub total_bytes: Option<u64>,+ pub percentage: f64,+}++#[derive(Debug, thiserror::Error)]+pub enum AssetStoreError {+ #[error(transparent)]+ Download(#[from] Error),+ #[error("asset is busy")]+ Busy,+}+impl Asset {pub fn file(components: Vec<String>, file: AssetFile) -> Result<Self, Error> {Self::files(components, vec![file])@@ -71,7 +89,8 @@ impl Asset {pub struct AssetStore {root: PathBuf,downloader: OnceLock<Downloader>,- mutation_gate: Mutex<()>,+ asset_locks: std::sync::Mutex<HashMap<Vec<String>, Arc<Mutex<()>>>>,+ asset_slots: Semaphore,}impl AssetStore {@@ -79,7 +98,8 @@ impl AssetStore {Self {root: root.into(),downloader: OnceLock::new(),- mutation_gate: Mutex::new(()),+ asset_locks: std::sync::Mutex::new(HashMap::new()),+ asset_slots: Semaphore::new(ASSET_CONCURRENCY),}}@@ -106,62 +126,134 @@ impl AssetStore {}}- pub async fn estimated_download_size(&self, asset: &Asset) -> Option<u64> {- if self.is_downloaded(asset) {- return Some(0);+ pub async fn estimated_download_size(&self, assets: &[Asset]) -> Option<u64> {+ let mut total = 0u64;+ for asset in assets {+ if self.is_downloaded(asset) {+ continue;+ }+ total = total.checked_add(+ self.downloader()+ .ok()?+ .estimated_download_size(&self.download_targets(asset))+ .await?,+ )?;}- self.downloader()- .ok()?- .estimated_download_size(&self.download_targets(asset))- .await+ Some(total)}pub async fn download(&self,- asset: &Asset,- mut on_progress: impl FnMut(Progress) + Send,+ assets: &[Asset],+ on_progress: impl FnMut(AssetDownloadProgress) + Send,cancellation: CancellationToken,) -> Result<(), Error> {- let _guard = self.mutation_gate.lock().await;- if self.is_downloaded(asset) {- return Ok(());+ if cancellation.is_cancelled() {+ return Err(Error::Cancelled);}++ let mut keys = HashSet::new();+ for asset in assets {+ if !keys.insert(&asset.components) {+ return Err(Error::InvalidTarget(format!(+ "duplicate asset key {}",+ asset.components.join("/")+ )));+ }+ }++ let locks = assets+ .iter()+ .map(|asset| self.asset_lock(asset))+ .collect::<Result<Vec<_>, _>>()?;+ let progress = std::sync::Mutex::new(BatchProgress::new(assets.len(), on_progress));+ let jobs = assets+ .iter()+ .zip(locks)+ .enumerate()+ .map(|(asset_index, (asset, lock))| {+ self.download_asset(asset_index, asset, lock, &progress, cancellation.clone())+ });+ let results = join_all(jobs).await;if cancellation.is_cancelled() {return Err(Error::Cancelled);}+ if let Some(error) = results.into_iter().find_map(Result::err) {+ return Err(error);+ }+ Ok(())+ }++ pub async fn remove(&self, asset: &Asset) -> Result<(), AssetStoreError> {+ let lock = self.asset_lock(asset)?;+ let _guard = lock.try_lock().map_err(|_| AssetStoreError::Busy)?;+ remove_path(&self.asset_dir(asset))?;+ remove_path(&self.staging_dir(asset))?;+ Ok(())+ }++ async fn download_asset<F>(+ &self,+ asset_index: usize,+ asset: &Asset,+ lock: Arc<Mutex<()>>,+ progress: &std::sync::Mutex<BatchProgress<F>>,+ cancellation: CancellationToken,+ ) -> Result<(), Error>+ where+ F: FnMut(AssetDownloadProgress) + Send,+ {+ let _guard = tokio::select! {+ guard = lock.lock() => guard,+ _ = cancellation.cancelled() => return Err(Error::Cancelled),+ };+ if self.is_downloaded(asset) {+ progress.lock().expect("progress lock").skip(asset_index);+ return Ok(());+ }+ let _slot = tokio::select! {+ slot = self.asset_slots.acquire() => slot.expect("asset semaphore closed"),+ _ = cancellation.cancelled() => return Err(Error::Cancelled),+ };- let mut last_progress = None;self.downloader()?.download(self.download_targets(asset),- |mut progress| {- progress.complete = false;- last_progress = Some(progress.clone());- on_progress(progress);+ |mut update| {+ update.complete = false;+ progress+ .lock()+ .expect("progress lock")+ .update(asset_index, update);},cancellation.clone(),).await?;-match &asset.kind {AssetKind::Files(files) => self.publish_files(asset, files)?,AssetKind::TarGz { .. } => self.publish_archive(asset, cancellation).await?,}-- if let Some(mut progress) = last_progress {- progress.percentage = 100.0;- progress.file_complete = false;- progress.complete = true;- on_progress(progress);- }Ok(())}- pub async fn remove(&self, asset: &Asset) -> Result<(), Error> {- let _guard = self.mutation_gate.lock().await;- remove_path(&self.asset_dir(asset))?;- remove_path(&self.staging_dir(asset))?;- Ok(())+ fn asset_lock(&self, asset: &Asset) -> Result<Arc<Mutex<()>>, Error> {+ let mut locks = self.asset_locks.lock().expect("asset lock registry");+ if let Some((key, lock)) = locks+ .iter()+ .find(|(key, _)| keys_overlap(key, &asset.components))+ {+ if *key == asset.components {+ return Ok(Arc::clone(lock));+ }+ return Err(Error::InvalidTarget(format!(+ "asset keys {} and {} overlap",+ key.join("/"),+ asset.components.join("/")+ )));+ }+ let lock = Arc::new(Mutex::new(()));+ locks.insert(asset.components.clone(), Arc::clone(&lock));+ Ok(lock)}fn downloader(&self) -> Result<&Downloader, Error> {@@ -271,6 +363,67 @@ impl AssetStore {}}+struct BatchProgress<F> {+ assets: Vec<Option<Progress>>,+ pending: Vec<bool>,+ callback: F,+}++impl<F> BatchProgress<F>+where+ F: FnMut(AssetDownloadProgress),+{+ fn new(asset_count: usize, callback: F) -> Self {+ Self {+ assets: vec![None; asset_count],+ pending: vec![true; asset_count],+ callback,+ }+ }++ fn skip(&mut self, asset_index: usize) {+ self.pending[asset_index] = false;+ }++ fn update(&mut self, asset_index: usize, asset_progress: Progress) {+ self.pending[asset_index] = false;+ self.assets[asset_index] = Some(asset_progress.clone());+ self.emit(asset_progress);+ }++ fn emit(&mut self, asset_progress: Progress) {+ let downloaded_bytes = self+ .assets+ .iter()+ .flatten()+ .map(|progress| progress.downloaded_bytes)+ .sum();+ let total_bytes = (!self.pending.iter().any(|pending| *pending))+ .then(|| {+ self.assets+ .iter()+ .flatten()+ .map(|progress| progress.total_bytes)+ .try_fold(0u64, |total, value| total.checked_add(value?))+ })+ .flatten();+ let percentage = total_bytes+ .filter(|total| *total > 0)+ .map(|total| ((downloaded_bytes as f64 / total as f64) * 100.0).clamp(0.0, 100.0))+ .unwrap_or(0.0);+ (self.callback)(AssetDownloadProgress {+ asset_progress,+ downloaded_bytes,+ total_bytes,+ percentage,+ });+ }+}++fn keys_overlap(left: &[String], right: &[String]) -> bool {+ left.starts_with(right) || right.starts_with(left)+}+fn validate_components(components: &[String]) -> Result<(), Error> {if components.is_empty() {return Err(Error::InvalidTarget(@@ -355,8 +508,12 @@ mod tests {let store = AssetStore::new("assets");let asset =Asset::files(key(&["models", "clip"]), vec![file("model.onnx", b"model")]).unwrap();- assert_send(store.download(&asset, |_| {}, CancellationToken::default()));- assert_send(store.estimated_download_size(&asset));+ assert_send(store.download(+ std::slice::from_ref(&asset),+ |_| {},+ CancellationToken::default(),+ ));+ assert_send(store.estimated_download_size(std::slice::from_ref(&asset)));assert_send(store.remove(&asset));}@@ -379,7 +536,7 @@ mod tests {}#[tokio::test]- async fn publishes_all_files_before_reporting_completion() {+ async fn publishes_all_files() {let root = scratch_dir("files");let store = AssetStore::new(&root);let asset = Asset::files(@@ -394,21 +551,15 @@ mod tests {);let final_dir = store.asset_dir(&asset);- let mut completion_observed_after_publish = false;store.download(- &asset,- |progress| {- if progress.complete {- completion_observed_after_publish = final_dir.is_dir();- }- },+ std::slice::from_ref(&asset),+ |_| {},CancellationToken::default(),).await.unwrap();- assert!(completion_observed_after_publish);assert!(store.is_downloaded(&asset));assert_eq!(fs::read(final_dir.join("model.onnx")).unwrap(), b"model");assert_eq!(fs::read(final_dir.join("vocab.txt")).unwrap(), b"vocab");@@ -416,6 +567,118 @@ mod tests {let _ = fs::remove_dir_all(root);}+ #[tokio::test]+ async fn aggregates_progress_across_assets() {+ let root = scratch_dir("batch");+ let store = AssetStore::new(&root);+ let first = Asset::files(key(&["models", "first"]), vec![file("model", b"first")]).unwrap();+ let second =+ Asset::files(key(&["models", "second"]), vec![file("model", b"second")]).unwrap();+ stage_files(&store, &first, &[("model", b"first")]);+ stage_files(&store, &second, &[("model", b"second")]);+ let mut latest_progress = None;++ store+ .download(+ &[first.clone(), second.clone()],+ |progress| {+ latest_progress = Some((+ progress.downloaded_bytes,+ progress.total_bytes,+ progress.percentage,+ ));+ },+ CancellationToken::default(),+ )+ .await+ .unwrap();++ assert!(store.is_downloaded(&first));+ assert!(store.is_downloaded(&second));+ assert_eq!(latest_progress, Some((11, Some(11), 100.0)));+ let _ = fs::remove_dir_all(root);+ }++ #[tokio::test]+ async fn publishes_successful_assets_when_a_sibling_fails() {+ let root = scratch_dir("batch-failure");+ let store = AssetStore::new(&root);+ let good = Asset::files(key(&["models", "good"]), vec![file("model", b"good")]).unwrap();+ let mut bad_file = file("model", b"bad");+ bad_file.url = ":".to_string();+ let bad = Asset::files(key(&["models", "bad"]), vec![bad_file]).unwrap();+ stage_files(&store, &good, &[("model", b"good")]);++ store+ .download(+ &[good.clone(), bad.clone()],+ |_| {},+ CancellationToken::default(),+ )+ .await+ .unwrap_err();++ assert!(store.is_downloaded(&good));+ assert!(!store.is_downloaded(&bad));+ let _ = fs::remove_dir_all(root);+ }++ #[tokio::test]+ async fn asset_locks_are_keyed_and_cancellable() {+ let root = scratch_dir("locks");+ let store = Arc::new(AssetStore::new(&root));+ let asset = Asset::files(key(&["models", "same"]), vec![file("model", b"model")]).unwrap();+ assert!(matches!(+ store+ .download(+ &[asset.clone(), asset.clone()],+ |_| {},+ CancellationToken::default()+ )+ .await,+ Err(Error::InvalidTarget(_))+ ));+ let lock = store.asset_lock(&asset).unwrap();+ let guard = lock.lock().await;+ assert!(matches!(+ store.remove(&asset).await,+ Err(AssetStoreError::Busy)+ ));++ let token = CancellationToken::new();+ let cancellation = token.clone();+ let waiting_store = Arc::clone(&store);+ let waiting_asset = asset.clone();+ let waiter = tokio::spawn(async move {+ waiting_store+ .download(&[waiting_asset], |_| {}, token)+ .await+ });+ tokio::task::yield_now().await;+ cancellation.cancel();+ assert!(matches!(waiter.await.unwrap(), Err(Error::Cancelled)));+ drop(guard);++ stage_files(&store, &asset, &[("model", b"model")]);+ let first_assets = [asset.clone()];+ let second_assets = [asset.clone()];+ let (first, second) = tokio::join!(+ store.download(&first_assets, |_| {}, CancellationToken::default()),+ store.download(&second_assets, |_| {}, CancellationToken::default())+ );+ first.unwrap();+ second.unwrap();+ assert!(store.is_downloaded(&asset));++ let nested = Asset::files(+ key(&["models", "same", "nested"]),+ vec![file("model", b"model")],+ )+ .unwrap();+ assert!(store.asset_lock(&nested).is_err());+ let _ = fs::remove_dir_all(root);+ }+#[tokio::test]async fn ignores_derived_files_and_discards_them_when_rebuilding() {let root = scratch_dir("derived");@@ -427,7 +690,11 @@ mod tests {.unwrap();stage_files(&store, &asset, &[("runtime.tgz", b"archive")]);store- .download(&asset, |_| {}, CancellationToken::default())+ .download(+ std::slice::from_ref(&asset),+ |_| {},+ CancellationToken::default(),+ ).await.unwrap();@@ -439,7 +706,11 @@ mod tests {assert!(!store.is_downloaded(&asset));stage_files(&store, &asset, &[("runtime.tgz", b"archive")]);store- .download(&asset, |_| {}, CancellationToken::default())+ .download(+ std::slice::from_ref(&asset),+ |_| {},+ CancellationToken::default(),+ ).await.unwrap();@@ -467,7 +738,11 @@ mod tests {fs::write(staging.join(ARCHIVE_FILE), archive).unwrap();store- .download(&asset, |_| {}, CancellationToken::default())+ .download(+ std::slice::from_ref(&asset),+ |_| {},+ CancellationToken::default(),+ ).await.unwrap();@@ -498,7 +773,11 @@ mod tests {assert!(store- .download(&asset, |_| {}, CancellationToken::default())+ .download(+ std::slice::from_ref(&asset),+ |_| {},+ CancellationToken::default(),+ ).await.is_err());diff --git a/rust/crates/ensu/src/model/mod.rs b/rust/crates/ensu/src/model/mod.rsindex 0fd9304bb0..7aa51a0c4f 100644--- a/rust/crates/ensu/src/model/mod.rs+++ b/rust/crates/ensu/src/model/mod.rs@@ -2,7 +2,7 @@ pub mod migrations;use std::path::PathBuf;-use ente_assets::{Asset, AssetFile, AssetStore, download::Progress};+use ente_assets::{Asset, AssetDownloadProgress, AssetFile, AssetStore};use crate::config::{self, ModelPreset};@@ -123,7 +123,7 @@ pub(crate) fn trimmed(value: Option<&str>) -> Option<&str> {value.map(str::trim).filter(|value| !value.is_empty())}-pub fn display_progress(progress: Progress) -> ModelDownloadProgress {+pub fn display_progress(progress: &AssetDownloadProgress) -> ModelDownloadProgress {let total = progress.total_bytes.filter(|total| *total > 0);let percent = total.map(|total| ((progress.downloaded_bytes * 100 / total) as i32).clamp(0, 99))@@ -134,31 +134,20 @@ pub fn display_progress(progress: Progress) -> ModelDownloadProgress {format_bytes(progress.downloaded_bytes),format_bytes(total))- } else if progress.file_downloaded_bytes > 0 {- format!(- "Downloading {}... {}",- progress.label.to_lowercase(),- format_bytes(progress.file_downloaded_bytes)- )+ } else if progress.downloaded_bytes > 0 {+ format!("Downloading... {}", format_bytes(progress.downloaded_bytes))} else {- format!("Downloading {}...", progress.label.to_lowercase())+ "Downloading...".to_string()};- let log_line = if progress.file_complete {+ let asset = &progress.asset_progress;+ let log_line = if asset.file_complete {Some(format!("Asset download file complete label={} bytes={} elapsedMs={} rate={}/s retries={}",- progress.label,- progress.file_downloaded_bytes,- progress.file_elapsed_ms,- format_bytes(rate_bytes(progress.file_bytes_per_second)),- progress.file_retry_count- ))- } else if progress.complete {- Some(format!(- "Asset download complete bytes={} elapsedMs={} rate={}/s retries={}",- progress.downloaded_bytes,- progress.elapsed_ms,- format_bytes(rate_bytes(progress.bytes_per_second)),- progress.retry_count+ asset.label,+ asset.file_downloaded_bytes,+ asset.file_elapsed_ms,+ format_bytes(rate_bytes(asset.file_bytes_per_second)),+ asset.file_retry_count))} else {Nonediff --git a/rust/crates/photos/tests/support/ml_indexing.rs b/rust/crates/photos/tests/support/ml_indexing.rsindex 6d07361dcc..7269c9dd32 100644--- a/rust/crates/photos/tests/support/ml_indexing.rs+++ b/rust/crates/photos/tests/support/ml_indexing.rs@@ -827,7 +827,11 @@ async fn download_file().with_context(|| format!("define asset {namespace}/{key}/{name}"))?;store- .download(&asset, |_| {}, download::CancellationToken::default())+ .download(+ std::slice::from_ref(&asset),+ |_| {},+ download::CancellationToken::default(),+ ).await.with_context(|| format!("download {name} from {url}"))?;store