diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e21281..9d412a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Select or deselect files inside the existing preview, with previous/next navigation across previewable files in table order, keyboard controls, pagination safeguards, and unsaved-edit protection. Selection stays in the table after closing. Adapted from @antonp2k's contribution in PR [#39](https://github.com/rgcsekaraa/brows3/pull/39), retaining the current image viewer and zoom controls. +- Local preview cache: previewed and prefetched images, PDFs and text files are kept on disk under `//`, mirroring the remote layout. A copy is reused only while its size, modification date and ETag match the remote object; otherwise a new copy is downloaded. When the server cannot be reached, the last copy is shown with an offline label. Configurable size limit with least-recently-used eviction and a Clear button in Settings. - Saved local-folder-to-S3 sync jobs with manual runs or in-app interval schedules, explicit future-upload approval, filters, saved bandwidth limits, pause/resume, confirmed cancellation and deletion, and completion/failure notifications. - Durable job recovery that pauses interrupted, failed, or missed-while-closed runs, prevents overlapping runs, and prevents multiple Brows3 instances from executing the same schedules. Jobs always compare fresh content and retain the existing guarded upload behavior. diff --git a/docs/PREVIEW_NAVIGATION.md b/docs/PREVIEW_NAVIGATION.md index cec07ce..3fb5f7e 100644 --- a/docs/PREVIEW_NAVIGATION.md +++ b/docs/PREVIEW_NAVIGATION.md @@ -10,6 +10,37 @@ At the end of the loaded sequence, Next can fetch additional listing pages. Each Context identity guards prevent completed requests from navigating a closed preview or applying navigation to a different object, folder, sort, or search context. +## Prefetching + +While a preview is open, the previous and next previewable files are loaded in advance so navigation shows them without a spinner. The window slides: opening a preview loads both neighbours after the visible file has loaded, Next loads one more next file, and Previous loads one more previous file. Files outside the window are evicted. + +- Only neighbours smaller than 10 MB (by listing size) are prefetched. Larger files load when they become visible. +- Images, PDFs and text files are saved to the local preview cache (see below); images are also decoded in advance. Video and audio files get metadata and a signed URL only. +- Prefetching never loads additional listing pages. +- Signed URLs are reused for 50 minutes; text and local copies are rechecked against S3 after 5 minutes. Failed loads are not cached, and Retry always requests a fresh load. +- Closing the preview, saving, object cache invalidation, and profile, bucket, or text-limit changes discard prefetched content. Saving prefetched text remains ETag-guarded. + +## Local preview cache + +Images, PDFs and text files that are previewed or prefetched are stored on disk, in the app cache directory under `preview-cache/files///`. The folder structure mirrors the remote keys. Video and audio are always streamed from S3. + +When a file is opened: + +1. The app asks S3 for the object's size, `LastModified` and ETag (one HEAD request). +2. If a local copy exists and its size, modification date and ETag all match, the local copy is shown. +3. Otherwise the object is downloaded into the cache, pinned to the ETag it was checked against (`If-Match`). Its file modification time is set to the object's `LastModified`, and it replaces the old copy atomically. +4. If S3 cannot be reached and a local copy exists, that copy is shown with an "Offline copy" label. Offline results are rechecked after 30 seconds. + +Details: + +- ETags, sizes, dates and last-access times are kept in `preview-cache/index.json`. A copy whose file was changed on disk, or that is missing from the index, is never trusted. +- Key segments that are not valid file names on every platform are percent-encoded: `%`, `<>:"|?*\`, control characters, trailing dots or spaces, Windows device names such as `CON`, and empty, `.` or `..` segments. Keys that differ only in letter case never share a copy, even on case-insensitive file systems. +- An object whose name matches an existing cached folder (for example `photos` next to `photos/a.jpg`) is previewed from S3 without being cached. +- Objects over 100 MB, text over the text preview limit, and objects without a `LastModified` date are not cached. +- Above the size limit in Settings (default 1 GB), the least recently used copies are removed. Settings can also disable or clear the cache. Deleting a profile removes its cached files. Saving a text file removes its copy, so the next preview downloads the new version. +- On startup, orphaned files, index entries without intact files, and partial downloads older than one hour are removed. +- The webview loads cached files through Tauri's asset protocol, scoped to `$APPCACHE/preview-cache/files/**`. + ## Controls and draft protection - Left and Right move between previews; Space toggles file selection. Space on a focused button retains the button's native activation. @@ -25,6 +56,10 @@ The existing image viewer and BaseDialog remain authoritative. Preserve their li | Source | Responsibility | | --- | --- | | `src/hooks/usePreviewNavigation.ts` | Previewable sequence, boundaries, bounded pagination, retry feedback, and stale-result guards | +| `src/lib/previewPrefetch.ts` | Shared preview loader (local cache first, S3 fallback), prefetch size limit, and request cache with expiry | +| `src-tauri/src/preview_cache.rs` | On-disk layout, key encoding, version index, validation, eviction and cleanup | +| `src-tauri/src/commands/preview_cache.rs` | HEAD with offline fallback, ETag-pinned fill, cached text reads, usage and clearing | +| `src/hooks/usePreviewPrefetch.ts` | Sliding previous/next prefetch window and cache clearing | | `src/lib/objectSort.ts` | Shared table and preview comparison for name, size, date, and storage class | | `src/components/dialogs/ObjectPreviewDialog.tsx` | Mixed file previews, selection controls, keyboard exclusions, editing and discard protection | | `src/components/dialogs/ImagePreviewViewer.tsx` | Existing image rendering, zoom and pan, plus selection and navigation controls | diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 2f0224f..777090e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2765,6 +2765,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2149c4b4b83390c71fab669730347d578ec6bdf759f2160c581ad8b8819733b4" + [[package]] name = "httparse" version = "1.10.1" @@ -5896,6 +5902,7 @@ dependencies = [ "gtk", "heck 0.5.0", "http 1.4.0", + "http-range", "jni", "libc", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 57feee8..b87bc52 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -27,7 +27,7 @@ tauri-build = { version = "2.5.3", features = [] } [dependencies] # Tauri core -tauri = { version = "2.9.5", features = [] } +tauri = { version = "2.9.5", features = ["protocol-asset"] } tauri-plugin-log = "2" tauri-plugin-shell = "2" tauri-plugin-dialog = "2" diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 18f0296..6ff58b3 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -4,6 +4,7 @@ pub mod cross_copy; pub mod jobs; pub mod objects; pub mod operations; +pub mod preview_cache; pub mod profiles; pub mod sync; pub mod transfer; diff --git a/src-tauri/src/commands/objects.rs b/src-tauri/src/commands/objects.rs index 614207c..9df7f45 100644 --- a/src-tauri/src/commands/objects.rs +++ b/src-tauri/src/commands/objects.rs @@ -14,7 +14,7 @@ const MAX_SEARCH_REQUESTS: usize = 100; const DEFAULT_MAX_TEXT_PREVIEW_BYTES: u64 = 2 * 1024 * 1024; const MAX_TEXT_PREVIEW_BYTES: u64 = 100 * 1024 * 1024; -fn normalized_text_preview_limit(max_bytes: Option) -> u64 { +pub(crate) fn normalized_text_preview_limit(max_bytes: Option) -> u64 { max_bytes .unwrap_or(DEFAULT_MAX_TEXT_PREVIEW_BYTES) .clamp(1, MAX_TEXT_PREVIEW_BYTES) @@ -61,6 +61,21 @@ fn is_likely_binary_text_mismatch(bytes: &[u8]) -> bool { control_count.saturating_mul(100) > bytes.len().saturating_mul(5) } +/// Rejects binary and non-UTF-8 content before it reaches the text editor. +pub(crate) fn decode_preview_text(bytes: Vec) -> Result { + if is_likely_binary_text_mismatch(&bytes) { + return Err(crate::error::AppError::InvalidContent( + "This object appears to contain binary data and cannot be edited safely in the text editor. Download it to inspect locally.".to_string(), + )); + } + String::from_utf8(bytes).map_err(|_| { + crate::error::AppError::InvalidContent( + "This object is not readable as UTF-8 text. Download it to inspect locally." + .to_string(), + ) + }) +} + #[derive(Debug, Serialize, Deserialize)] pub struct ListObjectsResult { pub objects: Vec, @@ -1021,18 +1036,7 @@ pub async fn get_object_content( bytes.extend_from_slice(&chunk); } - if is_likely_binary_text_mismatch(&bytes) { - return Err(crate::error::AppError::InvalidContent( - "This object appears to contain binary data and cannot be edited safely in the text editor. Download it to inspect locally.".to_string(), - )); - } - - let content = String::from_utf8(bytes).map_err(|_| { - crate::error::AppError::InvalidContent( - "This object is not readable as UTF-8 text. Download it to inspect locally." - .to_string(), - ) - })?; + let content = decode_preview_text(bytes)?; Ok(ObjectText { content, e_tag, diff --git a/src-tauri/src/commands/preview_cache.rs b/src-tauri/src/commands/preview_cache.rs new file mode 100644 index 0000000..f2279ee --- /dev/null +++ b/src-tauri/src/commands/preview_cache.rs @@ -0,0 +1,324 @@ +use crate::commands::profiles::ProfileState; +use crate::credentials::Profile; +use crate::error::{AppError, Result}; +use crate::preview_cache::{ + secs_to_system_time, CachePath, CacheUsage, ObjectVersion, PreviewCacheState, +}; +use crate::s3::S3State; +use aws_sdk_s3::error::SdkError; +use aws_sdk_s3::operation::head_object::{HeadObjectError, HeadObjectOutput}; +use aws_sdk_s3::Client; +use serde::Serialize; +use tauri::State; + +/// What the preview needs to know about an object, and where its local copy is when one can be used. +#[derive(Debug, Serialize)] +pub struct PreviewCacheLookup { + pub profile_id: String, + pub size: u64, + pub last_modified: Option, + pub content_type: Option, + pub e_tag: Option, + /// A local copy matching the remote object, or the last saved copy when `offline`. + pub local_path: Option, + /// The remote could not be reached; the metadata and copy come from the cache. + pub offline: bool, + /// The remote has no `LastModified`, so a copy could not be validated and is not saved. + pub cacheable: bool, +} + +enum Head { + Found(Box), + NotFound, + Unreachable(String), +} + +async fn active_profile( + profile_state: &ProfileState, + expected_profile_id: &str, +) -> Result { + let manager = profile_state.read().await; + let profile = manager + .get_active_profile() + .await? + .ok_or_else(|| AppError::ProfileNotFound("No active profile".into()))?; + drop(manager); + super::operations::validate_operation_profile(Some(expected_profile_id), &profile.id)?; + Ok(profile) +} + +async fn client_for( + profile: &Profile, + bucket: &str, + region_hint: Option, + s3_state: &S3State, +) -> Result { + let region = { + let manager = s3_state.read().await; + manager.get_bucket_region(profile, bucket) + } + .or(region_hint); + let mut manager = s3_state.write().await; + Ok(match region { + Some(region) => manager + .get_client_for_region(profile, ®ion) + .await? + .clone(), + None => manager.get_client(profile).await?.clone(), + }) +} + +#[allow(clippy::result_large_err)] // The error is only inspected, never propagated. +fn classify( + error: SdkError, +) -> std::result::Result> { + match &error { + SdkError::ServiceError(service) if service.err().is_not_found() => Ok(Head::NotFound), + SdkError::ServiceError(_) => Err(error), + // Network, timeout, credential resolution and malformed responses: the remote is unreachable. + _ => Ok(Head::Unreachable(error.to_string())), + } +} + +async fn head( + profile: &Profile, + bucket: &str, + region_hint: Option, + key: &str, + s3_state: &S3State, +) -> Result { + let client = client_for(profile, bucket, region_hint, s3_state).await?; + let error = match client.head_object().bucket(bucket).key(key).send().await { + Ok(output) => return Ok(Head::Found(Box::new(output))), + Err(error) => match classify(error) { + Ok(head) => return Ok(head), + Err(error) => error, + }, + }; + if error.raw_response().map(|r| r.status().as_u16()) == Some(403) { + return Err(AppError::AccessDenied(error.to_string())); + } + + // Probably a region mismatch; discover the bucket's region and try once more. + log::warn!("Preview cache head_object failed, attempting region discovery: {error}"); + let discovery_client = { + let mut manager = s3_state.write().await; + manager.get_client(profile).await?.clone() + }; + let Some(region) = crate::s3::get_bucket_region(&discovery_client, bucket) + .await + .ok() + else { + return Err(AppError::S3Error(error.to_string())); + }; + let client = { + let mut manager = s3_state.write().await; + manager.set_bucket_region(profile, bucket, region.clone()); + manager + .get_client_for_region(profile, ®ion) + .await? + .clone() + }; + match client.head_object().bucket(bucket).key(key).send().await { + Ok(output) => Ok(Head::Found(Box::new(output))), + Err(error) => classify(error).map_err(|error| { + if error.raw_response().map(|r| r.status().as_u16()) == Some(403) { + AppError::AccessDenied(error.to_string()) + } else { + AppError::S3Error(error.to_string()) + } + }), + } +} + +fn cache_path(profile_id: &str, bucket: &str, key: &str) -> Result { + CachePath::new(profile_id, bucket, key) + .ok_or_else(|| AppError::ConfigError("This object cannot be cached locally".into())) +} + +fn format_secs(secs: i64) -> Option { + chrono::DateTime::from_timestamp(secs, 0) + .map(|time| time.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) +} + +/// Asks the remote for the object's current version and returns the local copy if it still matches. +/// When the remote cannot be reached, returns the last saved copy marked `offline`. +#[tauri::command] +pub async fn preview_cache_lookup( + bucket_name: String, + bucket_region: Option, + key: String, + expected_profile_id: String, + profile_state: State<'_, ProfileState>, + s3_state: State<'_, S3State>, + cache: State<'_, PreviewCacheState>, +) -> Result { + let profile = active_profile(&profile_state, &expected_profile_id).await?; + let path = cache_path(&profile.id, &bucket_name, &key)?; + match head(&profile, &bucket_name, bucket_region, &key, &s3_state).await? { + Head::Found(output) => { + let size = output + .content_length() + .and_then(|n| u64::try_from(n).ok()) + .unwrap_or(0); + let last_modified = output.last_modified().map(|time| time.secs()); + let version = last_modified.map(|last_modified| ObjectVersion { + size, + last_modified, + e_tag: output.e_tag().map(str::to_string), + content_type: output.content_type().map(str::to_string), + }); + let local_path = match &version { + Some(version) => cache.lookup(&path, version).await, + None => None, + }; + Ok(PreviewCacheLookup { + profile_id: profile.id, + size, + last_modified: output.last_modified().map(|time| time.to_string()), + content_type: output.content_type().map(str::to_string), + e_tag: output.e_tag().map(str::to_string), + local_path: local_path.map(|p| p.to_string_lossy().into_owned()), + offline: false, + cacheable: version.is_some(), + }) + } + Head::NotFound => { + if let Err(error) = cache.remove(&path).await { + log::warn!("Could not remove a deleted object's cached copy: {error}"); + } + Err(AppError::S3Error("The object no longer exists.".into())) + } + Head::Unreachable(message) => { + let Some((local, version)) = cache.offline_copy(&path).await else { + return Err(AppError::ConnectionFailed(message)); + }; + log::warn!("Remote unreachable, showing the cached copy: {message}"); + Ok(PreviewCacheLookup { + profile_id: profile.id, + size: version.size, + last_modified: format_secs(version.last_modified), + content_type: version.content_type, + e_tag: version.e_tag, + local_path: Some(local.to_string_lossy().into_owned()), + offline: true, + cacheable: true, + }) + } + } +} + +/// Downloads the object version identified by `e_tag` and `size` into the cache. +#[tauri::command] +#[allow(clippy::too_many_arguments)] +pub async fn preview_cache_fill( + bucket_name: String, + bucket_region: Option, + key: String, + e_tag: Option, + size: u64, + max_cache_bytes: u64, + expected_profile_id: String, + profile_state: State<'_, ProfileState>, + s3_state: State<'_, S3State>, + cache: State<'_, PreviewCacheState>, +) -> Result { + if size > max_cache_bytes { + return Err(AppError::ConfigError( + "The object is larger than the local cache".into(), + )); + } + let profile = active_profile(&profile_state, &expected_profile_id).await?; + let path = cache_path(&profile.id, &bucket_name, &key)?; + let client = client_for(&profile, &bucket_name, bucket_region, &s3_state).await?; + let mut request = client.get_object().bucket(&bucket_name).key(&key); + if let Some(e_tag) = &e_tag { + // The copy must be exactly the version the preview validated against. + request = request.if_match(e_tag); + } + let response = request + .send() + .await + .map_err(|e| AppError::S3Error(e.to_string()))?; + let last_modified = response + .last_modified() + .map(|time| time.secs()) + .ok_or_else(|| AppError::S3Error("The object has no modification date".into()))?; + let version = ObjectVersion { + size, + last_modified, + e_tag: response.e_tag().map(str::to_string).or(e_tag), + content_type: response.content_type().map(str::to_string), + }; + + let mut pending = cache.begin_fill(&path).await?; + let mut body = response.body; + let mut written: u64 = 0; + while let Some(chunk) = body + .try_next() + .await + .map_err(|e| AppError::S3Error(e.to_string()))? + { + written += chunk.len() as u64; + if written > size { + return Err(AppError::S3Error( + "The object changed while it was being cached".into(), + )); + } + pending.write_all(&chunk).await?; + } + if written != size { + return Err(AppError::S3Error( + "The object changed while it was being cached".into(), + )); + } + pending + .finish_writing_with_modified(Some(secs_to_system_time(last_modified))) + .await?; + let local = cache + .commit_fill(&path, pending, version, max_cache_bytes) + .await?; + Ok(local.to_string_lossy().into_owned()) +} + +/// Reads a cached copy as text with the same checks as remote text previews. +#[tauri::command] +pub async fn preview_cache_read_text( + bucket_name: String, + key: String, + max_bytes: Option, + expected_profile_id: String, + profile_state: State<'_, ProfileState>, + cache: State<'_, PreviewCacheState>, +) -> Result { + let profile = active_profile(&profile_state, &expected_profile_id).await?; + let path = cache_path(&profile.id, &bucket_name, &key)?; + let max_bytes = super::objects::normalized_text_preview_limit(max_bytes); + let bytes = cache.read(&path, max_bytes).await?; + super::objects::decode_preview_text(bytes) +} + +#[tauri::command] +pub async fn preview_cache_remove( + bucket_name: String, + key: String, + expected_profile_id: String, + profile_state: State<'_, ProfileState>, + cache: State<'_, PreviewCacheState>, +) -> Result<()> { + let profile = active_profile(&profile_state, &expected_profile_id).await?; + cache + .remove(&cache_path(&profile.id, &bucket_name, &key)?) + .await?; + Ok(()) +} + +#[tauri::command] +pub async fn preview_cache_usage(cache: State<'_, PreviewCacheState>) -> Result { + Ok(cache.usage().await?) +} + +#[tauri::command] +pub async fn clear_preview_cache(cache: State<'_, PreviewCacheState>) -> Result<()> { + Ok(cache.clear(None).await?) +} diff --git a/src-tauri/src/commands/profiles.rs b/src-tauri/src/commands/profiles.rs index 4ff94e4..1c00058 100644 --- a/src-tauri/src/commands/profiles.rs +++ b/src-tauri/src/commands/profiles.rs @@ -56,9 +56,21 @@ pub async fn update_profile( } #[tauri::command] -pub async fn delete_profile(id: String, state: State<'_, ProfileState>) -> Result<(), String> { +pub async fn delete_profile( + id: String, + state: State<'_, ProfileState>, + preview_cache: State<'_, crate::preview_cache::PreviewCacheState>, +) -> Result<(), String> { let mut manager = state.write().await; - manager.delete_profile(&id).await.map_err(|e| e.to_string()) + manager + .delete_profile(&id) + .await + .map_err(|e| e.to_string())?; + drop(manager); + if let Err(error) = preview_cache.clear(Some(&id)).await { + log::warn!("Could not remove the deleted profile's cached previews: {error}"); + } + Ok(()) } #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 4d01421..65eee7f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,6 +1,7 @@ pub mod commands; pub mod credentials; pub mod error; +pub mod preview_cache; pub mod s3; pub mod transfer; @@ -251,6 +252,18 @@ pub fn run() { app.manage(jobs.clone()); commands::jobs::start_scheduler(app.handle().clone(), jobs); + let preview_cache = match app.path().app_cache_dir() { + Ok(dir) => Arc::new(preview_cache::PreviewCache::open(dir.join("preview-cache"))), + Err(error) => { + log::error!("Local preview cache unavailable: {error}"); + Arc::new(preview_cache::PreviewCache::open( + data_dir.join("preview-cache"), + )) + } + }; + app.manage(preview_cache.clone()); + tauri::async_runtime::spawn(async move { preview_cache.reconcile().await }); + // Show the main window after initialization to prevent white flash if let Some(window) = app.get_webview_window("main") { let _ = window.show(); @@ -321,6 +334,12 @@ pub fn run() { operations::move_object, operations::delete_objects, operations::get_object_metadata, + commands::preview_cache::preview_cache_lookup, + commands::preview_cache::preview_cache_fill, + commands::preview_cache::preview_cache_read_text, + commands::preview_cache::preview_cache_remove, + commands::preview_cache::preview_cache_usage, + commands::preview_cache::clear_preview_cache, operations::set_object_content_type, operations::get_object_permissions, operations::set_object_permissions, diff --git a/src-tauri/src/preview_cache.rs b/src-tauri/src/preview_cache.rs new file mode 100644 index 0000000..d893524 --- /dev/null +++ b/src-tauri/src/preview_cache.rs @@ -0,0 +1,727 @@ +//! On-disk cache of previewed objects. +//! +//! Files mirror the remote layout under `files///`. +//! A copy is only reused while its size, modification time and ETag match the remote object. +//! The modification time of each cached file is set to the object's `LastModified`. + +use crate::transfer::download::{DownloadDestination, PendingDownload}; +use cap_std::fs::Dir; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::fmt::Write as _; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::sync::Mutex; + +const FILES_DIR: &str = "files"; +const INDEX_FILE: &str = "index.json"; +const TEMP_PREFIX: &str = ".brows3-"; +const INDEX_VERSION: u32 = 1; +/// Partial downloads younger than this may still be in progress and are left alone on startup. +const STALE_TEMP_AGE: Duration = Duration::from_secs(60 * 60); + +pub type PreviewCacheState = Arc; + +/// The remote state a cached copy must match. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ObjectVersion { + pub size: u64, + /// Seconds since the Unix epoch (S3 `LastModified` has one-second precision). + pub last_modified: i64, + pub e_tag: Option, + pub content_type: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct IndexEntry { + /// Exact relative path; the map key is its lowercase form so case-insensitive file systems + /// cannot serve one key's copy for another key that differs only in case. + path: String, + #[serde(flatten)] + version: ObjectVersion, + accessed: i64, +} + +#[derive(Default, Serialize, Deserialize)] +struct Index { + version: u32, + entries: HashMap, +} + +struct Inner { + dir: Arc, + index: Index, +} + +pub struct PreviewCache { + files_root: PathBuf, + index_path: PathBuf, + inner: Option>, +} + +#[derive(Debug, Clone, Copy, Serialize)] +pub struct CacheUsage { + pub files: u64, + pub bytes: u64, +} + +/// A cached object's location relative to the cache's file root, with `/` separators. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CachePath(String); + +impl CachePath { + pub fn new(profile_id: &str, bucket: &str, key: &str) -> Option { + if profile_id.is_empty() || bucket.is_empty() || key.is_empty() { + return None; + } + let mut path = format!("{}/{}", encode_segment(profile_id), encode_segment(bucket)); + for segment in key.split('/') { + path.push('/'); + path.push_str(&encode_segment(segment)); + } + Some(Self(path)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + fn index_key(&self) -> String { + self.0.to_lowercase() + } + + fn relative(&self) -> PathBuf { + self.0.split('/').collect() + } + + fn profile_prefix(profile_id: &str) -> String { + format!("{}/", encode_segment(profile_id)) + } +} + +fn is_windows_reserved(segment: &str) -> bool { + let stem = segment + .split('.') + .next() + .unwrap_or("") + .trim_end() + .to_ascii_uppercase(); + matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + || (stem.len() == 4 + && (stem.starts_with("COM") || stem.starts_with("LPT")) + && matches!(stem.as_bytes()[3], b'1'..=b'9')) +} + +/// Encodes one key segment as a file name that is valid on Windows, macOS and Linux. +/// Safe names are kept as-is; the encoding is injective because `%` itself is always escaped. +pub fn encode_segment(segment: &str) -> String { + match segment { + "" => return "%".to_string(), + "." => return "%2E".to_string(), + ".." => return "%2E%2E".to_string(), + _ => {} + } + let reserved = is_windows_reserved(segment); + let temp_like = segment.starts_with(TEMP_PREFIX); + let count = segment.chars().count(); + let mut out = String::with_capacity(segment.len()); + for (index, ch) in segment.chars().enumerate() { + let last = index + 1 == count; + let escape = matches!( + ch, + '%' | '<' | '>' | ':' | '"' | '|' | '?' | '*' | '\\' | '/' + ) || ch.is_control() + || (last && (ch == '.' || ch == ' ')) + || (index == 0 && (reserved || temp_like)); + if escape { + let mut buffer = [0u8; 4]; + for byte in ch.encode_utf8(&mut buffer).bytes() { + let _ = write!(out, "%{byte:02X}"); + } + } else { + out.push(ch); + } + } + out +} + +fn now_secs() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +pub fn system_time_secs(time: SystemTime) -> i64 { + match time.duration_since(UNIX_EPOCH) { + Ok(after) => after.as_secs() as i64, + Err(before) => -(before.duration().as_secs_f64().ceil() as i64), + } +} + +pub fn secs_to_system_time(secs: i64) -> SystemTime { + if secs >= 0 { + UNIX_EPOCH + Duration::from_secs(secs as u64) + } else { + UNIX_EPOCH - Duration::from_secs(secs.unsigned_abs()) + } +} + +fn unavailable() -> io::Error { + io::Error::other("The local preview cache is unavailable") +} + +impl Inner { + fn entry(&self, path: &CachePath) -> Option<&IndexEntry> { + self.index + .entries + .get(&path.index_key()) + .filter(|entry| entry.path == path.0) + } + + /// True when the file on disk is a regular file with the entry's size and modification time. + fn file_matches(&self, path: &CachePath, version: &ObjectVersion) -> bool { + let Ok(metadata) = self.dir.symlink_metadata(path.relative()) else { + return false; + }; + let modified = metadata.modified().map(|time| time.into_std()); + metadata.is_file() + && metadata.len() == version.size + && modified.is_ok_and(|time| system_time_secs(time) == version.last_modified) + } + + fn remove(&mut self, path: &CachePath) { + if let Some(entry) = self.index.entries.remove(&path.index_key()) { + remove_file_and_empty_parents(&self.dir, &entry.path); + } + remove_file_and_empty_parents(&self.dir, &path.0); + } + + fn evict(&mut self, max_bytes: u64, keep: &str) { + let mut total: u64 = self.index.entries.values().map(|e| e.version.size).sum(); + if total <= max_bytes { + return; + } + let mut candidates: Vec<(i64, String)> = self + .index + .entries + .iter() + .filter(|(key, _)| key.as_str() != keep) + .map(|(key, entry)| (entry.accessed, key.clone())) + .collect(); + candidates.sort(); + for (_, key) in candidates { + if total <= max_bytes { + break; + } + if let Some(entry) = self.index.entries.remove(&key) { + remove_file_and_empty_parents(&self.dir, &entry.path); + total = total.saturating_sub(entry.version.size); + } + } + } + + fn usage(&self) -> CacheUsage { + CacheUsage { + files: self.index.entries.len() as u64, + bytes: self.index.entries.values().map(|e| e.version.size).sum(), + } + } +} + +/// Removes a cached file and any directories it leaves empty, never the profile directory's parent. +fn remove_file_and_empty_parents(dir: &Dir, path: &str) { + let relative: PathBuf = path.split('/').collect(); + match dir.remove_file(&relative) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => { + log::warn!("Could not remove cached preview {path}: {error}"); + return; + } + } + let mut parent = relative.parent(); + while let Some(current) = parent.filter(|p| !p.as_os_str().is_empty()) { + if dir.remove_dir(current).is_err() { + break; + } + parent = current.parent(); + } +} + +impl PreviewCache { + /// Opens the cache at `root`. Failures leave the cache disabled so previews fall back to S3. + pub fn open(root: PathBuf) -> Self { + let files_root = root.join(FILES_DIR); + let index_path = root.join(INDEX_FILE); + let inner = std::fs::create_dir_all(&files_root) + .and_then(|_| DownloadDestination::open_root(&files_root)) + .map(|dir| { + let index = std::fs::read(&index_path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|index| index.version == INDEX_VERSION) + .unwrap_or(Index { + version: INDEX_VERSION, + entries: HashMap::new(), + }); + Mutex::new(Inner { dir, index }) + }); + match inner { + Ok(inner) => Self { + files_root, + index_path, + inner: Some(inner), + }, + Err(error) => { + log::error!("Local preview cache unavailable: {error}"); + Self { + files_root, + index_path, + inner: None, + } + } + } + } + + fn inner(&self) -> io::Result<&Mutex> { + self.inner.as_ref().ok_or_else(unavailable) + } + + pub fn absolute(&self, path: &CachePath) -> PathBuf { + self.files_root.join(path.relative()) + } + + fn persist(&self, inner: &Inner) { + let result = serde_json::to_vec(&inner.index) + .map_err(io::Error::other) + .and_then(|bytes| { + let temporary = self.index_path.with_extension("json.tmp"); + std::fs::write(&temporary, bytes)?; + std::fs::rename(&temporary, &self.index_path) + }); + if let Err(error) = result { + log::warn!("Could not save the preview cache index: {error}"); + } + } + + /// Returns the local copy when it matches the remote version exactly. + pub async fn lookup(&self, path: &CachePath, remote: &ObjectVersion) -> Option { + let mut inner = self.inner().ok()?.lock().await; + let matches = inner + .entry(path) + .is_some_and(|entry| &entry.version == remote) + && inner.file_matches(path, remote); + if !matches { + return None; + } + if let Some(entry) = inner.index.entries.get_mut(&path.index_key()) { + entry.accessed = now_secs(); + } + Some(self.absolute(path)) + } + + /// Returns an intact local copy and the version it was saved from, without asking the remote. + pub async fn offline_copy(&self, path: &CachePath) -> Option<(PathBuf, ObjectVersion)> { + let inner = self.inner().ok()?.lock().await; + let version = inner.entry(path)?.version.clone(); + inner + .file_matches(path, &version) + .then(|| (self.absolute(path), version)) + } + + #[cfg(test)] + pub async fn version(&self, path: &CachePath) -> Option { + let inner = self.inner().ok()?.lock().await; + inner.entry(path).map(|entry| entry.version.clone()) + } + + /// Starts writing a new copy into a temporary file next to its final location. + pub async fn begin_fill(&self, path: &CachePath) -> io::Result { + let dir = self.inner()?.lock().await.dir.clone(); + DownloadDestination::new(dir, path.relative(), true)?.begin() + } + + /// Moves a fully written copy into place, records its version, and evicts old copies. + pub async fn commit_fill( + &self, + path: &CachePath, + pending: PendingDownload, + version: ObjectVersion, + max_bytes: u64, + ) -> io::Result { + let mut inner = self.inner()?.lock().await; + let key = path.index_key(); + if let Some(previous) = inner.index.entries.remove(&key) { + if previous.path != path.0 { + remove_file_and_empty_parents(&inner.dir, &previous.path); + } + } + pending.commit()?; + inner.index.entries.insert( + key.clone(), + IndexEntry { + path: path.0.clone(), + version, + accessed: now_secs(), + }, + ); + inner.evict(max_bytes, &key); + self.persist(&inner); + Ok(self.absolute(path)) + } + + pub async fn read(&self, path: &CachePath, max_bytes: u64) -> io::Result> { + let inner = self.inner()?.lock().await; + let metadata = inner.dir.symlink_metadata(path.relative())?; + if !metadata.is_file() { + return Err(io::Error::new(io::ErrorKind::NotFound, "No cached copy")); + } + if metadata.len() > max_bytes { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "The cached copy exceeds the preview limit", + )); + } + inner.dir.read(path.relative()) + } + + pub async fn remove(&self, path: &CachePath) -> io::Result<()> { + let mut inner = self.inner()?.lock().await; + inner.remove(path); + self.persist(&inner); + Ok(()) + } + + pub async fn usage(&self) -> io::Result { + Ok(self.inner()?.lock().await.usage()) + } + + /// Removes every cached file, or only those of one profile. + pub async fn clear(&self, profile_id: Option<&str>) -> io::Result<()> { + let mut inner = self.inner()?.lock().await; + match profile_id { + Some(profile_id) => { + let prefix = CachePath::profile_prefix(profile_id); + inner + .index + .entries + .retain(|_, entry| !entry.path.starts_with(&prefix)); + match inner.dir.remove_dir_all(encode_segment(profile_id)) { + Err(error) if error.kind() != io::ErrorKind::NotFound => { + log::warn!("Could not clear cached previews for a profile: {error}") + } + _ => {} + } + } + None => { + inner.index.entries.clear(); + for entry in inner.dir.entries()? { + let entry = entry?; + let name = entry.file_name(); + let result = if entry.file_type()?.is_dir() { + inner.dir.remove_dir_all(&name) + } else { + inner.dir.remove_file(&name) + }; + if let Err(error) = result { + log::warn!("Could not clear a cached preview: {error}"); + } + } + } + } + self.persist(&inner); + Ok(()) + } + + /// Drops index entries without intact files, and files and stale partial downloads without entries. + pub async fn reconcile(&self) { + let Ok(inner) = self.inner() else { return }; + let mut inner = inner.lock().await; + let mut found = Vec::new(); + collect_files(&self.files_root, "", &mut found); + let known: HashMap = inner + .index + .entries + .iter() + .map(|(key, entry)| (entry.path.clone(), key.clone())) + .collect(); + let cutoff = SystemTime::now() - STALE_TEMP_AGE; + for (relative, modified) in &found { + let name = relative.rsplit('/').next().unwrap_or(relative); + let is_temporary = name.starts_with(TEMP_PREFIX) && name.ends_with(".part"); + let remove = if is_temporary { + modified.is_some_and(|time| time < cutoff) + } else { + !known.contains_key(relative) + }; + if remove { + remove_file_and_empty_parents(&inner.dir, relative); + } + } + let stale: Vec = inner + .index + .entries + .iter() + .filter(|(_, entry)| { + !inner.file_matches(&CachePath(entry.path.clone()), &entry.version) + }) + .map(|(key, _)| key.clone()) + .collect(); + for key in stale { + if let Some(entry) = inner.index.entries.remove(&key) { + remove_file_and_empty_parents(&inner.dir, &entry.path); + } + } + self.persist(&inner); + } +} + +/// Lists regular files and symlinks below `root` without following links. +fn collect_files(root: &Path, prefix: &str, found: &mut Vec<(String, Option)>) { + let Ok(entries) = std::fs::read_dir(root.join(prefix)) else { + return; + }; + for entry in entries.flatten() { + let Some(name) = entry.file_name().to_str().map(str::to_string) else { + continue; + }; + let relative = if prefix.is_empty() { + name + } else { + format!("{prefix}/{name}") + }; + let Ok(file_type) = entry.file_type() else { + continue; + }; + if file_type.is_dir() { + collect_files(root, &relative, found); + } else { + let modified = entry.metadata().ok().and_then(|m| m.modified().ok()); + found.push((relative, modified)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn version(size: u64, last_modified: i64, e_tag: &str) -> ObjectVersion { + ObjectVersion { + size, + last_modified, + e_tag: Some(e_tag.to_string()), + content_type: Some("image/png".to_string()), + } + } + + async fn fill( + cache: &PreviewCache, + path: &CachePath, + bytes: &[u8], + v: &ObjectVersion, + max: u64, + ) -> PathBuf { + let mut pending = cache.begin_fill(path).await.unwrap(); + pending.write_all(bytes).await.unwrap(); + pending + .finish_writing_with_modified(Some(secs_to_system_time(v.last_modified))) + .await + .unwrap(); + cache + .commit_fill(path, pending, v.clone(), max) + .await + .unwrap() + } + + #[test] + fn keys_mirror_the_remote_layout() { + let path = CachePath::new("p1", "bucket", "photos/2024/a.jpg").unwrap(); + assert_eq!(path.as_str(), "p1/bucket/photos/2024/a.jpg"); + assert_eq!( + path.relative(), + PathBuf::from("p1/bucket/photos/2024/a.jpg") + ); + } + + #[test] + fn unsafe_segments_are_encoded_injectively() { + assert_eq!(encode_segment(""), "%"); + assert_eq!(encode_segment("."), "%2E"); + assert_eq!(encode_segment(".."), "%2E%2E"); + assert_eq!(encode_segment("%"), "%25"); + assert_eq!(encode_segment("a:b?.txt"), "a%3Ab%3F.txt"); + assert_eq!(encode_segment("name. "), "name.%20"); + assert_eq!(encode_segment("trail."), "trail%2E"); + assert_eq!(encode_segment("CON"), "%43ON"); + assert_eq!(encode_segment("com1.txt"), "%63om1.txt"); + assert_eq!(encode_segment("console"), "console"); + assert_eq!(encode_segment(".brows3-x.part"), "%2Ebrows3-x.part"); + assert_eq!(encode_segment("tab\there"), "tab%09here"); + assert_eq!(encode_segment("фото.jpg"), "фото.jpg"); + let path = CachePath::new("p", "b", "a//../b/").unwrap(); + assert_eq!(path.as_str(), "p/b/a/%/%2E%2E/b/%"); + assert!(path + .relative() + .components() + .all(|c| matches!(c, std::path::Component::Normal(_)))); + } + + #[tokio::test] + async fn copies_are_reused_only_while_size_date_and_etag_match() { + let root = tempfile::tempdir().unwrap(); + let cache = PreviewCache::open(root.path().to_path_buf()); + let path = CachePath::new("p", "b", "dir/a.png").unwrap(); + let v = version(3, 1_700_000_000, "\"e1\""); + assert!(cache.lookup(&path, &v).await.is_none()); + + let local = fill(&cache, &path, b"abc", &v, 1 << 20).await; + assert_eq!(local, root.path().join("files/p/b/dir/a.png")); + assert_eq!(std::fs::read(&local).unwrap(), b"abc"); + assert_eq!(cache.lookup(&path, &v).await, Some(local.clone())); + + assert!(cache + .lookup(&path, &version(4, v.last_modified, "\"e1\"")) + .await + .is_none()); + assert!(cache + .lookup(&path, &version(3, v.last_modified + 1, "\"e1\"")) + .await + .is_none()); + assert!(cache + .lookup(&path, &version(3, v.last_modified, "\"e2\"")) + .await + .is_none()); + + // A copy changed on disk is not trusted even though the index still matches. + std::fs::write(&local, b"abcd").unwrap(); + assert!(cache.lookup(&path, &v).await.is_none()); + assert!(cache.offline_copy(&path).await.is_none()); + } + + #[tokio::test] + async fn index_survives_reopening_and_offline_copies_are_available() { + let root = tempfile::tempdir().unwrap(); + let path = CachePath::new("p", "b", "a.txt").unwrap(); + let v = version(2, 1_600_000_000, "\"e\""); + { + let cache = PreviewCache::open(root.path().to_path_buf()); + fill(&cache, &path, b"hi", &v, 1 << 20).await; + } + let cache = PreviewCache::open(root.path().to_path_buf()); + let (local, cached) = cache.offline_copy(&path).await.unwrap(); + assert_eq!(cached, v); + assert_eq!(std::fs::read(local).unwrap(), b"hi"); + assert_eq!(cache.read(&path, 10).await.unwrap(), b"hi"); + assert!(cache.read(&path, 1).await.is_err()); + } + + #[tokio::test] + async fn keys_differing_only_in_case_never_share_a_copy() { + let root = tempfile::tempdir().unwrap(); + let cache = PreviewCache::open(root.path().to_path_buf()); + let upper = CachePath::new("p", "b", "A.png").unwrap(); + let lower = CachePath::new("p", "b", "a.png").unwrap(); + let v = version(1, 1_700_000_000, "\"e\""); + fill(&cache, &upper, b"A", &v, 1 << 20).await; + fill(&cache, &lower, b"a", &v, 1 << 20).await; + assert!(cache.lookup(&upper, &v).await.is_none()); + assert!(cache.lookup(&lower, &v).await.is_some()); + } + + #[tokio::test] + async fn least_recently_used_copies_are_evicted_over_the_limit() { + let root = tempfile::tempdir().unwrap(); + let cache = PreviewCache::open(root.path().to_path_buf()); + let paths: Vec<_> = ["a", "b", "c"] + .iter() + .map(|name| CachePath::new("p", "b", &format!("x/{name}")).unwrap()) + .collect(); + let v = version(4, 1_700_000_000, "\"e\""); + fill(&cache, &paths[0], b"aaaa", &v, 10).await; + fill(&cache, &paths[1], b"bbbb", &v, 10).await; + { + let mut inner = cache.inner().unwrap().lock().await; + inner + .index + .entries + .get_mut(&paths[0].index_key()) + .unwrap() + .accessed = 1; + } + fill(&cache, &paths[2], b"cccc", &v, 10).await; + assert!(cache.lookup(&paths[0], &v).await.is_none()); + assert!(cache.lookup(&paths[1], &v).await.is_some()); + assert!(cache.lookup(&paths[2], &v).await.is_some()); + assert_eq!(cache.usage().await.unwrap().bytes, 8); + } + + #[tokio::test] + async fn removing_and_clearing_prunes_files_and_empty_folders() { + let root = tempfile::tempdir().unwrap(); + let cache = PreviewCache::open(root.path().to_path_buf()); + let v = version(1, 1_700_000_000, "\"e\""); + let one = CachePath::new("p1", "b", "deep/nested/a").unwrap(); + let two = CachePath::new("p2", "b", "b").unwrap(); + fill(&cache, &one, b"1", &v, 1 << 20).await; + fill(&cache, &two, b"2", &v, 1 << 20).await; + cache.remove(&one).await.unwrap(); + assert!(!root.path().join("files/p1").exists()); + fill(&cache, &one, b"1", &v, 1 << 20).await; + cache.clear(Some("p1")).await.unwrap(); + assert!(cache.lookup(&one, &v).await.is_none()); + assert!(cache.lookup(&two, &v).await.is_some()); + cache.clear(None).await.unwrap(); + assert_eq!(cache.usage().await.unwrap().files, 0); + assert!(std::fs::read_dir(root.path().join("files")) + .unwrap() + .next() + .is_none()); + } + + #[tokio::test] + async fn reconcile_removes_orphans_and_missing_entries() { + let root = tempfile::tempdir().unwrap(); + let cache = PreviewCache::open(root.path().to_path_buf()); + let v = version(1, 1_700_000_000, "\"e\""); + let kept = CachePath::new("p", "b", "kept").unwrap(); + let lost = CachePath::new("p", "b", "lost").unwrap(); + fill(&cache, &kept, b"k", &v, 1 << 20).await; + fill(&cache, &lost, b"l", &v, 1 << 20).await; + std::fs::remove_file(cache.absolute(&lost)).unwrap(); + std::fs::write(root.path().join("files/p/b/orphan"), b"o").unwrap(); + let fresh_temp = root.path().join("files/p/b/.brows3-new.part"); + std::fs::write(&fresh_temp, b"t").unwrap(); + cache.reconcile().await; + assert!(cache.lookup(&kept, &v).await.is_some()); + assert!(cache.version(&lost).await.is_none()); + assert!(!root.path().join("files/p/b/orphan").exists()); + assert!(fresh_temp.exists(), "in-progress downloads are kept"); + } + + #[tokio::test] + async fn an_object_cannot_replace_a_cached_folder() { + let root = tempfile::tempdir().unwrap(); + let cache = PreviewCache::open(root.path().to_path_buf()); + let v = version(1, 1_700_000_000, "\"e\""); + fill( + &cache, + &CachePath::new("p", "b", "photos/a").unwrap(), + b"a", + &v, + 1 << 20, + ) + .await; + let folder_named = CachePath::new("p", "b", "photos").unwrap(); + let mut pending = cache.begin_fill(&folder_named).await.unwrap(); + pending.write_all(b"x").await.unwrap(); + pending.finish_writing().await.unwrap(); + assert!(cache + .commit_fill(&folder_named, pending, v, 1 << 20) + .await + .is_err()); + } +} diff --git a/src-tauri/src/transfer/download.rs b/src-tauri/src/transfer/download.rs index b2f803f..a710ee9 100644 --- a/src-tauri/src/transfer/download.rs +++ b/src-tauri/src/transfer/download.rs @@ -102,13 +102,24 @@ impl PendingDownload { } pub async fn finish_writing(&mut self) -> io::Result<()> { + self.finish_writing_with_modified(None).await + } + + /// Finishes writing and optionally stamps the file's modification time before it is committed. + pub async fn finish_writing_with_modified( + &mut self, + modified: Option, + ) -> io::Result<()> { let file = self .file .as_mut() .ok_or_else(|| io::Error::other("Download is closed"))?; file.flush().await?; file.sync_all().await?; - self.file.take(); + let file = self.file.take().expect("file checked above"); + if let Some(modified) = modified { + file.into_std().await.set_modified(modified)?; + } Ok(()) } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 67c424d..3e3afbf 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -28,7 +28,14 @@ } ], "security": { - "csp": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; img-src 'self' asset: https: http: data:; connect-src 'self' https: ipc:; frame-src 'self' https: http:; media-src 'self' https: http:; object-src 'self' https: http:; worker-src 'self' blob:;" + "csp": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; img-src 'self' asset: http://asset.localhost https: http: data:; connect-src 'self' https: ipc:; frame-src 'self' asset: http://asset.localhost https: http:; media-src 'self' asset: http://asset.localhost https: http:; object-src 'self' asset: http://asset.localhost https: http:; worker-src 'self' blob:;", + "assetProtocol": { + "enable": true, + "scope": { + "allow": ["$APPCACHE/preview-cache/files/**"], + "requireLiteralLeadingDot": false + } + } } }, "bundle": { diff --git a/src/app/bucket/page.tsx b/src/app/bucket/page.tsx index 8cb0fd4..898d5dc 100644 --- a/src/app/bucket/page.tsx +++ b/src/app/bucket/page.tsx @@ -66,6 +66,8 @@ import PermissionsDialog from '@/components/dialogs/PermissionsDialog'; import ObjectPreviewDialog from '@/components/dialogs/ObjectPreviewDialog'; import { canObjectBeEdited, getObjectName } from '@/lib/objectCapabilities'; import { usePreviewNavigation } from '@/hooks/usePreviewNavigation'; +import { usePreviewPrefetch } from '@/hooks/usePreviewPrefetch'; +import { usePreviewContext } from '@/lib/previewPrefetch'; import PresignedUrlDialog from '@/components/dialogs/PresignedUrlDialog'; import PublicUrlsDialog from '@/components/dialogs/PublicUrlsDialog'; import UrlImportDialog from '@/components/dialogs/UrlImportDialog'; @@ -328,6 +330,11 @@ function BucketContent() { hasMore: !isDeepSearch && hasMore, query: isDeepSearch ? '' : deferredSearchQuery.trim(), loadMore, onNavigate: object => { setPreviewKey(object.key); setPreviewSize(object.size); setStartInEditMode(false); }, }); + const previewContext = usePreviewContext(bucketName || '', bucketRegion); + usePreviewPrefetch({ + sequence: previewNavigation.sequence, index: previewNavigation.index, + open: previewOpen && previewScope === viewKey, ctx: previewContext, + }); // Presigned URL Dialog State const [presignedUrlOpen, setPresignedUrlOpen] = useState(false); diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index d38c825..0be7c9f 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -34,13 +34,16 @@ import { import { MAX_TEXT_PREVIEW_SIZE_MB, MIN_TEXT_PREVIEW_SIZE_MB, + MAX_LOCAL_CACHE_MB, + MIN_LOCAL_CACHE_MB, useSettingsStore, } from '@/store/settingsStore'; import { useAppStore } from '@/store/appStore'; import { useMonitorStore } from '@/store/monitorStore'; import { invalidateBucketCache } from '@/hooks/useBuckets'; import { toast } from '@/store/toastStore'; -import { bucketApi, copyToClipboard, invalidateCache, isTauri, logApi, transferApi, type LogFileInfo } from '@/lib/tauri'; +import { bucketApi, copyToClipboard, invalidateCache, isTauri, logApi, previewCacheApi, transferApi, type LogFileInfo } from '@/lib/tauri'; +import { previewCache } from '@/lib/previewPrefetch'; export default function SettingsPage() { // Theme is controlled by appStore (used by the actual app) @@ -51,8 +54,32 @@ export default function SettingsPage() { maxConcurrentTransfers, setMaxConcurrentTransfers, transferBandwidthKiB, setTransferBandwidthKiB, maxTextPreviewSizeMb, setMaxTextPreviewSizeMb, - autoRefreshOnFocus, setAutoRefreshOnFocus + autoRefreshOnFocus, setAutoRefreshOnFocus, + localCacheEnabled, setLocalCacheEnabled, + localCacheMaxMb, setLocalCacheMaxMb, } = useSettingsStore(); + const [pendingCacheLimit, setPendingCacheLimit] = useState(localCacheMaxMb); + const [cacheUsage, setCacheUsage] = useState<{ files: number; bytes: number } | null>(null); + const [clearingLocalCache, setClearingLocalCache] = useState(false); + const refreshCacheUsage = () => { + if (!isTauri()) return; + previewCacheApi.usage().then(setCacheUsage).catch(() => setCacheUsage(null)); + }; + useEffect(refreshCacheUsage, []); + useEffect(() => { setPendingCacheLimit(localCacheMaxMb); }, [localCacheMaxMb]); + const handleClearLocalCache = async () => { + setClearingLocalCache(true); + try { + await previewCacheApi.clear(); + previewCache.clear(); + toast.success('Local cache cleared', 'Previews will be downloaded again when opened.'); + } catch (error) { + toast.error('Could not clear the local cache', String(error)); + } finally { + setClearingLocalCache(false); + refreshCacheUsage(); + } + }; const [version, setVersion] = useState('...'); const [appDataDir, setAppDataDir] = useState('Loading...'); @@ -254,7 +281,7 @@ export default function SettingsPage() { + + + + { + setLocalCacheEnabled(e.target.checked); + previewCache.clear(); + toast.success('Local cache updated', `Local preview cache ${e.target.checked ? 'enabled' : 'disabled'}`); + }} + /> + + + + = 1024 ? `${(pendingCacheLimit / 1024).toFixed(1)} GB` : `${pendingCacheLimit} MB`}. In use: ${cacheUsage ? `${(cacheUsage.bytes / 1024 / 1024).toFixed(1)} MB in ${cacheUsage.files} files` : 'unknown'}.`} + /> + + `${value} MB`} + onChange={(_, value) => setPendingCacheLimit(value as number)} + onChangeCommitted={(_, value) => { + const nextValue = value as number; + setPendingCacheLimit(nextValue); + if (nextValue !== localCacheMaxMb) setLocalCacheMaxMb(nextValue); + }} + /> + + + void; } @@ -53,7 +55,7 @@ export default function ImagePreviewViewer(props: Props) { ); } -function ImagePreviewCanvas({ open, name, url, error, onClose, onRetry, titleId, index = 0, total = 0, onPrevious, onNext, navigationLabel = 'image', navigationBusy = false, navigationError, isSelected = false, onToggleSelect }: Props & { titleId: string }) { +function ImagePreviewCanvas({ open, name, url, error, onClose, onRetry, titleId, index = 0, total = 0, onPrevious, onNext, navigationLabel = 'image', navigationBusy = false, navigationError, notice, isSelected = false, onToggleSelect }: Props & { titleId: string }) { const helpId = useId(); const rootRef = useRef(null); useEffect(() => { @@ -247,6 +249,7 @@ function ImagePreviewCanvas({ open, name, url, error, onClose, onRetry, titleId, )} + {notice && {notice}} {(navigationBusy || navigationError) && {navigationBusy ? 'Looking for the next previewable file...' : navigationError}} {navigable && <> diff --git a/src/components/dialogs/ObjectPreviewDialog.tsx b/src/components/dialogs/ObjectPreviewDialog.tsx index 931e38b..f63f07f 100644 --- a/src/components/dialogs/ObjectPreviewDialog.tsx +++ b/src/components/dialogs/ObjectPreviewDialog.tsx @@ -13,14 +13,14 @@ import { Save as SaveIcon, ContentCopy as CopyIcon, } from '@mui/icons-material'; -import { copyToClipboard, objectApi } from '@/lib/tauri'; +import { copyToClipboard, objectApi, previewCacheApi } from '@/lib/tauri'; import Editor from '@monaco-editor/react'; import { toast } from '@/store/toastStore'; import { BaseDialog } from '../common/BaseDialog'; import ImagePreviewViewer from './ImagePreviewViewer'; import { ConfirmDialog } from '../common/ConfirmDialog'; import { getEditorLanguage, getObjectExtension, getObjectKind, getObjectName } from '@/lib/objectCapabilities'; -import { useSettingsStore } from '@/store/settingsStore'; +import { OFFLINE_NOTICE, previewCache, usePreviewContext, type PreviewPayload } from '@/lib/previewPrefetch'; interface ObjectPreviewDialogProps { open: boolean; @@ -54,13 +54,14 @@ export default function ObjectPreviewDialog({ onToggleSelect, }: ObjectPreviewDialogProps) { const theme = useTheme(); - const maxTextPreviewSizeMb = useSettingsStore((state) => state.maxTextPreviewSizeMb); + const previewContext = usePreviewContext(bucketName, bucketRegion); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [content, setContent] = useState(''); const [editedContent, setEditedContent] = useState(''); const [contentType, setContentType] = useState(null); const [presignedUrl, setPresignedUrl] = useState(null); + const [offline, setOffline] = useState(false); const [isEditing, setIsEditing] = useState(startInEditMode); const [isSaving, setIsSaving] = useState(false); const [textIdentity, setTextIdentity] = useState<{ etag: string | null; profileId: string } | null>(null); @@ -91,6 +92,9 @@ export default function ObjectPreviewDialog({ // Monaco assigns a new version even when restoring the original text. const hasChanges = editedContent !== content; + // Prefetched content only lives while a preview is open; reopening always loads fresh. + useEffect(() => { if (open) return () => previewCache.clear(); }, [open]); + useEffect(() => { if (!open || !objectKey) return; const requestId = ++loadRequestIdRef.current; @@ -105,6 +109,7 @@ export default function ObjectPreviewDialog({ setEditedContent(''); setContentType(null); setPresignedUrl(null); + setOffline(false); setIsEditing(startInEditMode); // Reset edit mode based on prop if (loadTimeoutRef.current) { clearTimeout(loadTimeoutRef.current); @@ -115,11 +120,32 @@ export default function ObjectPreviewDialog({ pdfLoadingTimeoutRef.current = null; } - const maxPreviewBytes = maxTextPreviewSizeMb * 1024 * 1024; + const isCurrent = () => !cancelled && requestId === loadRequestIdRef.current; + const apply = (payload: PreviewPayload) => { + setContentType(payload.contentType); + if (payload.kind === 'unavailable') { setError(payload.message); return; } + setOffline(!!payload.offline); + if (payload.kind === 'text') { + // Even if empty, it's valid content + setContent(payload.content); + setEditedContent(payload.content); + setTextIdentity({ etag: payload.etag, profileId: payload.profileId }); + return; + } + if (payload.objectKind === 'pdf') { + setIsPdfLoading(true); + pdfLoadingTimeoutRef.current = setTimeout(() => { if (isCurrent()) setIsPdfLoading(false); }, 5000); + } + setPresignedUrl(payload.url); + }; + + // A prefetched neighbour renders in the same batch as the reset above, without a spinner. + const prefetched = previewCache.peek(previewContext, objectKey); + if (prefetched) { apply(prefetched); setIsLoading(false); return; } // Safety timeout to prevent infinite spinner loadTimeoutRef.current = setTimeout(() => { - if (!cancelled && requestId === loadRequestIdRef.current) { + if (isCurrent()) { console.error("Content loading timed out"); setIsLoading(false); setError("Loading timed out. Please try again."); @@ -127,59 +153,8 @@ export default function ObjectPreviewDialog({ }, 120000); try { - let resolvedContentType: string | null = null; - let resolvedObjectSize = objectSize; - try { - const metadata = await objectApi.getObjectMetadata(bucketName, bucketRegion, objectKey); - resolvedContentType = metadata.content_type; - resolvedObjectSize = metadata.size; - if (!cancelled && requestId === loadRequestIdRef.current) { - setContentType(metadata.content_type); - } - } catch (metadataErr) { - console.warn('Failed to load object metadata, falling back to filename-based detection:', metadataErr); - } - - if (cancelled || requestId !== loadRequestIdRef.current) return; - - const resolvedKind = getObjectKind(filename, resolvedContentType); - if (resolvedKind === 'text' && resolvedObjectSize && resolvedObjectSize > maxPreviewBytes) { - setError(`File is too large to preview (${(resolvedObjectSize / 1024 / 1024).toFixed(2)} MB). Increase the ${maxTextPreviewSizeMb} MB text preview limit in Settings or download it.`); - return; - } - - if (resolvedKind === 'image' || resolvedKind === 'audio' || resolvedKind === 'video' || resolvedKind === 'pdf') { - // Get presigned URL for preview - if (resolvedKind === 'pdf') { - setIsPdfLoading(true); - pdfLoadingTimeoutRef.current = setTimeout(() => { - if (!cancelled && requestId === loadRequestIdRef.current) { - setIsPdfLoading(false); - } - }, 5000); - } - const url = await objectApi.getPresignedUrl(bucketName, bucketRegion, objectKey, 3600); - if (!cancelled && requestId === loadRequestIdRef.current) { - setPresignedUrl(url); - } - } else if (resolvedKind === 'text') { - // Get text content - const textContent = await objectApi.getObjectContent( - bucketName, - bucketRegion, - objectKey, - maxPreviewBytes - ); - - // Even if empty, it's valid content - if (!cancelled && requestId === loadRequestIdRef.current) { - setContent(textContent.content); - setEditedContent(textContent.content); - setTextIdentity({ etag: textContent.e_tag, profileId: textContent.profile_id }); - } - } else { - setError('This object is not previewable in the app. Please download it to inspect locally.'); - } + const payload = await previewCache.get(previewContext, objectKey, objectSize); + if (isCurrent()) apply(payload); } catch (err) { console.error("Failed to load object content:", err); if (!cancelled && requestId === loadRequestIdRef.current) { @@ -210,7 +185,7 @@ export default function ObjectPreviewDialog({ pdfLoadingTimeoutRef.current = null; } }; - }, [open, objectKey, bucketName, bucketRegion, objectSize, startInEditMode, filename, maxTextPreviewSizeMb, reloadAttempt]); + }, [open, objectKey, objectSize, startInEditMode, previewContext, reloadAttempt]); const handleSave = async () => { if (!isEditing || isSaving || !textIdentity?.etag) return; @@ -221,7 +196,11 @@ export default function ObjectPreviewDialog({ try { const etag = await objectApi.putObjectContent(bucketName, bucketRegion, objectKey, editedContent, textIdentity.etag, textIdentity.profileId); + previewCache.delete(previewContext, objectKey); + // The saved object has a new version; the next preview downloads a fresh local copy. + void previewCacheApi.remove(bucketName, objectKey).catch(() => undefined); if (requestId !== loadRequestIdRef.current) return; + setOffline(false); setTextIdentity({ ...textIdentity, etag }); setContent(editedContent); toast.success('File Saved', `${filename} saved successfully`); @@ -272,12 +251,13 @@ export default function ObjectPreviewDialog({ return = 0 ? imageSequence.length : 0)} onPrevious={navigation ? navigation.onPrevious : onNavigateImage && index > 0 ? () => onNavigateImage(imageSequence[index - 1]) : undefined} onNext={navigation ? navigation.onNext : onNavigateImage && index >= 0 && index < imageSequence.length - 1 ? () => onNavigateImage(imageSequence[index + 1]) : undefined} navigationLabel={navigation ? 'file' : 'image'} navigationBusy={navigation?.busy} navigationError={navigation?.error} isSelected={isSelected} onToggleSelect={onToggleSelect} - onClose={handleClose} onRetry={() => setReloadAttempt(attempt => attempt + 1)} + onClose={handleClose} onRetry={() => { previewCache.delete(previewContext, objectKey); setReloadAttempt(attempt => attempt + 1); }} />; } @@ -401,6 +381,8 @@ export default function ObjectPreviewDialog({ )} + {!isLoading && offline && {OFFLINE_NOTICE}} + {!isLoading && isText && textIdentity && !textIdentity.etag && ( This provider did not return an ETag. Download or copy the text to edit it safely. )} diff --git a/src/hooks/usePreviewNavigation.ts b/src/hooks/usePreviewNavigation.ts index 7ba118d..91e463c 100644 --- a/src/hooks/usePreviewNavigation.ts +++ b/src/hooks/usePreviewNavigation.ts @@ -60,5 +60,5 @@ export function usePreviewNavigation({ objects, field, direction, context, objec } catch (e) { if (current()) report(String(e)); } finally { if (lock.current === identity) { lock.current = null; if (current()) setBusy(null); } } } - return { index, total: sequence.length, previous: index > 0, next: index >= 0 && (index < sequence.length - 1 || hasMore), busy: busy === latest.current, error: error?.identity === latest.current ? error.message : '', navigate }; + return { sequence, index, total: sequence.length, previous: index > 0, next: index >= 0 && (index < sequence.length - 1 || hasMore), busy: busy === latest.current, error: error?.identity === latest.current ? error.message : '', navigate }; } diff --git a/src/hooks/usePreviewPrefetch.ts b/src/hooks/usePreviewPrefetch.ts new file mode 100644 index 0000000..682239c --- /dev/null +++ b/src/hooks/usePreviewPrefetch.ts @@ -0,0 +1,34 @@ +import { useEffect } from 'react'; +import { subscribeCacheInvalidation, type S3Object } from '@/lib/tauri'; +import { previewCache as defaultCache, type PreviewCache, type PreviewContext } from '@/lib/previewPrefetch'; + +/** + * Keeps the previous and next previewable files loaded around the current one. + * Moving Next or Previous slides the window, so only the newly adjacent file is fetched. + * Never loads more listing pages just to prefetch. + */ +export function usePreviewPrefetch({ sequence, index, open, ctx, cache = defaultCache }: { + sequence: S3Object[]; index: number; open: boolean; ctx: PreviewContext; cache?: PreviewCache; +}) { + const previous = open && index > 0 ? sequence[index - 1] : undefined; + const current = open && index >= 0 ? sequence[index] : undefined; + const next = open && index >= 0 ? sequence[index + 1] : undefined; + + useEffect(() => { + if (!open) { cache.clear(); return; } + return subscribeCacheInvalidation(scope => { if (scope === 'objects') cache.clear(); }); + }, [open, cache]); + + useEffect(() => { + if (!current) return; + let cancelled = false; + cache.retain(ctx, [previous?.key, current.key, next?.key].filter((key): key is string => !!key)); + // Shares the dialog's request; neighbours start only after the visible file has loaded. + cache.get(ctx, current.key, current.size).catch(() => undefined).then(() => { + if (cancelled) return; + if (previous) void cache.prefetch(ctx, previous); + if (next) void cache.prefetch(ctx, next); + }); + return () => { cancelled = true; }; + }, [cache, ctx, previous, current, next]); +} diff --git a/src/lib/previewPrefetch.ts b/src/lib/previewPrefetch.ts new file mode 100644 index 0000000..1319289 --- /dev/null +++ b/src/lib/previewPrefetch.ts @@ -0,0 +1,196 @@ +import { useMemo } from 'react'; +import { objectApi, previewCacheApi, type PreviewCacheLookup, type S3Object } from '@/lib/tauri'; +import { getObjectKind, getObjectName } from '@/lib/objectCapabilities'; +import { useProfileStore } from '@/store/profileStore'; +import { useSettingsStore } from '@/store/settingsStore'; + +/** Neighbours at or above this listing size are not prefetched. */ +export const PREFETCH_MAX_BYTES = 10 * 1024 * 1024; +const PRESIGN_SECONDS = 3600; +// Signed URLs must stay usable for the whole time they are displayed. +const MEDIA_MAX_AGE_MS = 50 * 60 * 1000; +// Text and local copies can change remotely, so they are revalidated after this. Saving is ETag-guarded. +const TEXT_MAX_AGE_MS = 5 * 60 * 1000; +// Offline copies are retried soon so the label clears once the server is reachable again. +const OFFLINE_MAX_AGE_MS = 30 * 1000; +/** Larger objects are previewed from S3 directly instead of being copied to the local cache. */ +export const LOCAL_CACHE_MAX_FILE_BYTES = 100 * 1024 * 1024; +const CACHED_KINDS = new Set(['image', 'pdf', 'text']); + +export interface PreviewContext { + profileId: string; bucketName: string; bucketRegion: string; maxTextMb: number; + /** Local disk cache limit in MB; 0 disables the cache. */ + localCacheMb?: number; +} + +export type PreviewPayload = + | { kind: 'media'; objectKind: 'image' | 'audio' | 'video' | 'pdf'; contentType: string | null; url: string; image?: HTMLImageElement; local?: boolean; offline?: boolean } + | { kind: 'text'; contentType: string | null; content: string; etag: string | null; profileId: string; local?: boolean; offline?: boolean } + | { kind: 'unavailable'; contentType: string | null; message: string }; + +export const OFFLINE_NOTICE = 'Offline copy: the server could not be reached, so this cached version may be outdated.'; + +export const shouldPrefetch = (object: S3Object) => Number.isFinite(object.size) && object.size >= 0 && object.size < PREFETCH_MAX_BYTES; + +export function usePreviewContext(bucketName: string, bucketRegion: string): PreviewContext { + const profileId = useProfileStore(state => state.activeProfileId) || ''; + const maxTextMb = useSettingsStore(state => state.maxTextPreviewSizeMb); + const localCacheMb = useSettingsStore(state => state.localCacheEnabled ? state.localCacheMaxMb : 0); + return useMemo(() => ({ profileId, bucketName, bucketRegion, maxTextMb, localCacheMb }), [profileId, bucketName, bucketRegion, maxTextMb, localCacheMb]); +} + +async function warmImage(url: string) { + const image = new Image(); + image.decoding = 'async'; + image.src = url; + // Holding the decoded element keeps the bytes in the webview's memory cache for the viewer's . + try { await image.decode?.(); return image; } catch { return undefined; } +} + +const tooLargeForText = (ctx: PreviewContext, size: number): PreviewPayload => ({ + kind: 'unavailable', contentType: null, + message: `File is too large to preview (${(size / 1024 / 1024).toFixed(2)} MB). Increase the ${ctx.maxTextMb} MB text preview limit in Settings or download it.`, +}); + +/** Loads a preview straight from S3 once the object's content type and size are known. */ +async function loadRemotePayload(ctx: PreviewContext, key: string, contentType: string | null, size: number | undefined, warm: boolean): Promise { + const kind = getObjectKind(getObjectName(key), contentType); + const maxTextBytes = ctx.maxTextMb * 1024 * 1024; + if (kind === 'text') { + if (size && size > maxTextBytes) return { ...tooLargeForText(ctx, size), contentType }; + const text = await objectApi.getObjectContent(ctx.bucketName, ctx.bucketRegion, key, maxTextBytes); + return { kind: 'text', contentType, content: text.content, etag: text.e_tag, profileId: text.profile_id }; + } + if (kind === 'image' || kind === 'audio' || kind === 'video' || kind === 'pdf') { + const url = await objectApi.getPresignedUrl(ctx.bucketName, ctx.bucketRegion, key, PRESIGN_SECONDS); + // Option B: only images get their bytes prefetched; other media prefetch metadata and the signed URL. + const image = warm && kind === 'image' ? await warmImage(url) : undefined; + return { kind: 'media', objectKind: kind, contentType, url, image }; + } + return { kind: 'unavailable', contentType, message: 'This object is not previewable in the app. Please download it to inspect locally.' }; +} + +async function loadLocalPayload(ctx: PreviewContext, key: string, lookup: PreviewCacheLookup, path: string, warm: boolean): Promise { + const contentType = lookup.content_type; + const offline = lookup.offline; + const kind = getObjectKind(getObjectName(key), contentType); + if (kind === 'text') { + const content = await previewCacheApi.readText(ctx.bucketName, key, ctx.maxTextMb * 1024 * 1024); + return { kind: 'text', contentType, content, etag: lookup.e_tag, profileId: lookup.profile_id, local: true, offline }; + } + const url = await previewCacheApi.fileUrl(path); + const image = warm && kind === 'image' ? await warmImage(url) : undefined; + return { kind: 'media', objectKind: kind as 'image' | 'pdf', contentType, url, image, local: true, offline }; +} + +/** + * Serves images, PDFs and text from the local disk cache while the copy's size, date and ETag + * match the remote object, downloading a new copy otherwise. When the remote is unreachable, the + * last copy is shown marked offline. Returns null to fall back to loading from S3. + */ +async function loadCachedPayload(ctx: PreviewContext, key: string, warm: boolean): Promise { + let lookup: PreviewCacheLookup; + try { + lookup = await previewCacheApi.lookup(ctx.bucketName, ctx.bucketRegion, key); + } catch (err) { + console.warn('Local cache lookup failed, loading from S3:', err); + return null; + } + const kind = getObjectKind(getObjectName(key), lookup.content_type); + const maxTextBytes = ctx.maxTextMb * 1024 * 1024; + if (kind === 'text' && lookup.size > maxTextBytes) return { ...tooLargeForText(ctx, lookup.size), contentType: lookup.content_type }; + const cacheable = CACHED_KINDS.has(kind) && lookup.cacheable; + if (cacheable && lookup.local_path) { + try { + return await loadLocalPayload(ctx, key, lookup, lookup.local_path, warm); + } catch (err) { + if (lookup.offline) throw err; + console.warn('Cached copy unreadable, downloading again:', err); + } + } + const maxCacheBytes = (ctx.localCacheMb ?? 0) * 1024 * 1024; + if (cacheable && lookup.size <= Math.min(LOCAL_CACHE_MAX_FILE_BYTES, maxCacheBytes)) { + try { + const path = await previewCacheApi.fill(ctx.bucketName, ctx.bucketRegion, key, lookup.e_tag, lookup.size, maxCacheBytes); + return await loadLocalPayload(ctx, key, { ...lookup, offline: false }, path, warm); + } catch (err) { + console.warn('Could not cache a local copy, loading from S3:', err); + } + } + return loadRemotePayload(ctx, key, lookup.content_type, lookup.size, warm); +} + +export async function loadPreviewPayload(ctx: PreviewContext, key: string, sizeHint: number | undefined, warm: boolean): Promise { + if (ctx.localCacheMb) { + const cached = await loadCachedPayload(ctx, key, warm); + if (cached) return cached; + } + let contentType: string | null = null; + let size = sizeHint; + try { + const metadata = await objectApi.getObjectMetadata(ctx.bucketName, ctx.bucketRegion, key); + contentType = metadata.content_type; + size = metadata.size; + } catch (err) { + console.warn('Failed to load object metadata, falling back to filename-based detection:', err); + } + return loadRemotePayload(ctx, key, contentType, size, warm); +} + +interface Entry { promise: Promise; value?: PreviewPayload; settledAt?: number } + +export class PreviewCache { + private entries = new Map(); + constructor(private load = loadPreviewPayload, private now = () => Date.now()) {} + + static id(ctx: PreviewContext, key: string) { + return JSON.stringify([ctx.profileId, ctx.bucketName, ctx.bucketRegion, ctx.maxTextMb, ctx.localCacheMb ?? 0, key]); + } + + private fresh(entry: Entry) { + if (!entry.value || entry.settledAt === undefined) return true; // in flight + const value = entry.value; + const maxAge = value.kind !== 'unavailable' && value.offline ? OFFLINE_MAX_AGE_MS + : value.kind === 'media' && !value.local ? MEDIA_MAX_AGE_MS : TEXT_MAX_AGE_MS; + return this.now() - entry.settledAt < maxAge; + } + + /** Returns the shared request for a key, starting one if none is cached and fresh. */ + get(ctx: PreviewContext, key: string, sizeHint?: number, warm = false): Promise { + const id = PreviewCache.id(ctx, key); + const existing = this.entries.get(id); + if (existing && this.fresh(existing)) return existing.promise; + const entry: Entry = { promise: this.load(ctx, key, sizeHint, warm) }; + this.entries.set(id, entry); + entry.promise.then( + value => { entry.value = value; entry.settledAt = this.now(); }, + // Failed loads are never cached, so Retry and later visits ask again. + () => { if (this.entries.get(id) === entry) this.entries.delete(id); }, + ); + return entry.promise; + } + + prefetch(ctx: PreviewContext, object: S3Object) { + if (!shouldPrefetch(object)) return Promise.resolve(); + return this.get(ctx, object.key, object.size, true).then(() => undefined, () => undefined); + } + + /** Synchronous access to a loaded, fresh payload so navigation can skip the spinner. */ + peek(ctx: PreviewContext, key: string) { + const entry = this.entries.get(PreviewCache.id(ctx, key)); + return entry?.value && this.fresh(entry) ? entry.value : undefined; + } + + delete(ctx: PreviewContext, key: string) { this.entries.delete(PreviewCache.id(ctx, key)); } + + /** Evicts everything except the given keys in the given context. */ + retain(ctx: PreviewContext, keys: string[]) { + const keep = new Set(keys.map(key => PreviewCache.id(ctx, key))); + for (const id of this.entries.keys()) if (!keep.has(id)) this.entries.delete(id); + } + + clear() { this.entries.clear(); } + get size() { return this.entries.size; } +} + +export const previewCache = new PreviewCache(); diff --git a/src/lib/tauri.ts b/src/lib/tauri.ts index f675bb5..410c5ab 100644 --- a/src/lib/tauri.ts +++ b/src/lib/tauri.ts @@ -356,6 +356,37 @@ export const objectApi = { }, }; +export interface PreviewCacheLookup { + profile_id: string; + size: number; + last_modified: string | null; + content_type: string | null; + e_tag: string | null; + /** A local copy matching the remote object, or the last saved copy when `offline`. */ + local_path: string | null; + /** The remote could not be reached; metadata and copy come from the local cache. */ + offline: boolean; + /** False when the remote reports no modification date, so copies cannot be validated. */ + cacheable: boolean; +} + +export const previewCacheApi = { + lookup: (bucketName: string, bucketRegion: string | undefined, key: string) => + invoke('preview_cache_lookup', { bucketName, bucketRegion, key }), + fill: (bucketName: string, bucketRegion: string | undefined, key: string, eTag: string | null, size: number, maxCacheBytes: number) => + invoke('preview_cache_fill', { bucketName, bucketRegion, key, eTag, size, maxCacheBytes }), + readText: (bucketName: string, key: string, maxBytes: number) => + invoke('preview_cache_read_text', { bucketName, key, maxBytes }), + remove: (bucketName: string, key: string) => invoke('preview_cache_remove', { bucketName, key }), + usage: () => invoke<{ files: number; bytes: number }>('preview_cache_usage'), + clear: () => invoke('clear_preview_cache'), + /** Converts a cached file path into a URL the webview can load through the asset protocol. */ + async fileUrl(path: string) { + const { convertFileSrc } = await import('@tauri-apps/api/core'); + return convertFileSrc(path); + }, +}; + export const operationsApi = { async copyBetweenProfiles(items: import('@/store/clipboardStore').ClipboardItem[], destinationBucket: string, destinationRegion: string, destinationPrefix: string, expectedProfileId: string): Promise { if (expectedProfileId !== useProfileStore.getState().activeProfileId) { diff --git a/src/store/settingsStore.ts b/src/store/settingsStore.ts index fbd56d7..32fe7c1 100644 --- a/src/store/settingsStore.ts +++ b/src/store/settingsStore.ts @@ -4,6 +4,8 @@ import { browserStorage } from './browserStorage'; export const MIN_TEXT_PREVIEW_SIZE_MB = 1; export const MAX_TEXT_PREVIEW_SIZE_MB = 100; +export const MIN_LOCAL_CACHE_MB = 100; +export const MAX_LOCAL_CACHE_MB = 20480; interface SettingsState { defaultRegion: string; @@ -12,6 +14,11 @@ interface SettingsState { setTransferBandwidthKiB: (value: number) => void; maxTextPreviewSizeMb: number; autoRefreshOnFocus: boolean; + /** Keep previewed images, PDFs and text on disk and reuse them while they match the remote. */ + localCacheEnabled: boolean; + localCacheMaxMb: number; + setLocalCacheEnabled: (enabled: boolean) => void; + setLocalCacheMaxMb: (max: number) => void; setDefaultRegion: (region: string) => void; setMaxConcurrentTransfers: (max: number) => void; setMaxTextPreviewSizeMb: (max: number) => void; @@ -36,6 +43,12 @@ export const useSettingsStore = create()( ), }), setAutoRefreshOnFocus: (autoRefreshOnFocus) => set({ autoRefreshOnFocus }), + localCacheEnabled: true, + localCacheMaxMb: 1024, + setLocalCacheEnabled: (localCacheEnabled) => set({ localCacheEnabled }), + setLocalCacheMaxMb: (value) => set({ + localCacheMaxMb: Math.min(MAX_LOCAL_CACHE_MB, Math.max(MIN_LOCAL_CACHE_MB, Math.round(value))), + }), }), { name: 'brows3-settings', diff --git a/tests/components/text-save.test.tsx b/tests/components/text-save.test.tsx index 5a21fb2..c259a0d 100644 --- a/tests/components/text-save.test.tsx +++ b/tests/components/text-save.test.tsx @@ -1,9 +1,14 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { beforeEach, expect, test, vi } from 'vitest'; import ObjectPreviewDialog from '@/components/dialogs/ObjectPreviewDialog'; -import { objectApi } from '@/lib/tauri'; +import { objectApi, previewCacheApi } from '@/lib/tauri'; -vi.mock('@/lib/tauri', () => ({ objectApi: { getObjectMetadata: vi.fn(), getObjectContent: vi.fn(), putObjectContent: vi.fn() }, copyToClipboard: vi.fn() })); +vi.mock('@/lib/tauri', () => ({ + objectApi: { getObjectMetadata: vi.fn(), getObjectContent: vi.fn(), putObjectContent: vi.fn() }, + // Lookup failures fall back to loading from S3, which these tests exercise. + previewCacheApi: { lookup: vi.fn().mockRejectedValue(new Error('no cache')), remove: vi.fn().mockResolvedValue(undefined) }, + copyToClipboard: vi.fn(), +})); vi.mock('@monaco-editor/react', () => ({ default: ({ value, onChange, options }: { value: string; onChange: (value: string) => void; options: { readOnly: boolean } }) =>