From 0244d3ddc7c898db7a457bf8362b444ba08a0dff Mon Sep 17 00:00:00 2001 From: AptS-1547 Date: Sat, 19 Sep 2026 01:23:53 +0800 Subject: [PATCH] fix(upload): use reliable staging preallocation --- CHANGELOG.md | 6 ++ CHANGELOG.zh.md | 6 ++ Cargo.lock | 12 +++- Cargo.toml | 2 +- .../design/upload-finalization-contracts.md | 2 +- .../design/upload-finalization-contracts.md | 2 +- src/services/files/upload/ingest/chunk.rs | 4 +- src/services/files/upload/ingest/staging.rs | 16 ++--- src/storage/drivers/local/driver_impl.rs | 4 +- tests/files/upload.rs | 67 ++++++++++++++++--- 10 files changed, 95 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b81c9a758..332f15e10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- **Upload staging reservation on Apple filesystems** — Server-managed staged uploads now use the revision-pinned `aster-fs` allocation contract. New APFS reservations are all-or-nothing and validate the kernel-reported byte count before extending logical EOF; existing sparse sessions recover their actual holes without changing stored data or falsely reporting success. Insufficient new staging capacity returns the existing stable 507 error without leaving a partial session reservation. + ## [v0.6.1] - 2026-09-16 ### Breaking diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index 7b85ef51b..41d583182 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- **Apple 文件系统上的上传暂存预留** — 服务端 staged upload 改用固定 revision 的 `aster-fs` allocation 契约。新 APFS reservation 采用 all-or-nothing 语义,并在扩展逻辑 EOF 前校验内核返回的实际分配字节数;已有 sparse session 按真实 hole 恢复物理块,不改变已存数据,也不会把不完整恢复误报为成功。新 staging 空间不足时返回现有稳定 507 错误,且不留下部分 session reservation。 + ## [v0.6.1] - 2026-09-16 ### Breaking diff --git a/Cargo.lock b/Cargo.lock index 89b04ffee..3f882dc7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -737,6 +737,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "aster-fs" +version = "0.1.0" +source = "git+https://github.com/AsterCommunity/AsterFs?rev=913ed30598119c184f49f18e5b339fc98869fff2#913ed30598119c184f49f18e5b339fc98869fff2" +dependencies = [ + "libc", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "aster_drive" version = "0.6.1" @@ -747,6 +757,7 @@ dependencies = [ "actix-web", "actix-ws", "aes-gcm 0.11.1", + "aster-fs", "aster_drive_metrics", "aster_drive_migration", "aster_drive_model", @@ -799,7 +810,6 @@ dependencies = [ "data-encoding", "dotenvy", "encoding_rs", - "fs2", "futures", "governor", "hex", diff --git a/Cargo.toml b/Cargo.toml index 1c9434c59..2c2fdd0a8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -226,7 +226,7 @@ dotenvy = "0.15" encoding_rs = "0.8" oem_cp = "2" futures = { workspace = true } -fs2 = "0.4" +aster-fs = { git = "https://github.com/AsterCommunity/AsterFs", rev = "913ed30598119c184f49f18e5b339fc98869fff2", default-features = false, features = ["sync"] } hex = { workspace = true } hmac = "0.13" http = "1" diff --git a/developer-docs/en/design/upload-finalization-contracts.md b/developer-docs/en/design/upload-finalization-contracts.md index fa7082dfc..37db48419 100644 --- a/developer-docs/en/design/upload-finalization-contracts.md +++ b/developer-docs/en/design/upload-finalization-contracts.md @@ -16,7 +16,7 @@ Capacity observation and operation-specific assessment are separate contracts: Capacity probes use a demand-driven coordinator owned by `DriverRegistry`, with no periodic scan. It caches raw observations rather than size-specific assessments, coalesces probes per policy, and bounds concurrency across policies. Each driver owns a `StorageCapacityProbePolicy`: Local uses a two-second fresh window, 30-second sufficient stale window, 250-millisecond negative window, and fixed two-second timeout; OneDrive and Remote use a 30-second fresh window, five-minute sufficient stale window, one-second negative window, and a connector-configurable timeout from two to 30 seconds (default ten). Stale insufficient or unavailable decisions require refresh confirmation. A failed refresh preserves the last usable observation for requests it still classifies as sufficient, while larger requests receive the latest probe failure instead of a stale rejection. Policy, credential, and driver invalidation clears the observation, and probe tasks survive HTTP request cancellation while recording failure and latency. -Before session Init returns, `OffsetStaging` / `StreamStaging` serialize capacity admission against the filesystem containing `upload_temp_dir` and use `fs2::FileExt::allocate` to reserve physical blocks for the complete `total_size`; a sparse length created by `set_len` is no longer treated as a reservation. Admission keeps the configured `server.upload_temp_min_free_bytes` safety floor (256 MiB by default), accepts an exact `required + floor` fit, and returns stable `upload.staging_capacity_insufficient` (HTTP 507) while cleaning the session, temporary directory, and Init-created relative-path directories when space is insufficient. Setting the floor to `0` disables the margin, not physical preallocation. +Before session Init returns, `OffsetStaging` / `StreamStaging` serialize capacity admission against the filesystem containing `upload_temp_dir` and use the revision-pinned `aster-fs` allocation contract to reserve physical blocks for the complete `total_size`; a sparse length created by `set_len` is no longer treated as a reservation. On Apple filesystems, new extents use all-or-nothing allocation and validate the kernel-reported byte count before extending logical EOF, while recovery materializes actual sparse holes without changing existing data or falsely reporting success. Admission keeps the configured `server.upload_temp_min_free_bytes` safety floor (256 MiB by default), accepts an exact `required + floor` fit, and returns stable `upload.staging_capacity_insufficient` (HTTP 507) while cleaning the session, temporary directory, and Init-created relative-path directories when space is insufficient. Setting the floor to `0` disables the margin, not physical preallocation. The cluster profile permits the same staging protocol when operators make every Primary's `upload_temp_dir` resolve to one shared filesystem. Durable receipts, `received_count`, completion state, and the assembly lease remain authoritative in the shared writer database; exclusion for writes to the same chunk depends on cross-instance advisory locks supplied by the deployed filesystem. AsterDrive does not infer mount identity from path strings or create a second shared-filesystem session kind. diff --git a/developer-docs/zh-CN/design/upload-finalization-contracts.md b/developer-docs/zh-CN/design/upload-finalization-contracts.md index 88d40233b..0f2d66ebb 100644 --- a/developer-docs/zh-CN/design/upload-finalization-contracts.md +++ b/developer-docs/zh-CN/design/upload-finalization-contracts.md @@ -48,7 +48,7 @@ 容量探测使用 `DriverRegistry` 所有的请求驱动协调器,不运行周期扫描。协调器缓存原始 observation 而不是特定文件大小的 assessment;同 policy probe 使用 singleflight,跨 policy probe 受全局并发限制。每个 driver 提供 `StorageCapacityProbePolicy`:Local 使用 fresh 2 秒、充足值 stale 30 秒、negative 250 毫秒和固定 2 秒 timeout;OneDrive 与 Remote 使用 fresh 30 秒、充足值 stale 5 分钟、negative 1 秒,并允许 connector 将 timeout 配置为 2 至 30 秒(默认 10 秒)。stale 不足或不可用值先刷新确认,避免旧低水位误报。刷新失败时保留最后一个可用 observation,小请求可以继续使用 stale 充足值,而该 observation 对更大请求显示不足时返回最新探测错误。policy/credential/driver 失效会同步清除对应 observation,probe 任务独立于 HTTP 请求取消并记录失败与时延。 -`OffsetStaging` / `StreamStaging` 在 session Init 返回前,对 `upload_temp_dir` 所在文件系统执行串行容量准入,并通过 `fs2::FileExt::allocate` 预留完整 `total_size` 的物理块;单纯 `set_len` 形成的稀疏文件不再视为 reservation。准入保证分配后仍保留 `server.upload_temp_min_free_bytes`(默认 256 MiB)的 safety floor,恰好满足 `required + floor` 时允许,空间不足返回稳定的 `upload.staging_capacity_insufficient`(HTTP 507),并清理 session、临时目录和 Init 创建的相对路径目录。`0` 可关闭 safety floor,但不会关闭物理预分配。 +`OffsetStaging` / `StreamStaging` 在 session Init 返回前,对 `upload_temp_dir` 所在文件系统执行串行容量准入,并通过固定 revision 的 `aster-fs` allocation 契约预留完整 `total_size` 的物理块;单纯 `set_len` 形成的稀疏文件不再视为 reservation。Apple 文件系统上的新 extent 使用 all-or-nothing allocation,并在扩展逻辑 EOF 前校验内核返回的实际分配字节数;恢复已有 sparse session 时按真实 hole 补足物理块,不改变已有数据,也不会把不完整恢复误报为成功。准入保证分配后仍保留 `server.upload_temp_min_free_bytes`(默认 256 MiB)的 safety floor,恰好满足 `required + floor` 时允许,空间不足返回稳定的 `upload.staging_capacity_insufficient`(HTTP 507),并清理 session、临时目录和 Init 创建的相对路径目录。`0` 可关闭 safety floor,但不会关闭物理预分配。 cluster profile 下允许使用同一套 staging 协议,但部署者必须让所有 Primary 的 `upload_temp_dir` 指向同一个共享文件系统。Durable receipt、`received_count`、completion 状态与 assembly lease 仍以共享 writer database 为权威;同一 chunk 写入的排他性依赖部署文件系统提供跨实例 advisory lock。AsterDrive 不根据路径字符串推断 mount identity,也不建立第二套 shared-filesystem session kind。 diff --git a/src/services/files/upload/ingest/chunk.rs b/src/services/files/upload/ingest/chunk.rs index cedab730a..3789574e2 100644 --- a/src/services/files/upload/ingest/chunk.rs +++ b/src/services/files/upload/ingest/chunk.rs @@ -70,7 +70,7 @@ fn relay_multipart_fields(session: &upload_session::Model) -> Result<(&str, &str impl Drop for LocalChunkWriteLock { fn drop(&mut self) { - if let Err(error) = fs2::FileExt::unlock(&self.file) { + if let Err(error) = aster_fs::FileExt::unlock(&self.file) { tracing::warn!("failed to unlock local chunk write lock: {error}"); } } @@ -96,7 +96,7 @@ async fn acquire_local_chunk_write_lock( format!("open chunk write lock for upload {upload_id}: {error}"), ) })?; - fs2::FileExt::lock_exclusive(&file).map_err(|error| { + aster_fs::FileExt::lock(&file).map_err(|error| { chunk_upload_error_with_code( ApiErrorCode::UploadChunkPersistFailed, format!("lock chunk write for upload {upload_id}: {error}"), diff --git a/src/services/files/upload/ingest/staging.rs b/src/services/files/upload/ingest/staging.rs index 7fa53adf1..e9faa85eb 100644 --- a/src/services/files/upload/ingest/staging.rs +++ b/src/services/files/upload/ingest/staging.rs @@ -234,7 +234,7 @@ async fn available_space(root: &StdPath) -> Result { let mut probe = root.as_path(); loop { match std::fs::metadata(probe) { - Ok(_) => return fs2::available_space(probe), + Ok(_) => return aster_fs::available_space(probe), Err(error) if error.kind() == ErrorKind::NotFound => { probe = probe.parent().ok_or_else(|| { std::io::Error::new( @@ -402,13 +402,13 @@ async fn physically_allocate( format!("create chunk staging file: {error}"), ) })?; - let allocated_size = fs2::FileExt::allocated_size(&file).map_err(|error| { + let allocated_size = aster_fs::FileExt::allocated_size(&file).map_err(|error| { chunk_upload_error_with_code( ApiErrorCode::UploadTempFileWriteFailed, format!("inspect chunk staging allocation: {error}"), ) })?; - let available_bytes = fs2::available_space(&root).map_err(|error| { + let available_bytes = aster_fs::available_space(&root).map_err(|error| { chunk_upload_error_with_code( ApiErrorCode::UploadTempFileWriteFailed, format!("inspect upload staging capacity: {error}"), @@ -423,8 +423,8 @@ async fn physically_allocate( let PhysicalAllocation::Allocated { .. } = assessment else { return Ok(assessment); }; - if let Err(error) = fs2::FileExt::allocate(&file, total_size) { - let available_after_error = fs2::available_space(&root).unwrap_or(available_bytes); + if let Err(error) = aster_fs::FileExt::allocate(&file, total_size) { + let available_after_error = aster_fs::available_space(&root).unwrap_or(available_bytes); if error.kind() == ErrorKind::StorageFull || matches!( assess_physical_allocation( @@ -447,7 +447,7 @@ async fn physically_allocate( format!("physically allocate chunk staging file: {error}"), )); } - let reserved_size = fs2::FileExt::allocated_size(&file).map_err(|error| { + let reserved_size = aster_fs::FileExt::allocated_size(&file).map_err(|error| { chunk_upload_error_with_code( ApiErrorCode::UploadTempFileWriteFailed, format!("verify chunk staging allocation: {error}"), @@ -462,7 +462,7 @@ async fn physically_allocate( if let PhysicalAllocation::Allocated { additional_bytes } = assessment && additional_bytes > 0 { - let available_after_allocation = fs2::available_space(&root).map_err(|error| { + let available_after_allocation = aster_fs::available_space(&root).map_err(|error| { chunk_upload_error_with_code( ApiErrorCode::UploadTempFileWriteFailed, format!("verify upload staging safety floor: {error}"), @@ -578,7 +578,7 @@ pub(crate) async fn open_for_chunk_write( #[cfg(test)] mod tests { use super::{PhysicalAllocation, assess_physical_allocation, physically_allocate}; - use fs2::FileExt; + use aster_fs::FileExt; #[test] fn physical_allocation_assessment_preserves_floor_and_accepts_exact_fit() { diff --git a/src/storage/drivers/local/driver_impl.rs b/src/storage/drivers/local/driver_impl.rs index 9bb542c1a..aa4b423c2 100644 --- a/src/storage/drivers/local/driver_impl.rs +++ b/src/storage/drivers/local/driver_impl.rs @@ -135,9 +135,9 @@ impl StorageDriver for LocalDriver { let base_path = self.base_path.clone(); tokio::task::spawn_blocking(move || { let probe_path = nearest_existing_capacity_path(&base_path)?; - let total = fs2::total_space(&probe_path) + let total = aster_fs::total_space(&probe_path) .map_storage_err_ctx(StorageErrorKind::Transient, "local capacity total_space")?; - let available = fs2::available_space(&probe_path).map_storage_err_ctx( + let available = aster_fs::available_space(&probe_path).map_storage_err_ctx( StorageErrorKind::Transient, "local capacity available_space", )?; diff --git a/tests/files/upload.rs b/tests/files/upload.rs index 46bc4bc17..cca1b4fcd 100644 --- a/tests/files/upload.rs +++ b/tests/files/upload.rs @@ -4920,7 +4920,7 @@ async fn test_chunked_init_persists_explicit_offset_staging_kind() { ); let staging_file = std::fs::File::open(&staging_path).unwrap(); assert!( - fs2::FileExt::allocated_size(&staging_file).unwrap() >= 10 * 1024 * 1024, + aster_fs::FileExt::allocated_size(&staging_file).unwrap() >= 10 * 1024 * 1024, "successful staged init must reserve physical blocks, not only sparse length" ); drop(staging_file); @@ -4933,6 +4933,53 @@ async fn test_chunked_init_persists_explicit_offset_staging_kind() { ); } +#[cfg(target_os = "macos")] +#[tokio::test] +async fn macos_chunked_init_reserves_large_apfs_staging_file() { + use aster_drive::services::files::upload; + use aster_drive_model::types::UploadTransport; + + const STAGING_BYTES: i64 = 128 * 1024 * 1024; + + let state = common::setup().await; + let user = + common::create_test_account(&state, "apfsstage", "apfs-staging@test.com", "password123") + .await + .unwrap(); + + let response = upload::init_upload( + &state, + user.id, + "apfs-staging.bin", + STAGING_BYTES, + None, + None, + ) + .await + .unwrap(); + assert_eq!(response.mode, UploadTransport::Chunked); + let upload_id = response.upload_id.as_deref().unwrap(); + let staging_path = upload::test_support::offset_staging_file_path( + &state.config.server.upload_temp_dir, + upload_id, + ); + let staging_file = std::fs::File::open(&staging_path).unwrap(); + assert_eq!(staging_file.metadata().unwrap().len(), STAGING_BYTES as u64); + assert!( + aster_fs::FileExt::allocated_size(&staging_file).unwrap() >= STAGING_BYTES as u64, + "successful APFS staged init must reserve the complete declared size" + ); + drop(staging_file); + + upload::cancel_upload(&state, upload_id, user.id) + .await + .unwrap(); + assert!( + !tokio::fs::try_exists(staging_path).await.unwrap(), + "cancel must release the large APFS staging reservation" + ); +} + #[tokio::test] async fn staged_init_rejects_safety_floor_violation_without_session_or_folder_side_effects() { use aster_drive::db::repository::{folder_repo, policy_repo, upload_session_repo}; @@ -5051,7 +5098,7 @@ async fn resumed_staged_chunk_recovers_physical_reservation_for_active_sparse_se let old_file = std::fs::File::open(old_path).unwrap(); assert!( - fs2::FileExt::allocated_size(&old_file).unwrap() >= 10, + aster_fs::FileExt::allocated_size(&old_file).unwrap() >= 10, "active sparse session must regain physical allocation after runtime restart" ); } @@ -5093,7 +5140,7 @@ async fn resumed_staged_chunk_recreates_unstarted_reservation_after_init_crash() &upload_id, ); let file = std::fs::File::open(&path).unwrap(); - assert!(fs2::FileExt::allocated_size(&file).unwrap() >= 10); + assert!(aster_fs::FileExt::allocated_size(&file).unwrap() >= 10); assert_eq!(&std::fs::read(path).unwrap()[..5], b"12345"); } @@ -5145,7 +5192,7 @@ async fn staged_completion_is_not_blocked_by_another_unrecoverable_reservation() let mut file = std::fs::File::create(path).unwrap(); file.set_len(10).unwrap(); if upload_id == ¤t_id { - fs2::FileExt::allocate(&file, 10).unwrap(); + aster_fs::FileExt::allocate(&file, 10).unwrap(); std::io::Write::write_all(&mut file, b"1234567890").unwrap(); } } @@ -5183,7 +5230,7 @@ async fn staged_completion_recovers_current_sparse_physical_reservation() { use aster_drive::services::files::upload; use aster_drive_model::types::{UploadSessionKind, UploadSessionStatus}; - const SIZE: i64 = 1024 * 1024; + const SIZE: i64 = 128 * 1024 * 1024; let state = common::setup().await; let user = common::create_test_account( @@ -5211,7 +5258,7 @@ async fn staged_completion_recovers_current_sparse_physical_reservation() { let path = create_sparse_staging_file(&state, &upload_id, SIZE as u64, b"valid-prefix").await; let before = std::fs::File::open(&path).unwrap(); assert!( - fs2::FileExt::allocated_size(&before).unwrap() < SIZE as u64, + aster_fs::FileExt::allocated_size(&before).unwrap() < SIZE as u64, "fixture must begin as a partially allocated sparse file" ); drop(before); @@ -5242,7 +5289,7 @@ async fn staged_completion_capacity_failure_marks_current_session_failed() { use aster_drive::services::files::upload; use aster_drive_model::types::{UploadSessionKind, UploadSessionStatus}; - const SIZE: i64 = 1024 * 1024; + const SIZE: i64 = 128 * 1024 * 1024; let base_state = common::setup().await; let mut config = (*base_state.config).clone(); @@ -5358,7 +5405,7 @@ async fn failed_global_recovery_is_retried_before_a_staged_chunk_write() { .write(true) .open(request_path) .unwrap(); - fs2::FileExt::allocate(&request_file, SIZE as u64).unwrap(); + aster_fs::FileExt::allocate(&request_file, SIZE as u64).unwrap(); drop(request_file); let chunk = vec![7_u8; usize::try_from(SIZE).unwrap()]; @@ -5472,7 +5519,7 @@ async fn concurrent_staged_init_creates_independent_physical_reservations() { response.upload_id.as_deref().unwrap(), ); let file = std::fs::File::open(path).unwrap(); - assert!(fs2::FileExt::allocated_size(&file).unwrap() >= 10 * 1024 * 1024); + assert!(aster_fs::FileExt::allocated_size(&file).unwrap() >= 10 * 1024 * 1024); drop(file); upload::cancel_upload( state.as_ref(), @@ -5519,7 +5566,7 @@ async fn sftp_stream_staging_uses_the_same_physical_reservation_contract() { &session.id, ); let file = std::fs::File::open(path).unwrap(); - assert!(fs2::FileExt::allocated_size(&file).unwrap() >= 10 * 1024 * 1024); + assert!(aster_fs::FileExt::allocated_size(&file).unwrap() >= 10 * 1024 * 1024); drop(file); upload::cancel_upload(&state, &session.id, user.id) .await