diff --git a/.config/nextest.toml b/.config/nextest.toml index eb0b7eaafa..2c724ca165 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -162,10 +162,10 @@ setup = 'ecstore-base-stack' filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))' setup = 'lifecycle-large-stack' -# This conditional GET fixture composes real-store futures that overflowed -# the default Linux test-thread stack. +# These conditional GET and delete-marker fixtures overflowed the default +# Linux test-thread stack while composing real-store futures. [[profile.default.scripts]] -filter = 'package(rustfs) & test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data)' +filter = 'package(rustfs) & (test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data) | test(=app::delete_objects_stat_gating_test::batch_delete_can_purge_an_explicit_delete_marker_version))' setup = 'ecstore-large-stack' # These heal fixtures compose deep real-store recovery futures that can @@ -507,10 +507,10 @@ setup = 'ecstore-base-stack' filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))' setup = 'lifecycle-large-stack' -# This conditional GET fixture composes real-store futures that overflowed -# the default Linux test-thread stack. +# These conditional GET and delete-marker fixtures overflowed the default +# Linux test-thread stack while composing real-store futures. [[profile.ci.scripts]] -filter = 'package(rustfs) & test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data)' +filter = 'package(rustfs) & (test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data) | test(=app::delete_objects_stat_gating_test::batch_delete_can_purge_an_explicit_delete_marker_version))' setup = 'ecstore-large-stack' # These heal fixtures compose deep real-store recovery futures that can diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ebc729be3a..0584cc67b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -113,7 +113,7 @@ jobs: printf '%s\n' 'mode=full' >> "$GITHUB_OUTPUT" echo "Base CI policy unavailable; running the full matrix." fi - if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=11$' "$GITHUB_OUTPUT"; then + if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=12$' "$GITHUB_OUTPUT"; then printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT" echo "Base policy does not cover this workflow contract; retaining the full matrix." fi diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index 90c3f32187..6c7bd67ddd 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -221,9 +221,9 @@ jobs: binary_root="fuzz/prebuilt/${CARGO_BUILD_TARGET}/release" mkdir -p "${binary_root}" # Keep this list in sync with fuzz/Cargo.toml, scripts/fuzz/run.sh, - # scripts/fuzz/select_targets.py, and the nightly matrix below (all 7 + # scripts/fuzz/select_targets.py, and the nightly matrix below (all 13 # buildable bins). The *_storage_api.rs files are `mod` submodules. - for target in archive_extract bucket_validation local_metadata notify_xml path_containment policy_ingress sigv4_request; do + for target in archive_extract bucket_validation fuzz_bitrot_framing fuzz_filemeta_decode fuzz_iam_policy_eval fuzz_kms_envelope fuzz_s3_select_sql fuzz_s3_sigv4_and_xml local_metadata notify_xml path_containment policy_ingress sigv4_request; do case ",${SELECTED_TARGETS_CSV}," in *",${target},"*) install -Dm755 "fuzz/target/${CARGO_BUILD_TARGET}/release/${target}" "${binary_root}/${target}" @@ -352,7 +352,7 @@ jobs: retention-days: 7 # ────────────────────────────────────────────────────────────── - # Phase 2 (Nightly): Run all 7 targets in parallel via matrix. + # Phase 2 (Nightly): Run all 13 targets in parallel via matrix. # ────────────────────────────────────────────────────────────── nightly-fuzz-corpus: name: "Nightly / ${{ matrix.target }}" @@ -368,7 +368,7 @@ jobs: strategy: fail-fast: false matrix: - target: [archive_extract, bucket_validation, local_metadata, notify_xml, path_containment, policy_ingress, sigv4_request] + target: [archive_extract, bucket_validation, fuzz_bitrot_framing, fuzz_filemeta_decode, fuzz_iam_policy_eval, fuzz_kms_envelope, fuzz_s3_select_sql, fuzz_s3_sigv4_and_xml, local_metadata, notify_xml, path_containment, policy_ingress, sigv4_request] env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu diff --git a/Cargo.lock b/Cargo.lock index d5df8826fa..6e6b8222fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -67,14 +67,15 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.12" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" dependencies = [ "cfg-if", "const-random", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", + "serde", "version_check", "zerocopy", ] @@ -103,34 +104,19 @@ dependencies = [ "equator", ] -[[package]] -name = "alloc-no-stdlib" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" - [[package]] name = "alloc-no-stdlib" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a" -[[package]] -name = "alloc-stdlib" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" -dependencies = [ - "alloc-no-stdlib 2.0.4", -] - [[package]] name = "alloc-stdlib" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1" dependencies = [ - "alloc-no-stdlib 3.0.0", + "alloc-no-stdlib", ] [[package]] @@ -144,9 +130,9 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.21" +version = "0.2.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +checksum = "57b212daf2e827b1ccdd778b7eb48ba433e58cb0e4f27b43cd6b7a608425a014" [[package]] name = "ambient-authority" @@ -156,9 +142,9 @@ checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" [[package]] name = "amq-protocol" -version = "10.7.0" +version = "10.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba56915f72aa721b4bca471fa71ff8ec10aecc0d5e2d99497edb44358ccedd7b" +checksum = "fca0186b1795fd920c536dcc6ee40e8b518fe6d757b54ba3c0142ea7bd4f39a3" dependencies = [ "amq-protocol-tcp", "amq-protocol-types", @@ -170,9 +156,9 @@ dependencies = [ [[package]] name = "amq-protocol-tcp" -version = "10.7.0" +version = "10.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84153f37233d155953ccbacb21257b4cb82edb68e57066495ff86495d8783a32" +checksum = "98a14c2c46887f925a77adc70ce0d7147a2ad8cfdbcd0103eabec21672a44879" dependencies = [ "amq-protocol-uri", "async-rs", @@ -183,9 +169,9 @@ dependencies = [ [[package]] name = "amq-protocol-types" -version = "10.7.0" +version = "10.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aca84dae6981386bc016fc44434ff9cb6b1f99c25fd0e890ddb048c91261db1" +checksum = "762f02fc9e708baba81b36cdfffbb2402eca28414ea34925582eecd4c7386ae0" dependencies = [ "cookie-factory", "nom 8.0.0", @@ -195,9 +181,9 @@ dependencies = [ [[package]] name = "amq-protocol-uri" -version = "10.7.0" +version = "10.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b58add0b63b221e87956f3ec47d6b8f1a0a6f69cc970b668590000c3aa701af" +checksum = "3d478e1bb5ff98bc9bbc1925c7ea250613996d4782982e80a28f4c2dc3dc9d91" dependencies = [ "amq-protocol-types", "percent-encoding", @@ -255,7 +241,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -266,14 +252,14 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "anyhow" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" [[package]] name = "apache-avro" @@ -299,7 +285,7 @@ dependencies = [ "strum", "thiserror 2.0.21", "uuid", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -331,9 +317,9 @@ dependencies = [ [[package]] name = "archive-trait" -version = "0.0.16" +version = "0.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5040ca935c09888e7dfb04383b4d62fa3571e25bc66b6f345b591e97958524" +checksum = "24ed9d753c6bf6ad6855ea6295df8aa0828bc9ee091633b49fe240402b3eb664" dependencies = [ "cap-std", "thiserror 2.0.21", @@ -360,6 +346,12 @@ dependencies = [ "password-hash", ] +[[package]] +name = "array-const-fn-init" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bcb85e548c05d407fa6faff46b750ba287714ef32afc0f5e15b4641ffd6affb" + [[package]] name = "array-init" version = "2.1.0" @@ -374,9 +366,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" [[package]] name = "arrow" @@ -401,23 +393,23 @@ dependencies = [ [[package]] name = "arrow" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f234f0ed15170301e948de79bb5ba02ac52e58c824f7ce63180ccf5ceec272d3" +checksum = "c5ae4998cf4c111d52898382fbe81f37213b1a420677f480c55925eddfd46217" dependencies = [ - "arrow-arith 59.3.3", - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-cast 59.3.3", - "arrow-csv 59.3.3", - "arrow-data 59.3.3", - "arrow-ipc 59.3.3", - "arrow-json 59.3.3", - "arrow-ord 59.3.3", - "arrow-row 59.3.3", - "arrow-schema 59.3.3", - "arrow-select 59.3.3", - "arrow-string 59.3.3", + "arrow-arith 60.2.0", + "arrow-array 60.2.0", + "arrow-buffer 60.2.0", + "arrow-cast 60.2.0", + "arrow-csv 60.2.0", + "arrow-data 60.2.0", + "arrow-ipc 60.2.0", + "arrow-json 60.2.0", + "arrow-ord 60.2.0", + "arrow-row 60.2.0", + "arrow-schema 60.2.0", + "arrow-select 60.2.0", + "arrow-string 60.2.0", ] [[package]] @@ -436,14 +428,14 @@ dependencies = [ [[package]] name = "arrow-arith" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de71a4e3f13a20dcf695f2fd47a4a95287d4a04e5e4e9b7ab61db5a5cfcb1c81" +checksum = "e5a50de298a7c0069ad475c66db65e731df547e85a9e1e7b6e7e0bf8f0c53725" dependencies = [ - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-schema 59.3.3", + "arrow-array 60.2.0", + "arrow-buffer 60.2.0", + "arrow-data 60.2.0", + "arrow-schema 60.2.0", "chrono", "num-traits", ] @@ -467,25 +459,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arrow-array" -version = "59.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48fd7dff6ff36252331feeb62a29b343e75f24d07f5519fd8ef0b175d06570fc" -dependencies = [ - "ahash", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-schema 59.3.3", - "chrono", - "chrono-tz", - "half", - "hashbrown 0.17.2", - "num-complex", - "num-integer", - "num-traits", -] - [[package]] name = "arrow-array" version = "60.2.0" @@ -497,6 +470,7 @@ dependencies = [ "arrow-data 60.2.0", "arrow-schema 60.2.0", "chrono", + "chrono-tz", "half", "hashbrown 0.17.2", "num-complex", @@ -516,18 +490,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arrow-buffer" -version = "59.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2efd8a063bdc2e88c67a6f5fa130346bb0ec9089754dea276380858535030c5" -dependencies = [ - "bytes", - "half", - "num-bigint 0.5.1", - "num-traits", -] - [[package]] name = "arrow-buffer" version = "60.2.0" @@ -555,7 +517,7 @@ dependencies = [ "atoi 2.0.0", "base64 0.22.1", "chrono", - "comfy-table", + "comfy-table 7.2.2", "half", "lexical-core", "num-traits", @@ -564,20 +526,20 @@ dependencies = [ [[package]] name = "arrow-cast" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d369007e1a06d2e34ef790105dc2a29aa98c41f11e5ce72dd4d8f187c2d77ea0" +checksum = "fcad6713dda348c245cd6ef36a578b4362c143c3a9dd829aa19e89f407c3e48b" dependencies = [ - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-ord 59.3.3", - "arrow-schema 59.3.3", - "arrow-select 59.3.3", - "atoi 2.0.0", + "arrow-array 60.2.0", + "arrow-buffer 60.2.0", + "arrow-data 60.2.0", + "arrow-ord 60.2.0", + "arrow-schema 60.2.0", + "arrow-select 60.2.0", + "atoi 3.1.1", "base64 0.23.1", "chrono", - "comfy-table", + "comfy-table 8.0.1", "half", "lexical-core", "num-traits", @@ -612,13 +574,13 @@ dependencies = [ [[package]] name = "arrow-csv" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "430e8bf06a50850ce9c33c87484fe059b464ab8e2cd3c7d0df0d2252df06aa74" +checksum = "2c9168dc86bba5375cb5a884f684d320148c6b556db18c0dace9f1d60ac543a1" dependencies = [ - "arrow-array 59.3.3", - "arrow-cast 59.3.3", - "arrow-schema 59.3.3", + "arrow-array 60.2.0", + "arrow-cast 60.2.0", + "arrow-schema 60.2.0", "chrono", "csv", "csv-core", @@ -638,19 +600,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arrow-data" -version = "59.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aee86955e4b574e821fd64d65bd9bf41c2c61b863750671ecb38c75fa56de5d" -dependencies = [ - "arrow-buffer 59.3.3", - "arrow-schema 59.3.3", - "half", - "num-integer", - "num-traits", -] - [[package]] name = "arrow-data" version = "60.2.0" @@ -680,22 +629,6 @@ dependencies = [ "zstd 0.13.4", ] -[[package]] -name = "arrow-ipc" -version = "59.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea79f6056557715de2b463ea7f979fe54fbfd6088ffcd144401a777ef28914f9" -dependencies = [ - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-schema 59.3.3", - "arrow-select 59.3.3", - "flatbuffers", - "lz4_flex 0.14.2", - "zstd 0.13.4", -] - [[package]] name = "arrow-ipc" version = "60.2.0" @@ -708,7 +641,8 @@ dependencies = [ "arrow-schema 60.2.0", "arrow-select 60.2.0", "flatbuffers", - "zstd 0.14.4", + "lz4_flex 0.14.2", + "zstd 0.14.5", ] [[package]] @@ -738,16 +672,16 @@ dependencies = [ [[package]] name = "arrow-json" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40baa7ed2527eee2ad6435725d37aaddd2708fcc973319155d5cd1394e9c55bd" +checksum = "19629d9e810280f0878738e2a361757b8ac53eae14336bb449e6879a68f71b9a" dependencies = [ - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-cast 59.3.3", - "arrow-ord 59.3.3", - "arrow-schema 59.3.3", - "arrow-select 59.3.3", + "arrow-array 60.2.0", + "arrow-buffer 60.2.0", + "arrow-cast 60.2.0", + "arrow-ord 60.2.0", + "arrow-schema 60.2.0", + "arrow-select 60.2.0", "chrono", "half", "indexmap 2.14.2", @@ -776,15 +710,16 @@ dependencies = [ [[package]] name = "arrow-ord" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b76eb3624bbba115639f1ad84853f94efa8ee50160f3e6a9625767b879471b46" +checksum = "a3935eb956aeb858ab67685e167e230facd7bf4b294cf003a72d85a80edac1d2" dependencies = [ - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-schema 59.3.3", - "arrow-select 59.3.3", + "arrow-array 60.2.0", + "arrow-buffer 60.2.0", + "arrow-cmp", + "arrow-data 60.2.0", + "arrow-schema 60.2.0", + "arrow-select 60.2.0", ] [[package]] @@ -802,14 +737,14 @@ dependencies = [ [[package]] name = "arrow-row" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "258667467d0ca987050ec3402144264bf342e7eea6b510c70fd0299748cb74f4" +checksum = "79af8292302d7c3a1b64469a91afd33b34e7567365030098fdf4faa8130d43c3" dependencies = [ - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-schema 59.3.3", + "arrow-array 60.2.0", + "arrow-buffer 60.2.0", + "arrow-data 60.2.0", + "arrow-schema 60.2.0", "half", ] @@ -826,20 +761,14 @@ dependencies = [ [[package]] name = "arrow-schema" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f56aa009563c7100bafca7f0c4259b9ae83a439d676a6314b3a8c96f12a92f51" +checksum = "3e7574c4175cc731e0d26a8384bc25d455c5e220250988a772c1af843592444b" dependencies = [ "serde_core", "serde_json", ] -[[package]] -name = "arrow-schema" -version = "60.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e7574c4175cc731e0d26a8384bc25d455c5e220250988a772c1af843592444b" - [[package]] name = "arrow-select" version = "58.4.2" @@ -854,20 +783,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arrow-select" -version = "59.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83df2939d169e46983b07a65bea222bcca9aa564d33e1529877ecb3395cd20e6" -dependencies = [ - "ahash", - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-schema 59.3.3", - "num-traits", -] - [[package]] name = "arrow-select" version = "60.2.0" @@ -902,15 +817,15 @@ dependencies = [ [[package]] name = "arrow-string" -version = "59.3.3" +version = "60.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2c1c51a9fb05f1b0860ed5bf39797a61c2daad3aa1dbf188ffe4f1dae29efb5" +checksum = "d9eb6c979ef0582fd29189b66fa252e717ee32b41fd03158e801ac61005aefb9" dependencies = [ - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-schema 59.3.3", - "arrow-select 59.3.3", + "arrow-array 60.2.0", + "arrow-buffer 60.2.0", + "arrow-data 60.2.0", + "arrow-schema 60.2.0", + "arrow-select 60.2.0", "memchr", "num-traits", "regex", @@ -999,9 +914,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.52" +version = "0.4.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" +checksum = "0c31224bd2c09447484a1143f2fc1d871eb405789859c8e5470a3e7f95f40a18" dependencies = [ "compression-codecs", "compression-core", @@ -1098,9 +1013,9 @@ dependencies = [ [[package]] name = "async-rs" -version = "0.8.13" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "407bdac3815af195d2d63fa50595610ea8ba4d47b7fc5a37895b05d3b571c241" +checksum = "a8db2f6b977344cace6a5f3d8e060771430b997d5fdaf42bebe1fd0479b79f55" dependencies = [ "async-compat", "async-global-executor", @@ -1217,9 +1132,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-config" -version = "1.13.3" +version = "1.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3a314ce5fe1e5bdfbc6495e5e1f9ad066d34e567b26c41864eef40c22bfe16" +checksum = "dc9f8505240e2371ce912cb5b0c5f99754f32ba7187b77c6c6ba74b56f97f4fa" dependencies = [ "aws-credential-types", "aws-runtime", @@ -1326,9 +1241,9 @@ dependencies = [ [[package]] name = "aws-sdk-kms" -version = "1.133.0" +version = "1.134.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4b7155f6147d4f78cb4600e142de8cf390818f3b49d12d7a815f08e9cd24577" +checksum = "5715759a5e5c323213f1889dc7f7e4347d6aca039146260d7376a05e1f1811fb" dependencies = [ "arc-swap", "aws-credential-types", @@ -1349,9 +1264,9 @@ dependencies = [ [[package]] name = "aws-sdk-s3" -version = "1.161.0" +version = "1.162.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c63e3ca6e56670513469e992759f4a51041603fde329471b29c5c1f5eaeefe" +checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4" dependencies = [ "arc-swap", "aws-credential-types", @@ -1378,7 +1293,7 @@ dependencies = [ "lru 0.18.5", "percent-encoding", "regex-lite", - "sha2 0.11.1", + "sha2 0.11.2", "tracing", "url", ] @@ -1410,9 +1325,9 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "1.122.0" +version = "1.123.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2dd812c2090bec82fd410ac3fb37e72432c8830eb1293c19d49d1ebd4c30c0e" +checksum = "079bf718682e4f41ccb38b3a7e0817bfea9f290cb3d7d9aa780c633fc984d53d" dependencies = [ "arc-swap", "aws-credential-types", @@ -1435,9 +1350,9 @@ dependencies = [ [[package]] name = "aws-sdk-ssooidc" -version = "1.124.0" +version = "1.125.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fba228d6f4566858501a057dd1febc225a0f7a22b6f66f1475e2445d72d40621" +checksum = "74311f2de3e5f8559a419eb82edc4f533a3d81a94e170f78cc471f5059fbb286" dependencies = [ "arc-swap", "aws-credential-types", @@ -1458,9 +1373,9 @@ dependencies = [ [[package]] name = "aws-sdk-sts" -version = "1.128.0" +version = "1.129.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c357588cdf8c9ae96c0d9930fff757f9b678d06b8f68d8e37a1278fe034912" +checksum = "801a8310fa3cb59c4f74679421170c2a93b3e91ccb02f9e1305cc99f4dc5aaa6" dependencies = [ "arc-swap", "aws-credential-types", @@ -1502,7 +1417,7 @@ dependencies = [ "http 1.5.0", "p256", "percent-encoding", - "sha2 0.11.1", + "sha2 0.11.2", "subtle", "time", "tracing", @@ -1537,7 +1452,7 @@ dependencies = [ "md-5", "pin-project-lite", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "tracing", ] @@ -1682,9 +1597,9 @@ dependencies = [ [[package]] name = "aws-smithy-runtime-api" -version = "1.22.0" +version = "1.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b79dbb5331ccd297686df811d50ab3f39db171f5c765372a69272a0990b014" +checksum = "20b0ce5fd8f8ec576f6737cf9a3a02172fddad2b90b8874577a4647fab11425c" dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", @@ -1721,9 +1636,9 @@ dependencies = [ [[package]] name = "aws-smithy-types" -version = "1.9.4" +version = "1.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aff4bf014c512840b2bba80a20417b723cbd6a0a65c02e2d81f50b4268aedfc7" +checksum = "2085f9721fb3755821f8db7611a67ed15f4d6fdba6785b4db8ed7cd18eebee0f" dependencies = [ "base64-simd", "bytes", @@ -1886,7 +1801,7 @@ checksum = "144e573728da132683b9488acd528274c790e07fc06ff81ee29f9d8f8b1041e0" dependencies = [ "blowfish", "pbkdf2 0.13.0", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -2041,14 +1956,14 @@ dependencies = [ [[package]] name = "blake3" -version = "1.8.7" +version = "1.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd" dependencies = [ "arrayvec", "cc", "cfg-if", - "constant_time_eq 0.4.2", + "constant_time_eq", "cpufeatures 0.3.1", ] @@ -2184,46 +2099,25 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "brotli" -version = "8.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" -dependencies = [ - "alloc-no-stdlib 2.0.4", - "alloc-stdlib 0.2.4", - "brotli-decompressor 5.0.3", -] - [[package]] name = "brotli" version = "9.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" dependencies = [ - "alloc-no-stdlib 3.0.0", - "alloc-stdlib 0.3.0", - "brotli-decompressor 6.3.2", + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", ] [[package]] name = "brotli-decompressor" -version = "5.0.3" +version = "6.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +checksum = "664148598c930650998ef56df301329ffe7b4cdb02d49b2a3fca3bcaf2185bcb" dependencies = [ - "alloc-no-stdlib 2.0.4", - "alloc-stdlib 0.2.4", -] - -[[package]] -name = "brotli-decompressor" -version = "6.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e" -dependencies = [ - "alloc-no-stdlib 3.0.0", - "alloc-stdlib 0.3.0", + "alloc-no-stdlib", + "alloc-stdlib", ] [[package]] @@ -2303,9 +2197,9 @@ checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" [[package]] name = "bytestring" -version = "1.6.0" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca79160522b4aed4a69bab673bee78d3884d44240c78c96cb04b7557d532b4dc" +checksum = "07acef387a61fe24ed2ee3924f1fe89ac9f4b862dfd72b110109133158d7f9f8" dependencies = [ "bytes", ] @@ -2348,7 +2242,7 @@ dependencies = [ "maybe-owned", "rustix", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -2423,14 +2317,14 @@ dependencies = [ [[package]] name = "cbor-diag" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc245b6ecd09b23901a4fbad1ad975701fd5061ceaef6afa93a2d70605a64429" +checksum = "e24857694f32616b928c28176f66aa976df9e92aacc02f2b08139864c12ff6da" dependencies = [ "bs58", - "chrono", "data-encoding", "half", + "jiff 1.0.3", "nom 7.1.3", "num-bigint 0.4.8", "num-rational", @@ -2442,9 +2336,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.11.3" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", "jobserver", @@ -2590,9 +2484,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.9" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" dependencies = [ "clap_builder", "clap_derive", @@ -2600,9 +2494,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.7" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" dependencies = [ "anstream", "anstyle", @@ -2696,6 +2590,16 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "comfy-table" +version = "8.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96a46ad395a5e00676eddaca4a45ed78b29c08be5a878d35e4b071c625637dd" +dependencies = [ + "unicode-segmentation", + "unicode-width", +] + [[package]] name = "compact_str" version = "0.10.0" @@ -2711,18 +2615,18 @@ dependencies = [ [[package]] name = "compression-codecs" -version = "0.4.48" +version = "0.4.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e41632c2efd201c62f1432f7cbee121b97878eab579da9d85676573d1fd33b9" +checksum = "f938fc0d88fbe2c8d6f0e1ba96ba1165d89ff698e98468cd019d92cff2ecd367" dependencies = [ - "brotli 9.1.3", + "brotli", "bzip2", "compression-core", "flate2", "liblzma", "lz4", "memchr", - "zstd 0.14.4", + "zstd 0.14.5", "zstd-safe", ] @@ -2766,21 +2670,20 @@ checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" [[package]] name = "const-random" -version = "0.1.18" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +checksum = "d38d4bb3e79c716fd0330d8da84171b0135e59e01076e99f22b75a64c56e952c" dependencies = [ "const-random-macro", ] [[package]] name = "const-random-macro" -version = "0.1.16" +version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +checksum = "d66bb491e9fc48cb3fed9d57df886880a751d540d645ebc86b6d9d35b8fa8457" dependencies = [ - "getrandom 0.2.17", - "once_cell", + "getrandom 0.4.3", "tiny-keccak", ] @@ -2827,15 +2730,9 @@ dependencies = [ [[package]] name = "constant_time_eq" -version = "0.4.2" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" - -[[package]] -name = "constant_time_eq" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" dependencies = [ "rustversion", ] @@ -2965,9 +2862,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.5" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" dependencies = [ "cfg-if", ] @@ -3177,9 +3074,9 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "5.0.0" +version = "5.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -3462,7 +3359,7 @@ dependencies = [ "log", "object_store 0.13.2", "parking_lot 0.12.5", - "sqlparser", + "sqlparser 0.62.0", "tempfile", "tokio", "url", @@ -3471,47 +3368,47 @@ dependencies = [ [[package]] name = "datafusion" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aad7900307bd9ee9d367e1b3a3ac0dfc4639cce0c6d98ec233f293030509c39" +checksum = "0d7fbede7d2bf609055871b98ad99151a2cdd95ba333f5a8874ad03e8dc07779" dependencies = [ - "arrow 59.3.3", - "arrow-schema 59.3.3", + "arrow 60.2.0", + "arrow-schema 60.2.0", "async-trait", "chrono", - "datafusion-catalog 55.3.0", - "datafusion-catalog-listing 55.3.0", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-datasource-arrow 55.3.0", - "datafusion-datasource-csv 55.3.0", - "datafusion-datasource-json 55.3.0", + "datafusion-catalog 56.0.0", + "datafusion-catalog-listing 56.0.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-datasource-arrow 56.0.0", + "datafusion-datasource-csv 56.0.0", + "datafusion-datasource-json 56.0.0", "datafusion-datasource-parquet", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-functions 55.3.0", - "datafusion-functions-aggregate 55.3.0", - "datafusion-functions-nested 55.3.0", - "datafusion-functions-table 55.3.0", - "datafusion-functions-window 55.3.0", - "datafusion-optimizer 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-adapter 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-optimizer 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-session 55.3.0", - "datafusion-sql 55.3.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-functions 56.0.0", + "datafusion-functions-aggregate 56.0.0", + "datafusion-functions-nested 56.0.0", + "datafusion-functions-table 56.0.0", + "datafusion-functions-window 56.0.0", + "datafusion-optimizer 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-adapter 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-optimizer 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-session 56.0.0", + "datafusion-sql 56.0.0", "futures", "indexmap 2.14.2", "itertools 0.15.0", "log", - "object_store 0.13.2", - "parking_lot 0.12.5", - "parquet 59.3.3", - "sqlparser", + "object_store 0.14.2", + "parking_lot 0.13.0", + "parquet", + "sqlparser 0.63.0", "tempfile", "tokio", "url", @@ -3545,26 +3442,26 @@ dependencies = [ [[package]] name = "datafusion-catalog" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fe012dc63cd690f5aeeb9f21d94643e0f226cf9cdb857ae42ba3758e68da4c9" +checksum = "c90ef4d2d5bbfa99f04ab9d6d081a343679a2950878b58346ced71b9fcfb154e" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "async-trait", "dashmap", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-session 55.3.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-session 56.0.0", "futures", "itertools 0.15.0", "log", - "object_store 0.13.2", - "parking_lot 0.12.5", + "object_store 0.14.2", + "parking_lot 0.13.0", "tokio", ] @@ -3593,25 +3490,25 @@ dependencies = [ [[package]] name = "datafusion-catalog-listing" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e26d381a45ddafdfaa184942ef7214cbd72b426705703f5ec6b517a051d012d7" +checksum = "117b31aa518e2f6c1bc073ceb8df6be85c9eb458d12bf1ae8023d7090d5d09eb" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "async-trait", - "datafusion-catalog 55.3.0", - "datafusion-common 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-adapter 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", + "datafusion-catalog 56.0.0", + "datafusion-common 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-adapter 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", "futures", "itertools 0.15.0", "log", - "object_store 0.13.2", + "object_store 0.14.2", "percent-encoding", ] @@ -3633,7 +3530,7 @@ dependencies = [ "libc", "log", "object_store 0.13.2", - "sqlparser", + "sqlparser 0.62.0", "tokio", "uuid", "web-time", @@ -3641,13 +3538,13 @@ dependencies = [ [[package]] name = "datafusion-common" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27cd16251809316e73f55cef0b8b615e6862400b49c69f9bbe18dc030a5f5342" +checksum = "9662d06bbe2dd999ec91ce363ca44798b6d0e30133d257486ec13eaff1811342" dependencies = [ - "arrow 59.3.3", - "arrow-ipc 59.3.3", - "arrow-schema 59.3.3", + "arrow 60.2.0", + "arrow-ipc 60.2.0", + "arrow-schema 60.2.0", "chrono", "foldhash 0.2.0", "half", @@ -3657,10 +3554,10 @@ dependencies = [ "libc", "log", "num-traits", - "object_store 0.13.2", - "parquet 59.3.3", + "object_store 0.14.2", + "parquet", "recursive", - "sqlparser", + "sqlparser 0.63.0", "tokio", "uuid", "web-time", @@ -3679,9 +3576,9 @@ dependencies = [ [[package]] name = "datafusion-common-runtime" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cbc1e45b0574bd727146ba04ee99de2d4b4e8fab19a89895f34c347639393e9" +checksum = "246405c03e299611d487086288109ad2295477538d2ae6247484a745c8eea66f" dependencies = [ "futures", "log", @@ -3720,29 +3617,30 @@ dependencies = [ [[package]] name = "datafusion-datasource" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db0f6f4916e3b52418740452ddef7b436352705771529f857aeea7af9ed3d0f7" +checksum = "e2652b6cbc45682ce959ea23fba683ce16918e581eab43652a0826251f1b8b11" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "async-trait", "bytes", "chrono", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-adapter 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-session 55.3.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-adapter 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-session 56.0.0", "futures", "glob", "itertools 0.15.0", "log", - "object_store 0.13.2", - "parking_lot 0.12.5", + "object_store 0.14.2", + "parking_lot 0.13.0", + "pin-project-lite", "rand 0.9.5", "tokio", "url", @@ -3774,25 +3672,25 @@ dependencies = [ [[package]] name = "datafusion-datasource-arrow" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cae20cd823fc4698958e6645440b9819aff96da3086c8219f83015f073229d5e" +checksum = "ce1ddc6a9aa6e157a3bffc41b57a7837015e87e7e2b473c8f55258fbb01354fd" dependencies = [ - "arrow 59.3.3", - "arrow-ipc 59.3.3", + "arrow 60.2.0", + "arrow-ipc 60.2.0", "async-trait", "bytes", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-session 55.3.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-session 56.0.0", "futures", "itertools 0.15.0", - "object_store 0.13.2", + "object_store 0.14.2", "tokio", ] @@ -3821,23 +3719,23 @@ dependencies = [ [[package]] name = "datafusion-datasource-csv" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7370ac9ab3ccf2207e89b7b63e4106733fdcda7c86ad3085e2dbb4f31869ceb0" +checksum = "0a4dd3a75d1463dc0b9c6edabf7c64c7219d9462df879fca485b644a0db44854" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "async-trait", "bytes", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-session 55.3.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-session 56.0.0", "futures", - "object_store 0.13.2", + "object_store 0.14.2", "regex", "tokio", ] @@ -3867,56 +3765,56 @@ dependencies = [ [[package]] name = "datafusion-datasource-json" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e8b92ed9c965b5af696e412dada1344a3b925b53ada314deb97ebeab5dbd520" +checksum = "de9e6bec264ad83d0e180807397178350477264bcd4808093a99a4b6493aff4a" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "async-trait", "bytes", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-session 55.3.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-session 56.0.0", "futures", - "object_store 0.13.2", + "object_store 0.14.2", "tokio", "tokio-stream", ] [[package]] name = "datafusion-datasource-parquet" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2bda397c797affe3a0104aa237f1c0ccb9c7dba30fd62526df1e62ffa1925cc" +checksum = "8529b066d6db51c6d9c86c7ffca5b5c7a259c4d3a01faf2b2706451396d8c4b9" dependencies = [ - "arrow 59.3.3", - "arrow-schema 59.3.3", + "arrow 60.2.0", + "arrow-schema 60.2.0", "async-trait", "bytes", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-functions 55.3.0", - "datafusion-functions-aggregate-common 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-adapter 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-pruning 55.3.0", - "datafusion-session 55.3.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-functions 56.0.0", + "datafusion-functions-aggregate-common 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-adapter 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-pruning 56.0.0", + "datafusion-session 56.0.0", "futures", "itertools 0.15.0", "log", - "object_store 0.13.2", - "parking_lot 0.12.5", - "parquet 59.3.3", + "object_store 0.14.2", + "parking_lot 0.13.0", + "parquet", "tokio", ] @@ -3928,9 +3826,9 @@ checksum = "fac247d54979aecd2741a12156741f66589420147959f013eb47358088875a13" [[package]] name = "datafusion-doc" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "347363d91e6c0c14ca2affa39434ed40bc7a2b84f2d9adbbb81a68dff406b763" +checksum = "333a64bd4c46658f853aff209d9dca835a5647fdc71db2b04951a6dfef33f1b6" [[package]] name = "datafusion-execution" @@ -3956,22 +3854,22 @@ dependencies = [ [[package]] name = "datafusion-execution" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "455e88f3950cf924483d9c0a5cf58387935b1c42ecba9958a56be27773800eb5" +checksum = "43c55897e1fc70408d95bebe31557bf1f698e320a2a0b2272c3d911ef4a63b2f" dependencies = [ - "arrow 59.3.3", - "arrow-buffer 59.3.3", + "arrow 60.2.0", + "arrow-buffer 60.2.0", "async-trait", "bytes", "dashmap", - "datafusion-common 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "datafusion-common 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", "futures", "log", - "object_store 0.13.2", - "parking_lot 0.12.5", + "object_store 0.14.2", + "parking_lot 0.13.0", "pin-project-lite", "rand 0.9.5", "tempfile", @@ -3999,31 +3897,31 @@ dependencies = [ "indexmap 2.14.2", "itertools 0.14.0", "serde_json", - "sqlparser", + "sqlparser 0.62.0", ] [[package]] name = "datafusion-expr" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "430f03af205af56a8e8f076930da26d515160d55c149409476dd7ddfb0e8bf6f" +checksum = "c79c079c96532190b643d20f942be8d320417b47dfdfcbf240095eaf5511d7cf" dependencies = [ - "arrow 59.3.3", - "arrow-schema 59.3.3", + "arrow 60.2.0", + "arrow-schema 60.2.0", "async-trait", "chrono", - "datafusion-common 55.3.0", - "datafusion-doc 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-functions-aggregate-common 55.3.0", - "datafusion-functions-window-common 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "datafusion-common 56.0.0", + "datafusion-doc 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-functions-aggregate-common 56.0.0", + "datafusion-functions-window-common 56.0.0", + "datafusion-physical-expr-common 56.0.0", "indexmap 2.14.2", "itertools 0.15.0", "recursive", "serde", "serde_json", - "sqlparser", + "sqlparser 0.63.0", ] [[package]] @@ -4040,12 +3938,12 @@ dependencies = [ [[package]] name = "datafusion-expr-common" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fecb4bcfcaf33aa5eec712116855b295a99478e3f894d77f3e6f735b69dd46da" +checksum = "68c5e6d00c4a50bcbab0b98d4c5e452784c91314b2ef9ddd79ebaafae971d6a2" dependencies = [ - "arrow 59.3.3", - "datafusion-common 55.3.0", + "arrow 60.2.0", + "datafusion-common 56.0.0", "indexmap 2.14.2", "itertools 0.15.0", ] @@ -4078,28 +3976,29 @@ dependencies = [ "num-traits", "rand 0.9.5", "regex", - "sha2 0.11.1", + "sha2 0.11.2", "uuid", ] [[package]] name = "datafusion-functions" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53044b411082e2c42f536ab25ee29cea34ad4d84436d585a4052d96594e98596" +checksum = "197f383e6564b565dd1090a1370eb8d0d5e7319b814a65f5796b57953c1fb670" dependencies = [ - "arrow 59.3.3", - "arrow-buffer 59.3.3", + "arrow 60.2.0", + "arrow-buffer 60.2.0", + "arrow-select 60.2.0", "base64 0.23.1", "chrono", "chrono-tz", - "datafusion-common 55.3.0", - "datafusion-doc 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-macros 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "datafusion-common 56.0.0", + "datafusion-doc 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-macros 56.0.0", + "datafusion-physical-expr-common 56.0.0", "hex", "itertools 0.15.0", "log", @@ -4133,21 +4032,23 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1a8e62677e244400c1a7ff5498eed0895fff803ef64ce03ab045788b79428dd" +checksum = "032f0b56b1783d1b454bbb34f119b4157474948cf7e8e0f90f87287ddb27a0b9" dependencies = [ - "arrow 59.3.3", - "datafusion-common 55.3.0", - "datafusion-doc 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-functions-aggregate-common 55.3.0", - "datafusion-macros 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "arrow 60.2.0", + "arrow-select 60.2.0", + "datafusion-common 56.0.0", + "datafusion-doc 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-functions-aggregate-common 56.0.0", + "datafusion-macros 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", "half", "hashbrown 0.17.2", + "itertools 0.15.0", "log", "num-traits", ] @@ -4166,14 +4067,14 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate-common" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daac0f44f1be4f73ffd84d43d69339a174bdd1875b16a4d47867e246040f2ded" +checksum = "146de3e14504448ed6065f88c20c73aef2337a7a013c7dc2fa0ab7be1efb6689" dependencies = [ - "arrow 59.3.3", - "datafusion-common 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "arrow 60.2.0", + "datafusion-common 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-physical-expr-common 56.0.0", ] [[package]] @@ -4203,22 +4104,22 @@ dependencies = [ [[package]] name = "datafusion-functions-nested" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31793d657743cb2d2f0b0cb343b7bf1a8bcfc6f3559b5e0c2a2ba05915b9ecc6" +checksum = "4d9d0f96a05df677b91a49eb41c29605bae6e63e56889b07deab2b7aba77032e" dependencies = [ - "arrow 59.3.3", - "arrow-ord 59.3.3", - "datafusion-common 55.3.0", - "datafusion-doc 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-functions 55.3.0", - "datafusion-functions-aggregate 55.3.0", - "datafusion-functions-aggregate-common 55.3.0", - "datafusion-macros 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "arrow 60.2.0", + "arrow-ord 60.2.0", + "datafusion-common 56.0.0", + "datafusion-doc 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-functions 56.0.0", + "datafusion-functions-aggregate 56.0.0", + "datafusion-functions-aggregate-common 56.0.0", + "datafusion-macros 56.0.0", + "datafusion-physical-expr-common 56.0.0", "hashbrown 0.17.2", "itertools 0.15.0", "itoa", @@ -4244,18 +4145,18 @@ dependencies = [ [[package]] name = "datafusion-functions-table" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5655c61b8bc4b8e80807fd58b15115072aceb91f3c836e61447d3a32b1ca7b7" +checksum = "716cdd1a12466c4fbfc4f6e7c1a0de9f8c8b11c35b0dc7d4fc45b41cbff230c5" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "async-trait", - "datafusion-catalog 55.3.0", - "datafusion-common 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-plan 55.3.0", - "parking_lot 0.12.5", + "datafusion-catalog 56.0.0", + "datafusion-common 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-plan 56.0.0", + "parking_lot 0.13.0", ] [[package]] @@ -4277,18 +4178,18 @@ dependencies = [ [[package]] name = "datafusion-functions-window" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d146bbbdb9358b4c12be0b3dc677bbf0e284cdb4b1f21b9271fd368661b15538" +checksum = "fc161c31ff0150021580fbb585f7bd70e6c5735f47ae2987e713c58c666bba52" dependencies = [ - "arrow 59.3.3", - "datafusion-common 55.3.0", - "datafusion-doc 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-functions-window-common 55.3.0", - "datafusion-macros 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "arrow 60.2.0", + "datafusion-common 56.0.0", + "datafusion-doc 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-functions-window-common 56.0.0", + "datafusion-macros 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", "log", ] @@ -4304,12 +4205,12 @@ dependencies = [ [[package]] name = "datafusion-functions-window-common" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e4e184861db524826e8594b092e16a215605ebde6cdeb5cd1674906147fdc50" +checksum = "656acfd826a91cfee4f8fdc0fccb3f3dc822d32682060f0343c602317c9a0f59" dependencies = [ - "datafusion-common 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "datafusion-common 56.0.0", + "datafusion-physical-expr-common 56.0.0", ] [[package]] @@ -4325,11 +4226,11 @@ dependencies = [ [[package]] name = "datafusion-macros" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cd2ef1add0af1d4a98453a4a5cb8ad0a8ddb16d57a7d95ed3dff7bba3a95d59" +checksum = "49488428b5600406ffa8c192e4afca667b177fac75d5a220feeafa06db29a867" dependencies = [ - "datafusion-doc 55.3.0", + "datafusion-doc 56.0.0", "quote", "syn 3.0.10", ] @@ -4355,16 +4256,16 @@ dependencies = [ [[package]] name = "datafusion-optimizer" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940d8776d8a7cf998a328df583f9ed5d79d7073b23252c9cd2dd9bdaac9bdfa3" +checksum = "deb7d46d59b4b7db9ff579c69ddec71a67fec3001829297b56cb8e36a04a7092" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "chrono", - "datafusion-common 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-physical-expr 55.3.0", + "datafusion-common 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-physical-expr 56.0.0", "indexmap 2.14.2", "itertools 0.15.0", "log", @@ -4396,24 +4297,25 @@ dependencies = [ [[package]] name = "datafusion-physical-expr" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04dacf5adddd309723e03a96aaef4cad268d2ac14a8298aee0dc1e24501e90c0" +checksum = "54f7a129fb8bd5347c8a251cffd532ef2fdd383114a448dfe90063fd9d9a812c" dependencies = [ - "arrow 59.3.3", - "arrow-schema 59.3.3", - "datafusion-common 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-functions-aggregate-common 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "arrow 60.2.0", + "arrow-schema 60.2.0", + "datafusion-common 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-functions-aggregate-common 56.0.0", + "datafusion-physical-expr-common 56.0.0", "half", "hashbrown 0.17.2", "indexmap 2.14.2", "itertools 0.15.0", - "parking_lot 0.12.5", + "parking_lot 0.13.0", "petgraph 0.8.3", "recursive", + "regex", "tokio", ] @@ -4434,16 +4336,16 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-adapter" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "498e0cb7b422e51e31393cd071f8c6a9aa0ec675b1a175e7b9956e4579d32213" +checksum = "e9c25b5401217775fb19e9ef0f405c892c92bb8b4f5f7e7c2791e1c1b46f78f2" dependencies = [ - "arrow 59.3.3", - "datafusion-common 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-functions 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "arrow 60.2.0", + "datafusion-common 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-functions 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", "itertools 0.15.0", ] @@ -4466,19 +4368,20 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-common" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "932106adbdfe48009ce472d0cb8a2f1bf7c2ddaadab3f5018445b5e2c296a80a" +checksum = "5c7a0eab92a39b5874905dfa96f7d4f99522dd68cdd99826fe9b55a80f35a9a9" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", "chrono", - "datafusion-common 55.3.0", - "datafusion-expr-common 55.3.0", + "datafusion-common 56.0.0", + "datafusion-expr-common 56.0.0", "hashbrown 0.17.2", "indexmap 2.14.2", "itertools 0.15.0", - "parking_lot 0.12.5", + "parking_lot 0.13.0", "pin-project", + "regex", ] [[package]] @@ -4501,20 +4404,21 @@ dependencies = [ [[package]] name = "datafusion-physical-optimizer" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64a40a175e1cb81d6a06bfa5fba888da5631495bfd0c1703b2e07bdf73b20203" +checksum = "de0ec66fa1a41b6a72a2a354967979d9d540b8e0b54c2b4b6563c9d302babde9" dependencies = [ - "arrow 59.3.3", - "datafusion-common 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", - "datafusion-pruning 55.3.0", - "datafusion-session 55.3.0", + "arrow 60.2.0", + "datafusion-common 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-functions-window 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", + "datafusion-pruning 56.0.0", + "datafusion-session 56.0.0", "itertools 0.15.0", "recursive", ] @@ -4554,26 +4458,28 @@ dependencies = [ [[package]] name = "datafusion-physical-plan" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffb0d157ad20d2fddd961b08447c18646fe3fb710e7ab76521f6eec2e9d9ab77" +checksum = "5acf70dcab32c05c21d33dfe2e4e10bcdf71f575fa798f08fc1e2e90c6733c43" dependencies = [ - "arrow 59.3.3", - "arrow-data 59.3.3", - "arrow-ipc 59.3.3", - "arrow-ord 59.3.3", - "arrow-schema 59.3.3", + "arrow 60.2.0", + "arrow-data 60.2.0", + "arrow-ipc 60.2.0", + "arrow-ord 60.2.0", + "arrow-schema 60.2.0", + "arrow-select 60.2.0", "async-trait", "bytes", - "datafusion-common 55.3.0", - "datafusion-common-runtime 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-functions 55.3.0", - "datafusion-functions-aggregate-common 55.3.0", - "datafusion-functions-window-common 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", + "datafusion-common 56.0.0", + "datafusion-common-runtime 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-functions 56.0.0", + "datafusion-functions-aggregate-common 56.0.0", + "datafusion-functions-window-common 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", "futures", "half", "hashbrown 0.17.2", @@ -4581,7 +4487,7 @@ dependencies = [ "itertools 0.15.0", "log", "num-traits", - "parking_lot 0.12.5", + "parking_lot 0.13.0", "pin-project-lite", "serde", "serde_json", @@ -4606,17 +4512,17 @@ dependencies = [ [[package]] name = "datafusion-pruning" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e32810991d17f888788abb45b8e8b3579f8f5fb6db4afe334a0230161323663" +checksum = "25c70b0dd64f3f13bb14501d2d4dae4647e15c3335803d80726398d1bc144401" dependencies = [ - "arrow 59.3.3", - "datafusion-common 55.3.0", - "datafusion-datasource 55.3.0", - "datafusion-expr-common 55.3.0", - "datafusion-physical-expr 55.3.0", - "datafusion-physical-expr-common 55.3.0", - "datafusion-physical-plan 55.3.0", + "arrow 60.2.0", + "datafusion-common 56.0.0", + "datafusion-datasource 56.0.0", + "datafusion-expr-common 56.0.0", + "datafusion-physical-expr 56.0.0", + "datafusion-physical-expr-common 56.0.0", + "datafusion-physical-plan 56.0.0", "log", ] @@ -4636,17 +4542,18 @@ dependencies = [ [[package]] name = "datafusion-session" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1322ccf7c7edf6e265ad15167d005445a08e95cbe4b7d2b02c1fcccba3c4bc74" +checksum = "edc953285bb4d83527ec6139587b5eece35df82e4c90fcbe53941d874195ecdf" dependencies = [ - "arrow-schema 59.3.3", + "arrow-schema 60.2.0", "async-trait", - "datafusion-common 55.3.0", - "datafusion-execution 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-physical-plan 55.3.0", - "parking_lot 0.12.5", + "datafusion-common 56.0.0", + "datafusion-execution 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-physical-plan 56.0.0", + "futures", + "parking_lot 0.13.0", ] [[package]] @@ -4664,26 +4571,27 @@ dependencies = [ "indexmap 2.14.2", "log", "regex", - "sqlparser", + "sqlparser 0.62.0", ] [[package]] name = "datafusion-sql" -version = "55.3.0" +version = "56.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8db13d66e854fa2f751fc69a8cc3ccbde795ac8a0369c153f9a2cf76735c8241" +checksum = "896599d41f0764a270caf2bdb75e6e49ff43e7d213ff0848d9b908ba28585bb6" dependencies = [ - "arrow 59.3.3", + "arrow 60.2.0", + "arrow-schema 60.2.0", "bigdecimal", "chrono", - "datafusion-common 55.3.0", - "datafusion-expr 55.3.0", - "datafusion-functions-nested 55.3.0", + "datafusion-common 56.0.0", + "datafusion-expr 56.0.0", + "datafusion-functions-nested 56.0.0", "indexmap 2.14.2", "log", "recursive", "regex", - "sqlparser", + "sqlparser 0.63.0", "stacker", ] @@ -5142,7 +5050,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -5217,7 +5125,7 @@ dependencies = [ "http-body-util", "hyper", "hyper-util", - "jiff 1.0.2", + "jiff 1.0.3", "local-ip-address", "md-5", "minlz", @@ -5255,7 +5163,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "suppaftp", "tempfile", "time", @@ -5269,7 +5177,7 @@ dependencies = [ "uuid", "walkdir", "zip", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -5325,11 +5233,11 @@ version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" dependencies = [ - "curve25519-dalek 5.0.0", + "curve25519-dalek 5.1.0", "ed25519 3.0.0", "rand_core 0.10.1", "serde", - "sha2 0.11.1", + "sha2 0.11.2", "signature 3.0.0", "subtle", "zeroize", @@ -5464,7 +5372,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5513,9 +5421,9 @@ checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" [[package]] name = "faster-hex" -version = "2.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4ede54fe330383a5de28c0a1f06668ff9dbf06c8094e1c5150c39488a5e911d" +checksum = "52094542d09210d54b87d1a7a13996182c8170cd84e7baa56b332b7ca0d7a7de" dependencies = [ "defmt 0.3.101", "serde", @@ -5561,9 +5469,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" [[package]] name = "findshlibs" @@ -5676,7 +5584,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5986,7 +5894,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "thiserror 2.0.21", "time", "tokio", @@ -6149,7 +6057,7 @@ dependencies = [ "serde", "serde_json", "serde_with", - "sha2 0.11.1", + "sha2 0.11.2", "thiserror 2.0.21", "tokio", "tokio-stream", @@ -6200,9 +6108,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +checksum = "b634322c4924093fe6a6e05ecbe5717cd3c6014934455f4ae8e5cf14ba3264a8" dependencies = [ "atomic-waker", "bytes", @@ -6389,9 +6297,9 @@ dependencies = [ [[package]] name = "hickory-net" -version = "0.26.3" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d" +checksum = "ea9b43710d47761c90da994eeec7e1bee50095f2b4bcdfd42acd67ca5f814e47" dependencies = [ "async-trait", "cfg-if", @@ -6413,9 +6321,9 @@ dependencies = [ [[package]] name = "hickory-proto" -version = "0.26.3" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +checksum = "927c672dc4fd1e4b7cfcb7b751fe1d5766638080b8d243b78165ef660c2061e7" dependencies = [ "data-encoding", "idna", @@ -6433,9 +6341,9 @@ dependencies = [ [[package]] name = "hickory-resolver" -version = "0.26.3" +version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981" +checksum = "e847eb9a1b4e6bd038c2ff9400aff8ba02b450baa7f691bc56359c9af0418145" dependencies = [ "cfg-if", "futures-util", @@ -6451,7 +6359,7 @@ dependencies = [ "rand 0.10.4", "resolv-conf", "smallvec", - "system-configuration", + "system-configuration 0.8.0", "thiserror 2.0.21", "tokio", "tracing", @@ -6703,7 +6611,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "socket2", - "system-configuration", + "system-configuration 0.7.0", "tokio", "tower-service", "tracing", @@ -6962,7 +6870,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" dependencies = [ "io-lifetimes 3.0.1", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -7003,9 +6911,9 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.12.2" +version = "2.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" dependencies = [ "serde", ] @@ -7082,12 +6990,12 @@ dependencies = [ [[package]] name = "jiff" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e77cbfb9fff4798e283c2d69dff39fc2c45e7da017e5ce95b654e46ea41236" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" dependencies = [ - "jiff-core 1.0.1", - "jiff-static 1.0.2", + "jiff-core 1.0.2", + "jiff-static 1.0.3", "jiff-tzdb-platform 1.0.0", "js-sys", "log", @@ -7109,9 +7017,9 @@ dependencies = [ [[package]] name = "jiff-core" -version = "1.0.1" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" dependencies = [ "log", ] @@ -7130,11 +7038,11 @@ dependencies = [ [[package]] name = "jiff-static" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9067a0b23e5be3147d56b2dcf652b18e6b1364caca93fb157653b6fbcab23a9" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" dependencies = [ - "jiff-core 1.0.1", + "jiff-core 1.0.2", "proc-macro2", "quote", "syn 3.0.10", @@ -7587,7 +7495,7 @@ dependencies = [ "tokio", "tracing", "xxhash-rust", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -8243,7 +8151,7 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890" dependencies = [ - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -8393,9 +8301,9 @@ dependencies = [ [[package]] name = "metrique" -version = "0.1.33" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d73091a31175e903e78e876a246659bd2b2c8e2bd87b7b29bfc9ce2ad337015" +checksum = "175b7bbf3ee915da1ac245e08615e7548d285d67f2e5113a9d1910cf7b1c5599" dependencies = [ "itoa", "metrique-core", @@ -8405,15 +8313,16 @@ dependencies = [ "metrique-writer", "metrique-writer-core", "metrique-writer-macro", + "pin-project-lite", "ryu", "tokio", ] [[package]] name = "metrique-core" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef48bd0b3616269daf647473b43a5a832db438392a2956c3a928ff859f9d2dac" +checksum = "d83f06c3376a43d928f31ac8c9ed03a4fcdade2bc63b4816be86e9397e902f55" dependencies = [ "itertools 0.14.0", "metrique-writer-core", @@ -8421,9 +8330,9 @@ dependencies = [ [[package]] name = "metrique-macro" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c35873982fe77f6876b701e095058785491bb415eb6bdcfc5b0b291ead76099" +checksum = "7c2d8ad7a16792f421fd39260b6224438bfda4f3755be639c45515cc8a245ff2" dependencies = [ "darling 0.24.1", "metrique-core", @@ -8434,24 +8343,24 @@ dependencies = [ [[package]] name = "metrique-service-metrics" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f3174803bacaeaa025a7b8ff998b415892d0bd0272d4694cb22ee55f93ee027" +checksum = "2636d8406b613eb1b16486babca1c4c669d790c6854f2943370a334dd5c23a7b" dependencies = [ "metrique-writer", ] [[package]] name = "metrique-timesource" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2faca4e4480069ff02b1763b3b79f5cec7e8628e24d9dc5b6073f53d2577a4d9" +checksum = "76b97ea03148eab45cc5fefc775a1c7eb874f1d01cda4eadb50567b4c2dc1004" [[package]] name = "metrique-writer" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b3d251bde7a2ef3cb27371d41751770191041ffe56f6ac22d2fa30ca99e68b" +checksum = "d8d2d66aaa527cfe55cd2b26e81c69154e65f7e4588e0056ebdf1c6539abe8d3" dependencies = [ "ahash", "crossbeam-queue", @@ -8470,9 +8379,9 @@ dependencies = [ [[package]] name = "metrique-writer-core" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e253373268b34ae3f1b0e0348dd56fd0924f45ea49b086913e18d273ee03098" +checksum = "2d4f27821aae2142961a971442fe8335cf1ee1ed13119b26d684461a33894f4a" dependencies = [ "derive-where", "dtoa", @@ -8484,9 +8393,9 @@ dependencies = [ [[package]] name = "metrique-writer-macro" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f0c50a61ecf0e0afd1778768ccb662ae5aa759b7ff15748003a4a920d61ff51" +checksum = "0fa66219265e71e292a81edf7ae893b2605c8d85747e79653d93a303811580d0" dependencies = [ "darling 0.24.1", "metrique-core", @@ -8887,7 +8796,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -9561,9 +9470,9 @@ checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e" [[package]] name = "owo-colors" -version = "4.4.0" +version = "4.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" +checksum = "87951d615e539b79093477ecd12fd25e8870d41a7f842dfb76bbda747f971117" [[package]] name = "p12-keystore" @@ -9598,7 +9507,7 @@ dependencies = [ "elliptic-curve", "primefield", "primeorder", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -9612,7 +9521,7 @@ dependencies = [ "fiat-crypto 0.3.0", "primefield", "primeorder", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -9626,7 +9535,7 @@ dependencies = [ "elliptic-curve", "primefield", "primeorder", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -9652,7 +9561,7 @@ dependencies = [ "futures", "log", "rand 0.10.4", - "sha2 0.11.1", + "sha2 0.11.2", "thiserror 2.0.21", "tokio", "windows", @@ -9710,40 +9619,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "parquet" -version = "59.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20033034bc38d6bbb14518717e115cceed4bce3f2425232034a6f6be91877425" -dependencies = [ - "ahash", - "arrow-array 59.3.3", - "arrow-buffer 59.3.3", - "arrow-data 59.3.3", - "arrow-ipc 59.3.3", - "arrow-schema 59.3.3", - "arrow-select 59.3.3", - "base64 0.23.1", - "brotli 8.0.4", - "bytes", - "chrono", - "flate2", - "futures", - "half", - "hashbrown 0.17.2", - "lz4_flex 0.14.2", - "num-bigint 0.5.1", - "num-integer", - "num-traits", - "object_store 0.13.2", - "seq-macro", - "simdutf8", - "snap", - "tokio", - "twox-hash", - "zstd 0.13.4", -] - [[package]] name = "parquet" version = "60.2.0" @@ -9758,16 +9633,24 @@ dependencies = [ "arrow-schema 60.2.0", "arrow-select 60.2.0", "base64 0.23.1", + "brotli", "bytes", "chrono", + "flate2", + "futures", "half", "hashbrown 0.17.2", + "lz4_flex 0.14.2", "num-bigint 0.5.1", "num-integer", "num-traits", + "object_store 0.14.2", "seq-macro", + "simdutf8", + "snap", + "tokio", "twox-hash", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -10120,7 +10003,7 @@ dependencies = [ "pbkdf2 0.13.0", "rand_core 0.10.1", "scrypt 0.12.0", - "sha2 0.11.1", + "sha2 0.11.2", "spki 0.8.1", ] @@ -10238,7 +10121,7 @@ dependencies = [ "md-5", "memchr", "rand 0.10.4", - "sha2 0.11.1", + "sha2 0.11.2", "stringprep", ] @@ -10289,13 +10172,15 @@ dependencies = [ [[package]] name = "prefix-trie" -version = "0.8.4" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7" +checksum = "77fe9ec8fb906114b52bc2e9aa142ac11817d0fcd33a32fb2feb94d823ad9a4d" dependencies = [ + "array-const-fn-init", "either", "ipnet", "num-traits", + "smallvec", ] [[package]] @@ -10861,7 +10746,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -11017,9 +10902,9 @@ dependencies = [ [[package]] name = "rangemap" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" +checksum = "f2d43a8c8c74056248124068fde0df374d1ddf9039e747d190f01c36faeaab08" [[package]] name = "rapidhash" @@ -11125,9 +11010,9 @@ dependencies = [ [[package]] name = "redis" -version = "1.8.2" +version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509" +checksum = "c85db9332bbc47e826283f0a6058d747c478ed2278976279cefd22154d541b98" dependencies = [ "arc-swap", "arcstr", @@ -11223,7 +11108,7 @@ dependencies = [ "cfg-if", "libc", "rustix", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -11450,7 +11335,7 @@ dependencies = [ "pkcs1", "pkcs8 0.11.0", "rand_core 0.10.1", - "sha2 0.11.1", + "sha2 0.11.2", "signature 3.0.0", "spki 0.8.1", "zeroize", @@ -11524,7 +11409,7 @@ dependencies = [ "cipher 0.5.2", "crypto-bigint", "ctr", - "curve25519-dalek 5.0.0", + "curve25519-dalek 5.1.0", "data-encoding", "delegate", "der 0.8.3", @@ -11564,7 +11449,7 @@ dependencies = [ "scrypt 0.12.0", "sec1", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "sha3", "signature 3.0.0", "spki 0.8.1", @@ -11600,7 +11485,7 @@ dependencies = [ "bytes", "dashmap", "gloo-timers", - "jiff 1.0.2", + "jiff 1.0.3", "log", "serde", "serde_bytes", @@ -11654,7 +11539,7 @@ version = "8.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b" dependencies = [ - "sha2 0.11.1", + "sha2 0.11.2", "walkdir", ] @@ -11686,6 +11571,7 @@ dependencies = [ "aes-gcm", "anyhow", "apache-avro", + "arc-swap", "async-trait", "async_zip", "atoi 3.1.1", @@ -11703,7 +11589,7 @@ dependencies = [ "chrono", "clap", "const-str", - "datafusion 55.3.0", + "datafusion 56.0.0", "ed25519-dalek 3.0.0", "faster-hex", "flatbuffers", @@ -11725,7 +11611,7 @@ dependencies = [ "hyper", "hyper-util", "insta", - "jiff 1.0.2", + "jiff 1.0.3", "lance", "lance-arrow", "lance-core", @@ -11830,7 +11716,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "serial_test", - "sha2 0.11.1", + "sha2 0.11.2", "shadow-rs", "snap", "socket2", @@ -11858,7 +11744,7 @@ dependencies = [ "xxhash-rust", "zeroize", "zip", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -11869,7 +11755,7 @@ dependencies = [ "futures", "hashbrown 0.17.2", "hotpath", - "jiff 1.0.2", + "jiff 1.0.3", "metrics", "rustfs-config", "rustfs-s3-types", @@ -11894,7 +11780,7 @@ dependencies = [ "md-5", "pretty_assertions", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "xxhash-rust", ] @@ -11941,7 +11827,7 @@ dependencies = [ "object 0.41.0", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "symbolic-demangle", ] @@ -11954,7 +11840,7 @@ dependencies = [ "rand 0.10.4", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "time", ] @@ -11972,7 +11858,7 @@ dependencies = [ "rsa", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "test-case", "thiserror 2.0.21", "time", @@ -12009,6 +11895,32 @@ dependencies = [ "serde_json", ] +[[package]] +name = "rustfs-dst-faults" +version = "0.1.0" +dependencies = [ + "rustfs-dst-runtime", + "serde", + "serde_json", + "sha2 0.10.9", + "tracing", +] + +[[package]] +name = "rustfs-dst-runtime" +version = "0.1.0" +dependencies = [ + "async-trait", + "bytes", + "rand 0.9.5", + "rand_chacha 0.9.0", + "serde", + "sha2 0.10.9", + "thiserror 2.0.21", + "tokio", + "uuid", +] + [[package]] name = "rustfs-ecstore" version = "1.0.5" @@ -12045,7 +11957,7 @@ dependencies = [ "hyper-rustls", "hyper-util", "insta", - "jiff 1.0.2", + "jiff 1.0.3", "lazy_static", "libc", "md-5", @@ -12075,6 +11987,8 @@ dependencies = [ "rustfs-credentials", "rustfs-crypto", "rustfs-data-usage", + "rustfs-dst-faults", + "rustfs-dst-runtime", "rustfs-erasure-codec", "rustfs-filemeta", "rustfs-gateway-types", @@ -12105,7 +12019,7 @@ dependencies = [ "serde", "serde_json", "serial_test", - "sha2 0.11.1", + "sha2 0.11.2", "shadow-rs", "slab", "smallvec", @@ -12174,7 +12088,7 @@ dependencies = [ "rustfs-utils", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "tempfile", "thiserror 2.0.21", "time", @@ -12187,7 +12101,7 @@ dependencies = [ [[package]] name = "rustfs-gateway" version = "0.70.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "arc-swap", "bytes", @@ -12207,7 +12121,7 @@ dependencies = [ "rustfs-gateway-stream", "rustfs-gateway-types", "rustfs-gateway-xml", - "sha2 0.11.1", + "sha2 0.11.2", "tokio", "tower", "tracing", @@ -12234,7 +12148,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-core" version = "0.67.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "bytes", "futures-core", @@ -12255,17 +12169,17 @@ dependencies = [ [[package]] name = "rustfs-gateway-corpus" version = "0.2.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] name = "rustfs-gateway-corpus-recorder" version = "0.1.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "bytes", "http 1.5.0", @@ -12280,7 +12194,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-dialect-rustfs-admin" version = "0.15.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "bytes", "form_urlencoded", @@ -12294,7 +12208,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-http" version = "0.1.4" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "hmac 0.13.0", "http 1.5.0", @@ -12304,7 +12218,7 @@ dependencies = [ "phf 0.14.0", "rustfs-gateway-stream", "rustfs-gateway-types", - "sha2 0.11.1", + "sha2 0.11.2", "smallvec", "subtle", "zeroize", @@ -12313,7 +12227,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-macros" version = "0.1.4" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "proc-macro2", "quote", @@ -12323,14 +12237,14 @@ dependencies = [ [[package]] name = "rustfs-gateway-sig" version = "0.18.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "hmac 0.13.0", "http 1.5.0", "p256", "rustfs-gateway-http", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "smallvec", "subtle", "zeroize", @@ -12339,7 +12253,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-stream" version = "0.2.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "bitflags 2.13.2", "bytes", @@ -12350,7 +12264,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-types" version = "0.44.0+aws.2026-10-02" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "bytes", "crc-fast", @@ -12362,7 +12276,7 @@ dependencies = [ "rustfs-gateway-stream", "rustfs-gateway-xml", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "time", "twox-hash", "unicode-normalization", @@ -12372,7 +12286,7 @@ dependencies = [ [[package]] name = "rustfs-gateway-xml" version = "0.4.0" -source = "git+https://github.com/rustfs/gateway.git?rev=5ef262952e66308ef2c01dcee7c487f7497fe4fe#5ef262952e66308ef2c01dcee7c487f7497fe4fe" +source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919" dependencies = [ "quick-xml 0.41.0", ] @@ -12388,7 +12302,7 @@ dependencies = [ "futures", "hotpath", "http 1.5.0", - "jiff 1.0.2", + "jiff 1.0.3", "metrics", "rustfs-common", "rustfs-concurrency", @@ -12406,7 +12320,7 @@ dependencies = [ "serde", "serde_json", "serial_test", - "sha2 0.11.1", + "sha2 0.11.2", "temp-env", "tempfile", "thiserror 2.0.21", @@ -12465,7 +12379,7 @@ dependencies = [ "serde_with", "serial_test", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "subtle", "temp-env", "tempfile", @@ -12521,7 +12435,7 @@ dependencies = [ "pbkdf2 0.13.0", "rand 0.10.4", "rustls", - "sha2 0.11.1", + "sha2 0.11.2", "socket2", "thiserror 2.0.21", "tracing", @@ -12545,7 +12459,7 @@ dependencies = [ "rand 0.10.4", "rustfs-kafka", "rustls", - "sha2 0.11.1", + "sha2 0.11.2", "tokio", "tokio-rustls", "tracing", @@ -12599,7 +12513,7 @@ dependencies = [ "hotpath", "http 1.5.0", "insta", - "jiff 1.0.2", + "jiff 1.0.3", "md-5", "metrics", "metrics-util", @@ -12614,7 +12528,7 @@ dependencies = [ "serde", "serde_ignored", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "subtle", "temp-env", "tempfile", @@ -12687,17 +12601,17 @@ name = "rustfs-log-analyzer" version = "1.0.5" dependencies = [ "flate2", - "jiff 1.0.2", + "jiff 1.0.3", "regex", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "tar", "tempfile", "thiserror 2.0.21", "walkdir", "zip", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -12707,7 +12621,7 @@ dependencies = [ "http 1.5.0", "humantime", "hyper", - "jiff 1.0.2", + "jiff 1.0.3", "reqwest 0.13.5", "rmp-serde", "rustfs-signer", @@ -12720,18 +12634,18 @@ dependencies = [ [[package]] name = "rustfs-mimalloc" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7914232a854336c62058c24a8362c553ac8e7adba2e2395ce9097db24d1510" +checksum = "d4775cf1923dc0d597f0c87b8cf510a75ac9e0a535b7bbc4fd6421c73906c9b2" dependencies = [ "rustfs-mimalloc-sys", ] [[package]] name = "rustfs-mimalloc-sys" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8073624242781448512682f1931624ee67108b6b7873b22fb29c1a1df689ac0c" +checksum = "067cc28d28e312fb91f97f49bf2cf15fa92d7377533ff686735681c767c89030" dependencies = [ "cc", ] @@ -12768,7 +12682,7 @@ dependencies = [ "form_urlencoded", "hashbrown 0.17.2", "hotpath", - "jiff 1.0.2", + "jiff 1.0.3", "metrics", "percent-encoding", "quick-xml 0.42.0", @@ -12840,7 +12754,7 @@ dependencies = [ "futures-util", "glob", "hotpath", - "jiff 1.0.2", + "jiff 1.0.3", "libc", "log", "metrics", @@ -12887,7 +12801,7 @@ dependencies = [ "tracing-opentelemetry", "tracing-subscriber", "url", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -12898,7 +12812,7 @@ dependencies = [ "base64-simd", "futures", "ipnetwork", - "jiff 1.0.2", + "jiff 1.0.3", "jsonwebtoken 12.0.0", "moka", "pollster", @@ -12972,7 +12886,7 @@ dependencies = [ "serde", "serde_json", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "socket2", "subtle", "sync_wrapper", @@ -13072,7 +12986,7 @@ dependencies = [ "serde", "serde_json", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "temp-env", "thiserror 2.0.21", "tokio", @@ -13100,7 +13014,7 @@ dependencies = [ "rustfs-utils", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "tokio", "walkdir", ] @@ -13138,7 +13052,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "thiserror 2.0.21", "time", "tokio", @@ -13184,18 +13098,18 @@ dependencies = [ "async-compression", "async-trait", "base64-simd", - "brotli 9.1.3", + "brotli", "bytes", "chrono", "crc-fast", - "datafusion 55.3.0", + "datafusion 56.0.0", "flatbuffers", "flate2", "futures", "futures-core", "hotpath", "http 1.5.0", - "jiff 1.0.2", + "jiff 1.0.3", "lz4", "lz4_flex 0.14.2", "memchr", @@ -13226,7 +13140,7 @@ dependencies = [ "async-trait", "bytes", "csv-core", - "datafusion 55.3.0", + "datafusion 56.0.0", "derive_builder", "flate2", "futures", @@ -13251,7 +13165,7 @@ dependencies = [ "hmac 0.13.0", "hotpath", "http 1.5.0", - "jiff 1.0.2", + "jiff 1.0.3", "metrics", "opentelemetry-proto", "opentelemetry_sdk", @@ -13281,7 +13195,7 @@ dependencies = [ "serde", "serde_json", "serial_test", - "sha2 0.11.1", + "sha2 0.11.2", "temp-env", "tempfile", "thiserror 2.0.21", @@ -13298,7 +13212,7 @@ dependencies = [ name = "rustfs-scanner-metrics" version = "1.0.5" dependencies = [ - "jiff 1.0.2", + "jiff 1.0.3", "metrics", "rmp-serde", "rustfs-heal-contracts", @@ -13355,7 +13269,7 @@ dependencies = [ "rustfs-utils", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "temp-env", "tempfile", "tokio", @@ -13391,7 +13305,7 @@ dependencies = [ "hotpath", "hyper", "hyper-rustls", - "jiff 1.0.2", + "jiff 1.0.3", "lapin", "libc", "metrics", @@ -13414,7 +13328,7 @@ dependencies = [ "rustls-native-certs", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "snap", "sysinfo", "tempfile", @@ -13459,7 +13373,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "tempfile", "thiserror 2.0.21", "tokio", @@ -13528,7 +13442,7 @@ dependencies = [ "aws-lc-rs", "base64-simd", "blake2 0.11.0", - "brotli 9.1.3", + "brotli", "bytes", "convert_case 0.12.0", "crc-fast", @@ -13551,7 +13465,7 @@ dependencies = [ "rustix", "serde", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "siphasher", "snap", "temp-env", @@ -13561,7 +13475,7 @@ dependencies = [ "transform-stream", "url", "windows", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] @@ -13575,7 +13489,7 @@ dependencies = [ "rustfs-tokio-tar", "serde", "serde_json", - "sha2 0.11.1", + "sha2 0.11.2", "tar-codec", "tar-framing", "thiserror 2.0.21", @@ -13635,7 +13549,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -13666,9 +13580,9 @@ dependencies = [ [[package]] name = "rustls-connector" -version = "0.23.10" +version = "0.23.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f799ef81c26fda57609b9456ae1e6750e2ca3dafc2dc5478232c0705f1458fbf" +checksum = "304d7aa7911485ca4c16c97575bc4ca7f515da8486e17ae5c296f6d0516e5e3c" dependencies = [ "futures-io", "futures-rustls", @@ -13718,7 +13632,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -13812,7 +13726,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "smallvec", "std-next", "subtle", @@ -13876,7 +13790,7 @@ dependencies = [ "jiff 0.2.46", "nom 8.0.0", "serde", - "sha2 0.11.1", + "sha2 0.11.2", "smallvec", "std-next", "subtle", @@ -13998,7 +13912,7 @@ dependencies = [ "cfg-if", "pbkdf2 0.13.0", "salsa20 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", ] [[package]] @@ -14209,7 +14123,7 @@ dependencies = [ "indexmap 1.9.3", "indexmap 2.14.2", "jiff 0.2.46", - "jiff 1.0.2", + "jiff 1.0.3", "schemars 0.9.0", "schemars 1.2.3", "serde_core", @@ -14306,9 +14220,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" dependencies = [ "cfg-if", "cpufeatures 0.3.1", @@ -14590,7 +14504,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -14648,10 +14562,20 @@ name = "sqlparser" version = "0.62.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c6d1b651dc4edf07eead2a0c6c78016ce971bc2c10da5266861b13f25e7cec" +dependencies = [ + "log", + "sqlparser_derive 0.5.0", +] + +[[package]] +name = "sqlparser" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3679862809bd1f92e563cf6fd820e28f39135303668001c10331d5027183e8b4" dependencies = [ "log", "recursive", - "sqlparser_derive", + "sqlparser_derive 0.6.0", ] [[package]] @@ -14665,6 +14589,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "sqlparser_derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2905ae8e8148d8f7f5748ea95d1e949fa4fc1d7f5161547b758ad118b2e4b0aa" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "ssh-cipher" version = "0.3.0" @@ -14718,7 +14653,7 @@ dependencies = [ "sec1", "serde", "sha1 0.11.0", - "sha2 0.11.1", + "sha2 0.11.2", "signature 3.0.0", "ssh-cipher", "ssh-encoding", @@ -14741,7 +14676,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -14842,12 +14777,12 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "suppaftp" -version = "13.0.0" +version = "13.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "919688e3d2128f0c3e77f4dff7a2035f2d73ccf488851ba96ba42002e850cad5" +checksum = "4e378a4b12a2879eb3949d64f529ca1e6039cfe9d965d0015b2f647f18843e24" dependencies = [ "async-trait", - "jiff 1.0.2", + "jiff 1.0.3", "lazy-regex", "log", "pin-project", @@ -14989,6 +14924,17 @@ dependencies = [ "system-configuration-sys", ] +[[package]] +name = "system-configuration" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "501336eb7ba9e417300a6a0fa985721065467aa83a6dcf0422a8e43e4c0328fa" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "system-configuration-sys", +] + [[package]] name = "system-configuration-sys" version = "0.6.0" @@ -15024,9 +14970,9 @@ dependencies = [ [[package]] name = "tar-codec" -version = "0.0.16" +version = "0.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6875ba507bbec6022500f46477159a03f07ebdffdb4ea043254974531df1dac2" +checksum = "4cac8b1341c7c68ea322a9c155ccdb09d32b1526be8da22c20b8cb3323814c98" dependencies = [ "archive-trait", "tar-framing", @@ -15036,9 +14982,9 @@ dependencies = [ [[package]] name = "tar-framing" -version = "0.0.16" +version = "0.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49727b1a300514960d425d0e741a7da3e693170f3db39de3180fdbbc07e542c5" +checksum = "c07c818ffdfc87f607073f986b6167218bc9e05d54ecec4d50299a949e09feb1" dependencies = [ "thiserror 2.0.21", "tokio", @@ -15046,9 +14992,9 @@ dependencies = [ [[package]] name = "tcp-stream" -version = "0.34.17" +version = "0.34.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2afa87967dbc0fa02957531aab16e5d5fe8a8aa71d8efd9d4173c1f14c59e381" +checksum = "cf0017b7b0584bc2633ed46bdd6f4743af6a1059e6d9e1c5cf9efef23ba39cc2" dependencies = [ "async-rs", "cfg-if", @@ -15079,7 +15025,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -15344,7 +15290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb" dependencies = [ "rustls", - "sha2 0.11.1", + "sha2 0.11.2", "tokio", "tokio-postgres", "tokio-rustls", @@ -15422,9 +15368,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.2.2+spec-1.1.0" +version = "1.2.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" dependencies = [ "indexmap 2.14.2", "serde_core", @@ -15446,9 +15392,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.20+spec-1.1.0" +version = "0.25.21+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" dependencies = [ "indexmap 2.14.2", "toml_datetime", @@ -15458,9 +15404,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.6+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ "winnow", ] @@ -16239,7 +16185,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -16453,6 +16399,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.60.2" @@ -16625,7 +16580,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" dependencies = [ "bitflags 2.13.2", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -16790,18 +16745,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.64" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.64" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" dependencies = [ "proc-macro2", "quote", @@ -16886,13 +16841,13 @@ dependencies = [ [[package]] name = "zip" -version = "9.8.1" +version = "9.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0" +checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9" dependencies = [ "aes 0.9.4", "bzip2", - "constant_time_eq 0.6.1", + "constant_time_eq", "crc32fast", "deflate64", "flate2", @@ -16908,17 +16863,17 @@ dependencies = [ "sha1 0.11.0", "time", "typed-path", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "zeroize", "zopfli", - "zstd 0.14.4", + "zstd 0.14.5", ] [[package]] name = "zlib-rs" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" [[package]] name = "zmij" @@ -16948,36 +16903,36 @@ dependencies = [ "arrow-schema 60.2.0", "bytes", "kafka-protocol", - "parquet 60.2.0", + "parquet", "semver", "toml", - "zstd 0.14.4", + "zstd 0.14.5", "zstd-safe", ] [[package]] name = "zstd" -version = "0.14.4" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad5020ab8f27bfc0024ad0a07aed6bf022a16208f479686fbed4fdd0c85eb0b3" +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "8.3.0" +version = "8.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a9ea9cc2576c2fcc104e9cec04f46e3ede564f4fbc206831e4ef7e859a4140d" +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" dependencies = [ "zstd-sys", ] [[package]] name = "zstd-sys" -version = "2.1.3+zstd.1.5.7" +version = "2.2.0+zstd.1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" dependencies = [ "bindgen 0.73.2", "cc", diff --git a/Cargo.toml b/Cargo.toml index d634ed903f..5da4415dc5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,12 @@ members = [ "crates/zip", # ZIP file handling and compression "crates/zstd-compat", # Fixed codec for dependencies requiring zstd 0.13 ] -exclude = ["vendor/hyper", "vendor/openidconnect"] +exclude = [ + "vendor/hyper", + "vendor/openidconnect", + "vendor/rustfs-dst-faults", + "vendor/rustfs-dst-runtime", +] resolver = "3" [workspace.package] @@ -151,25 +156,27 @@ rustfs-test-utils = { path = "crates/test-utils", version = "1.0.5" } rustfs-tls-runtime = { path = "crates/tls-runtime", version = "1.0.5" } rustfs-utils = { path = "crates/utils", version = "1.0.5" } rustfs-zip = { path = "./crates/zip", version = "1.0.5" } +rustfs-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = false } +rustfs-dst-faults = { path = "vendor/rustfs-dst-faults", default-features = false } # Pin the gateway and its protocol crates to the same revision. -rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.44.0", default-features = false } -rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.2.0", default-features = false } +rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.44.0", default-features = false } +rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.2.0", default-features = false } # The gateway framework itself, consumed for its extension traits by the ring-2 # adapter. `default-features = false` keeps the `server` feature, and with it the # server crate, out of the build. -rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.70.0", default-features = false } +rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.70.0", default-features = false } # Test-only: builds the `EffectiveHost` a host-resolution test queries with. -rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", default-features = false } -rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.67.0", default-features = false } -rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.1.0", default-features = false } -rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.15.0", default-features = false } +rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", default-features = false } +rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.67.0", default-features = false } +rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.1.0", default-features = false } +rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.15.0", default-features = false } # Async Runtime and Networking async-channel = "2.5.0" async_zip = { default-features = false, version = "0.0.19" } mysql_async = { default-features = false, version = "0.37.1" } -async-compression = { version = "0.4.52" } +async-compression = { version = "0.4.54" } async-trait = "0.1.92" async-nats = { version = "0.53.0", default-features = false } axum = "0.8.9" @@ -180,8 +187,8 @@ futures-util = "0.3.34" pollster = "1.0.3" pulsar = { default-features = false, version = "=6.9.0" } lapin = { default-features = false, version = "4.13.0" } -hyper = { version = "1.12.0" } -h2 = { version = "0.4.20" } +hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active. +h2 = { version = "0.4.21" } hyper-rustls = { default-features = false, version = "0.27.10" } hyper-util = { version = "0.1.21" } http = "1.5.0" @@ -253,7 +260,7 @@ rustls-native-certs = "0.8" rustls-pki-types = "1.16.0" x509-parser = "0.18.1" sha1 = "0.11.0" -sha2 = "0.11.1" +sha2 = "0.11.2" subtle = "2.6" zeroize = { version = "1.9.2" } proptest = "1" @@ -261,7 +268,7 @@ proptest = "1" # Time and Date chrono = { version = "0.4.45" } humantime = "2.4.0" -jiff = { version = "1.0.2" } +jiff = { version = "1.0.3" } time = { version = "0.3.55" } # Database @@ -270,27 +277,27 @@ tokio-postgres = { default-features = false, version = "0.7.18" } tokio-postgres-rustls = "0.14.0" # Utilities and Tools -anyhow = "1.0.104" +anyhow = "1.0.105" arc-swap = "1.9.5" rustfs-tokio-tar = { version = "0.7.1" } # Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures. -tar-codec = "0.0.16" -tar-framing = "0.0.16" +tar-codec = "0.0.17" +tar-framing = "0.0.17" atoi = "3.1.1" atomic_enum = "0.3.0" -aws-config = { version = "1.13.3" } +aws-config = { version = "1.13.4" } aws-credential-types = { version = "1.3.1" } -aws-sdk-kms = { default-features = false, version = "1.133.0" } -aws-sdk-s3 = { default-features = false, version = "1.161.0" } -aws-sdk-sts = { default-features = false, version = "1.128.0" } +aws-sdk-kms = { default-features = false, version = "1.134.0" } +aws-sdk-s3 = { default-features = false, version = "1.162.0" } +aws-sdk-sts = { default-features = false, version = "1.129.0" } aws-sdk-s3vectors = { default-features = false, version = "=1.49.0" } aws-smithy-async = { version = "1.3.1" } aws-smithy-http-client = { default-features = false, version = "1.5.3" } -aws-smithy-runtime-api = { version = "1.22.0" } -aws-smithy-types = { version = "1.9.4" } +aws-smithy-runtime-api = { version = "1.22.1" } +aws-smithy-types = { version = "1.9.5" } base64-simd = "0.8.0" brotli = "9.1.3" -clap = { version = "4.6.9" } +clap = { version = "4.6.10" } const-str = { version = "1.1.0" } convert_case = "0.12.0" criterion = { version = "0.8" } @@ -298,11 +305,11 @@ crossbeam-queue = "0.3.14" crossbeam-channel = "0.5.17" crossbeam-deque = "0.8.8" crossbeam-utils = "0.8.23" -datafusion = { default-features = false, version = "55.3.0" } +datafusion = { default-features = false, version = "56.0.0" } derive_builder = "0.20.2" ed25519-dalek = "3.0.0" enumset = "1.1.15" -faster-hex = "2.0.0" +faster-hex = "2.1.0" flate2 = "1.1.11" glob = "0.3.4" google-cloud-storage = "1.22.0" @@ -359,7 +366,7 @@ rustfs-erasure-codec = { version = "9.1.0" } reed-solomon-simd = "3.1.0" regex = { version = "1.13.2" } rumqttc = { package = "rumqttc-next", version = "0.34.0" } -redis = { version = "1.8.2" } +redis = { version = "1.8.3" } rustify = { version = "0.7", default-features = false } rustix = { version = "1.1.6" } rust-embed = { version = "8.14.0" } @@ -395,8 +402,8 @@ winapi-util = "0.1.11" windows = { version = "0.62.2" } windows-sys = "0.61.2" xxhash-rust = { version = "0.8.21" } -zip = "9.8.1" -zstd = "0.14.4" +zip = "9.9.0" +zstd = "0.14.5" # Observability and Metrics metrics = "0.24.6" @@ -414,7 +421,7 @@ pyroscope = { version = "2.1.5" } # FTP and SFTP libunftp = { version = "0.25.1" } unftp-core = "0.1.1" -suppaftp = { version = "13.0.0" } +suppaftp = { version = "13.1.0" } rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] } russh = { version = "0.65.4" } russh-sftp = "4.0.0" @@ -423,9 +430,9 @@ russh-sftp = "4.0.0" dav-server = "0.12.0" # Performance Analysis and Memory Profiling -rustfs-mimalloc = { version = "0.7.4" } -# Preserve Unicode focus filters until rustfs/backlog#2302 is resolved. -hotpath = { version = "0.32.1", default-features = false } +rustfs-mimalloc = { version = "0.7.5" } +# Preserve method names in existing HOTPATH_FOCUS filters and reports. +hotpath = { version = "=0.32.1", default-features = false } # Snapshot testing for output format regression detection insta = { version = "1.49" } diff --git a/crates/e2e_test/src/namespace_lock_quorum_test.rs b/crates/e2e_test/src/namespace_lock_quorum_test.rs index 67301633d5..7be1c96c93 100644 --- a/crates/e2e_test/src/namespace_lock_quorum_test.rs +++ b/crates/e2e_test/src/namespace_lock_quorum_test.rs @@ -15,6 +15,7 @@ use crate::common::{ClusterTopology, RustFSTestClusterEnvironment}; use aws_sdk_s3::Client; use aws_sdk_s3::error::SdkError; +use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart}; use bytes::Bytes; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -27,6 +28,7 @@ const KEY: &str = "thumb/79/concurrent-overwrite.jpg"; type TestResult = Result<(), Box>; async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> TestResult { + const PART_BODY: &[u8] = b"multipart publication guard regression"; let mut cluster = RustFSTestClusterEnvironment::new(4).await?; cluster.set_env("RUSTFS_STORAGE_CLASS_STANDARD", "EC:2"); cluster.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false"); @@ -48,6 +50,7 @@ async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> Tes }) .collect(); + let mut retained_uploads = Vec::new(); for alive in (1..=4).rev() { if alive < 4 { cluster.stop_node(alive)?; @@ -89,13 +92,24 @@ async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> Tes let upload_id = upload .upload_id() .expect("successful multipart initialization must return an upload ID"); - client + let abort = client .abort_multipart_upload() .bucket(BUCKET) .key(&multipart_key) .upload_id(upload_id) .send() - .await?; + .await; + if alive == 4 { + abort?; + } else { + // A native Abort needs a closure certificate from every original participant. + let err = abort.expect_err("an upload created with one node down cannot certify Abort"); + let response = err.raw_response().expect("Abort must return an S3 response"); + assert_eq!(response.status().as_u16(), 503); + assert_eq!(err.as_service_error().and_then(|error| error.meta().code()), Some("ServiceUnavailable")); + assert_eq!(response.headers().get("x-rustfs-error-cause"), Some("storage_write_quorum")); + retained_uploads.push((multipart_key, upload_id.to_owned())); + } } else { let err = multipart.expect_err("multipart initialization must reject writes without a write quorum"); assert_eq!( @@ -114,7 +128,33 @@ async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> Tes cluster.stop(); cluster.start().await?; + for (key, upload_id) in &retained_uploads { + let part = clients[0] + .upload_part() + .bucket(BUCKET) + .key(key) + .upload_id(upload_id) + .part_number(1) + .body(Bytes::from_static(PART_BODY).into()) + .send() + .await?; + let part = CompletedPart::builder() + .part_number(1) + .e_tag(part.e_tag().expect("uploaded part must have an ETag")) + .build(); + clients[0] + .complete_multipart_upload() + .bucket(BUCKET) + .key(key) + .upload_id(upload_id) + .multipart_upload(CompletedMultipartUpload::builder().parts(part).build()) + .send() + .await?; + } for client in &clients { + for (key, _) in &retained_uploads { + assert_quorum_object_body(client, BUCKET, key, PART_BODY).await?; + } for alive in [1, 3, 4] { for node in 0..alive { let key = format!("publication-put-{alive}-{node}"); diff --git a/crates/ecstore/Cargo.toml b/crates/ecstore/Cargo.toml index 329a1f40c6..c2ad4530bf 100644 --- a/crates/ecstore/Cargo.toml +++ b/crates/ecstore/Cargo.toml @@ -122,6 +122,11 @@ hotpath-cpu = [ # injection, xl.meta transition assertions) via `api::tier::test_util`. # Enable only from `[dev-dependencies]` (rustfs/backlog#1148 ilm-6). test-util = [] +# Deterministic Simulation Testing backend (`DstSimDisk` over `SimDiskIo`). +# Off by default so production builds carry zero extra dependencies or branches. +dst = ["dep:rustfs-dst-runtime", "dep:rustfs-dst-faults"] +# Exposes internal bitrot/shard framing types to `fuzz/` targets only. +fuzzing = [] # Observes real startup CAS only in the dedicated E2E binary. e2e-test-hooks = [] @@ -133,6 +138,8 @@ rustfs-filemeta.workspace = true rustfs-utils = { workspace = true, features = ["full"] } rustfs-rio.workspace = true rustfs-rio-v2 = { workspace = true, optional = true } +rustfs-dst-runtime = { workspace = true, optional = true } +rustfs-dst-faults = { workspace = true, optional = true } rustfs-storage-api.workspace = true rustfs-config = { workspace = true, features = ["notify", "audit", "server-config-model"] } rustfs-concurrency.workspace = true diff --git a/crates/ecstore/src/api/mod.rs b/crates/ecstore/src/api/mod.rs index f5ffc1871e..da12e94289 100644 --- a/crates/ecstore/src/api/mod.rs +++ b/crates/ecstore/src/api/mod.rs @@ -595,12 +595,13 @@ pub mod notification { ScannerPublicationLeaseGrant, acquire_cross_pool_fence_fleet_proof, acquire_ilm_recovery_export_fleet_proof, acquire_legacy_transition_state_reconcile_fleet_proof, acquire_mrf_lifecycle_writer_fleet_proof, configured_fleet_topology_fingerprint, cross_pool_fence_fleet_proof_matches, get_global_notification_sys, - ilm_recovery_export_fleet_proof_matches, ilm_recovery_export_local_process_epoch, - ilm_recovery_export_member_epochs_sha256, ilm_recovery_export_topology_generation, - legacy_transition_state_reconcile_fleet_proof_matches, mrf_lifecycle_reader_local_process_epoch, - mrf_lifecycle_writer_fleet_proof_current, mrf_lifecycle_writer_fleet_proof_matches, new_global_notification_sys, - scanner_peer_transport_error_message_is_retryable, start_remote_version_state_fleet_probe, - with_mrf_lifecycle_writer_fleet_proof, + has_decommission_target_fence_fleet_proof, ilm_recovery_export_fleet_proof_matches, + ilm_recovery_export_local_process_epoch, ilm_recovery_export_member_epochs_sha256, + ilm_recovery_export_topology_generation, legacy_transition_state_reconcile_fleet_proof_matches, + mrf_lifecycle_reader_local_process_epoch, mrf_lifecycle_writer_fleet_proof_current, + mrf_lifecycle_writer_fleet_proof_matches, new_global_notification_sys, replace_global_notification_sys, + replace_remote_version_state_probe_topology, scanner_peer_transport_error_message_is_retryable, + start_remote_version_state_fleet_probe, trigger_fleet_capability_probe_refresh, with_mrf_lifecycle_writer_fleet_proof, }; #[cfg(any(test, feature = "test-util"))] pub use crate::services::notification_sys::{ @@ -709,29 +710,29 @@ pub mod rpc { } pub use crate::cluster::rpc::{ AuthenticatedChannel, KMS_SIGNAL_SUBSYSTEM, LocalPeerS3Client, MAX_NETWORK_PROBE_BYTES, MAX_NETWORK_PROBE_DURATION, - NetworkPeerProbeClient, NetworkPeerProbeError, NetworkPeerProbeMeasurement, NetworkPeerTarget, PEER_RESTDRY_RUN, - PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, PeerS3Client, RpcReplayCacheAdmissionError, S3PeerSys, - SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerBucketListing, ScannerDirtyUsageAcknowledgement, - ScannerPeerActivity, ScannerPeerDirtyUsageBucket, ScannerPeerDirtyUsageSnapshot, ScannerPublicationLease, - ScannerScopedDirtyUsageAckEntry, StreamResponseAuthDomain, TONIC_RPC_PREFIX, TonicInterceptor, - build_put_file_auth_trailer, check_and_record_signed_rpc_nonce, check_and_record_signed_rpc_nonce_for_peer, - decode_heal_bucket_rpc_options, encode_heal_bucket_rpc_options, encode_stream_auth_data_frame, - encode_stream_auth_eof_frame, gen_signature_headers, gen_tonic_replay_scope_headers, gen_tonic_signature_headers, - gen_tonic_signature_interceptor, node_service_time_out_client, node_service_time_out_client_no_auth, - normalize_tonic_rpc_audience, rpc_auth_is_resource_exhausted, rpc_background_admission, set_tonic_canonical_body_digest, - sign_ns_scanner_capability, sign_ns_scanner_capability_with_checkpoint_coverage, - sign_ns_scanner_capability_with_durable_progress, sign_ns_scanner_capability_with_tier_registry_generation, - sign_ns_scanner_capability_with_usage_capabilities, sign_ns_scanner_tier_registry_preflight_capability, - sign_ns_scanner_usage_watch_capability, sign_put_file_capability, sign_tonic_rpc_response_proof, - tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers, tonic_boot_epoch_response_headers_with_msgpack_capability, - tonic_msgpack_manifest_capability_requested, tonic_rpc_auth_failure_reason, verify_ns_scanner_capability, - verify_ns_scanner_capability_with_checkpoint_coverage, verify_ns_scanner_capability_with_durable_progress, - verify_ns_scanner_capability_with_tier_registry_generation, verify_ns_scanner_capability_with_usage_capabilities, - verify_ns_scanner_tier_registry_preflight_capability, verify_ns_scanner_usage_watch_capability, - verify_put_file_auth_trailer, verify_put_file_capability, verify_rpc_signature, verify_stream_auth_data_frame, - verify_stream_auth_eof_frame, verify_tonic_boot_epoch_response, verify_tonic_canonical_body_digest, - verify_tonic_mutation_body_digest, verify_tonic_mutation_body_digest_reject_unsigned, verify_tonic_rpc_response_proof, - verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap, + NetworkPeerProbeClient, NetworkPeerProbeError, NetworkPeerProbeMeasurement, NetworkPeerTarget, PEER_REST_POOL_RELOAD_OP, + PEER_REST_POOL_RELOAD_PAYLOAD, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, POOL_RELOAD_SIGNAL_SUBSYSTEM, + PeerRestClient, PeerS3Client, RpcReplayCacheAdmissionError, S3PeerSys, SERVICE_SIGNAL_REFRESH_CONFIG, + SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerBucketListing, ScannerDirtyUsageAcknowledgement, ScannerPeerActivity, + ScannerPeerDirtyUsageBucket, ScannerPeerDirtyUsageSnapshot, ScannerPublicationLease, ScannerScopedDirtyUsageAckEntry, + StreamResponseAuthDomain, TONIC_RPC_PREFIX, TonicInterceptor, build_put_file_auth_trailer, + check_and_record_signed_rpc_nonce, check_and_record_signed_rpc_nonce_for_peer, decode_heal_bucket_rpc_options, + encode_heal_bucket_rpc_options, encode_stream_auth_data_frame, encode_stream_auth_eof_frame, gen_signature_headers, + gen_tonic_replay_scope_headers, gen_tonic_signature_headers, gen_tonic_signature_interceptor, + node_service_time_out_client, node_service_time_out_client_no_auth, normalize_tonic_rpc_audience, + rpc_auth_is_resource_exhausted, rpc_background_admission, set_tonic_canonical_body_digest, sign_ns_scanner_capability, + sign_ns_scanner_capability_with_checkpoint_coverage, sign_ns_scanner_capability_with_durable_progress, + sign_ns_scanner_capability_with_tier_registry_generation, sign_ns_scanner_capability_with_usage_capabilities, + sign_ns_scanner_tier_registry_preflight_capability, sign_ns_scanner_usage_watch_capability, sign_put_file_capability, + sign_tonic_rpc_response_proof, tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers, + tonic_boot_epoch_response_headers_with_msgpack_capability, tonic_msgpack_manifest_capability_requested, + tonic_rpc_auth_failure_reason, verify_ns_scanner_capability, verify_ns_scanner_capability_with_checkpoint_coverage, + verify_ns_scanner_capability_with_durable_progress, verify_ns_scanner_capability_with_tier_registry_generation, + verify_ns_scanner_capability_with_usage_capabilities, verify_ns_scanner_tier_registry_preflight_capability, + verify_ns_scanner_usage_watch_capability, verify_put_file_auth_trailer, verify_put_file_capability, verify_rpc_signature, + verify_stream_auth_data_frame, verify_stream_auth_eof_frame, verify_tonic_boot_epoch_response, + verify_tonic_canonical_body_digest, verify_tonic_mutation_body_digest, verify_tonic_mutation_body_digest_reject_unsigned, + verify_tonic_rpc_response_proof, verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap, verify_tonic_rpc_signature_with_bootstrap_and_peer, }; } @@ -778,10 +779,13 @@ pub mod storage { #[cfg(feature = "internode-transport")] pub use crate::store::external_rpc_disk; pub use crate::store::{ - BootstrapLocalTarget, ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk, - all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc, - init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map, - prewarm_local_disk_id_map_with_instance_ctx, + BootstrapLocalTarget, CandidateDiskFormatState, CandidateDiskProbe, CandidateDiskProbeReport, DynamicECStoreHandle, + ECStore, PoolGeometrySummary, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, TopologyDiff, + TopologyReloadMode, TopologyReloadOutcome, TopologyTransitionKind, all_local_disk, all_local_disk_path, + analyze_topology_transition, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, + find_local_disk_by_ref_for_scanner_rpc, init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, + prewarm_local_disk_id_map, prewarm_local_disk_id_map_with_instance_ctx, refresh_local_disks_for_topology_reload, + refresh_lock_clients, summarize_endpoint_pools, summarize_pool_geometry, }; pub use crate::store::{HealObjectAbsenceProof, HealObjectStorageResult}; } @@ -836,3 +840,20 @@ pub mod tier { }; } } + +#[cfg(feature = "dst")] +pub mod dst { + pub use crate::disk::dst_sim::{DstSimDisk, DstSimSetFixture, dst_object_options, make_dst_sim_set_disks}; + pub use crate::disk::format::{DistributionAlgoVersion, FormatBackend, FormatErasureV3, FormatErasureVersion, FormatV3}; + pub use crate::disk::{ + CHECK_PART_DISK_NOT_FOUND, CHECK_PART_FILE_CORRUPT, CHECK_PART_FILE_NOT_FOUND, CHECK_PART_SUCCESS, CHECK_PART_UNKNOWN, + CHECK_PART_VOLUME_NOT_FOUND, + }; + pub use crate::store::init_format::{load_format_erasure, save_format_file}; + pub use rustfs_dst_faults::crash::{CrashPoint, CrashRegistry}; + pub use rustfs_dst_runtime::{ + disk::{CrashSemantics, DiskError as SimDiskError, DiskFaultConfig, DiskIo, SimDiskIo}, + rng::{RngSource, SimRng}, + }; + pub use rustfs_heal_contracts::heal_channel::{DriveState, HealOpts, HealScanMode}; +} diff --git a/crates/ecstore/src/bucket/bandwidth/monitor.rs b/crates/ecstore/src/bucket/bandwidth/monitor.rs index 0a7d7a07fa..c907e556c7 100644 --- a/crates/ecstore/src/bucket/bandwidth/monitor.rs +++ b/crates/ecstore/src/bucket/bandwidth/monitor.rs @@ -55,10 +55,16 @@ fn consume_tokens(limiter: &Ratelimiter, n: u64) -> (u64, f64, u64) pub struct BucketThrottle { limiter: Arc>, pub node_bandwidth_per_sec: i64, + pub cluster_limit_bytes_per_sec: i64, } impl BucketThrottle { + #[allow(dead_code)] fn new(node_bandwidth_per_sec: i64) -> Result { + Self::new_with_cluster_limit(node_bandwidth_per_sec, node_bandwidth_per_sec) + } + + fn new_with_cluster_limit(node_bandwidth_per_sec: i64, cluster_limit_bytes_per_sec: i64) -> Result { let node_bandwidth_per_sec = node_bandwidth_per_sec.max(1); let amount = node_bandwidth_per_sec as u64; // ratelimit 2.0's builder takes a per-second rate; the refill period @@ -67,6 +73,7 @@ impl BucketThrottle { Ok(Self { limiter: Arc::new(Mutex::new(limiter_inner)), node_bandwidth_per_sec, + cluster_limit_bytes_per_sec, }) } @@ -359,7 +366,7 @@ impl Monitor { name: bucket.to_string(), replication_arn: arn.to_string(), }; - let throttle = match BucketThrottle::new(limit_bytes) { + let throttle = match BucketThrottle::new_with_cluster_limit(limit_bytes, limit) { Ok(t) => t, Err(e) => { warn!( @@ -381,6 +388,26 @@ impl Monitor { .insert(opts, throttle); } + /// Build a replacement monitor for an updated cluster node count while + /// preserving all configured per-bucket bandwidth limits. + pub fn with_inherited_limits(&self, num_nodes: u64) -> Arc { + let next = Self::new(num_nodes); + let configured: Vec<(BucketOptions, i64)> = self + .t_lock + .read() + .unwrap_or_else(|e| { + warn!("bucket monitor throttle rwlock read poisoned, recovering"); + e.into_inner() + }) + .iter() + .map(|(opts, throttle)| (opts.clone(), throttle.cluster_limit_bytes_per_sec)) + .collect(); + for (opts, cluster_limit) in configured { + next.set_bandwidth_limit(&opts.name, &opts.replication_arn, cluster_limit); + } + next + } + pub fn is_throttled(&self, bucket: &str, arn: &str) -> bool { let opt = BucketOptions { name: bucket.to_string(), diff --git a/crates/ecstore/src/bucket/lifecycle/bucket_lifecycle_ops.rs b/crates/ecstore/src/bucket/lifecycle/bucket_lifecycle_ops.rs index d63add15cb..7b8abf6fbf 100644 --- a/crates/ecstore/src/bucket/lifecycle/bucket_lifecycle_ops.rs +++ b/crates/ecstore/src/bucket/lifecycle/bucket_lifecycle_ops.rs @@ -1267,7 +1267,8 @@ impl ExpiryState { while state.tasks_tx.len() < n { let (tx, rx) = mpsc::channel(EXPIRY_WORKER_QUEUE_CAPACITY); - let api = Arc::downgrade(&api); + let instance_ctx = api.ctx.clone(); + let fallback_api = Arc::downgrade(&api); let rx = Arc::new(tokio::sync::Mutex::new(rx)); let stats = Arc::clone(&state.stats); let recovery_notify = Arc::clone(&state.recovery_notify); @@ -1276,8 +1277,7 @@ impl ExpiryState { state.stats.increment_workers(); tokio::spawn(async move { let mut rx = rx.lock().await; - //let mut expiry_state = runtime_sources::expiry_state_handle().read().await; - ExpiryState::worker(&mut rx, api, stats, recovery_notify).await; + ExpiryState::worker_with_instance_ctx(&mut rx, Some(instance_ctx), fallback_api, stats, recovery_notify).await; }); } @@ -1293,20 +1293,31 @@ impl ExpiryState { state.stats.record_scanner_expiry_state(); } + #[cfg(test)] async fn worker( rx: &mut Receiver>, - api: Weak, + fallback_api: Weak, stats: Arc, recovery_notify: Arc, ) { - let Some(initial_api) = api.upgrade() else { - return; - }; - let cancel_token = initial_api.ctx.background_cancel_token().unwrap_or_else(|| { - static FALLBACK: std::sync::OnceLock = std::sync::OnceLock::new(); - FALLBACK.get_or_init(tokio_util::sync::CancellationToken::new).clone() - }); - drop(initial_api); + let instance_ctx = fallback_api.upgrade().map(|s| s.ctx.clone()); + Self::worker_with_instance_ctx(rx, instance_ctx, fallback_api, stats, recovery_notify).await; + } + + async fn worker_with_instance_ctx( + rx: &mut Receiver>, + instance_ctx: Option>, + fallback_api: Weak, + stats: Arc, + recovery_notify: Arc, + ) { + let cancel_token = instance_ctx + .as_ref() + .and_then(|ctx| ctx.background_cancel_token()) + .unwrap_or_else(|| { + static FALLBACK: std::sync::OnceLock = std::sync::OnceLock::new(); + FALLBACK.get_or_init(tokio_util::sync::CancellationToken::new).clone() + }); loop { select! { @@ -1335,7 +1346,11 @@ impl ExpiryState { let v = v.expect("received None after None check"); stats.decrement_pending_tasks(); let _active_task = ExpiryActiveTask::begin(Arc::clone(&stats)); - let Some(api) = api.upgrade() else { + let Some(api) = instance_ctx + .as_ref() + .and_then(|ctx| ctx.live_store()) + .or_else(|| fallback_api.upgrade()) + else { return; }; if v.as_any().is::() { @@ -2140,7 +2155,11 @@ impl TransitionState { Self::counter_value(&self.compensation_running_tasks) } - async fn worker_with_cancel(api: Arc, cancel_token: CancellationToken) { + async fn worker_with_cancel( + instance_ctx: Arc, + fallback_api: Weak, + cancel_token: CancellationToken, + ) { let transition_state = runtime_sources::transition_state_handle(); loop { select! { @@ -2160,6 +2179,9 @@ impl TransitionState { return; } let task = task.expect("received None after None check"); + let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else { + return; + }; if task.as_any().is::() { let task = task.as_any().downcast_ref::().expect("TransitionTask downcast failed"); @@ -2311,11 +2333,12 @@ impl TransitionState { let previous_num_workers = workers.len() as i64; while workers.len() < target { - let clone_api = api.clone(); + let instance_ctx = api.ctx.clone(); + let fallback_api = Arc::downgrade(&api); let cancel = CancellationToken::new(); let worker_cancel = cancel.clone(); let handle = runtime.spawn(async move { - TransitionState::worker_with_cancel(clone_api, worker_cancel).await; + TransitionState::worker_with_cancel(instance_ctx, fallback_api, worker_cancel).await; }); workers.push(TransitionWorker { cancel, handle }); } @@ -3022,16 +3045,24 @@ fn spawn_tier_free_version_recovery_once_with_options( } Some(tokio::spawn(async move { - let cancel_token = api.ctx.background_cancel_token().unwrap_or_default(); - let acquire_api = Arc::clone(&api); + let instance_ctx = api.ctx.clone(); + let fallback_api = Arc::downgrade(&api); + drop(api); + let cancel_token = instance_ctx.background_cancel_token().unwrap_or_default(); + let acquire_ctx = Arc::clone(&instance_ctx); + let acquire_fallback = fallback_api.clone(); let acquire_lock_name = Arc::::from(leader_lock_name); run_tier_free_version_recovery_coordinator( cancel_token, retry_delay, move || { - let api = Arc::clone(&acquire_api); + let ctx = Arc::clone(&acquire_ctx); + let fallback = acquire_fallback.clone(); let lock_name = Arc::clone(&acquire_lock_name); async move { + let Some(api) = ctx.live_store().or_else(|| fallback.upgrade()) else { + return Ok(None); + }; let lock = api.new_ns_lock(RUSTFS_META_BUCKET, &lock_name).await?; match lock.get_write_lock_quiet(TIER_FREE_VERSION_RECOVERY_LOCK_TIMEOUT).await { Ok(guard) => Ok(Some(guard)), @@ -3041,15 +3072,24 @@ fn spawn_tier_free_version_recovery_once_with_options( } }, move |leader_cancel| { - let api = Arc::clone(&api); + let ctx = Arc::clone(&instance_ctx); + let fallback = fallback_api.clone(); async move { run_tier_free_version_recovery_loop( leader_cancel, - api.ctx.expiry_state(), + ctx.expiry_state(), jitter_tier_free_version_recovery_delay, move |bucket_marker, object_marker, recovery_cancel| { - let api = Arc::clone(&api); + let ctx = Arc::clone(&ctx); + let fallback = fallback.clone(); async move { + let Some(api) = ctx.live_store().or_else(|| fallback.upgrade()) else { + return Err(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "tier free-version recovery store dropped", + ) + .into()); + }; recover_configured_tier_free_versions(api, bucket_marker, object_marker, recovery_cancel).await } }, @@ -3981,7 +4021,8 @@ pub fn schedule_stale_multipart_upload_cleanup_once(api: Arc) { pub fn init_background_stale_multipart_upload_cleanup(api: Arc) { let cleanup_interval = stale_uploads_cleanup_interval(); let default_expiry = stale_uploads_expiry(); - let api = Arc::downgrade(&api); + let instance_ctx = api.ctx.clone(); + let fallback_api = Arc::downgrade(&api); tokio::spawn(async move { let mut interval = tokio::time::interval(cleanup_interval); @@ -3989,7 +4030,7 @@ pub fn init_background_stale_multipart_upload_cleanup(api: Arc) { loop { interval.tick().await; - let Some(api) = Weak::upgrade(&api) else { + let Some(api) = instance_ctx.live_store().or_else(|| Weak::upgrade(&fallback_api)) else { return; }; diff --git a/crates/ecstore/src/bucket/lifecycle/recovery_disposition_runtime.rs b/crates/ecstore/src/bucket/lifecycle/recovery_disposition_runtime.rs index e9398262eb..01014e8d77 100644 --- a/crates/ecstore/src/bucket/lifecycle/recovery_disposition_runtime.rs +++ b/crates/ecstore/src/bucket/lifecycle/recovery_disposition_runtime.rs @@ -578,6 +578,9 @@ pub(crate) async fn run_recovery_disposition_maintenance_pass( } pub(crate) async fn run_recovery_disposition_maintenance_loop(api: Arc, cancel_token: CancellationToken) { + let instance_ctx = api.ctx.clone(); + let fallback_api = Arc::downgrade(&api); + drop(api); let mut interval = tokio::time::interval(RECOVERY_DISPOSITION_MAINTENANCE_INTERVAL); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); let mut marker = None; @@ -594,6 +597,9 @@ pub(crate) async fn run_recovery_disposition_maintenance_loop(api: Arc, } else if cancel_token.is_cancelled() { return; } + let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else { + return; + }; let now_unix_nanos = match now_unix_nanos() { Ok(now) => now, Err(_) => { diff --git a/crates/ecstore/src/bucket/lifecycle/tier_delete_journal.rs b/crates/ecstore/src/bucket/lifecycle/tier_delete_journal.rs index 644511c3c4..d8b4f8a597 100644 --- a/crates/ecstore/src/bucket/lifecycle/tier_delete_journal.rs +++ b/crates/ecstore/src/bucket/lifecycle/tier_delete_journal.rs @@ -6167,14 +6167,24 @@ async fn drive_tier_delete_journal_recovery( pub async fn run_tier_delete_journal_recovery_loop(api: Arc, cancel_token: CancellationToken) { let mut marker: Option = None; let mut manifest_marker: Option = None; - let wake_context = api.ctx.clone(); + let instance_ctx = api.ctx.clone(); + let fallback_api = std::sync::Arc::downgrade(&api); + drop(api); + let wake_context = instance_ctx.clone(); let recovery_cancel_token = cancel_token.clone(); drive_tier_delete_journal_recovery( &cancel_token, async move || wake_context.wait_for_tier_delete_journal_recovery().await, async move || { + let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else { + recovery_cancel_token.cancel(); + return TierDeleteJournalRecoveryPassStats { + canceled: true, + ..Default::default() + }; + }; let stats = recover_tier_delete_journal_pass( - api.clone(), + api, &recovery_cancel_token, &mut manifest_marker, &mut marker, diff --git a/crates/ecstore/src/bucket/lifecycle/transition_transaction.rs b/crates/ecstore/src/bucket/lifecycle/transition_transaction.rs index 601b98b24a..350ea939ba 100644 --- a/crates/ecstore/src/bucket/lifecycle/transition_transaction.rs +++ b/crates/ecstore/src/bucket/lifecycle/transition_transaction.rs @@ -2118,6 +2118,9 @@ async fn recover_transition_transaction_records_with_now( } pub async fn run_transition_transaction_recovery_loop(api: Arc, cancel_token: CancellationToken) { + let instance_ctx = api.ctx.clone(); + let fallback_api = std::sync::Arc::downgrade(&api); + drop(api); let mut interval = tokio::time::interval(TRANSITION_TRANSACTION_RECOVERY_INTERVAL); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); let mut marker: Option = None; @@ -2129,8 +2132,10 @@ pub async fn run_transition_transaction_recovery_loop(api: Arc, cancel_ _ = interval.tick() => {}, } - let recovery = - recover_transition_transaction_records(api.clone(), DEFAULT_TRANSITION_TRANSACTION_RECOVERY_LIMIT, marker.clone()); + let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else { + return; + }; + let recovery = recover_transition_transaction_records(api, DEFAULT_TRANSITION_TRANSACTION_RECOVERY_LIMIT, marker.clone()); let Some(result) = await_transition_transaction_recovery(&cancel_token, TRANSITION_TRANSACTION_RECOVERY_TIMEOUT, recovery).await else { diff --git a/crates/ecstore/src/bucket/metadata_sys.rs b/crates/ecstore/src/bucket/metadata_sys.rs index 92ff02f9d4..67e6e9dbce 100644 --- a/crates/ecstore/src/bucket/metadata_sys.rs +++ b/crates/ecstore/src/bucket/metadata_sys.rs @@ -273,10 +273,11 @@ pub async fn init_bucket_metadata_sys(api: Arc, buckets: Vec) { let mut sys = BucketMetadataSys::new(api); sys.init(buckets).await; + let store_cell = sys.store_handle(); let sys = Arc::new(RwLock::new(sys)); - instance_ctx.init_bucket_metadata_sys(sys.clone()); + instance_ctx.init_bucket_metadata_sys_with_store_cell(sys.clone(), store_cell); if is_dist_erasure { start_refresh_buckets_metadata_loop(sys); @@ -2166,9 +2167,9 @@ pub(crate) fn needs_commit_metadata_snapshot( && !(opts.is_lockless_cache_write() && opts.quota_admission.is_none()); #[cfg(test)] let base_required = base_required && opts.quota_admission.is_none(); - #[cfg(any(test, feature = "test-util"))] + #[cfg(any(test, feature = "test-util", feature = "dst"))] let base_required = base_required && ctx.bucket_metadata_sys().is_some(); - #[cfg(not(any(test, feature = "test-util")))] + #[cfg(not(any(test, feature = "test-util", feature = "dst")))] let _ = ctx; base_required } @@ -2246,7 +2247,7 @@ pub(crate) async fn get_bucket_quota_limit_and_incarnation_in( ctx: &crate::runtime::instance::InstanceContext, bucket: &str, ) -> Result)>> { - #[cfg(any(test, feature = "test-util"))] + #[cfg(any(test, feature = "test-util", feature = "dst"))] if ctx.bucket_metadata_sys().is_none() { return Ok(None); } @@ -2568,7 +2569,7 @@ pub struct BucketMetadataSys { /// Physically missing names are TTL-bounded to limit memory under bogus /// name floods while avoiding repeated namespace and erasure reads. missing_buckets: moka::future::Cache, - api: Weak, + api: Arc>>, } impl BucketMetadataSys { @@ -2603,7 +2604,7 @@ impl BucketMetadataSys { .max_capacity(MISSING_BUCKET_MAX_ENTRIES) .time_to_live(MISSING_BUCKET_TTL) .build(), - api: Arc::downgrade(&api), + api: Arc::new(std::sync::RwLock::new(Arc::downgrade(&api))), } } @@ -2689,7 +2690,11 @@ impl BucketMetadataSys { } pub(crate) fn object_store_if_live(&self) -> Option> { - self.api.upgrade() + self.api.read().unwrap_or_else(|poisoned| poisoned.into_inner()).upgrade() + } + + pub(crate) fn store_handle(&self) -> Arc>> { + Arc::clone(&self.api) } /// Whether the backing `ECStore` has been dropped. @@ -2698,7 +2703,13 @@ impl BucketMetadataSys { /// `ECStore::drop` so a shared bootstrap context does not retain a /// `BucketMetadataSys` whose weak handle is dangling. pub(crate) fn is_store_stale(&self) -> bool { - self.api.upgrade().is_none() + self.object_store_if_live().is_none() + } + + /// Rebind this metadata system to a newly hot-reloaded `ECStore` generation + /// without blocking on outer async `BucketMetadataSys` read/write locks. + pub(crate) fn rebind_store(&self, api: Arc) { + *self.api.write().unwrap_or_else(|poisoned| poisoned.into_inner()) = Arc::downgrade(&api); } fn metadata_publish_lock(&self, bucket: &str) -> Arc> { diff --git a/crates/ecstore/src/bucket/quota/reservation.rs b/crates/ecstore/src/bucket/quota/reservation.rs index 34918069f1..63f03bc739 100644 --- a/crates/ecstore/src/bucket/quota/reservation.rs +++ b/crates/ecstore/src/bucket/quota/reservation.rs @@ -852,7 +852,7 @@ pub(crate) async fn begin( set_index: Some(set_index), }); } - #[cfg(any(test, feature = "test-util"))] + #[cfg(any(test, feature = "test-util", feature = "dst"))] if ctx.bucket_metadata_sys().is_none() { return Ok(QuotaContext { store: None, diff --git a/crates/ecstore/src/cluster/rpc/http_auth.rs b/crates/ecstore/src/cluster/rpc/http_auth.rs index 0d73146e9a..977742bc58 100644 --- a/crates/ecstore/src/cluster/rpc/http_auth.rs +++ b/crates/ecstore/src/cluster/rpc/http_auth.rs @@ -89,6 +89,7 @@ const RPC_RESPONSE_PROOF_DOMAIN: &[u8] = b"rustfs-rpc-response-proof-v1\0"; tokio::task_local! { static RPC_BACKGROUND_REQUEST: bool; + static RPC_OMIT_LEGACY_SIGNATURE: bool; } pub(crate) fn current_rpc_background_request() -> bool { @@ -97,6 +98,17 @@ pub(crate) fn current_rpc_background_request() -> bool { .unwrap_or_else(|_| crate::disk::has_resource_io_scope()) } +pub(crate) fn current_rpc_omit_legacy_signature() -> bool { + RPC_OMIT_LEGACY_SIGNATURE.try_with(|omit| *omit).unwrap_or(false) +} + +/// Execute `operation` while omitting the legacy unscoped v1 `x-rustfs-signature` +/// header from outbound gRPC metadata, ensuring candidate peer probes only send +/// audience-, method-, nonce-, and body-bound v2 signatures. +pub async fn with_v2_only_rpc_signing(operation: F) -> F::Output { + RPC_OMIT_LEGACY_SIGNATURE.scope(true, operation).await +} + /// Preserve the authenticated wire class while polling locally admitted work. /// This scope carries only the class, never node, disk, or memory ownership. pub async fn with_rpc_background_request(background: bool, operation: F) -> F::Output { @@ -2111,7 +2123,6 @@ pub fn gen_tonic_signature_headers( let body_nonce = (content_sha256 != UNSIGNED_PAYLOAD).then(|| Uuid::new_v4().to_string()); let nonce = body_nonce.as_deref().unwrap_or(UNSIGNED_PAYLOAD_NONCE); let background = current_rpc_background_request(); - let legacy_signature = generate_signature(&secret, TONIC_RPC_PREFIX, &Method::GET, timestamp, background); let signature_v2 = generate_signature_v2( &secret, SignatureV2Scope { @@ -2124,10 +2135,12 @@ pub fn gen_tonic_signature_headers( content_sha256, }, )?; - let mut headers = HeaderMap::new(); insert_background_admission(&mut headers, background); - headers.insert(SIGNATURE_HEADER, header_value(&legacy_signature, SIGNATURE_HEADER)?); + if !current_rpc_omit_legacy_signature() { + let legacy_signature = generate_signature(&secret, TONIC_RPC_PREFIX, &Method::GET, timestamp, background); + headers.insert(SIGNATURE_HEADER, header_value(&legacy_signature, SIGNATURE_HEADER)?); + } headers.insert(TIMESTAMP_HEADER, header_value(×tamp_header, TIMESTAMP_HEADER)?); headers.insert(RPC_AUTH_VERSION_HEADER, HeaderValue::from_static(RPC_AUTH_VERSION_V2)); headers.insert(RPC_SIGNATURE_V2_HEADER, header_value(&signature_v2, RPC_SIGNATURE_V2_HEADER)?); diff --git a/crates/ecstore/src/cluster/rpc/mod.rs b/crates/ecstore/src/cluster/rpc/mod.rs index f765693240..4ed1cb95cc 100644 --- a/crates/ecstore/src/cluster/rpc/mod.rs +++ b/crates/ecstore/src/cluster/rpc/mod.rs @@ -65,9 +65,10 @@ pub use network_probe::{ }; pub(crate) use peer_rest_client::TierConfigReloadOutcome; pub use peer_rest_client::{ - KMS_SIGNAL_SUBSYSTEM, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, SERVICE_SIGNAL_REFRESH_CONFIG, - SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerDirtyUsageAcknowledgement, ScannerPeerActivity, ScannerPeerDirtyUsageBucket, - ScannerPeerDirtyUsageSnapshot, ScannerPublicationLease, ScannerScopedDirtyUsageAckEntry, + KMS_SIGNAL_SUBSYSTEM, PEER_REST_POOL_RELOAD_OP, PEER_REST_POOL_RELOAD_PAYLOAD, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, + PEER_RESTSUB_SYS, POOL_RELOAD_SIGNAL_SUBSYSTEM, PeerRestClient, SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC, + ScannerDirtyUsageAcknowledgement, ScannerPeerActivity, ScannerPeerDirtyUsageBucket, ScannerPeerDirtyUsageSnapshot, + ScannerPublicationLease, ScannerScopedDirtyUsageAckEntry, }; pub(crate) use peer_s3_client::heal_bucket_local_on_disks; pub use peer_s3_client::{ diff --git a/crates/ecstore/src/cluster/rpc/peer_rest_client.rs b/crates/ecstore/src/cluster/rpc/peer_rest_client.rs index 6932ea845a..912a61d9f0 100644 --- a/crates/ecstore/src/cluster/rpc/peer_rest_client.rs +++ b/crates/ecstore/src/cluster/rpc/peer_rest_client.rs @@ -88,6 +88,12 @@ pub const SERVICE_SIGNAL_RELOAD_DYNAMIC: u64 = 2; /// config document, so it is not a `ServerConfig` subsystem; it only shares the /// reload signal transport. pub const KMS_SIGNAL_SUBSYSTEM: &str = "kms"; +/// Dynamic signal subsystem for zero-downtime pool topology maintenance & hot-reload coordination. +pub const POOL_RELOAD_SIGNAL_SUBSYSTEM: &str = "pool_reload"; +/// Signal variable key identifying the pool reload RPC operation (`probe`, `sync_maintenance`, `prepare`, `commit`, `abort`). +pub const PEER_REST_POOL_RELOAD_OP: &str = "pool-reload-op"; +/// Signal variable key carrying the JSON request payload for pool reload coordination. +pub const PEER_REST_POOL_RELOAD_PAYLOAD: &str = "pool-reload-payload"; const BACKGROUND_HEAL_STATUS_MAX_MESSAGE_SIZE: usize = 64 * 1024; const REPLACEMENT_RECOVERY_STATUS_MAX_MESSAGE_SIZE: usize = 64 * 1024; const PEER_DRIVE_ADMISSION_MAX_MESSAGE_SIZE: usize = 256 * 1024; @@ -181,7 +187,10 @@ fn validate_signal_service_protocol(sig: u64, sub_sys: &str, protocol_version: u // Subsystems added after a peer was built are rejected by that peer's own // subsystem allow-list, which surfaces as an explicit failed signal. if sig == SERVICE_SIGNAL_RELOAD_DYNAMIC - && matches!(sub_sys, SCANNER_SUB_SYS | HEAL_SUB_SYS | KMS_SIGNAL_SUBSYSTEM) + && matches!( + sub_sys, + SCANNER_SUB_SYS | HEAL_SUB_SYS | KMS_SIGNAL_SUBSYSTEM | POOL_RELOAD_SIGNAL_SUBSYSTEM + ) && protocol_version < rustfs_protos::DYNAMIC_CONFIG_PROTOCOL_VERSION { return Err(Error::other(format!("peer does not support dynamic {sub_sys} config convergence"))); @@ -2405,11 +2414,38 @@ impl PeerRestClient { .map(|response| response.config_fingerprint) } + /// Send an authenticated, body-bound pool topology maintenance / hot-reload + /// coordination signal (`probe`, `sync_maintenance`, `prepare`, `commit`, `abort`) + /// to this peer and return its optional JSON response payload. + pub async fn pool_reload_signal(&self, op: &str, payload_json: &str, dry_run: bool) -> Result> { + let mut extra_vars = HashMap::new(); + extra_vars.insert(PEER_REST_POOL_RELOAD_OP.to_string(), op.to_string()); + extra_vars.insert(PEER_REST_POOL_RELOAD_PAYLOAD.to_string(), payload_json.to_string()); + super::http_auth::with_v2_only_rpc_signing(self.signal_service_checked_with_vars( + SERVICE_SIGNAL_RELOAD_DYNAMIC, + POOL_RELOAD_SIGNAL_SUBSYSTEM, + dry_run, + extra_vars, + )) + .await + .map(|response| response.config_fingerprint) + } + async fn signal_service_checked(&self, sig: u64, sub_sys: &str, dry_run: bool) -> Result { + self.signal_service_checked_with_vars(sig, sub_sys, dry_run, HashMap::new()) + .await + } + + async fn signal_service_checked_with_vars( + &self, + sig: u64, + sub_sys: &str, + dry_run: bool, + mut vars: HashMap, + ) -> Result { self.finalize_result( async { let mut client = self.get_client().await?; - let mut vars = HashMap::new(); vars.insert(PEER_RESTSIGNAL.to_string(), sig.to_string()); vars.insert(PEER_RESTSUB_SYS.to_string(), sub_sys.to_string()); vars.insert(PEER_RESTDRY_RUN.to_string(), dry_run.to_string()); diff --git a/crates/ecstore/src/cluster/rpc/peer_s3_client.rs b/crates/ecstore/src/cluster/rpc/peer_s3_client.rs index 994d63412f..6afd0777bb 100644 --- a/crates/ecstore/src/cluster/rpc/peer_s3_client.rs +++ b/crates/ecstore/src/cluster/rpc/peer_s3_client.rs @@ -1086,6 +1086,12 @@ pub struct RemotePeerS3Client { cancel_token: CancellationToken, } +impl Drop for RemotePeerS3Client { + fn drop(&mut self) { + self.cancel_token.cancel(); + } +} + impl RemotePeerS3Client { fn encode_delete_bucket_options(opts: &DeleteBucketOptions) -> Result { let mut remote_opts = opts.clone(); diff --git a/crates/ecstore/src/cluster/rpc/remote_disk.rs b/crates/ecstore/src/cluster/rpc/remote_disk.rs index 686edd840d..9eebcc2686 100644 --- a/crates/ecstore/src/cluster/rpc/remote_disk.rs +++ b/crates/ecstore/src/cluster/rpc/remote_disk.rs @@ -339,7 +339,7 @@ fn attach_quota_mutation_body_digest( let topology = crate::services::notification_sys::configured_fleet_topology_fingerprint() .ok_or_else(|| Error::other("quota mutation topology is not initialized or conflicts with startup"))?; let body = canonical_body.map_err(|_| Error::other("quota request length cannot be represented"))?; - let body = rustfs_protos::canonical_quota_mutation_request_body(topology, &body) + let body = rustfs_protos::canonical_quota_mutation_request_body(&topology, &body) .map_err(|_| Error::other("quota topology envelope length cannot be represented"))?; request.metadata_mut().insert( rustfs_protos::QUOTA_MUTATION_TOPOLOGY_HEADER, @@ -1026,6 +1026,8 @@ pub struct RemoteDisk { pub scanning: Arc, /// Whether health checking is enabled health_check: bool, + /// Ensures `enable_health_check` spawns at most one active monitor per handle + health_monitor_started: AtomicBool, /// Health tracker for connection monitoring health: Arc, /// Cancellation token for monitoring tasks @@ -1049,6 +1051,12 @@ pub struct RemoteDisk { rename_admission: Option>, } +impl Drop for RemoteDisk { + fn drop(&mut self) { + self.cancel_token.cancel(); + } +} + /// Shortest gap between two failure warnings of one kind from one remote disk. const REMOTE_DISK_RPC_FAILURE_LOG_INTERVAL_MS: u64 = 5_000; const BULK_BODY_ADMISSION_REGISTRY_CAPACITY: usize = 512; @@ -1840,6 +1848,7 @@ impl RemoteDisk { endpoint: ep.clone(), scanning: Arc::new(AtomicU32::new(0)), health_check: opt.health_check && env_health_check, + health_monitor_started: AtomicBool::new(false), health: Arc::new(DiskHealthTracker::new()), cancel_token: CancellationToken::new(), recovery_monitor_active: Arc::new(AtomicBool::new(false)), @@ -2185,7 +2194,7 @@ impl RemoteDisk { /// Used to defer health checks until after startup format loading completes, /// so that remote peers have time to come online. pub fn enable_health_check(&self) { - if !self.health_check { + if !self.health_check || self.health_monitor_started.swap(true, Ordering::AcqRel) { return; } let health = Arc::clone(&self.health); @@ -14744,7 +14753,7 @@ mod tests { async fn remote_disk_builds_optional_complete_body_gate_from_configuration() { temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, Some("3"))], async { let disk = remote_disk_for_addr("http://127.0.0.1:59996").await; - let gate = disk.bulk_body_admission.expect("configured body gate"); + let gate = disk.bulk_body_admission.clone().expect("configured body gate"); assert_eq!(gate.available_permits(), 3); }) .await; diff --git a/crates/ecstore/src/config/storageclass.rs b/crates/ecstore/src/config/storageclass.rs index 3abfaa3810..a78b14f03c 100644 --- a/crates/ecstore/src/config/storageclass.rs +++ b/crates/ecstore/src/config/storageclass.rs @@ -368,6 +368,22 @@ pub fn lookup_config_for_pools(kvs: &KVS, set_drive_counts: &[usize]) -> Result< lookup_config_for_pools_with_env(kvs, set_drive_counts, StorageClassEnvOverrides::from_process()?) } +pub fn lookup_config_for_pools_with_overrides( + kvs: &KVS, + set_drive_counts: &[usize], + standard_override: Option, + rrs_override: Option, +) -> Result { + let mut overrides = StorageClassEnvOverrides::from_process()?; + if standard_override.is_some() { + overrides.standard = standard_override; + } + if rrs_override.is_some() { + overrides.rrs = rrs_override; + } + lookup_config_for_pools_with_env(kvs, set_drive_counts, overrides) +} + fn lookup_config_for_pools_with_env( kvs: &KVS, set_drive_counts: &[usize], diff --git a/crates/ecstore/src/core/pools.rs b/crates/ecstore/src/core/pools.rs index 8fd752db02..5ddb2b144c 100644 --- a/crates/ecstore/src/core/pools.rs +++ b/crates/ecstore/src/core/pools.rs @@ -1164,25 +1164,80 @@ fn capacity_target_physical_bytes(data_bytes: usize, layout: DecommissionErasure Ok(capacity_mul_div_ceil(data_bytes, layout.width(), layout.data)) } +fn directory_owned_bytes_excluding_meta_sync(root: &std::path::Path) -> usize { + let mut total = 0usize; + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + if dir == root && name.to_string_lossy() == crate::disk::RUSTFS_META_BUCKET { + continue; + } + let Ok(ft) = entry.file_type() else { + continue; + }; + if ft.is_symlink() { + continue; + } + if ft.is_dir() { + stack.push(entry.path()); + } else if ft.is_file() + && let Ok(meta) = entry.metadata() + { + total = total.saturating_add(usize::try_from(meta.len()).unwrap_or(usize::MAX)); + } + } + } + total +} + async fn decommission_owned_physical_usage(sets: &Sets, layout: DecommissionErasureLayout) -> HashMap { + let bypass_shared_mount_check = rustfs_utils::get_env_bool_with_aliases( + rustfs_config::ENV_UNSAFE_BYPASS_DISK_CHECK, + &[rustfs_config::ENV_MINIO_CI], + rustfs_config::DEFAULT_UNSAFE_BYPASS_DISK_CHECK, + ); let mut usage = HashMap::with_capacity(sets.disk_set.len()); for (set_index, set) in sets.disk_set.iter().enumerate() { - let Ok(cache) = load_data_usage_cache(set.as_ref(), DATA_USAGE_CACHE_NAME).await else { + let Ok(set_index_i32) = i32::try_from(set_index) else { continue; }; - let data_usage = cache.dui(DATA_USAGE_ROOT, &[]); - if !data_usage.is_complete_bucket_usage_snapshot() { - continue; + if let Ok(cache) = load_data_usage_cache(set.as_ref(), DATA_USAGE_CACHE_NAME).await { + let data_usage = cache.dui(DATA_USAGE_ROOT, &[]); + if data_usage.is_complete_bucket_usage_snapshot() + && let Ok(logical_bytes) = usize::try_from(data_usage.objects_total_size) + { + // The data-usage snapshot excludes unrelated files on a shared mount. + // Convert logical object bytes to the source set's physical EC footprint. + usage.insert(set_index_i32, capacity_mul_div_ceil(logical_bytes, layout.width(), layout.data)); + continue; + } + } + if bypass_shared_mount_check { + let local_roots: Vec = sets + .endpoints + .endpoints + .as_ref() + .iter() + .filter(|ep| ep.is_local && ep.set_idx == set_index_i32) + .map(|ep| std::path::PathBuf::from(ep.get_file_path())) + .collect(); + if !local_roots.is_empty() + && let Ok(max_drive_bytes) = tokio::task::spawn_blocking(move || { + local_roots + .iter() + .map(|root| directory_owned_bytes_excluding_meta_sync(root)) + .max() + .unwrap_or(0) + }) + .await + { + usage.insert(set_index_i32, max_drive_bytes.saturating_mul(layout.width())); + } } - let Ok(logical_bytes) = usize::try_from(data_usage.objects_total_size) else { - continue; - }; - let Ok(set_index) = i32::try_from(set_index) else { - continue; - }; - // The data-usage snapshot excludes unrelated files on a shared mount. - // Convert logical object bytes to the source set's physical EC footprint. - usage.insert(set_index, capacity_mul_div_ceil(logical_bytes, layout.width(), layout.data)); } usage } @@ -15171,6 +15226,31 @@ impl ECStore { Ok(()) } + pub(crate) async fn rollback_pool_meta_after_failed_reload(&self, previous: &PoolMeta) -> Result<()> { + let mut save_guard = self.pool_meta_save_gate.write().await; + let (pool_meta_guard, _current_on_disk) = self + .acquire_pool_meta_write_guard(&mut save_guard, "pool metadata rollback failed") + .await?; + let mut restored = previous.clone(); + restored.dont_save = false; + let indices: Vec = (0..restored.pools.len()).collect(); + let outcome = restored + .save_no_lock_armed( + self.pools.clone(), + &mut save_guard, + PoolMetaPersistenceFence::Owned(Arc::clone(&pool_meta_guard)), + &indices, + ) + .await?; + let mut pool_meta = self.pool_meta.write().await; + ensure_pool_meta_write_fence(&pool_meta_guard, "pool metadata rollback failed")?; + *pool_meta = outcome.committed.clone(); + ensure_pool_meta_write_fence(&pool_meta_guard, "pool metadata rollback failed")?; + drop(pool_meta); + outcome.disarm(); + Ok(()) + } + #[cfg(test)] pub(crate) async fn save_current_pool_meta_for_test(&self, indices: &[usize]) -> Result<()> { self.save_current_pool_meta(indices).await @@ -20378,9 +20458,14 @@ impl ECStore { #[cfg(test)] pause_decommission_start_for_test(self.id, DecommissionStartPausePoint::StartGate).await; + let movement_start_gate = self.ctx.movement_start_gate(); + let _instance_start_guard = budget + .acquire(DECOMMISSION_ACTIVATION_START_GATE, movement_start_gate.lock()) + .await?; let _start_guard = budget .acquire(DECOMMISSION_ACTIVATION_START_GATE, self.start_gate.lock()) .await?; + self.ensure_not_retired()?; self.ensure_decommission_rebalance_idle_after_refresh_under_start_gate(budget) .await?; // Another start may have activated these pools since the unlocked diff --git a/crates/ecstore/src/core/sets.rs b/crates/ecstore/src/core/sets.rs index fb94b0f2a8..37c0c6dcd2 100644 --- a/crates/ecstore/src/core/sets.rs +++ b/crates/ecstore/src/core/sets.rs @@ -239,16 +239,43 @@ impl Sets { pool_idx: usize, parity_count: usize, instance_ctx: Arc, + ) -> Result> { + Self::new_with_staged_resources(disks, endpoints, fm, pool_idx, parity_count, instance_ctx, None, None, None, None).await + } + + #[allow(clippy::too_many_arguments)] + pub(crate) async fn new_with_staged_resources( + disks: Vec>, + endpoints: &PoolEndpoints, + fm: &FormatV3, + pool_idx: usize, + parity_count: usize, + instance_ctx: Arc, + staged_is_dist_erasure: Option, + staged_local_set_drives: Option<&[Vec>]>, + staged_lock_registry: Option<&runtime_sources::LockRegistry>, + staged_local_node_name: Option, ) -> Result> { let set_count = fm.erasure.sets.len(); let set_drive_count = fm.erasure.sets[0].len(); let mut disk_set = Vec::with_capacity(set_count); - let pool_lockers = runtime_sources::lock_registry() - .as_ref() - .map(|registry| registry.clients_for_endpoints(endpoints.endpoints.as_ref())) - .unwrap_or_default(); + let pool_lockers = match staged_lock_registry { + Some(registry) => registry.clients_for_endpoints(endpoints.endpoints.as_ref()), + None => runtime_sources::lock_registry() + .as_ref() + .map(|registry| registry.clients_for_endpoints(endpoints.endpoints.as_ref())) + .unwrap_or_default(), + }; + let is_dist = match staged_is_dist_erasure { + Some(flag) => flag, + None => instance_ctx.is_dist_erasure().await, + }; + let resolved_node_name = match staged_local_node_name { + Some(name) => name, + None => runtime_sources::local_node_name().await, + }; for i in 0..set_count { let mut set_drive = Vec::with_capacity(set_drive_count); @@ -265,8 +292,12 @@ impl Sets { continue; }; - if disk.is_local() && instance_ctx.is_dist_erasure().await { - let Some(local_disk) = runtime_sources::local_disk_set_drive(&instance_ctx, pool_idx, i, j).await else { + if disk.is_local() && is_dist { + let local_disk_opt = match staged_local_set_drives { + Some(pool_sets) => pool_sets.get(i).and_then(|s| s.get(j)).cloned().flatten(), + None => runtime_sources::local_disk_set_drive(&instance_ctx, pool_idx, i, j).await, + }; + let Some(local_disk) = local_disk_opt else { warn!("sets new set_drive {}-{} local_disk is none", i, j); set_drive.push(None); continue; @@ -306,7 +337,7 @@ impl Sets { .unwrap_or_else(|| pool_lockers.clone()); let set_disks = SetDisks::new_with_instance_ctx( - runtime_sources::local_node_name().await, + resolved_node_name.clone(), Arc::new(RwLock::new(set_drive)), set_drive_count, parity_count, @@ -356,6 +387,14 @@ impl Sets { &self.ctx } + /// Signal the background endpoint reconnect monitor to stop immediately + /// when a store generation is retired during hot-reload or aborted staging. + pub fn stop_endpoint_monitor(&self) { + if let Some(exit_signal) = &self.exit_signal { + let _ = exit_signal.send(()); + } + } + /// Stop endpoint reconnection and wait for any in-flight pass before a test owns disk probes. #[cfg(any(test, feature = "test-util"))] pub async fn stop_endpoint_monitor_for_test(&self) { diff --git a/crates/ecstore/src/disk/disk_store.rs b/crates/ecstore/src/disk/disk_store.rs index d2048d4b69..bbb7e55141 100644 --- a/crates/ecstore/src/disk/disk_store.rs +++ b/crates/ecstore/src/disk/disk_store.rs @@ -36,8 +36,6 @@ use rustfs_io_metrics::walk_metrics::LocalWalkGuard; use rustfs_madmin::{info_commands::DiskMetrics, metrics::TimedAction}; #[cfg(not(test))] use std::sync::OnceLock; -#[cfg(test)] -use std::sync::atomic::AtomicBool; use std::{ collections::HashMap, io, @@ -45,7 +43,7 @@ use std::{ pin::Pin, sync::{ Arc, LazyLock, RwLock as StdRwLock, - atomic::{AtomicI64, AtomicU32, AtomicU64, Ordering}, + atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering}, }, task::{Context, Poll}, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, @@ -66,6 +64,8 @@ pub async fn wait_for_multipart_index_bootstrap(disk: &crate::disk::DiskStore) - Ok(()) } crate::disk::Disk::Remote(_) => Err(DiskError::MethodNotAllowed), + #[cfg(feature = "dst")] + crate::disk::Disk::Sim(_) => Ok(()), } } @@ -1629,6 +1629,8 @@ pub struct LocalDiskWrapper { physical_admission: Arc, /// Whether health checking is enabled health_check: bool, + /// Ensures `enable_health_check` spawns at most one active monitor per wrapper epoch + health_monitor_started: Arc, /// Cancellation token for monitoring tasks cancel_token: CancellationToken, /// Retirement belongs to this wrapper instance, not its monitoring policy. @@ -1785,6 +1787,7 @@ impl LocalDiskWrapper { io_admission, physical_admission: Arc::new(crate::disk::io_admission::PhysicalDiskBinding::default()), health_check: health_check && env_health_check, + health_monitor_started: Arc::new(AtomicBool::new(false)), cancel_token: CancellationToken::new(), retired: CancellationToken::new(), disk_id: Arc::new(RwLock::new(None)), @@ -1967,7 +1970,7 @@ impl LocalDiskWrapper { /// Enable health monitoring after disk creation. /// Used to defer health checks until after startup format loading completes. pub fn enable_health_check(&self) { - if !self.health_check { + if !self.health_check || self.health_monitor_started.swap(true, Ordering::AcqRel) { return; } let health = Arc::clone(&self.health); diff --git a/crates/ecstore/src/disk/dst_sim.rs b/crates/ecstore/src/disk/dst_sim.rs new file mode 100644 index 0000000000..f0c2bbec56 --- /dev/null +++ b/crates/ecstore/src/disk/dst_sim.rs @@ -0,0 +1,2164 @@ +// Copyright 2026 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Production `DiskAPI` adapter over [`rustfs_dst_runtime::disk::SimDiskIo`]. +//! +//! Enables real `SetDisks` / `ECStore` erasure coding, SIMD Reed-Solomon, +//! HighwayHash256S bitrot framing, `xl.meta` `FileMeta`,recoverable deletes, +//! and production `HealOperations::heal_object` to execute deterministically +//! over in-memory crash-consistent drives with offline/EIO/`ENOSPC`, silent +//! bitrot, and ALICE `CrashSemantics::DirtySubsetAndSectorTear` power-loss +//! crashes. + +#![cfg(feature = "dst")] + +use std::collections::HashSet; +use std::fmt::Debug; +use std::io::{Cursor, Error as IoError, ErrorKind}; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::{ + Arc, RwLock, + atomic::{AtomicU32, Ordering}, +}; +use std::task::{Context, Poll}; + +use bytes::Bytes; +use rustfs_dst_faults::crash::{CrashPoint, CrashRegistry}; +use rustfs_dst_runtime::{ + disk::{CrashSemantics, DiskError as SimErr, DiskFaultConfig, DiskIo, SimDiskIo}, + rng::{RngSource, SimRng}, +}; +use rustfs_filemeta::{ + FileInfo, FileInfoOpts, FileMeta, MetaCacheEntry, MetacacheWriter, ObjectPartInfo, RawFileInfo, ValidationMode, get_file_info, +}; +use rustfs_madmin::info_commands::DiskMetrics; +use rustfs_utils::{ + HashAlgorithm, + path::{SLASH_SEPARATOR, path_join_buf}, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use time::OffsetDateTime; +use tokio::io::AsyncWrite; +use uuid::Uuid; + +use crate::bucket::utils::is_meta_bucketname; +use crate::disk::{ + BoundedDeleteRecoveryDiscovery, BoundedDeleteRecoveryInspection, BoundedDeleteRecoverySettlement, + BoundedDeleteRecoverySettlementReply, CHECK_PART_FILE_CORRUPT, CHECK_PART_FILE_NOT_FOUND, CHECK_PART_SUCCESS, + CHECK_PART_UNKNOWN, CheckPartsResp, ConditionalFileUpdate, DELETE_RECOVERY_PROTOCOL_VERSION, DataDirDeleteStatus, + DeleteOptions, DeleteRecoveryAction, DeleteRecoveryCursor, DeleteRecoveryDigest, DeleteRecoveryInspection, + DeleteRecoveryJournal, DeleteRecoveryPage, DeleteRecoverySettlementOutcome, DeleteRecoveryState, + DeleteRecoveryVersionIdentity, DeleteTransactionId, Disk, DiskAPI, DiskInfo, DiskInfoOptions, DiskLocation, DiskStore, + FORMAT_CONFIG_FILE, FileInfoVersions, FileReader, FileWriter, GuardedFileInfoVersions, OldCurrentSize, RUSTFS_META_BUCKET, + RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, + STORAGE_FORMAT_FILE, STORAGE_FORMAT_FILE_BACKUP, ScanGuard, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, + conv_part_err_to_int, + endpoint::Endpoint, + error::{DiskError, Error, Result}, + format::FormatV3, + validate_delete_recovery_options, validate_format_control_path, +}; +use crate::erasure::coding::{self, bitrot_verify}; +use crate::runtime::instance::InstanceContext; +use crate::set_disk::SetDisks; +use crate::store::init_format::save_format_file; + +const DST_DELETE_TX_DIR: &str = ".rustfs.sys/dst-del-tx"; +const DEFAULT_SIM_CAPACITY_BYTES: u64 = 10 * 1024 * 1024 * 1024; + +fn sim_to_io_err(err: SimErr) -> IoError { + match err { + SimErr::NotFound(m) => IoError::new(ErrorKind::NotFound, m), + SimErr::Offline => IoError::new(ErrorKind::NotConnected, "sim disk offline"), + SimErr::NoSpace => IoError::new(ErrorKind::StorageFull, "sim disk full (ENOSPC)"), + SimErr::InvalidPath(m) => IoError::new(ErrorKind::InvalidInput, m), + SimErr::AlreadyExists(m) => IoError::new(ErrorKind::AlreadyExists, m), + SimErr::Io(m) => IoError::other(m), + } +} + +fn map_sim_err(err: SimErr) -> Error { + match err { + SimErr::NotFound(_) => DiskError::FileNotFound, + SimErr::Offline => DiskError::DiskNotFound, + SimErr::NoSpace => DiskError::DiskFull, + SimErr::InvalidPath(_) => DiskError::InvalidPath, + SimErr::AlreadyExists(msg) => DiskError::Io(IoError::new(ErrorKind::AlreadyExists, msg)), + SimErr::Io(msg) => DiskError::Io(IoError::other(msg)), + } +} + +fn map_volume_sim_err(err: SimErr) -> Error { + match err { + SimErr::NotFound(_) => DiskError::VolumeNotFound, + other => map_sim_err(other), + } +} + +fn clean_rel(s: &str) -> &str { + s.trim_matches('/') +} + +fn join_vol_path(volume: &str, path: &str) -> Result { + let v = clean_rel(volume); + if v.is_empty() || v.split('/').any(|seg| seg == "..") { + return Err(DiskError::InvalidPath); + } + let p = clean_rel(path); + if p.split('/').any(|seg| seg == "..") { + return Err(DiskError::InvalidPath); + } + if p.is_empty() { + Ok(v.to_string()) + } else { + Ok(format!("{v}/{p}")) + } +} + +/// Async buffered writer staging bytes into `SimDiskIo`'s volatile page cache. +/// +/// Matches real OS `open(O_CREAT|O_WRONLY)` + `write()` semantics: file bytes +/// remain dirty (`dirty_data = true`) until an explicit `fsync_file` barrier. +type SyncSimWriteFut = Pin> + Send>>; + +struct SimBufferedWriter { + sim: SimDiskIo, + rel_path: String, + buf: Vec, + dirty: bool, + pending_write: std::sync::Mutex>, +} + +impl SimBufferedWriter { + fn new(sim: SimDiskIo, rel_path: String, initial: Vec) -> Self { + Self { + sim, + rel_path, + buf: initial, + dirty: false, + pending_write: std::sync::Mutex::new(None), + } + } + + fn poll_commit(&mut self, cx: &mut Context<'_>) -> Poll> { + let mut guard = self.pending_write.lock().unwrap_or_else(|p| p.into_inner()); + if guard.is_none() && self.dirty { + let sim = self.sim.clone(); + let path = self.rel_path.clone(); + let data = Bytes::from(self.buf.clone()); + *guard = Some(Box::pin(async move { sim.write_file(&path, data).await })); + } + if let Some(fut) = guard.as_mut() { + match fut.as_mut().poll(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(res) => { + *guard = None; + res.map_err(sim_to_io_err)?; + self.dirty = false; + } + } + } + Poll::Ready(Ok(())) + } +} + +impl AsyncWrite for SimBufferedWriter { + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, src: &[u8]) -> Poll> { + if self.sim.is_offline() { + return Poll::Ready(Err(IoError::new(ErrorKind::NotConnected, "sim disk offline"))); + } + let has_pending = self.pending_write.lock().unwrap_or_else(|p| p.into_inner()).is_some(); + if has_pending { + match self.poll_commit(cx) { + Poll::Pending => return Poll::Pending, + Poll::Ready(Err(e)) => return Poll::Ready(Err(e)), + Poll::Ready(Ok(())) => {} + } + } + self.buf.extend_from_slice(src); + self.dirty = true; + Poll::Ready(Ok(src.len())) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_commit(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_commit(cx) + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct SimDeleteTxRecord { + state: DeleteRecoveryState, + journal: DeleteRecoveryJournal, + backup_xl: Option>, +} + +/// Deterministic simulated disk implementing production [`DiskAPI`] directly +/// on top of [`SimDiskIo`]. +#[derive(Clone)] +pub struct DstSimDisk { + node_id: String, + pool_idx: usize, + set_idx: usize, + disk_idx: usize, + endpoint: Endpoint, + virtual_root: PathBuf, + disk_id: Arc>>, + sim: SimDiskIo, + crash_registry: CrashRegistry, + scanning: Arc, + delete_tx_lock: Arc>, + cas_lock: Arc>, + configured_capacity: Arc>>, +} + +impl Debug for DstSimDisk { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DstSimDisk") + .field("node_id", &self.node_id) + .field("pool_idx", &self.pool_idx) + .field("set_idx", &self.set_idx) + .field("disk_idx", &self.disk_idx) + .field("virtual_root", &self.virtual_root) + .field("online", &!self.sim.is_offline()) + .finish() + } +} + +impl DstSimDisk { + pub fn new(node_id: impl Into, pool_idx: usize, set_idx: usize, disk_idx: usize, seed: u64) -> Self { + let node = node_id.into(); + let derived_seed = seed + ^ ((pool_idx as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)) + ^ ((set_idx as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9)) + ^ ((disk_idx as u64).wrapping_mul(0x94D0_49BB_1331_11EB)); + Self::with_crash_registry(node, pool_idx, set_idx, disk_idx, SimRng::from_seed(derived_seed), CrashRegistry::new()) + } + + pub fn with_crash_registry( + node_id: impl Into, + pool_idx: usize, + set_idx: usize, + disk_idx: usize, + rng: SimRng, + crash_registry: CrashRegistry, + ) -> Self { + let node = node_id.into(); + let virtual_path = format!("/dst-sim/{node}/pool{pool_idx}-set{set_idx}-disk{disk_idx}"); + let mut endpoint = Endpoint::try_from(virtual_path.as_str()).expect("valid dst-sim virtual path endpoint"); + endpoint.set_pool_index(pool_idx); + endpoint.set_set_index(set_idx); + endpoint.set_disk_index(disk_idx); + let sim_id = format!("{node}:d{disk_idx}"); + Self { + node_id: node, + pool_idx, + set_idx, + disk_idx, + endpoint, + virtual_root: PathBuf::from(virtual_path), + disk_id: Arc::new(RwLock::new(None)), + sim: SimDiskIo::new(sim_id, rng), + crash_registry, + scanning: Arc::new(AtomicU32::new(0)), + delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())), + cas_lock: Arc::new(tokio::sync::Mutex::new(())), + configured_capacity: Arc::new(RwLock::new(None)), + } + } + + pub fn sim(&self) -> &SimDiskIo { + &self.sim + } + + pub fn crash_registry(&self) -> &CrashRegistry { + &self.crash_registry + } + + pub fn node_id(&self) -> &str { + &self.node_id + } + + pub fn disk_index(&self) -> usize { + self.disk_idx + } + + pub fn set_online(&self, online: bool) { + self.sim.set_offline(!online); + } + + pub fn set_offline(&self, offline: bool) { + self.sim.set_offline(offline); + } + + pub fn set_capacity_bytes(&self, capacity_bytes: Option) { + if let Ok(mut guard) = self.configured_capacity.write() { + *guard = capacity_bytes; + } + self.sim.set_capacity_bytes(capacity_bytes); + } + + pub fn set_faults(&self, faults: DiskFaultConfig) { + if let Ok(mut guard) = self.configured_capacity.write() { + *guard = faults.capacity_bytes; + } + self.sim.set_faults(faults); + } + + pub fn set_crash_semantics(&self, semantics: CrashSemantics) { + self.sim.set_crash_semantics(semantics); + } + + pub fn crash_and_reboot(&self) { + self.sim.crash_and_reboot(); + } + + pub fn crash_and_reboot_alice(&self) { + self.sim.crash_and_reboot_alice(); + } + + pub fn inject_bitrot(&self, rel_path: &str) -> bool { + self.sim.inject_bitrot(rel_path) + } + + pub fn inject_tail_truncate(&self, rel_path: &str, trim_bytes: usize) -> bool { + self.sim.inject_tail_truncate(rel_path, trim_bytes) + } + + fn ensure_online(&self) -> Result<()> { + if self.sim.is_offline() { + Err(DiskError::DiskNotFound) + } else { + Ok(()) + } + } + + fn check_crash_point(&self, point: CrashPoint, volume: &str, key: &str) -> Result<()> { + let trimmed_key = clean_rel(key); + let full_key = format!("{}/{trimmed_key}", clean_rel(volume)); + let fired = self + .crash_registry + .take_if_armed_on_drive(point, trimmed_key, &self.node_id, self.disk_idx) + || self + .crash_registry + .take_if_armed_on_drive(point, &full_key, &self.node_id, self.disk_idx); + if fired { + self.sim.crash_and_reboot(); + return Err(DiskError::FaultyDisk); + } + Ok(()) + } + + /// Persist directory entries from root `""` down through every component of `dir_path` + /// so newly created intermediate directories survive `SimDiskIo::crash_and_reboot` + /// (including ALICE `DirtySubsetAndSectorTear`). + async fn fsync_parent_chain(&self, dir_path: &str) -> Result<()> { + self.sim.fsync_dir("").await.map_err(map_sim_err)?; + let cleaned = clean_rel(dir_path); + if cleaned.is_empty() { + return Ok(()); + } + let mut cur = String::new(); + for seg in cleaned.split('/').filter(|s| !s.is_empty()) { + if !cur.is_empty() { + cur.push('/'); + } + cur.push_str(seg); + self.sim.fsync_dir(&cur).await.map_err(map_sim_err)?; + } + Ok(()) + } + + async fn ensure_volume_exists(&self, volume: &str) -> Result<()> { + let vol = clean_rel(volume); + if vol.is_empty() { + return Err(DiskError::InvalidPath); + } + if is_meta_bucketname(vol) { + self.sim.create_dir_all(vol).await.map_err(map_sim_err)?; + return Ok(()); + } + match self.sim.stat(vol).await { + Ok(st) if st.is_dir => Ok(()), + Ok(_) => Err(DiskError::VolumeNotFound), + Err(e) => Err(map_volume_sim_err(e)), + } + } + + async fn write_durable_file(&self, rel_path: &str, data: Bytes) -> Result<()> { + let parent = rel_path.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !parent.is_empty() { + self.sim.create_dir_all(parent).await.map_err(map_sim_err)?; + } + let tmp_name = format!(".dst-tmp-{}", Uuid::new_v4()); + let tmp_path = if parent.is_empty() { + tmp_name + } else { + format!("{parent}/{tmp_name}") + }; + self.sim.write_file(&tmp_path, data).await.map_err(map_sim_err)?; + self.sim.fsync_file(&tmp_path).await.map_err(map_sim_err)?; + self.sim.rename(&tmp_path, rel_path).await.map_err(map_sim_err)?; + self.fsync_parent_chain(parent).await?; + Ok(()) + } + + fn load_filemeta_preserving_inline(raw: &[u8]) -> Result { + let (mut fm, inline_buf) = FileMeta::load_with_borrowed_inline_data(raw)?; + if !inline_buf.is_empty() { + fm.data.update(inline_buf); + } + Ok(fm) + } + + fn delete_tx_path(volume: &str, tx: Uuid) -> Result { + let vol = clean_rel(volume); + if vol.is_empty() || vol.split('/').any(|seg| seg == "..") { + return Err(DiskError::InvalidPath); + } + Ok(format!("{DST_DELETE_TX_DIR}/{vol}/{tx}.json")) + } + + async fn read_live_versions_and_digest( + &self, + volume: &str, + object: &str, + ) -> Result<(Option, Option, Vec)> { + let xl_path = join_vol_path(volume, &format!("{}/{STORAGE_FORMAT_FILE}", clean_rel(object)))?; + match self.sim.read_file(&xl_path).await { + Ok(bytes) => { + let digest: DeleteRecoveryDigest = Sha256::digest(&bytes).into(); + let fm = Self::load_filemeta_preserving_inline(&bytes)?; + let versions = fm.get_file_info_versions(volume, object, true)?; + let mut out = Vec::with_capacity(versions.versions.len()); + for fi in versions.versions { + out.push(DeleteRecoveryVersionIdentity::from_file_info(fi)?); + } + Ok((Some(bytes), Some(digest), out)) + } + Err(SimErr::NotFound(_)) => Ok((None, None, Vec::new())), + Err(e) => Err(map_sim_err(e)), + } + } + + fn compute_delete_inspection_fingerprint( + tx: Uuid, + object: &str, + state: DeleteRecoveryState, + journal: &Option, + current_digest: Option, + current_versions: &[DeleteRecoveryVersionIdentity], + backup_digest: Option, + ) -> DeleteRecoveryDigest { + // Hash deterministic fields directly (avoiding `FileInfo::metadata` `HashMap` + // `RandomState` iteration order nondeterminism across JSON deserializations!). + let journal_sig = journal.as_ref().map(|j| { + ( + j.protocol_version, + &j.volume, + &j.object, + j.transaction, + j.bucket_incarnation, + j.original_digest, + j.target_digest, + &j.data_dirs, + &j.deleted_versions, + &j.predecessors, + ) + }); + let encoded = + serde_json::to_vec(&(tx, object, state, journal_sig, current_digest, current_versions.len(), backup_digest)) + .unwrap_or_default(); + Sha256::digest(encoded).into() + } + + async fn load_delete_tx_record(&self, volume: &str, tx: Uuid) -> Result> { + let tx_path = Self::delete_tx_path(volume, tx)?; + match self.sim.read_file(&tx_path).await { + Ok(bytes) => { + let rec: SimDeleteTxRecord = serde_json::from_slice(&bytes).map_err(|_| DiskError::FileCorrupt)?; + Ok(Some(rec)) + } + Err(SimErr::NotFound(_)) => Ok(None), + Err(e) => Err(map_sim_err(e)), + } + } + + async fn save_delete_tx_record(&self, volume: &str, tx: Uuid, rec: &SimDeleteTxRecord) -> Result<()> { + let tx_path = Self::delete_tx_path(volume, tx)?; + let encoded = serde_json::to_vec(rec).map_err(Error::other)?; + self.write_durable_file(&tx_path, Bytes::from(encoded)).await + } + + async fn remove_delete_tx_record(&self, volume: &str, tx: Uuid) -> Result<()> { + let tx_path = Self::delete_tx_path(volume, tx)?; + match self.sim.remove_file(&tx_path).await { + Ok(()) | Err(SimErr::NotFound(_)) => {} + Err(e) => return Err(map_sim_err(e)), + } + let parent = tx_path.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !parent.is_empty() { + let _ = self.sim.fsync_dir(parent).await; + } + Ok(()) + } + + async fn inspect_delete_tx_inner(&self, volume: &str, object: &str, transaction: Uuid) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let record = self.load_delete_tx_record(volume, transaction).await?; + let (_, current_digest, current_versions) = self.read_live_versions_and_digest(volume, object).await?; + let (state, journal, backup_digest) = match record { + Some(rec) if rec.journal.object == object => { + let bkp_digest = rec.backup_xl.as_ref().map(|b| Sha256::digest(b).into()); + (rec.state, Some(rec.journal), bkp_digest) + } + _ => (DeleteRecoveryState::Absent, None, None), + }; + let fingerprint = Self::compute_delete_inspection_fingerprint( + transaction, + object, + state, + &journal, + current_digest, + ¤t_versions, + backup_digest, + ); + Ok(DeleteRecoveryInspection { + protocol_version: DELETE_RECOVERY_PROTOCOL_VERSION, + id: DeleteTransactionId { + object: object.to_string(), + transaction, + }, + state, + journal, + current_digest, + current_versions, + backup_digest, + rollback_data_complete: true, + commit_data_safe: true, + explicit_delete_safe: true, + fingerprint, + }) + } + + async fn apply_delete_requests_to_live( + &self, + volume: &str, + object: &str, + requests: &[FileInfo], + force_del_marker: bool, + ) -> Result<(Option>, Option, Vec, Vec)> { + let obj_dir = join_vol_path(volume, object)?; + let xl_path = format!("{obj_dir}/{STORAGE_FORMAT_FILE}"); + let (old_raw_bytes, _, original_versions) = self.read_live_versions_and_digest(volume, object).await?; + let old_vec = old_raw_bytes.as_ref().map(|b| b.to_vec()); + + let mut fm = match &old_raw_bytes { + Some(raw) => Self::load_filemeta_preserving_inline(raw)?, + None => FileMeta::new(), + }; + let before_dirs: HashSet = fm + .get_data_dirs() + .unwrap_or_default() + .into_iter() + .flatten() + .filter(|id| !id.is_nil()) + .collect(); + + let had_live = old_raw_bytes.is_some(); + for fi in requests { + let is_del_marker = (fi.deleted && fi.mark_deleted) || (force_del_marker && fi.deleted); + if is_del_marker { + fm.add_version(fi.clone())?; + } else if had_live { + let _ = fm.delete_version(fi)?; + } + } + + let after_dirs: HashSet = fm + .get_data_dirs() + .unwrap_or_default() + .into_iter() + .flatten() + .filter(|id| !id.is_nil()) + .collect(); + let removed_data_dirs: Vec = before_dirs.difference(&after_dirs).copied().collect(); + + let target_bytes = if fm.versions.is_empty() { + match self.sim.remove_file(&xl_path).await { + Ok(()) => { + let _ = self.fsync_parent_chain(&obj_dir).await; + } + Err(SimErr::NotFound(_)) => {} + Err(e) => return Err(map_sim_err(e)), + } + None + } else { + let marshaled = Bytes::from(fm.marshal_msg()?); + self.write_durable_file(&xl_path, marshaled.clone()).await?; + Some(marshaled) + }; + + Ok((old_vec, target_bytes, removed_data_dirs, original_versions)) + } + + async fn cleanup_empty_ancestors(&self, volume: &str, object: &str) { + let vol = clean_rel(volume); + let mut cur = match join_vol_path(volume, object) { + Ok(p) => p, + Err(_) => return, + }; + while cur != vol && cur.starts_with(vol) { + let is_empty = self.sim.list_dir(&cur).await.is_ok_and(|entries| entries.is_empty()); + if !is_empty { + break; + } + if self.sim.remove_dir_all(&cur).await.is_err() { + break; + } + let parent = cur.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !parent.is_empty() { + let _ = self.sim.fsync_dir(parent).await; + } + cur = parent.to_string(); + } + } + + async fn scan_walk_recursive( + &self, + bucket: &str, + rel_dir: &str, + opts: &WalkDirOptions, + out: &mut MetacacheWriter<&mut W>, + objs_returned: &mut i32, + ) -> Result { + let full_dir = join_vol_path(bucket, rel_dir)?; + let entries = match self.sim.list_dir(&full_dir).await { + Ok(e) => e, + Err(SimErr::NotFound(_)) => { + if rel_dir == clean_rel(&opts.base_dir) && opts.report_notfound { + return Err(DiskError::FileNotFound); + } + return Ok(false); + } + Err(e) => return Err(map_sim_err(e)), + }; + + // Check if `rel_dir` itself is an object containing `xl.meta` + if !rel_dir.is_empty() && entries.iter().any(|e| e == STORAGE_FORMAT_FILE) { + let xl_path = format!("{full_dir}/{STORAGE_FORMAT_FILE}"); + if let Ok(bytes) = self.sim.read_file(&xl_path).await { + let mut skip_deleted = false; + if !opts.incl_deleted + && let Ok(fi) = get_file_info( + &bytes, + bucket, + rel_dir, + "", + FileInfoOpts { + data: false, + include_free_versions: false, + include_part_checksums: false, + }, + ) + && fi.deleted + { + skip_deleted = true; + } + let forward_ok = opts.forward_to.as_deref().is_none_or(|fwd| rel_dir >= clean_rel(fwd)); + let leaf_ok = opts + .identifier_tree_leaf + .as_deref() + .is_none_or(|leaf| crate::disk::identifier_tree_leaf_matches(&opts.base_dir, leaf, rel_dir)); + + if !skip_deleted && forward_ok && leaf_ok { + if opts.limit > 0 && *objs_returned >= opts.limit { + return Ok(true); + } + let entry = MetaCacheEntry { + name: rel_dir.to_string(), + metadata: bytes.to_vec(), + ..Default::default() + }; + out.write_obj(&entry).await.map_err(Error::other)?; + *objs_returned += 1; + } + } + } + + // Collect known `data_dir` UUIDs in `rel_dir` so we don't descend into shard folders + let mut data_dirs_to_skip = HashSet::new(); + if entries.iter().any(|e| e == STORAGE_FORMAT_FILE) { + let xl_path = format!("{full_dir}/{STORAGE_FORMAT_FILE}"); + if let Ok(bytes) = self.sim.read_file(&xl_path).await + && let Ok(fm) = FileMeta::load(&bytes) + && let Ok(dds) = fm.get_data_dirs() + { + for dd in dds.into_iter().flatten() { + data_dirs_to_skip.insert(dd.to_string()); + } + } + } + + for name in entries { + if name == STORAGE_FORMAT_FILE + || name == STORAGE_FORMAT_FILE_BACKUP + || name.starts_with('.') + || data_dirs_to_skip.contains(&name) + { + continue; + } + if rel_dir == clean_rel(&opts.base_dir) + && let Some(fp) = opts.filter_prefix.as_deref() + && !fp.is_empty() + && !name.starts_with(fp) + { + continue; + } + let child_rel = if rel_dir.is_empty() { + name.clone() + } else { + format!("{rel_dir}/{name}") + }; + let child_full = format!("{full_dir}/{name}"); + let Ok(st) = self.sim.stat(&child_full).await else { + continue; + }; + if !st.is_dir { + continue; + } + + if opts.recursive { + if Box::pin(self.scan_walk_recursive(bucket, &child_rel, opts, out, objs_returned)).await? { + return Ok(true); + } + } else { + // Non-recursive: check if child_rel has xl.meta directly, otherwise emit directory prefix + let child_xl = format!("{child_full}/{STORAGE_FORMAT_FILE}"); + if let Ok(bytes) = self.sim.read_file(&child_xl).await { + if opts.limit > 0 && *objs_returned >= opts.limit { + return Ok(true); + } + let entry = MetaCacheEntry { + name: child_rel, + metadata: bytes.to_vec(), + ..Default::default() + }; + out.write_obj(&entry).await.map_err(Error::other)?; + *objs_returned += 1; + } else { + if opts.limit > 0 && *objs_returned >= opts.limit { + return Ok(true); + } + let entry = MetaCacheEntry { + name: format!("{child_rel}{SLASH_SEPARATOR}"), + ..Default::default() + }; + out.write_obj(&entry).await.map_err(Error::other)?; + *objs_returned += 1; + } + } + } + + Ok(false) + } +} + +#[async_trait::async_trait] +impl DiskAPI for DstSimDisk { + fn to_string(&self) -> String { + self.virtual_root.to_string_lossy().into_owned() + } + + async fn is_online(&self) -> bool { + !self.sim.is_offline() + } + + fn is_local(&self) -> bool { + true + } + + fn host_name(&self) -> String { + self.node_id.clone() + } + + fn endpoint(&self) -> Endpoint { + self.endpoint.clone() + } + + async fn close(&self) -> Result<()> { + Ok(()) + } + + async fn get_disk_id(&self) -> Result> { + self.ensure_online()?; + let cached = *self.disk_id.read().unwrap_or_else(|p| p.into_inner()); + Ok(cached) + } + + async fn set_disk_id(&self, id: Option) -> Result<()> { + *self.disk_id.write().unwrap_or_else(|p| p.into_inner()) = id; + Ok(()) + } + + fn path(&self) -> PathBuf { + self.virtual_root.clone() + } + + fn get_disk_location(&self) -> DiskLocation { + DiskLocation { + pool_idx: Some(self.pool_idx), + set_idx: Some(self.set_idx), + disk_idx: Some(self.disk_idx), + } + } + + async fn make_volume(&self, volume: &str) -> Result<()> { + self.ensure_online()?; + let vol = clean_rel(volume); + if vol.is_empty() || vol.split('/').any(|seg| seg == "..") { + return Err(DiskError::InvalidPath); + } + if self.sim.stat(vol).await.is_ok() { + return Err(DiskError::VolumeExists); + } + self.sim.create_dir_all(vol).await.map_err(map_sim_err)?; + self.fsync_parent_chain(vol).await?; + Ok(()) + } + + async fn make_volumes(&self, volumes: Vec<&str>) -> Result<()> { + for v in volumes { + match self.make_volume(v).await { + Ok(()) | Err(DiskError::VolumeExists) => {} + Err(e) => return Err(e), + } + } + Ok(()) + } + + async fn list_volumes(&self) -> Result> { + self.ensure_online()?; + let entries = self.sim.list_dir("").await.map_err(map_sim_err)?; + let mut out = Vec::new(); + for name in entries { + if name.starts_with('.') { + continue; + } + if let Ok(st) = self.sim.stat(&name).await + && st.is_dir + { + out.push(VolumeInfo { + name, + created: Some(OffsetDateTime::UNIX_EPOCH), + }); + } + } + Ok(out) + } + + async fn stat_volume(&self, volume: &str) -> Result { + self.ensure_online()?; + let vol = clean_rel(volume); + match self.sim.stat(vol).await { + Ok(st) if st.is_dir => Ok(VolumeInfo { + name: vol.to_string(), + created: Some(OffsetDateTime::UNIX_EPOCH), + }), + Ok(_) => Err(DiskError::VolumeNotFound), + Err(e) => Err(map_volume_sim_err(e)), + } + } + + async fn delete_volume(&self, volume: &str, force_delete: bool) -> Result<()> { + self.ensure_online()?; + let vol = clean_rel(volume); + let st = self.sim.stat(vol).await.map_err(map_volume_sim_err)?; + if !st.is_dir { + return Err(DiskError::VolumeNotFound); + } + if !force_delete { + let children = self.sim.list_dir(vol).await.map_err(map_sim_err)?; + if !children.is_empty() { + return Err(DiskError::VolumeNotEmpty); + } + } + self.sim.remove_dir_all(vol).await.map_err(map_sim_err)?; + self.sim.fsync_dir("").await.map_err(map_sim_err)?; + Ok(()) + } + + async fn walk_dir(&self, opts: WalkDirOptions, wr: &mut W) -> Result<()> { + self.ensure_online()?; + self.ensure_volume_exists(&opts.bucket).await?; + let mut out = MetacacheWriter::new(wr); + let mut objs_returned = 0; + let base_dir = clean_rel(&opts.base_dir).to_string(); + let limit_reached = self + .scan_walk_recursive(&opts.bucket, &base_dir, &opts, &mut out, &mut objs_returned) + .await?; + out.close_with_limit_reached(limit_reached).await.map_err(Error::other)?; + Ok(()) + } + + async fn delete_version( + &self, + volume: &str, + path: &str, + fi: FileInfo, + force_del_marker: bool, + _opts: DeleteOptions, + ) -> Result<()> { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let (_, _, removed_data_dirs, _) = self + .apply_delete_requests_to_live(volume, path, std::slice::from_ref(&fi), force_del_marker) + .await?; + let obj_dir = join_vol_path(volume, path)?; + for dd in removed_data_dirs { + let dd_path = format!("{obj_dir}/{dd}"); + let _ = self.sim.remove_dir_all(&dd_path).await; + } + if self.sim.stat(&obj_dir).await.is_ok() { + let _ = self.sim.fsync_dir(&obj_dir).await; + } + self.cleanup_empty_ancestors(volume, path).await; + Ok(()) + } + + async fn delete_versions(&self, volume: &str, versions: Vec, opts: DeleteOptions) -> Vec> { + let mut out = Vec::with_capacity(versions.len()); + for group in versions { + let mut group_err = None; + for fi in group.versions { + if let Err(e) = self.delete_version(volume, &group.name, fi, false, opts.clone()).await { + group_err = Some(e); + break; + } + } + out.push(group_err); + } + out + } + + async fn delete_paths(&self, volume: &str, paths: &[String]) -> Result<()> { + self.ensure_online()?; + for p in paths { + self.delete( + volume, + p, + DeleteOptions { + recursive: true, + immediate: true, + ..Default::default() + }, + ) + .await?; + } + Ok(()) + } + + async fn delete_version_recoverable( + &self, + volume: &str, + object: &str, + file_info: FileInfo, + force_del_marker: bool, + opts: DeleteOptions, + ) -> Result<()> { + validate_delete_recovery_options(&opts)?; + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let tx = opts.old_data_dir.ok_or(DiskError::FileCorrupt)?; + let _guard = self.delete_tx_lock.lock().await; + + let (backup_xl, target_bytes, data_dirs, original_versions) = self + .apply_delete_requests_to_live(volume, object, std::slice::from_ref(&file_info), force_del_marker) + .await?; + + let original_digest = backup_xl.as_ref().map(|b| Sha256::digest(b).into()); + let target_digest = target_bytes.as_ref().map(|b| Sha256::digest(b).into()); + let journal = DeleteRecoveryJournal { + protocol_version: DELETE_RECOVERY_PROTOCOL_VERSION, + volume: volume.to_string(), + object: object.to_string(), + transaction: tx, + bucket_incarnation: opts.delete_recovery_bucket_incarnation, + original_digest, + target_digest, + data_dirs, + deleted_versions: vec![file_info.version_id.unwrap_or_default()], + requests: vec![file_info], + original_versions, + predecessors: Vec::new(), + }; + let record = SimDeleteTxRecord { + state: DeleteRecoveryState::NewPrepared, + journal, + backup_xl, + }; + self.save_delete_tx_record(volume, tx, &record).await + } + + async fn delete_versions_recoverable( + &self, + volume: &str, + versions: Vec, + opts: DeleteOptions, + ) -> Vec> { + let mut out = Vec::with_capacity(versions.len()); + for group in versions { + let mut group_err = None; + for fi in group.versions { + if let Err(e) = self + .delete_version_recoverable(volume, &group.name, fi, false, opts.clone()) + .await + { + group_err = Some(e); + break; + } + } + out.push(group_err); + } + out + } + + async fn supports_guarded_delete_versions(&self) -> Result<()> { + Ok(()) + } + + async fn delete_versions_guarded_recoverable( + &self, + volume: &str, + versions: Vec, + opts: DeleteOptions, + ) -> Vec> { + let plain: Vec = versions.into_iter().map(|g| g.group).collect(); + self.delete_versions_recoverable(volume, plain, opts).await + } + + async fn has_delete_transaction_evidence(&self, volume: &str, object: &str) -> Result { + let disc = self.discover_delete_transactions_bounded(volume, object, 16).await?; + Ok(!disc.transactions.is_empty()) + } + + async fn discover_delete_transactions_bounded( + &self, + volume: &str, + object: &str, + max_entries: u32, + ) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let tx_root = format!("{DST_DELETE_TX_DIR}/{}", clean_rel(volume)); + let entries = match self.sim.list_dir(&tx_root).await { + Ok(e) => e, + Err(SimErr::NotFound(_)) => { + return Ok(BoundedDeleteRecoveryDiscovery { + transactions: Vec::new(), + visited: 0, + complete: true, + }); + } + Err(e) => return Err(map_sim_err(e)), + }; + + let mut transactions = Vec::new(); + let mut visited = 0u32; + for entry in entries { + if visited >= max_entries { + return Ok(BoundedDeleteRecoveryDiscovery { + transactions, + visited, + complete: false, + }); + } + visited += 1; + let Some(hex_id) = entry.strip_suffix(".json") else { + continue; + }; + let Ok(tx) = Uuid::parse_str(hex_id) else { + continue; + }; + if let Some(rec) = self.load_delete_tx_record(volume, tx).await? + && rec.journal.object == object + { + transactions.push(DeleteTransactionId { + object: object.to_string(), + transaction: tx, + }); + } + } + + Ok(BoundedDeleteRecoveryDiscovery { + transactions, + visited, + complete: true, + }) + } + + async fn discover_delete_transactions( + &self, + volume: &str, + object: Option<&str>, + _cursor: Option, + limit: u32, + ) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let tx_root = format!("{DST_DELETE_TX_DIR}/{}", clean_rel(volume)); + let entries = match self.sim.list_dir(&tx_root).await { + Ok(e) => e, + Err(SimErr::NotFound(_)) => { + return Ok(DeleteRecoveryPage { + transactions: Vec::new(), + next: None, + }); + } + Err(e) => return Err(map_sim_err(e)), + }; + let mut transactions = Vec::new(); + for entry in entries { + if transactions.len() >= limit as usize { + break; + } + let Some(hex_id) = entry.strip_suffix(".json") else { + continue; + }; + let Ok(tx) = Uuid::parse_str(hex_id) else { + continue; + }; + if let Some(rec) = self.load_delete_tx_record(volume, tx).await? + && object.is_none_or(|target| rec.journal.object == target) + { + transactions.push(DeleteTransactionId { + object: rec.journal.object, + transaction: tx, + }); + } + } + Ok(DeleteRecoveryPage { + transactions, + next: None, + }) + } + + async fn inspect_delete_transaction( + &self, + volume: &str, + object: &str, + transaction: Uuid, + ) -> Result { + let _guard = self.delete_tx_lock.lock().await; + self.inspect_delete_tx_inner(volume, object, transaction).await + } + + async fn inspect_delete_transaction_bounded( + &self, + volume: &str, + object: &str, + transaction: Uuid, + _max_entries: u32, + ) -> Result { + let inspection = self.inspect_delete_transaction(volume, object, transaction).await?; + Ok(BoundedDeleteRecoveryInspection { inspection, visited: 1 }) + } + + async fn settle_delete_transaction( + &self, + volume: &str, + object: &str, + transaction: Uuid, + expected_fingerprint: DeleteRecoveryDigest, + action: DeleteRecoveryAction, + ) -> Result { + let _guard = self.delete_tx_lock.lock().await; + let current = self.inspect_delete_tx_inner(volume, object, transaction).await?; + if current.fingerprint != expected_fingerprint { + return Err(DiskError::OutdatedXLMeta); + } + + let obj_dir = join_vol_path(volume, object)?; + let xl_path = format!("{obj_dir}/{STORAGE_FORMAT_FILE}"); + + match action { + DeleteRecoveryAction::PublishCommit => { + if let Some(mut rec) = self.load_delete_tx_record(volume, transaction).await? { + rec.state = DeleteRecoveryState::QuorumCommitted; + self.save_delete_tx_record(volume, transaction, &rec).await?; + } + } + DeleteRecoveryAction::AdoptCommit { authority } => { + let (backup_xl, _, _, _) = self + .apply_delete_requests_to_live(volume, object, &authority.requests, false) + .await?; + let rec = SimDeleteTxRecord { + state: DeleteRecoveryState::QuorumCommitted, + journal: *authority, + backup_xl, + }; + self.save_delete_tx_record(volume, transaction, &rec).await?; + } + DeleteRecoveryAction::FinishCommit => { + if let Some(mut rec) = self.load_delete_tx_record(volume, transaction).await? { + for dd in &rec.journal.data_dirs { + let dd_path = format!("{obj_dir}/{dd}"); + let _ = self.sim.remove_dir_all(&dd_path).await; + } + if rec.journal.target_digest.is_none() { + let _ = self.sim.remove_file(&xl_path).await; + } + if self.sim.stat(&obj_dir).await.is_ok() { + let _ = self.sim.fsync_dir(&obj_dir).await; + } + rec.state = DeleteRecoveryState::CommitFinished; + self.save_delete_tx_record(volume, transaction, &rec).await?; + } + } + DeleteRecoveryAction::FinalizeCommit | DeleteRecoveryAction::DiscardLegacy => { + self.remove_delete_tx_record(volume, transaction).await?; + self.cleanup_empty_ancestors(volume, object).await; + } + DeleteRecoveryAction::Rollback => { + if let Some(rec) = self.load_delete_tx_record(volume, transaction).await? { + match rec.backup_xl { + Some(old_bytes) => { + self.write_durable_file(&xl_path, Bytes::from(old_bytes)).await?; + } + None => { + let _ = self.sim.remove_file(&xl_path).await; + if self.sim.stat(&obj_dir).await.is_ok() { + let _ = self.sim.fsync_dir(&obj_dir).await; + } + } + } + } + self.remove_delete_tx_record(volume, transaction).await?; + self.cleanup_empty_ancestors(volume, object).await; + } + } + + self.inspect_delete_tx_inner(volume, object, transaction).await + } + + async fn settle_delete_transaction_bounded( + &self, + volume: &str, + request: BoundedDeleteRecoverySettlement, + _namespace_owner: Option>, + ) -> Result { + let inspection = self + .settle_delete_transaction(volume, &request.object, request.transaction, request.expected_fingerprint, request.action) + .await?; + Ok(BoundedDeleteRecoverySettlementReply { + outcome: DeleteRecoverySettlementOutcome::Inspected(Box::new(inspection)), + visited: 1, + }) + } + + async fn write_metadata(&self, _org_volume: &str, volume: &str, path: &str, fi: FileInfo) -> Result<()> { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let obj_dir = join_vol_path(volume, path)?; + let xl_path = format!("{obj_dir}/{STORAGE_FORMAT_FILE}"); + + let mut fm = match self.sim.read_file(&xl_path).await { + Ok(existing) => Self::load_filemeta_preserving_inline(&existing).unwrap_or_else(|_| FileMeta::new()), + Err(SimErr::NotFound(_)) => FileMeta::new(), + Err(e) => return Err(map_sim_err(e)), + }; + fm.add_version(fi)?; + let encoded = Bytes::from(fm.marshal_msg()?); + + let tmp_dir = format!("{RUSTFS_META_TMP_BUCKET}/{}", Uuid::new_v4()); + let tmp_xl = format!("{tmp_dir}/{STORAGE_FORMAT_FILE}"); + self.sim.create_dir_all(&tmp_dir).await.map_err(map_sim_err)?; + self.sim.write_file(&tmp_xl, encoded).await.map_err(map_sim_err)?; + self.sim.fsync_file(&tmp_xl).await.map_err(map_sim_err)?; + + self.check_crash_point(CrashPoint::MetaWriteAfterTmpBeforeRename, volume, path)?; + + self.sim.create_dir_all(&obj_dir).await.map_err(map_sim_err)?; + self.sim.rename(&tmp_xl, &xl_path).await.map_err(map_sim_err)?; + self.fsync_parent_chain(&obj_dir).await?; + let _ = self.sim.remove_dir_all(&tmp_dir).await; + Ok(()) + } + + async fn update_metadata(&self, volume: &str, path: &str, fi: FileInfo, opts: &UpdateMetadataOpts) -> Result<()> { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let obj_dir = join_vol_path(volume, path)?; + let xl_path = format!("{obj_dir}/{STORAGE_FORMAT_FILE}"); + let raw = match self.sim.read_file(&xl_path).await { + Ok(b) => b, + Err(SimErr::NotFound(_)) if fi.version_id.is_some() => return Err(DiskError::FileVersionNotFound), + Err(e) => return Err(map_sim_err(e)), + }; + let mut fm = Self::load_filemeta_preserving_inline(&raw)?; + fm.update_object_version_with_opts(fi, opts.replace_user_metadata)?; + let encoded = Bytes::from(fm.marshal_msg()?); + if opts.no_persistence { + self.sim.write_file(&xl_path, encoded).await.map_err(map_sim_err)?; + Ok(()) + } else { + self.write_durable_file(&xl_path, encoded).await + } + } + + async fn read_version( + &self, + org_volume: &str, + volume: &str, + path: &str, + version_id: &str, + opts: &ReadOptions, + ) -> Result { + self.ensure_online()?; + if !org_volume.is_empty() && org_volume != volume { + self.ensure_volume_exists(org_volume).await?; + } + self.ensure_volume_exists(volume).await?; + let raw = match self.read_xl(volume, path, opts.read_data).await { + Ok(r) => r, + Err(DiskError::FileNotFound) if !version_id.is_empty() => return Err(DiskError::FileVersionNotFound), + Err(e) => return Err(e), + }; + let mut fi = get_file_info( + &raw.buf, + volume, + path, + version_id, + FileInfoOpts { + data: opts.read_data, + include_free_versions: opts.incl_free_versions, + include_part_checksums: false, + }, + )?; + fi.validate_for_metadata_read()?; + if fi.is_canonical_delete_marker() { + return Ok(fi); + } + if opts.read_data && (fi.data.as_ref().is_some_and(|d| !d.is_empty()) || fi.size == 0) { + if fi.inline_data() { + return Ok(fi); + } + if fi.size == 0 || fi.version_id.is_none_or(|v| v.is_nil()) { + fi.set_inline_data(); + return Ok(fi); + } + if let Some(part) = fi.parts.first() { + let part_rel = path_join_buf(&[ + clean_rel(path), + fi.data_dir.map_or_else(String::new, |d| d.to_string()).as_str(), + &format!("part.{}", part.number), + ]); + let full_part = join_vol_path(volume, &part_rel)?; + if self.sim.stat(&full_part).await.is_err() { + fi.set_inline_data(); + return Ok(fi); + } + } + fi.data = None; + } + Ok(fi) + } + + async fn read_xl(&self, volume: &str, path: &str, _read_data: bool) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let obj_dir = join_vol_path(volume, path)?; + let xl_path = if obj_dir.ends_with(&format!("/{STORAGE_FORMAT_FILE}")) { + obj_dir + } else { + format!("{obj_dir}/{STORAGE_FORMAT_FILE}") + }; + let bytes = self.sim.read_file(&xl_path).await.map_err(map_sim_err)?; + Ok(RawFileInfo { buf: bytes.to_vec() }) + } + + async fn read_metadata(&self, volume: &str, path: &str) -> Result { + let raw = self.read_xl(volume, path, false).await?; + Ok(Bytes::from(raw.buf)) + } + + /// Production atomic commit path (`LocalDisk::rename_data` equivalent) over `SimDiskIo`: + /// + /// 1. Load existing `dst_dir/xl.meta` (if present) preserving inline blobs for older versions, + /// and compute `old_current_size` & `has_old_data_dir`. + /// 2. Merge `file_info` via `xlmeta.add_version` and serialize `new_meta_bytes`. + /// 3. For non-inline erasure objects, `fsync_file` every `part.N` in `src_data`, move + /// `src_data -> dst_data`, and `fsync_dir` `dst_data` + `dst_dir` **before** committing + /// `xl.meta` (preventing ALICE out-of-order directory persistence from ever exposing an + /// `xl.meta` pointing to a non-durable `data_dir`). + /// 4. Check `CrashPoint::RenameAfterDataRename`, stage & `fsync_file` `xl.meta.bkp` (when + /// overwriting), check `CrashPoint::RenameAfterBackupBeforeMetaCommit`, stage & `fsync_file` + /// `src_dir/xl.meta`, atomically `rename` to `dst_dir/xl.meta`, check + /// `CrashPoint::RenameAfterMetaCommit`, and `fsync_parent_chain(&dst_dir)`. + async fn rename_data( + &self, + src_volume: &str, + src_path: &str, + file_info: FileInfo, + dst_volume: &str, + dst_path: &str, + ) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(src_volume).await?; + self.ensure_volume_exists(dst_volume).await?; + + let src_dir = join_vol_path(src_volume, src_path)?; + let dst_dir = join_vol_path(dst_volume, dst_path)?; + let dst_meta = format!("{dst_dir}/{STORAGE_FORMAT_FILE}"); + let bkp_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE_BACKUP}"); + let src_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE}"); + + let existing_raw = match self.sim.read_file(&dst_meta).await { + Ok(b) => Some(b), + Err(SimErr::NotFound(_)) => None, + Err(e) => return Err(map_sim_err(e)), + }; + + let mut xlmeta = FileMeta::new(); + let mut has_old_data_dir = None; + let old_current_size = match &existing_raw { + None => Some(OldCurrentSize::Absent), + Some(old_bytes) => { + if let Ok(loaded) = Self::load_filemeta_preserving_inline(old_bytes) { + xlmeta = loaded; + let vid = file_info.version_id.unwrap_or_default(); + has_old_data_dir = xlmeta.find_unshared_data_dir_for_version(Some(vid)); + if let Some(old_dd) = has_old_data_dir { + let _ = xlmeta.data.remove_two(vid, old_dd); + } + } + match get_file_info( + old_bytes, + dst_volume, + dst_path, + "", + FileInfoOpts { + data: false, + include_free_versions: false, + include_part_checksums: false, + }, + ) { + Ok(cur) => Some(OldCurrentSize::Present(if cur.deleted { 0 } else { cur.size })), + Err(_) => Some(OldCurrentSize::Absent), + } + } + }; + + xlmeta.add_version(file_info.clone())?; + let new_meta_bytes = Bytes::from(xlmeta.marshal_msg()?); + + self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?; + self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?; + + let has_external_parts = !file_info.inline_data() && file_info.data.is_none() && file_info.size > 0; + if has_external_parts + && let Some(data_dir) = file_info.data_dir + && !data_dir.is_nil() + { + let src_data = format!("{src_dir}/{data_dir}"); + let dst_data = format!("{dst_dir}/{data_dir}"); + if self.sim.stat(&src_data).await.is_ok() { + let staged_parts = self.sim.list_dir(&src_data).await.map_err(map_sim_err)?; + for part in staged_parts { + let part_file = format!("{src_data}/{part}"); + if let Ok(st) = self.sim.stat(&part_file).await + && !st.is_dir + { + self.sim.fsync_file(&part_file).await.map_err(map_sim_err)?; + } + } + self.sim.fsync_dir(&src_data).await.map_err(map_sim_err)?; + if self.sim.stat(&dst_data).await.is_ok() { + let _ = self.sim.remove_dir_all(&dst_data).await; + } + self.sim.rename(&src_data, &dst_data).await.map_err(map_sim_err)?; + self.sim.fsync_dir(&dst_data).await.map_err(map_sim_err)?; + self.fsync_parent_chain(&dst_dir).await?; + } + } else { + // Ensure ancestor directories of `dst_dir` are durable before publishing `xl.meta` + self.fsync_parent_chain(&dst_dir).await?; + } + + self.check_crash_point(CrashPoint::RenameAfterDataRename, dst_volume, dst_path)?; + + if let Some(old_bytes) = existing_raw { + self.sim.write_file(&bkp_meta, old_bytes).await.map_err(map_sim_err)?; + self.sim.fsync_file(&bkp_meta).await.map_err(map_sim_err)?; + } + + self.check_crash_point(CrashPoint::RenameAfterBackupBeforeMetaCommit, dst_volume, dst_path)?; + + self.sim.write_file(&src_meta, new_meta_bytes).await.map_err(map_sim_err)?; + self.sim.fsync_file(&src_meta).await.map_err(map_sim_err)?; + self.sim.rename(&src_meta, &dst_meta).await.map_err(map_sim_err)?; + + self.check_crash_point(CrashPoint::RenameAfterMetaCommit, dst_volume, dst_path)?; + + self.fsync_parent_chain(&dst_dir).await?; + let _ = self.sim.remove_file(&bkp_meta).await; + let _ = self.sim.remove_dir_all(&src_dir).await; + + Ok(RenameDataResp { + old_data_dir: has_old_data_dir, + cleanup_data_dir: has_old_data_dir, + old_current_size, + old_current_source_checked: true, + ..Default::default() + }) + } + + async fn list_dir(&self, _origvolume: &str, volume: &str, dir_path: &str, count: i32) -> Result> { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, dir_path)?; + let entries = self.sim.list_dir(&rel).await.map_err(map_sim_err)?; + let mut out = Vec::with_capacity(entries.len()); + for name in entries { + if count > 0 && out.len() >= count as usize { + break; + } + let child = format!("{rel}/{name}"); + let formatted = match self.sim.stat(&child).await { + Ok(st) if st.is_dir => format!("{name}{SLASH_SEPARATOR}"), + _ => name, + }; + out.push(formatted); + } + Ok(out) + } + + async fn read_file(&self, volume: &str, path: &str) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, path)?; + let data = self.sim.read_file(&rel).await.map_err(map_sim_err)?; + Ok(Box::new(Cursor::new(data))) + } + + async fn read_file_stream(&self, volume: &str, path: &str, offset: usize, length: usize) -> Result { + let slice = self.read_file_mmap_copy(volume, path, offset, length).await?; + Ok(Box::new(Cursor::new(slice))) + } + + async fn read_file_mmap_copy(&self, volume: &str, path: &str, offset: usize, length: usize) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, path)?; + let data = self.sim.read_file(&rel).await.map_err(map_sim_err)?; + let end = offset.checked_add(length).ok_or(DiskError::FileCorrupt)?; + if end > data.len() { + return Err(DiskError::FileCorrupt); + } + Ok(data.slice(offset..end)) + } + + async fn append_file(&self, volume: &str, path: &str) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, path)?; + let existing = match self.sim.read_file(&rel).await { + Ok(b) => b.to_vec(), + Err(SimErr::NotFound(_)) => { + self.sim.write_file(&rel, Bytes::new()).await.map_err(map_sim_err)?; + Vec::new() + } + Err(e) => return Err(map_sim_err(e)), + }; + Ok(Box::new(SimBufferedWriter::new(self.sim.clone(), rel, existing))) + } + + async fn create_file(&self, origvolume: &str, volume: &str, path: &str, file_size: i64) -> Result { + self.ensure_online()?; + if !origvolume.is_empty() && origvolume != volume { + self.ensure_volume_exists(origvolume).await?; + } + self.ensure_volume_exists(volume).await?; + if file_size > 0 + && let Some(cap) = *self.configured_capacity.read().unwrap_or_else(|p| p.into_inner()) + && self.sim.used_bytes().saturating_add(file_size as u64) > cap + { + return Err(DiskError::DiskFull); + } + let rel = join_vol_path(volume, path)?; + self.sim.write_file(&rel, Bytes::new()).await.map_err(map_sim_err)?; + let cap_hint = usize::try_from(file_size).ok().unwrap_or(0).min(1024 * 1024); + Ok(Box::new(SimBufferedWriter::new(self.sim.clone(), rel, Vec::with_capacity(cap_hint)))) + } + + async fn rename_file(&self, src_volume: &str, src_path: &str, dst_volume: &str, dst_path: &str) -> Result<()> { + self.ensure_online()?; + let src = join_vol_path(src_volume, src_path)?; + let dst = join_vol_path(dst_volume, dst_path)?; + let dst_parent = dst.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !dst_parent.is_empty() { + self.sim.create_dir_all(dst_parent).await.map_err(map_sim_err)?; + } + self.sim.rename(&src, &dst).await.map_err(map_sim_err) + } + + async fn rename_file_durable(&self, src_volume: &str, src_path: &str, dst_volume: &str, dst_path: &str) -> Result<()> { + self.ensure_online()?; + let src = join_vol_path(src_volume, src_path)?; + let dst = join_vol_path(dst_volume, dst_path)?; + let dst_parent = dst.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !dst_parent.is_empty() { + self.sim.create_dir_all(dst_parent).await.map_err(map_sim_err)?; + } + self.sim.fsync_file(&src).await.map_err(map_sim_err)?; + self.sim.rename(&src, &dst).await.map_err(map_sim_err)?; + self.fsync_parent_chain(dst_parent).await + } + + async fn rename_part(&self, src_volume: &str, src_path: &str, dst_volume: &str, dst_path: &str, meta: Bytes) -> Result<()> { + self.ensure_online()?; + let src = join_vol_path(src_volume, src_path)?; + let dst = join_vol_path(dst_volume, dst_path)?; + let dst_parent = dst.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !dst_parent.is_empty() { + self.sim.create_dir_all(dst_parent).await.map_err(map_sim_err)?; + } + self.sim.fsync_file(&src).await.map_err(map_sim_err)?; + self.sim.rename(&src, &dst).await.map_err(map_sim_err)?; + let meta_path = format!("{dst}.meta"); + self.write_durable_file(&meta_path, meta).await + } + + async fn delete(&self, volume: &str, path: &str, opt: DeleteOptions) -> Result<()> { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, path)?; + let st = match self.sim.stat(&rel).await { + Ok(st) => st, + Err(SimErr::NotFound(_)) => return Err(DiskError::FileNotFound), + Err(e) => return Err(map_sim_err(e)), + }; + if st.is_dir { + if opt.recursive || opt.orphan_data_dir { + self.sim.remove_dir_all(&rel).await.map_err(map_sim_err)?; + } else { + let children = self.sim.list_dir(&rel).await.map_err(map_sim_err)?; + if !children.is_empty() { + return Err(DiskError::VolumeNotEmpty); + } + self.sim.remove_dir_all(&rel).await.map_err(map_sim_err)?; + } + } else { + self.sim.remove_file(&rel).await.map_err(map_sim_err)?; + } + let parent = rel.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !parent.is_empty() && self.sim.stat(parent).await.is_ok() { + let _ = self.sim.fsync_dir(parent).await; + } + self.cleanup_empty_ancestors(volume, parent.strip_prefix(clean_rel(volume)).unwrap_or("")) + .await; + Ok(()) + } + + async fn delete_data_dir(&self, volume: &str, path: &str, opts: DeleteOptions) -> Result { + let mut del_opts = opts; + del_opts.recursive = true; + match self.delete(volume, path, del_opts).await { + Ok(()) | Err(DiskError::FileNotFound) => Ok(DataDirDeleteStatus::Deleted), + Err(e) => Err(e), + } + } + + async fn verify_file(&self, volume: &str, path: &str, fi: &FileInfo) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + + let erasure = &fi.erasure; + let codec_erasure = coding::Erasure::try_new_with_options( + erasure.data_blocks, + erasure.parity_blocks, + erasure.block_size, + fi.uses_legacy_checksum, + ) + .map_err(DiskError::from)?; + fi.validate(ValidationMode::RequireErasure)?; + let frame_size = crate::object_api::persisted_ec_read_quantum( + &fi.metadata, + codec_erasure.block_size, + codec_erasure.data_shards, + codec_erasure.shard_size(), + ) + .map_err(|_| DiskError::FileCorrupt)? + .unwrap_or_else(|| codec_erasure.shard_size()); + + let mut resp = CheckPartsResp { + results: vec![CHECK_PART_UNKNOWN; fi.parts.len()], + }; + + for (i, part) in fi.parts.iter().enumerate() { + let checksum_info = erasure.get_checksum_info(part.number); + let checksum_algo = if fi.uses_legacy_checksum && checksum_info.algorithm == HashAlgorithm::HighwayHash256S { + HashAlgorithm::HighwayHash256SLegacy + } else { + checksum_info.algorithm + }; + let part_rel = path_join_buf(&[ + clean_rel(path), + &fi.data_dir.map_or_else(String::new, |dir| dir.to_string()), + &format!("part.{}", part.number), + ]); + let full_part = join_vol_path(volume, &part_rel)?; + let err: Option = match self.sim.read_file(&full_part).await { + Ok(raw_bytes) => { + let file_size = raw_bytes.len(); + let logical_shard_size = codec_erasure.shard_file_size(part.size as i64) as usize; + bitrot_verify(Cursor::new(raw_bytes), file_size, logical_shard_size, checksum_algo, frame_size) + .await + .err() + .map(|_| DiskError::FileCorrupt) + } + Err(e) => Some(map_sim_err(e)), + }; + resp.results[i] = conv_part_err_to_int(&err); + } + + Ok(resp) + } + + async fn check_parts(&self, volume: &str, path: &str, fi: &FileInfo) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let layout = fi.validate(ValidationMode::RequireErasure)?.ok_or(DiskError::FileCorrupt)?; + let mut resp = CheckPartsResp { + results: vec![CHECK_PART_UNKNOWN; fi.parts.len()], + }; + for (i, part) in fi.parts.iter().enumerate() { + let part_rel = path_join_buf(&[ + clean_rel(path), + &fi.data_dir.map_or_else(String::new, |dir| dir.to_string()), + &format!("part.{}", part.number), + ]); + let full_part = join_vol_path(volume, &part_rel)?; + match self.sim.stat(&full_part).await { + Ok(st) => { + if st.is_dir { + resp.results[i] = CHECK_PART_FILE_NOT_FOUND; + continue; + } + let expected_size = layout.shard_file_size(part.size).ok_or(DiskError::FileCorrupt)?; + let expected_size = u64::try_from(expected_size).map_err(|_| DiskError::FileCorrupt)?; + resp.results[i] = if st.size < expected_size { + CHECK_PART_FILE_CORRUPT + } else { + CHECK_PART_SUCCESS + }; + } + Err(e) => { + let mapped = Some(map_sim_err(e)); + resp.results[i] = conv_part_err_to_int(&mapped); + } + } + } + Ok(resp) + } + + async fn read_parts(&self, bucket: &str, paths: &[String]) -> Result> { + self.ensure_online()?; + self.ensure_volume_exists(bucket).await?; + let mut out = Vec::with_capacity(paths.len()); + for p in paths { + let meta_rel = if p.ends_with(".meta") { + join_vol_path(bucket, p)? + } else { + format!("{}.meta", join_vol_path(bucket, p)?) + }; + let raw = self.sim.read_file(&meta_rel).await.map_err(map_sim_err)?; + let info = ObjectPartInfo::unmarshal(&raw)?; + out.push(info); + } + Ok(out) + } + + async fn read_multiple(&self, req: ReadMultipleReq) -> Result> { + self.ensure_online()?; + let mut out = Vec::with_capacity(req.files.len()); + let mut found = 0usize; + for f in &req.files { + let rel_in_bucket = if req.prefix.is_empty() { + f.clone() + } else { + format!("{}/{}", clean_rel(&req.prefix), clean_rel(f)) + }; + let mut resp = ReadMultipleResp { + bucket: req.bucket.clone(), + prefix: req.prefix.clone(), + file: f.clone(), + ..Default::default() + }; + match self.read_all(&req.bucket, &rel_in_bucket).await { + Ok(bytes) => { + found += 1; + if req.max_size > 0 && bytes.len() > req.max_size { + resp.exists = true; + resp.error = format!("max size ({}) exceeded: {}", req.max_size, bytes.len()); + out.push(resp); + break; + } + resp.exists = true; + resp.data = bytes.to_vec(); + resp.mod_time = Some(OffsetDateTime::UNIX_EPOCH); + out.push(resp); + if req.max_results > 0 && found >= req.max_results { + break; + } + } + Err(DiskError::FileNotFound) if req.abort404 => { + resp.exists = false; + out.push(resp); + break; + } + Err(e) => { + resp.exists = false; + resp.error = e.to_string(); + out.push(resp); + } + } + } + Ok(out) + } + + async fn write_all(&self, volume: &str, path: &str, data: Bytes) -> Result<()> { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, path)?; + self.write_durable_file(&rel, data).await + } + + async fn write_format_control(&self, path: &str, data: Bytes) -> Result<()> { + validate_format_control_path(path)?; + let parsed = FormatV3::try_from(data.as_ref()).map_err(|_| DiskError::CorruptedFormat)?; + self.write_all(RUSTFS_META_BUCKET, path, data).await?; + if path == FORMAT_CONFIG_FILE && !parsed.erasure.this.is_nil() { + self.set_disk_id(Some(parsed.erasure.this)).await?; + } + Ok(()) + } + + async fn read_all(&self, volume: &str, path: &str) -> Result { + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, path)?; + self.sim.read_file(&rel).await.map_err(map_sim_err) + } + + async fn compare_and_update_file( + &self, + volume: &str, + path: &str, + expected: Option, + replacement: Option, + ) -> Result { + let _cas_guard = self.cas_lock.lock().await; + self.ensure_online()?; + self.ensure_volume_exists(volume).await?; + let rel = join_vol_path(volume, path)?; + let current = match self.sim.read_file(&rel).await { + Ok(b) => Some(b), + Err(SimErr::NotFound(_)) => None, + Err(e) => return Err(map_sim_err(e)), + }; + match (¤t, &expected) { + (None, Some(_)) => return Ok(ConditionalFileUpdate::Missing), + (cur, exp) if cur != exp => return Ok(ConditionalFileUpdate::Mismatch), + _ => {} + } + match replacement { + Some(bytes) => self.write_durable_file(&rel, bytes).await?, + None => { + match self.sim.remove_file(&rel).await { + Ok(()) | Err(SimErr::NotFound(_)) => {} + Err(e) => return Err(map_sim_err(e)), + } + let parent = rel.rsplit_once('/').map(|(p, _)| p).unwrap_or(""); + if !parent.is_empty() && self.sim.stat(parent).await.is_ok() { + self.sim.fsync_dir(parent).await.map_err(map_sim_err)?; + } + } + } + Ok(ConditionalFileUpdate::Updated) + } + + async fn disk_info(&self, _opts: &DiskInfoOptions) -> Result { + self.ensure_online()?; + let total = (*self.configured_capacity.read().unwrap_or_else(|p| p.into_inner())).unwrap_or(DEFAULT_SIM_CAPACITY_BYTES); + let used = self.sim.used_bytes(); + let free = total.saturating_sub(used); + let disk_id = *self.disk_id.read().unwrap_or_else(|p| p.into_inner()); + Ok(DiskInfo { + total, + free, + used, + used_inodes: 0, + free_inodes: 1_000_000, + major: 0, + minor: 0, + nr_requests: 128, + fs_type: "simfs-dst".to_string(), + root_disk: false, + healing: false, + scanning: self.scanning.load(Ordering::Acquire) > 0, + endpoint: self.endpoint.to_string(), + mount_path: self.virtual_root.to_string_lossy().into_owned(), + physical_device_ids: vec![format!("simdev-{}-{}", self.node_id, self.disk_idx)], + id: disk_id, + rotational: false, + metrics: DiskMetrics::default(), + error: String::new(), + fresh_capacity: true, + }) + } + + fn start_scan(&self) -> ScanGuard { + self.scanning.fetch_add(1, Ordering::AcqRel); + ScanGuard(Arc::clone(&self.scanning)) + } +} + +/// Complete multi-drive production [`SetDisks`] erasure set backed by [`DstSimDisk`]s. +pub struct DstSimSetFixture { + pub set_disks: Arc, + pub disks: Vec, + pub sim_disks: Vec, + pub format: FormatV3, + pub crash_registry: CrashRegistry, + pub instance_ctx: Arc, +} + +impl DstSimSetFixture { + /// Reboot all simulated drives under their configured [`CrashSemantics`] + /// (e.g., ALICE `CrashSemantics::DirtySubsetAndSectorTear`) and invalidate + /// `SetDisks`'s in-memory GET metadata cache so subsequent reads observe + /// the post-power-loss media state directly from disk. + pub fn crash_and_reboot_all(&self) { + for sim in &self.sim_disks { + sim.crash_and_reboot(); + } + self.invalidate_set_caches(); + } + + /// Clear `SetDisks`'s ephemeral in-memory GET metadata cache so tests inspect + /// physical on-disk `xl.meta` and bitrot-framed `part.N` shards directly. + pub fn invalidate_set_caches(&self) { + self.set_disks.invalidate_metadata_cache_for_dst(); + } +} + +/// Build [`crate::object_api::ObjectOptions`] suitable for driving a standalone +/// [`SetDisks`] erasure set in DST without requiring a global `ECStore` +/// `BucketMetadataSys` singleton (`ObjectLockConfigState::ConfirmedAbsent`, +/// `WriteCompletion::TailDrained`). +pub fn dst_object_options() -> crate::object_api::ObjectOptions { + crate::object_api::ObjectOptions { + write_completion: crate::object_api::WriteCompletion::TailDrained, + object_lock_config_snapshot: Some(Arc::new(crate::object_api::ObjectLockConfigSnapshot::new( + crate::bucket::metadata_sys::ObjectLockConfigState::ConfirmedAbsent, + ))), + ..Default::default() + } +} + +/// Build an isolated, formatted production [`SetDisks`] erasure set over +/// `drive_count` deterministic [`DstSimDisk`] drives seeded from `seed`. +pub async fn make_dst_sim_set_disks( + seed: u64, + drive_count: usize, + parity_count: usize, + capacity_bytes: Option, +) -> Result { + let instance_ctx = Arc::new(InstanceContext::default()); + let crash_registry = CrashRegistry::new(); + let root_rng = SimRng::from_seed(seed); + let mut format = FormatV3::new(1, drive_count); + // Derive deterministic deployment & drive UUIDs from `seed` so identical seeds + // yield bit-identical cluster topologies and shard distributions. + format.id = root_rng.gen_uuid_v4(); + for slot_id in format.erasure.sets[0].iter_mut().take(drive_count) { + let mut id = root_rng.gen_uuid_v4(); + if id.is_nil() { + id = Uuid::from_u128(1); + } + *slot_id = id; + } + + let mut sim_disks = Vec::with_capacity(drive_count); + let mut disk_stores = Vec::with_capacity(drive_count); + let mut opt_disks = Vec::with_capacity(drive_count); + let mut endpoints = Vec::with_capacity(drive_count); + + for disk_idx in 0..drive_count { + let drive_rng = root_rng.fork(&format!("dst-drive:{disk_idx}")); + let sim_disk = DstSimDisk::with_crash_registry("dst-node0", 0, 0, disk_idx, drive_rng, crash_registry.clone()); + if let Some(cap) = capacity_bytes { + sim_disk.set_capacity_bytes(Some(cap)); + } + + // Pre-create and fsync system directories on each simulated drive + for sys_dir in [ + RUSTFS_META_BUCKET, + RUSTFS_META_TMP_BUCKET, + RUSTFS_META_MULTIPART_BUCKET, + ".rustfs.sys/buckets", + DST_DELETE_TX_DIR, + ] { + sim_disk.sim().create_dir_all(sys_dir).await.map_err(map_sim_err)?; + sim_disk.fsync_parent_chain(sys_dir).await?; + } + + let endpoint = sim_disk.endpoint(); + let store: DiskStore = Arc::new(Disk::Sim(Box::new(sim_disk.clone()))); + + let mut disk_format = format.clone(); + disk_format.erasure.this = format.erasure.sets[0][disk_idx]; + save_format_file(&Some(store.clone()), &Some(disk_format)).await?; + + endpoints.push(endpoint); + sim_disks.push(sim_disk); + opt_disks.push(Some(store.clone())); + disk_stores.push(store); + } + + let topology = crate::layout::endpoints::EndpointServerPools(vec![crate::layout::endpoints::PoolEndpoints { + legacy: false, + set_count: 1, + drives_per_set: drive_count, + endpoints: endpoints.clone().into(), + cmd_line: String::new(), + platform: "dst-sim".into(), + }]); + let authority = instance_ctx.bind_multipart_proof_topology(&topology).map_err(Error::other)?; + crate::disk::multipart_source::bind_multipart_proof_snapshot(&opt_disks, &authority)?; + + let set_disks = SetDisks::new_with_instance_ctx( + format!("dst-sim-seed-{seed}"), + Arc::new(tokio::sync::RwLock::new(opt_disks)), + drive_count, + parity_count, + 0, + 0, + endpoints, + format.clone(), + Vec::new(), + instance_ctx.clone(), + ) + .await; + + Ok(DstSimSetFixture { + set_disks, + disks: disk_stores, + sim_disks, + format, + crash_registry, + instance_ctx, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::AsyncWriteExt; + + #[tokio::test] + async fn sim_buffered_writer_retains_dirty_state_after_failed_flush() { + let disk = DstSimDisk::new("node0", 0, 0, 0, 0x1234); + disk.make_volume("bkt").await.expect("make_volume"); + + let mut writer = disk.create_file("", "bkt", "obj.bin", -1).await.expect("create_file"); + writer.write_all(&[0xAB; 64]).await.expect("buffer write"); + + // Cap capacity below buffered payload size so flush fails inside poll_commit with ENOSPC + disk.set_capacity_bytes(Some(16)); + let flush_err = writer.flush().await.expect_err("flush must fail under ENOSPC"); + assert_eq!(flush_err.kind(), ErrorKind::StorageFull); + + // A subsequent shutdown while still out of space MUST NOT silently report Ok(()) + let shutdown_err = writer + .shutdown() + .await + .expect_err("shutdown must retry dirty buffer and surface ENOSPC"); + assert_eq!(shutdown_err.kind(), ErrorKind::StorageFull); + + // Once space is restored, retrying flush/shutdown commits the buffered bytes cleanly + disk.set_capacity_bytes(Some(4096)); + writer.shutdown().await.expect("shutdown should succeed after space recovery"); + let persisted = disk.read_all("bkt", "obj.bin").await.expect("read_all"); + assert_eq!(persisted.as_ref(), &[0xAB; 64]); + } + + #[tokio::test] + async fn compare_and_update_file_serializes_concurrent_cas_racers() { + let disk = DstSimDisk::new("node0", 0, 0, 0, 0x5678); + disk.make_volume("cas-bkt").await.expect("make_volume"); + let initial = Bytes::from_static(b"gen-0"); + assert_eq!( + disk.compare_and_update_file("cas-bkt", "state.json", None, Some(initial.clone())) + .await + .expect("seed cas"), + ConditionalFileUpdate::Updated + ); + + let mut tasks = Vec::new(); + for idx in 0..16u8 { + let d = disk.clone(); + let exp = initial.clone(); + let next = Bytes::from(vec![b'g', idx]); + tasks.push(tokio::spawn(async move { + d.compare_and_update_file("cas-bkt", "state.json", Some(exp), Some(next)) + .await + .expect("cas call") + })); + } + + let mut updated = 0usize; + let mut mismatch = 0usize; + for t in tasks { + match t.await.expect("join") { + ConditionalFileUpdate::Updated => updated += 1, + ConditionalFileUpdate::Mismatch => mismatch += 1, + other => panic!("unexpected CAS outcome: {other:?}"), + } + } + assert_eq!(updated, 1, "strict CAS linearizability allows exactly one winner"); + assert_eq!(mismatch, 15); + } + + #[tokio::test] + async fn volume_and_delete_tx_paths_allow_dotdot_substrings_but_reject_parent_segments() { + let disk = DstSimDisk::new("node0", 0, 0, 0, 0x9ABC); + disk.make_volume("my..valid..vol") + .await + .expect("volume containing '..' substring should succeed"); + let tx = Uuid::from_u128(42); + assert!(DstSimDisk::delete_tx_path("my..valid..vol", tx).is_ok()); + + assert!(matches!(disk.make_volume("..").await, Err(DiskError::InvalidPath))); + assert!(matches!(disk.make_volume("a/../b").await, Err(DiskError::InvalidPath))); + assert!(matches!(DstSimDisk::delete_tx_path("../escape", tx), Err(DiskError::InvalidPath))); + } +} diff --git a/crates/ecstore/src/disk/local.rs b/crates/ecstore/src/disk/local.rs index 6d3d7b97a7..31e61a401e 100644 --- a/crates/ecstore/src/disk/local.rs +++ b/crates/ecstore/src/disk/local.rs @@ -3947,12 +3947,22 @@ fn run_format_probe_hook(path: &Path, read: bool) { } } +#[derive(Debug, Clone)] +pub(crate) struct CachedSlotCohort { + pub disk_id: Uuid, + pub data: Bytes, + pub set: usize, + pub physical_slot: usize, + pub disk_ids: Vec, +} + #[derive(Debug, Clone)] pub struct FormatInfo { pub id: Option, pub data: Bytes, pub file_info: Option, pub last_check: Option, + pub(crate) slot_cohort: Option, } fn read_format_control_record( @@ -8384,6 +8394,7 @@ pub struct LocalDisk { // handles while separating replacement roots at the same configured path. format_control_key: PathBuf, pub endpoint: Endpoint, + endpoint_pool_idx: std::sync::atomic::AtomicI32, pub disk_info_cache: Arc>, pub scanning: Arc, pub rotational: bool, @@ -8652,6 +8663,16 @@ impl LocalDisk { .unwrap_or(crate::disk::multipart_source::ProofVerificationContext::RpcOnly) } + pub(crate) fn current_endpoint(&self) -> Endpoint { + let mut ep = self.endpoint.clone(); + ep.pool_idx = self.endpoint_pool_idx.load(Ordering::Acquire); + ep + } + + pub(crate) fn set_pool_index(&self, pool_idx: i32) { + self.endpoint_pool_idx.store(pool_idx, Ordering::Release); + } + pub(crate) fn bind_multipart_proof_authority( &self, authority: &crate::disk::multipart_source::ProofVerificationContext, @@ -8663,7 +8684,7 @@ impl LocalDisk { Err(DiskError::ConditionalDeleteConflict) }; } - authority.validate_endpoint(&self.endpoint)?; + authority.validate_endpoint(&self.current_endpoint())?; let stored = self.multipart_proof_authority.get_or_init(|| authority.clone()); if !stored.same_authority(authority) { return Err(DiskError::ConditionalDeleteConflict); @@ -8867,6 +8888,7 @@ impl LocalDisk { let mut id = None; // let mut format_legacy = false; let mut format_last_check = None; + let mut slot_cohort = None; if !format_data.is_empty() { let s = format_data.as_ref(); @@ -8880,6 +8902,15 @@ impl LocalDisk { id = Some(fm.erasure.this); // format_legacy = fm.erasure.distribution_algo == DistributionAlgoVersion::V1; format_last_check = Some(OffsetDateTime::now_utc()); + if let Some(cohort) = fm.erasure.sets.get(set_idx) { + slot_cohort = Some(CachedSlotCohort { + disk_id: fm.erasure.this, + data: format_data.clone(), + set: set_idx, + physical_slot: disk_idx, + disk_ids: cohort.clone(), + }); + } } let format_info = FormatInfo { @@ -8887,6 +8918,7 @@ impl LocalDisk { data: format_data, file_info: format_meta, last_check: format_last_check, + slot_cohort, }; let root_clone = root.clone(); let update_fn: UpdateFn = Box::new(move || { @@ -8965,6 +8997,7 @@ impl LocalDisk { #[cfg(target_os = "linux")] mount_lease_identity, endpoint: ep.clone(), + endpoint_pool_idx: std::sync::atomic::AtomicI32::new(ep.pool_idx), format_path, io_format_path, format_info: Arc::new(RwLock::new(format_info)), @@ -12804,6 +12837,7 @@ impl LocalDisk { if volume == RUSTFS_META_BUCKET && path == super::FORMAT_CONFIG_FILE { let mut format_info = self.format_info.write().await; format_info.data.clone_from(&data); + format_info.slot_cohort = None; } let volume_dir = self.io_get_bucket_path(volume)?; @@ -15451,7 +15485,7 @@ impl DiskAPI for LocalDisk { } fn endpoint(&self) -> Endpoint { - self.endpoint.clone() + self.current_endpoint() } async fn close(&self) -> Result<()> { @@ -15475,14 +15509,9 @@ impl DiskAPI for LocalDisk { } fn get_disk_location(&self) -> DiskLocation { + let pool_idx = self.endpoint_pool_idx.load(Ordering::Acquire); DiskLocation { - pool_idx: { - if self.endpoint.pool_idx < 0 { - None - } else { - Some(self.endpoint.pool_idx as usize) - } - }, + pool_idx: { if pool_idx < 0 { None } else { Some(pool_idx as usize) } }, set_idx: { if self.endpoint.set_idx < 0 { None @@ -15502,21 +15531,18 @@ impl DiskAPI for LocalDisk { #[tracing::instrument(level = "trace", skip_all)] async fn get_disk_id(&self) -> Result> { - let format_info = { + let (id, cached_file_info) = { let format_info = self.format_info.read().await; - format_info.clone() - }; - - let id = format_info.id; - - if format_info.file_info.is_some() && id.is_some() { - // Reuse the cached disk id only when the cached format check is fresh. - if let Some(last_check) = format_info.last_check + let id = format_info.id; + if format_info.file_info.is_some() + && id.is_some() + && let Some(last_check) = format_info.last_check && last_check.unix_timestamp() + 1 >= OffsetDateTime::now_utc().unix_timestamp() { return Ok(id); } - } + (id, format_info.file_info.clone()) + }; let file_meta = match self.check_format_json().await { Ok(meta) => meta, @@ -15527,12 +15553,13 @@ impl DiskAPI for LocalDisk { format_info.data = Bytes::new(); format_info.file_info = None; format_info.last_check = None; + format_info.slot_cohort = None; } return Err(err); } }; - if let Some(file_info) = &format_info.file_info + if let Some(file_info) = &cached_file_info && super::fs::same_file(&file_meta, file_info) { let mut format_info = self.format_info.write().await; @@ -15565,11 +15592,21 @@ impl DiskAPI for LocalDisk { return Err(DiskError::InconsistentDisk); } + let data_bytes: Bytes = b.into(); + let slot_cohort = fm.erasure.sets.get(m).map(|cohort| CachedSlotCohort { + disk_id, + data: data_bytes.clone(), + set: m, + physical_slot: n, + disk_ids: cohort.clone(), + }); + let mut format_info = self.format_info.write().await; format_info.id = Some(disk_id); format_info.file_info = Some(file_meta); - format_info.data = b.into(); + format_info.data = data_bytes; format_info.last_check = Some(OffsetDateTime::now_utc()); + format_info.slot_cohort = slot_cohort; drop(format_info); Ok(Some(disk_id)) @@ -15626,6 +15663,7 @@ impl DiskAPI for LocalDisk { format_info.id = None; format_info.file_info = None; format_info.last_check = None; + format_info.slot_cohort = None; } }; // The native owner outlives a cancelled RPC. Both invalidations diff --git a/crates/ecstore/src/disk/local/commit.rs b/crates/ecstore/src/disk/local/commit.rs index dadc5d557e..fd58b42035 100644 --- a/crates/ecstore/src/disk/local/commit.rs +++ b/crates/ecstore/src/disk/local/commit.rs @@ -15,6 +15,8 @@ //! Single-disk object rename publication and rollback. The shared execution core //! retains instrumentation, mutation leases, and commit guards through the syscall. +#[cfg(target_os = "linux")] +use super::has_rename_data_test_failpoints; #[cfg(all(test, windows))] use super::run_destination_commit_directory_preparation; #[cfg(any(not(windows), test))] @@ -22,8 +24,8 @@ use super::should_fail_local_inline_rollback_hardlink; use super::{ EVENT_DISK_LOCAL_ACCESS_FAILED, EVENT_DISK_LOCAL_HEAL_PURGE_FAILED, EVENT_DISK_LOCAL_RENAME_REJECTED, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_DISK_LOCAL, LocalDisk, SyncMode, effective_durability, has_inline_commit_test_failpoints, - has_rename_data_test_failpoints, inline_metadata_rollback_dir, observe_old_current, remove_dir_all_if_exists, - remove_dst_base_before_commit, remove_file_if_exists, rename_data_versions_signature, run_inline_preparation_before_backup, + inline_metadata_rollback_dir, observe_old_current, remove_dir_all_if_exists, remove_dst_base_before_commit, + remove_file_if_exists, rename_data_versions_signature, run_inline_preparation_before_backup, should_fail_after_metadata_commit, should_fail_before_old_metadata_backup, should_fail_commit_rename, should_remove_staged_meta_before_commit, skip_access_checks, tmp_staging_mutation_path, }; diff --git a/crates/ecstore/src/disk/local/delete_recovery.rs b/crates/ecstore/src/disk/local/delete_recovery.rs index d0a41e86ee..6c159e92c8 100644 --- a/crates/ecstore/src/disk/local/delete_recovery.rs +++ b/crates/ecstore/src/disk/local/delete_recovery.rs @@ -329,49 +329,67 @@ pub(in crate::disk) fn generation(mut canonical: FileInfo) -> Result = plan - .versions - .iter() - .map(|version| (version.header.version_id, std::mem::discriminant(&version.header.version_type))) - .collect(); - deleted_headers.retain(|header| !surviving.contains(header)); + if !plan.versions.is_empty() { + if plan.versions.len() <= 8 { + deleted_headers.retain(|header| { + !plan + .versions + .iter() + .any(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type)) == *header) + }); + } else { + let surviving: HashSet<_> = plan + .versions + .iter() + .map(|version| (version.header.version_id, std::mem::discriminant(&version.header.version_type))) + .collect(); + deleted_headers.retain(|header| !surviving.contains(header)); + } + } let deleted_versions = deleted_headers.into_iter().map(|(id, _)| id.unwrap_or_default()).collect(); let requests = requests .iter() @@ -3286,12 +3315,23 @@ impl LocalDisk { check_path_length(old_path.to_string_lossy().as_ref())?; old_path_to_verify = Some(old_path); } - let surviving: HashSet<_> = meta - .versions - .iter() - .map(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type))) - .collect(); - deleted_headers.retain(|header| !surviving.contains(header)); + if !meta.versions.is_empty() { + if meta.versions.len() <= 8 { + deleted_headers.retain(|header| { + !meta + .versions + .iter() + .any(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type)) == *header) + }); + } else { + let surviving: HashSet<_> = meta + .versions + .iter() + .map(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type))) + .collect(); + deleted_headers.retain(|header| !surviving.contains(header)); + } + } let deleted_versions = deleted_headers.into_iter().map(|(id, _)| id.unwrap_or_default()).collect(); let target = (!meta.versions.is_empty()).then(|| meta.marshal_msg()).transpose()?; let DeleteObjectDirScanOutcome { diff --git a/crates/ecstore/src/disk/local/multipart_source_state.rs b/crates/ecstore/src/disk/local/multipart_source_state.rs index d7d35c59cf..f45f329fba 100644 --- a/crates/ecstore/src/disk/local/multipart_source_state.rs +++ b/crates/ecstore/src/disk/local/multipart_source_state.rs @@ -175,6 +175,36 @@ impl ValidatedOwnedCertificate { } impl LocalDisk { + pub(super) async fn get_disk_slot_and_cohort(&self, disk_id: Uuid) -> Result<(usize, usize, Vec)> { + { + let format_info = self.format_info.read().await; + if let Some(cached) = &format_info.slot_cohort + && cached.disk_id == disk_id + && cached.data.as_ptr() == format_info.data.as_ptr() + && cached.data.len() == format_info.data.len() + { + return Ok((cached.set, cached.physical_slot, cached.disk_ids.clone())); + } + } + let format_bytes = self.format_info.read().await.data.clone(); + let format = crate::disk::format::FormatV3::try_from(format_bytes.as_ref()).map_err(|_| DiskError::CorruptedBackend)?; + let (set, physical_slot) = format.find_disk_index_by_disk_id(disk_id)?; + let disk_ids = format.erasure.sets.get(set).ok_or(DiskError::CorruptedBackend)?.clone(); + { + let mut format_info = self.format_info.write().await; + if format_info.data.as_ptr() == format_bytes.as_ptr() && format_info.data.len() == format_bytes.len() { + format_info.slot_cohort = Some(super::CachedSlotCohort { + disk_id, + data: format_bytes, + set, + physical_slot, + disk_ids: disk_ids.clone(), + }); + } + } + Ok((set, physical_slot, disk_ids)) + } + pub(super) async fn open_multipart_source_store( &self, path: &str, @@ -195,12 +225,9 @@ impl LocalDisk { .await? .filter(|id| !id.is_nil()) .ok_or(DiskError::UnformattedDisk)?; - let format = self.format_info.read().await.data.clone(); - let format = crate::disk::format::FormatV3::try_from(format.as_ref()).map_err(|_| DiskError::CorruptedBackend)?; - let (set, physical_slot) = format.find_disk_index_by_disk_id(disk_id)?; - let disk_ids = format.erasure.sets.get(set).ok_or(DiskError::CorruptedBackend)?.clone(); + let (_set, physical_slot, disk_ids) = self.get_disk_slot_and_cohort(disk_id).await?; if (self.endpoint.disk_idx >= 0 && self.endpoint.disk_idx as usize != physical_slot) - || (self.endpoint.set_idx >= 0 && self.endpoint.set_idx as usize != set) + || (self.endpoint.set_idx >= 0 && self.endpoint.set_idx as usize != _set) { return Err(DiskError::ConditionalDeleteConflict); } @@ -1690,10 +1717,8 @@ impl LocalDisk { if self.root != proof.root || self.io_root() != proof.base || self.get_disk_id().await? != Some(proof.disk_id) { return Err(DiskError::ConditionalDeleteConflict); } - let format = self.format_info.read().await.data.clone(); - let format = crate::disk::format::FormatV3::try_from(format.as_ref()).map_err(|_| DiskError::CorruptedBackend)?; - let (set, slot) = format.find_disk_index_by_disk_id(proof.disk_id)?; - if slot != proof.physical_slot || format.erasure.sets.get(set) != Some(&proof.disk_ids) { + let (_set, slot, cohort) = self.get_disk_slot_and_cohort(proof.disk_id).await?; + if slot != proof.physical_slot || cohort != proof.disk_ids { return Err(DiskError::ConditionalDeleteConflict); } let volume = proof.publication.lineage.bucket.clone(); @@ -2859,10 +2884,7 @@ impl LocalDisk { .await? .filter(|id| !id.is_nil()) .ok_or(DiskError::UnformattedDisk)?; - let format = self.format_info.read().await.data.clone(); - let format = crate::disk::format::FormatV3::try_from(format.as_ref()).map_err(|_| DiskError::CorruptedBackend)?; - let (set, slot) = format.find_disk_index_by_disk_id(disk_id)?; - let cohort = format.erasure.sets.get(set).ok_or(DiskError::CorruptedBackend)?; + let (_set, slot, cohort) = self.get_disk_slot_and_cohort(disk_id).await?; if anchor.protocol_version != MULTIPART_SOURCE_PROTOCOL_VERSION || anchor.disk_id != disk_id || anchor.physical_slot != slot diff --git a/crates/ecstore/src/disk/local/multipart_staging.rs b/crates/ecstore/src/disk/local/multipart_staging.rs index 4421fe69cf..8f34070966 100644 --- a/crates/ecstore/src/disk/local/multipart_staging.rs +++ b/crates/ecstore/src/disk/local/multipart_staging.rs @@ -563,7 +563,6 @@ impl LocalDisk { cleaned: Arc::new(std::sync::atomic::AtomicBool::new(false)), fresh_source_head: None, }; - let canonical_metadata = self.io_get_object_path(RUSTFS_META_MULTIPART_BUCKET, &format!("{source_path}/xl.meta"))?; let source_object = self.io_get_object_path(RUSTFS_META_MULTIPART_BUCKET, source_path)?; let private_object = staging.io_path.clone(); let base = self.io_root().to_path_buf(); @@ -581,6 +580,10 @@ impl LocalDisk { let (raw, source, from_active_cache) = if let Some((raw, source)) = cached_head { (raw, source, true) } else { + let canonical_metadata = source_object.join(crate::disk::STORAGE_FORMAT_FILE); + if std::fs::symlink_metadata(&canonical_metadata).is_ok_and(|meta| meta.file_type().is_symlink()) { + return Err(std::io::Error::from(DiskError::InvalidPath)); + } let raw = os::read_multipart_source_metadata(&canonical_metadata, &base, &publication_root).map_err(|error| { // A retired source has no authority for this delayed completion. // Preserve confinement and other I/O failures as their real errors. diff --git a/crates/ecstore/src/disk/mod.rs b/crates/ecstore/src/disk/mod.rs index cf3e048903..e3c4c6cf33 100644 --- a/crates/ecstore/src/disk/mod.rs +++ b/crates/ecstore/src/disk/mod.rs @@ -16,6 +16,8 @@ pub(crate) mod cleanup_runtime; pub mod disk_store; +#[cfg(feature = "dst")] +pub mod dst_sim; pub mod endpoint; pub mod error; pub mod error_conv; @@ -357,6 +359,8 @@ pub struct MmapCopyStageMetrics { pub enum Disk { Local(Box), Remote(Box), + #[cfg(feature = "dst")] + Sim(Box), } impl Disk { @@ -365,6 +369,8 @@ impl Disk { match self { Self::Local(disk) => disk.read_file(volume, path).await, Self::Remote(disk) => disk.read_format_control(volume, path).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.read_file(volume, path).await, } } @@ -373,6 +379,8 @@ impl Disk { match self { Self::Local(disk) => Some(disk.physical_admission()), Self::Remote(_) => None, + #[cfg(feature = "dst")] + Self::Sim(_) => None, } } @@ -381,6 +389,8 @@ impl Disk { match self { Self::Local(disk) => disk.get_disk().is_plain_orphan_data_dir(volume, path).await, Self::Remote(disk) => disk.is_plain_orphan_data_dir(volume, path).await, + #[cfg(feature = "dst")] + Self::Sim(_) => Ok(true), } } @@ -400,6 +410,11 @@ impl Disk { let _owner = namespace_owner; disk.delete_versions(volume, versions, opts).await } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let _owner = namespace_owner; + disk.delete_versions(volume, versions, opts).await + } } } @@ -426,6 +441,11 @@ impl Disk { let _owner = namespace_owner; disk.delete_versions_recoverable(volume, versions, opts).await } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let _owner = namespace_owner; + disk.delete_versions_recoverable(volume, versions, opts).await + } } } @@ -455,6 +475,12 @@ impl Disk { disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action) .await } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let _owner = namespace_owner; + disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action) + .await + } } } @@ -462,6 +488,8 @@ impl Disk { match self { Self::Local(disk) => disk.has_clean_active_multipart_source(upload_or_part_path, part_path), Self::Remote(_) => false, + #[cfg(feature = "dst")] + Self::Sim(_) => false, } } @@ -474,6 +502,8 @@ impl Disk { match self { Self::Local(disk) => disk.has_active_multipart_source_matching(upload_path, expected_data_dir, expected_mod_time), Self::Remote(_) => false, + #[cfg(feature = "dst")] + Self::Sim(_) => false, } } @@ -498,6 +528,8 @@ impl Disk { .await } Self::Remote(_) => Ok(None), + #[cfg(feature = "dst")] + Self::Sim(_) => Ok(None), } } @@ -526,6 +558,8 @@ impl Disk { .await } Self::Remote(_) => Ok(false), + #[cfg(feature = "dst")] + Self::Sim(_) => Ok(false), } } @@ -552,6 +586,12 @@ impl Disk { disk.delete_version_recoverable(volume, path, fi, force_del_marker, opts) .await } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let _owner = namespace_owner; + disk.delete_version_recoverable(volume, path, fi, force_del_marker, opts) + .await + } } } pub(crate) async fn set_disk_id_state(&self, id: Option) -> Result<()> { @@ -561,6 +601,8 @@ impl Disk { Ok(()) } Disk::Remote(remote_disk) => remote_disk.set_disk_id(id).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.set_disk_id(id).await, } } @@ -568,6 +610,8 @@ impl Disk { match self { Disk::Local(local_disk) => Some(local_disk.health_tracker_epoch_for_reconnect()), Disk::Remote(_) => None, + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -587,6 +631,11 @@ impl Disk { let _owner = namespace_owner; disk.delete_versions_guarded_recoverable(volume, versions, opts).await } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let _owner = namespace_owner; + disk.delete_versions_guarded_recoverable(volume, versions, opts).await + } } } @@ -594,6 +643,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.get_current_disk_id().await, Disk::Remote(remote_disk) => remote_disk.get_disk_id().await.ok().flatten(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.get_disk_id().await.ok().flatten(), } } } @@ -608,6 +659,8 @@ impl DiskAPI for Disk { match self { Self::Local(disk) => disk.list_multipart_index_roots(bucket, marker).await, Self::Remote(disk) => disk.list_multipart_index_roots(bucket, marker).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.list_multipart_index_roots(bucket, marker).await, } } @@ -615,6 +668,8 @@ impl DiskAPI for Disk { match self { Self::Local(disk) => disk.supports_guarded_delete_versions().await, Self::Remote(disk) => disk.supports_guarded_delete_versions().await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.supports_guarded_delete_versions().await, } } async fn delete_versions_guarded_recoverable( @@ -646,12 +701,16 @@ impl DiskAPI for Disk { match self { Self::Local(disk) => disk.delete_versions_recoverable(volume, versions, opts).await, Self::Remote(disk) => disk.delete_versions_recoverable(volume, versions, opts).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.delete_versions_recoverable(volume, versions, opts).await, } } async fn has_delete_transaction_evidence(&self, volume: &str, object: &str) -> Result { match self { Self::Local(disk) => disk.has_delete_transaction_evidence(volume, object).await, Self::Remote(disk) => disk.has_delete_transaction_evidence(volume, object).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.has_delete_transaction_evidence(volume, object).await, } } async fn discover_delete_transactions_bounded( @@ -663,6 +722,8 @@ impl DiskAPI for Disk { match self { Self::Local(disk) => disk.discover_delete_transactions_bounded(volume, object, max_entries).await, Self::Remote(disk) => disk.discover_delete_transactions_bounded(volume, object, max_entries).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.discover_delete_transactions_bounded(volume, object, max_entries).await, } } async fn discover_delete_transactions( @@ -675,6 +736,8 @@ impl DiskAPI for Disk { match self { Self::Local(disk) => disk.discover_delete_transactions(volume, object, cursor, limit).await, Self::Remote(disk) => disk.discover_delete_transactions(volume, object, cursor, limit).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.discover_delete_transactions(volume, object, cursor, limit).await, } } async fn settle_delete_transaction_bounded( @@ -686,6 +749,8 @@ impl DiskAPI for Disk { match self { Self::Local(disk) => disk.settle_delete_transaction_bounded(volume, request, namespace_owner).await, Self::Remote(disk) => disk.settle_delete_transaction_bounded(volume, request, namespace_owner).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.settle_delete_transaction_bounded(volume, request, namespace_owner).await, } } async fn inspect_delete_transaction_bounded( @@ -704,6 +769,11 @@ impl DiskAPI for Disk { disk.inspect_delete_transaction_bounded(volume, object, transaction, max_entries) .await } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + disk.inspect_delete_transaction_bounded(volume, object, transaction, max_entries) + .await + } } } async fn inspect_delete_transaction( @@ -715,6 +785,8 @@ impl DiskAPI for Disk { match self { Self::Local(disk) => disk.inspect_delete_transaction(volume, object, transaction).await, Self::Remote(disk) => disk.inspect_delete_transaction(volume, object, transaction).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => disk.inspect_delete_transaction(volume, object, transaction).await, } } async fn settle_delete_transaction( @@ -734,12 +806,19 @@ impl DiskAPI for Disk { disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action) .await } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action) + .await + } } } fn to_string(&self) -> String { match self { Disk::Local(local_disk) => local_disk.to_string(), Disk::Remote(remote_disk) => remote_disk.to_string(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.to_string(), } } @@ -747,6 +826,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.is_online().await, Disk::Remote(remote_disk) => remote_disk.is_online().await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.is_online().await, } } @@ -754,6 +835,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.is_local(), Disk::Remote(remote_disk) => remote_disk.is_local(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.is_local(), } } @@ -761,6 +844,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.host_name(), Disk::Remote(remote_disk) => remote_disk.host_name(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.host_name(), } } @@ -768,6 +853,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.endpoint(), Disk::Remote(remote_disk) => remote_disk.endpoint(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.endpoint(), } } @@ -775,6 +862,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.close().await, Disk::Remote(remote_disk) => remote_disk.close().await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.close().await, } } @@ -782,6 +871,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.get_disk_id().await, Disk::Remote(remote_disk) => remote_disk.get_disk_id().await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.get_disk_id().await, } } @@ -789,6 +880,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.set_disk_id(id).await, Disk::Remote(remote_disk) => remote_disk.set_disk_id(id).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.set_disk_id(id).await, } } @@ -796,6 +889,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.path(), Disk::Remote(remote_disk) => remote_disk.path(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.path(), } } @@ -803,6 +898,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.get_disk_location(), Disk::Remote(remote_disk) => remote_disk.get_disk_location(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.get_disk_location(), } } @@ -810,6 +907,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.bucket_creation_witness(volume).await, Disk::Remote(_) => Ok(None), + #[cfg(feature = "dst")] + Disk::Sim(_) => Ok(None), } } @@ -818,6 +917,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.make_volume(volume).await, Disk::Remote(remote_disk) => remote_disk.make_volume(volume).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.make_volume(volume).await, } } @@ -826,6 +927,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.make_volumes(volumes).await, Disk::Remote(remote_disk) => remote_disk.make_volumes(volumes).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.make_volumes(volumes).await, } } @@ -834,6 +937,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.list_volumes().await, Disk::Remote(remote_disk) => remote_disk.list_volumes().await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.list_volumes().await, } } @@ -841,6 +946,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.stat_volume(volume).await, Disk::Remote(remote_disk) => remote_disk.stat_volume(volume).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.stat_volume(volume).await, } } @@ -849,6 +956,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.delete_volume(volume, force_delete).await, Disk::Remote(remote_disk) => remote_disk.delete_volume(volume, force_delete).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.delete_volume(volume, force_delete).await, } } @@ -857,6 +966,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.walk_dir(opts, wr).await, Disk::Remote(remote_disk) => remote_disk.walk_dir(opts, wr).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.walk_dir(opts, wr).await, } } @@ -880,6 +991,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.delete_version(volume, path, fi, force_del_marker, opts).await, Disk::Remote(remote_disk) => remote_disk.delete_version(volume, path, fi, force_del_marker, opts).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.delete_version(volume, path, fi, force_del_marker, opts).await, } } @@ -888,6 +1001,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.delete_versions(volume, versions, opts).await, Disk::Remote(remote_disk) => remote_disk.delete_versions(volume, versions, opts).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.delete_versions(volume, versions, opts).await, } } @@ -896,6 +1011,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.delete_paths(volume, paths).await, Disk::Remote(remote_disk) => remote_disk.delete_paths(volume, paths).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.delete_paths(volume, paths).await, } } @@ -903,6 +1020,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.acquire_snapshot_lease(volume, path).await, Disk::Remote(remote_disk) => remote_disk.acquire_snapshot_lease(volume, path).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.acquire_snapshot_lease(volume, path).await, } } @@ -910,6 +1029,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.release_snapshot_lease(volume, path, token).await, Disk::Remote(remote_disk) => remote_disk.release_snapshot_lease(volume, path, token).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.release_snapshot_lease(volume, path, token).await, } } @@ -917,6 +1038,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.renew_snapshot_lease(volume, path, token).await, Disk::Remote(remote_disk) => remote_disk.renew_snapshot_lease(volume, path, token).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.renew_snapshot_lease(volume, path, token).await, } } @@ -924,6 +1047,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.delete_data_dir(volume, path, opts).await, Disk::Remote(remote_disk) => remote_disk.delete_data_dir(volume, path, opts).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.delete_data_dir(volume, path, opts).await, } } @@ -932,6 +1057,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.write_metadata(_org_volume, volume, path, fi).await, Disk::Remote(remote_disk) => remote_disk.write_metadata(_org_volume, volume, path, fi).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.write_metadata(_org_volume, volume, path, fi).await, } } @@ -940,6 +1067,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.update_metadata(volume, path, fi, opts).await, Disk::Remote(remote_disk) => remote_disk.update_metadata(volume, path, fi, opts).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.update_metadata(volume, path, fi, opts).await, } } @@ -957,6 +1086,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_version(_org_volume, volume, path, version_id, opts).await, Disk::Remote(remote_disk) => remote_disk.read_version(_org_volume, volume, path, version_id, opts).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_version(_org_volume, volume, path, version_id, opts).await, } }; #[cfg(feature = "diagnostic-read-version-caller")] @@ -974,6 +1105,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.batch_read_version(req).await, Disk::Remote(remote_disk) => remote_disk.batch_read_version(req).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.batch_read_version(req).await, } } @@ -982,6 +1115,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_xl(volume, path, read_data).await, Disk::Remote(remote_disk) => remote_disk.read_xl(volume, path, read_data).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_xl(volume, path, read_data).await, } } @@ -1015,6 +1150,11 @@ impl DiskAPI for Disk { disk.rename_data_with_pool_meta_cas(src_volume, src_path, fi, dst_volume, dst_path) .await } + #[cfg(feature = "dst")] + Disk::Sim(disk) => { + disk.rename_data_with_pool_meta_cas(src_volume, src_path, fi, dst_volume, dst_path) + .await + } } } @@ -1022,6 +1162,8 @@ impl DiskAPI for Disk { match self { Disk::Local(disk) => disk.undo_pool_meta_write(volume, path, fi, opts).await, Disk::Remote(disk) => disk.undo_pool_meta_write(volume, path, fi, opts).await, + #[cfg(feature = "dst")] + Disk::Sim(disk) => disk.undo_pool_meta_write(volume, path, fi, opts).await, } } @@ -1032,6 +1174,8 @@ impl DiskAPI for Disk { match self { Disk::Local(disk) => disk.recover_multipart_source(request).await, Disk::Remote(disk) => disk.recover_multipart_source(request).await, + #[cfg(feature = "dst")] + Disk::Sim(disk) => disk.recover_multipart_source(request).await, } } @@ -1039,6 +1183,8 @@ impl DiskAPI for Disk { match self { Disk::Local(disk) => disk.pool_meta_native_recovery(request).await, Disk::Remote(disk) => disk.pool_meta_native_recovery(request).await, + #[cfg(feature = "dst")] + Disk::Sim(disk) => disk.pool_meta_native_recovery(request).await, } } @@ -1047,6 +1193,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.list_dir(_origvolume, volume, dir_path, count).await, Disk::Remote(remote_disk) => remote_disk.list_dir(_origvolume, volume, dir_path, count).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.list_dir(_origvolume, volume, dir_path, count).await, } } @@ -1055,6 +1203,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_file(volume, path).await, Disk::Remote(remote_disk) => remote_disk.read_file(volume, path).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_file(volume, path).await, } } @@ -1063,6 +1213,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_file_stream(volume, path, offset, length).await, Disk::Remote(remote_disk) => remote_disk.read_file_stream(volume, path, offset, length).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_file_stream(volume, path, offset, length).await, } } @@ -1076,6 +1228,8 @@ impl DiskAPI for Disk { match self { Disk::Local(_) => Ok(None), Disk::Remote(remote_disk) => remote_disk.read_file_stream_chunks(volume, path, offset, length).await, + #[cfg(feature = "dst")] + Disk::Sim(_) => Ok(None), } } @@ -1084,6 +1238,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_file_mmap_copy(volume, path, offset, length).await, Disk::Remote(remote_disk) => remote_disk.read_file_mmap_copy(volume, path, offset, length).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_file_mmap_copy(volume, path, offset, length).await, } } @@ -1102,6 +1258,8 @@ impl DiskAPI for Disk { .await } Disk::Remote(remote_disk) => remote_disk.read_file_mmap_copy(volume, path, offset, length).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_file_mmap_copy(volume, path, offset, length).await, } } @@ -1110,6 +1268,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.append_file(volume, path).await, Disk::Remote(remote_disk) => remote_disk.append_file(volume, path).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.append_file(volume, path).await, } } @@ -1118,6 +1278,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.create_file(_origvolume, volume, path, _file_size).await, Disk::Remote(remote_disk) => remote_disk.create_file(_origvolume, volume, path, _file_size).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.create_file(_origvolume, volume, path, _file_size).await, } } @@ -1126,6 +1288,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.rename_file(src_volume, src_path, dst_volume, dst_path).await, Disk::Remote(remote_disk) => remote_disk.rename_file(src_volume, src_path, dst_volume, dst_path).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.rename_file(src_volume, src_path, dst_volume, dst_path).await, } } @@ -1134,6 +1298,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_parts(bucket, paths).await, Disk::Remote(remote_disk) => remote_disk.read_parts(bucket, paths).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_parts(bucket, paths).await, } } @@ -1141,6 +1307,8 @@ impl DiskAPI for Disk { match self { Disk::Local(disk) => disk.rename_file_durable(src_volume, src_path, dst_volume, dst_path).await, Disk::Remote(disk) => disk.rename_file_durable(src_volume, src_path, dst_volume, dst_path).await, + #[cfg(feature = "dst")] + Disk::Sim(disk) => disk.rename_file_durable(src_volume, src_path, dst_volume, dst_path).await, } } @@ -1153,6 +1321,8 @@ impl DiskAPI for Disk { .rename_part(src_volume, src_path, dst_volume, dst_path, meta) .await } + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.rename_part(src_volume, src_path, dst_volume, dst_path, meta).await, } } @@ -1175,6 +1345,12 @@ impl DiskAPI for Disk { .prepare_part_transaction(src_volume, src_path, dst_volume, dst_path, meta) .await } + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => { + sim_disk + .prepare_part_transaction(src_volume, src_path, dst_volume, dst_path, meta) + .await + } } } @@ -1182,6 +1358,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.settle_part_transaction(volume, path, action).await, Disk::Remote(remote_disk) => remote_disk.settle_part_transaction(volume, path, action).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.settle_part_transaction(volume, path, action).await, } } @@ -1196,6 +1374,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.delete(volume, path, opt).await, Disk::Remote(remote_disk) => remote_disk.delete(volume, path, opt).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.delete(volume, path, opt).await, } } @@ -1204,6 +1384,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.verify_file(volume, path, fi).await, Disk::Remote(remote_disk) => remote_disk.verify_file(volume, path, fi).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.verify_file(volume, path, fi).await, } } @@ -1212,6 +1394,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.check_parts(volume, path, fi).await, Disk::Remote(remote_disk) => remote_disk.check_parts(volume, path, fi).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.check_parts(volume, path, fi).await, } } @@ -1220,6 +1404,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_multiple(req).await, Disk::Remote(remote_disk) => remote_disk.read_multiple(req).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_multiple(req).await, } } @@ -1228,6 +1414,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.write_all(volume, path, data).await, Disk::Remote(remote_disk) => remote_disk.write_all(volume, path, data).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.write_all(volume, path, data).await, } } @@ -1235,6 +1423,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.write_format_control(path, data).await, Disk::Remote(remote_disk) => remote_disk.write_format_control(path, data).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.write_format_control(path, data).await, } } @@ -1248,6 +1438,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.compare_and_update_file(volume, path, expected, replacement).await, Disk::Remote(remote_disk) => remote_disk.compare_and_update_file(volume, path, expected, replacement).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.compare_and_update_file(volume, path, expected, replacement).await, } } @@ -1255,6 +1447,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.has_replacement_mount_lease(), Disk::Remote(remote_disk) => remote_disk.has_replacement_mount_lease(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.has_replacement_mount_lease(), } } @@ -1263,6 +1457,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_all(volume, path).await, Disk::Remote(remote_disk) => remote_disk.read_all(volume, path).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_all(volume, path).await, } } @@ -1271,6 +1467,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.disk_info(opts).await, Disk::Remote(remote_disk) => remote_disk.disk_info(opts).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.disk_info(opts).await, } } @@ -1278,6 +1476,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.start_scan(), Disk::Remote(remote_disk) => remote_disk.start_scan(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.start_scan(), } } @@ -1285,6 +1485,8 @@ impl DiskAPI for Disk { match self { Disk::Local(local_disk) => local_disk.read_metadata(volume, path).await, Disk::Remote(remote_disk) => remote_disk.read_metadata(volume, path).await, + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.read_metadata(volume, path).await, } } } @@ -1309,6 +1511,11 @@ impl Disk { .delete_with_scanner_publication_lease(volume, path, opts, scanner_publication_lease_token) .await } + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => { + let _ = (scanner_publication_lease_token, external_guard); + sim_disk.delete(volume, path, opts).await + } } } @@ -1332,6 +1539,12 @@ impl Disk { drop(namespace_owner); result } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let result = disk.delete_version(volume, path, fi, force_del_marker, opts).await; + drop(namespace_owner); + result + } } } @@ -1349,6 +1562,12 @@ impl Disk { drop(namespace_owner); result } + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let result = disk.delete(volume, path, opts).await; + drop(namespace_owner); + result + } } } @@ -1368,6 +1587,11 @@ impl Disk { .await } Self::Remote(disk) => disk.delete_version(volume, path, fi, false, opts).await, + #[cfg(feature = "dst")] + Self::Sim(disk) => { + let _owner = namespace_owner; + disk.delete_version(volume, path, fi, false, opts).await + } } } @@ -1409,6 +1633,15 @@ impl Disk { .rename_data_observed(src_volume, src_path, fi, dst_volume, dst_path, guards) .await } + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => { + let _guards = guards; + RenameDataObservation::unknown( + sim_disk + .rename_data(src_volume, src_path, fi.clone(), dst_volume, dst_path) + .await, + ) + } } } @@ -1462,6 +1695,13 @@ impl Disk { ) .await } + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => { + let _ = (scanner_publication_lease_token, external_guard); + sim_disk + .rename_data(src_volume, src_path, fi.clone(), dst_volume, dst_path) + .await + } } } } @@ -1474,6 +1714,8 @@ impl Disk { match self { Disk::Local(_) => Ok(None), Disk::Remote(remote_disk) => remote_disk.ns_scanner_progress_capability().await, + #[cfg(feature = "dst")] + Disk::Sim(_) => Ok(None), } } @@ -1481,6 +1723,8 @@ impl Disk { match self { Disk::Local(_) => Ok(None), Disk::Remote(remote_disk) => remote_disk.ns_scanner_server_epoch().await, + #[cfg(feature = "dst")] + Disk::Sim(_) => Ok(None), } } @@ -1488,6 +1732,8 @@ impl Disk { match self { Disk::Remote(remote_disk) => remote_disk.open_ns_scanner_stream(request).await, Disk::Local(_) => Err(Error::other("namespace scanner stream requires a remote disk")), + #[cfg(feature = "dst")] + Disk::Sim(_) => Err(Error::other("namespace scanner stream requires a remote disk")), } } @@ -1495,6 +1741,14 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.runtime_state(), Disk::Remote(remote_disk) => remote_disk.runtime_state(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => { + if sim_disk.sim().is_offline() { + RuntimeDriveHealthState::Offline + } else { + RuntimeDriveHealthState::Online + } + } } } @@ -1502,6 +1756,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.is_faulty(), Disk::Remote(remote_disk) => remote_disk.is_faulty(), + #[cfg(feature = "dst")] + Disk::Sim(_) => false, } } @@ -1511,6 +1767,8 @@ impl Disk { match self { Disk::Local(local_disk) => Some(local_disk.retirement_token()), Disk::Remote(_) => None, + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1518,6 +1776,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.offline_duration_secs(), Disk::Remote(remote_disk) => remote_disk.offline_duration_secs(), + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1525,6 +1785,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.last_capacity_snapshot(), Disk::Remote(remote_disk) => remote_disk.last_capacity_snapshot(), + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1532,6 +1794,8 @@ impl Disk { match self { Disk::Local(local_disk) => Some(local_disk.metrics_snapshot()), Disk::Remote(_) => None, + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1540,6 +1804,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.health_check_enabled_for_test(), Disk::Remote(remote_disk) => remote_disk.health_check_enabled_for_test(), + #[cfg(feature = "dst")] + Disk::Sim(_) => false, } } @@ -1547,6 +1813,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.record_capacity_probe(total, used, free), Disk::Remote(remote_disk) => remote_disk.record_capacity_probe(total, used, free), + #[cfg(feature = "dst")] + Disk::Sim(_) => {} } } @@ -1555,6 +1823,10 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.force_runtime_state_for_test(state), Disk::Remote(remote_disk) => remote_disk.force_runtime_state_for_test(state), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => { + sim_disk.set_offline(matches!(state, RuntimeDriveHealthState::Offline)); + } } } @@ -1563,6 +1835,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.force_offline_for_test(), Disk::Remote(remote_disk) => remote_disk.force_offline_for_test(), + #[cfg(feature = "dst")] + Disk::Sim(sim_disk) => sim_disk.set_offline(true), } } } @@ -1586,6 +1860,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.reset_health_for_store_init_retry(), Disk::Remote(remote_disk) => remote_disk.reset_health_for_store_init_retry(), + #[cfg(feature = "dst")] + Disk::Sim(_) => {} } } @@ -1596,6 +1872,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.enable_health_check(), Disk::Remote(remote_disk) => remote_disk.enable_health_check(), + #[cfg(feature = "dst")] + Disk::Sim(_) => {} } } @@ -1605,6 +1883,8 @@ impl Disk { match self { Disk::Local(w) => Some(w.get_object_path_if_local(volume, path)), Disk::Remote(_) => None, + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1617,6 +1897,8 @@ impl Disk { match self { Disk::Local(w) => Some(w.get_object_path_for_io(volume, path)), Disk::Remote(_) => None, + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1624,6 +1906,8 @@ impl Disk { match self { Disk::Local(w) => Some(w.get_bucket_path_for_io(volume)), Disk::Remote(_) => None, + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1634,6 +1918,8 @@ impl Disk { match self { Disk::Local(local_disk) => local_disk.replacement_mount_lease_root(), Disk::Remote(_) => None, + #[cfg(feature = "dst")] + Disk::Sim(_) => None, } } @@ -1643,6 +1929,8 @@ impl Disk { match self { Self::Local(disk) => disk.get_disk().replacement_mount(mount_roots), Self::Remote(_) => None, + #[cfg(feature = "dst")] + Self::Sim(_) => None, } } @@ -1650,6 +1938,8 @@ impl Disk { match self { Self::Local(disk) => disk.get_disk().acquire_replacement_execution_lease().await, Self::Remote(_) => Err(DiskError::other("replacement execution requires a local target")), + #[cfg(feature = "dst")] + Self::Sim(_) => Err(DiskError::other("replacement execution requires a local target")), } } diff --git a/crates/ecstore/src/disk/multipart_source.rs b/crates/ecstore/src/disk/multipart_source.rs index 0ecc8964a6..cada4cf848 100644 --- a/crates/ecstore/src/disk/multipart_source.rs +++ b/crates/ecstore/src/disk/multipart_source.rs @@ -118,6 +118,22 @@ impl ProofVerificationContext { } } + /// Atomically replace the active local endpoint set on a committed live + /// topology hot-reload so removed pools' endpoints are pruned cleanly. + pub(crate) fn replace_topology(&self, candidate: &Self) -> Result<()> { + match (self, candidate) { + (Self::RpcOnly, Self::RpcOnly) => Ok(()), + (Self::Local(existing), Self::Local(next)) => { + if !Arc::ptr_eq(existing, next) { + let endpoints = next.endpoints.read().clone(); + *existing.endpoints.write() = endpoints; + } + Ok(()) + } + _ => Err(DiskError::InconsistentDisk), + } + } + pub(crate) fn validate_endpoint(&self, endpoint: &super::endpoint::Endpoint) -> Result<()> { if let Self::Local(authority) = self && (!endpoint.is_local || !authority.endpoints.read().contains(endpoint)) @@ -165,6 +181,12 @@ pub(crate) fn bind_multipart_proof_snapshot( return Err(DiskError::InconsistentDisk); } super::Disk::Remote(_) => {} + #[cfg(feature = "dst")] + super::Disk::Sim(sim) => { + if sim.disk_index() != slot { + return Err(DiskError::InconsistentDisk); + } + } } } Ok(()) diff --git a/crates/ecstore/src/erasure/codec/bridge.rs b/crates/ecstore/src/erasure/codec/bridge.rs index 65c35db8ee..e3567b7bc9 100644 --- a/crates/ecstore/src/erasure/codec/bridge.rs +++ b/crates/ecstore/src/erasure/codec/bridge.rs @@ -15,6 +15,7 @@ use crate::erasure::codec::shard_buf::ShardBytes; use crate::erasure::codec::workspace::RustfsCodecDecodeWorkspace; use crate::erasure::coding::Erasure; +use crate::erasure::coding::erasure::{data_reconstruction_sources, recover_empty_payload_data_shards}; use rustfs_erasure_codec::galois_8::ReedSolomon; use smallvec::SmallVec; use std::io; @@ -55,44 +56,6 @@ pub(crate) trait ErasureDecodeEngine: Send + Sync + 'static { ) -> io::Result<&'static str>; } -fn data_shards_complete(shards: &[Option], data_shards: usize) -> bool { - shards.len() >= data_shards && shards.iter().take(data_shards).all(Option::is_some) -} - -fn recover_empty_payload_data_shards( - shards: &mut [Option], - data_shards: usize, - parity_shards: usize, -) -> io::Result { - let expected_shards = data_shards + parity_shards; - if shards.len() != expected_shards { - return Err(io::Error::other(format!( - "invalid shard count: got {}, expected {}", - shards.len(), - expected_shards - ))); - } - - let mut present_shards = 0usize; - for shard in shards.iter().filter_map(Option::as_ref) { - present_shards += 1; - if !shard.is_empty() { - return Ok(false); - } - } - if present_shards == 0 || present_shards < data_shards { - return Ok(false); - } - - for shard in shards.iter_mut().take(data_shards) { - if shard.is_none() { - *shard = Some(S::from(Vec::new())); - } - } - - Ok(true) -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct LegacyDecodeWorkspace { shard_len: usize, @@ -163,12 +126,12 @@ impl ErasureDecodeEngine for LegacyEcDecodeEngine { shards: &mut [Option], _workspace: &mut Self::Workspace, ) -> io::Result<&'static str> { - if data_shards_complete(shards, self.erasure.data_shards) { - return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE); - } - - self.erasure.decode_data_with_reconstruction_verification(shards)?; - Ok(GET_RECONSTRUCT_OUTCOME_LEGACY_CALLED) + let reconstructed = self.erasure.decode_data_with_reconstruction_verification(shards)?; + Ok(if reconstructed { + GET_RECONSTRUCT_OUTCOME_LEGACY_CALLED + } else { + GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE + }) } } @@ -190,41 +153,19 @@ impl RustfsCodecDecodeEngine { }) } - fn codec(&self) -> io::Result>> { - if self.parity_shards == 0 { - return Ok(None); - } - + fn codec(&self) -> io::Result<&ReedSolomon> { if let Some(codec) = self.codec.get() { - return Ok(Some(Arc::clone(codec))); + return Ok(codec); } let codec = Arc::new( ReedSolomon::new(self.data_shards, self.parity_shards) .map_err(|err| io::Error::other(format!("Failed to create RustFS codec decode engine: {err:?}")))?, ); - if self.codec.set(Arc::clone(&codec)).is_err() { - return Ok(self.codec.get().map(Arc::clone).or(Some(codec))); - } - Ok(Some(codec)) + Ok(self.codec.get_or_init(|| codec)) } - fn needs_source_parity_verification(&self, shards: &[Option]) -> bool { - let missing_data_source = shards.iter().take(self.data_shards).any(|shard| shard.is_none()); - let available_shards = shards.iter().filter(|shard| shard.is_some()).count(); - missing_data_source && available_shards > self.data_shards - } - - fn verify_source_parity( - &self, - codec: &ReedSolomon, - shards: &[Option], - needs_verification: bool, - ) -> io::Result<()> { - if !needs_verification { - return Ok(()); - } - + fn verify_source_parity(&self, codec: &ReedSolomon, shards: &[Option]) -> io::Result<()> { // All slots must be present here: the verification path reconstructs // missing parity alongside data (see `reconstruct_into`), so a `None` // slot is an internal invariant violation, not a degraded-read state. @@ -291,45 +232,61 @@ impl ErasureDecodeEngine for RustfsCodecDecodeEngine { shards: &mut [Option], _workspace: &mut Self::Workspace, ) -> io::Result<&'static str> { - if data_shards_complete(shards, self.data_shards) { + let Some(available) = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)? else { return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE); - } - if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? { + }; + if recover_empty_payload_data_shards(shards, self.data_shards) { return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_EMPTY_PAYLOAD); } - if let Some(codec) = self.codec()? { - let needs_source_parity_verification = self.needs_source_parity_verification(shards); - // The codec works on plain vectors: hand it the shard bytes (a - // move for heap buffers, a copy out of arena blocks) and put the - // results back. Reconstruction is the rare path, so the copy is - // acceptable. - let mut owned: Vec>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect(); - let vec_shards = owned.as_mut_slice(); - if needs_source_parity_verification { - // Rebuild missing parity together with missing data so the - // shard set is complete for `verify`. Rebuilt parity is - // consistent with the reconstructed data by construction, so - // the verification below is equivalent to checking only the - // originally-present source parity — the same semantics as the - // legacy `decode_data_with_reconstruction_verification` path. - // Rebuilding only data here would leave missing parity slots - // as `None` and misreport a recoverable degraded read (for - // example one missing data shard plus one missing parity - // shard) as an inconsistent-source failure. - codec - .reconstruct_opt(vec_shards) - .map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))?; - } else { - codec - .reconstruct_data_opt(vec_shards) - .map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))?; - } - for (slot, shard) in shards.iter_mut().zip(owned) { - *slot = shard.map(S::from); - } - self.verify_source_parity(&codec, shards, needs_source_parity_verification)?; + let needs_source_parity_verification = available > self.data_shards; + let codec = self.codec()?; + let mut missing_parity: SmallVec<[usize; 16]> = SmallVec::new(); + if needs_source_parity_verification { + missing_parity.extend( + shards + .iter() + .enumerate() + .skip(self.data_shards) + .filter_map(|(index, slot)| slot.is_none().then_some(index)), + ); } + // The codec works on plain vectors: hand it the shard bytes (a + // move for heap buffers, a copy out of arena blocks) and put the + // results back. Reconstruction is the rare path, so the copy is + // acceptable. + let mut owned: Vec>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect(); + let result = if needs_source_parity_verification { + // Rebuild missing parity together with missing data so the + // shard set is complete for `verify`. Rebuilt parity is + // consistent with the reconstructed data by construction, so + // the verification below is equivalent to checking only the + // originally-present source parity — the same semantics as the + // legacy `decode_data_with_reconstruction_verification` path. + // Rebuilding only data here would leave missing parity slots + // as `None` and misreport a recoverable degraded read (for + // example one missing data shard plus one missing parity + // shard) as an inconsistent-source failure. + codec.reconstruct_opt(owned.as_mut_slice()) + } else { + codec.reconstruct_data_opt(owned.as_mut_slice()) + } + .map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}"))) + .and_then(|()| { + if needs_source_parity_verification { + self.verify_source_parity(codec, &owned)?; + } + Ok(()) + }); + if result.is_err() { + for index in missing_parity { + owned[index] = None; + } + } + for (slot, shard) in shards.iter_mut().zip(owned) { + *slot = shard.map(S::from); + } + result?; Ok(GET_RECONSTRUCT_OUTCOME_RUSTFS_CALLED) } @@ -483,7 +440,7 @@ mod tests { fn data_shards_complete_ignores_parity_slots() { let shards = vec![Some(vec![1]), Some(vec![2]), None]; - assert!(data_shards_complete(&shards, 2)); + assert_eq!(data_reconstruction_sources(&shards, 2, 1).expect("complete data"), None); } #[test] @@ -491,8 +448,8 @@ mod tests { let missing_data = vec![Some(vec![1]), None, Some(vec![3])]; let short = vec![Some(vec![1])]; - assert!(!data_shards_complete(&missing_data, 2)); - assert!(!data_shards_complete(&short, 2)); + assert_eq!(data_reconstruction_sources(&missing_data, 2, 1).expect("valid shape"), Some(2)); + assert!(data_reconstruction_sources(&short, 2, 1).is_err()); } #[test] @@ -585,18 +542,22 @@ mod tests { #[test] fn rustfs_codec_decode_engine_errors_on_insufficient_shards_like_legacy() { let erasure = Erasure::new(4, 2, 16); - let mut legacy_shards = encoded_shards(&erasure, b"insufficient shards must fail"); - let mut rustfs_shards = legacy_shards.clone(); - for index in [0, 1, 2] { - legacy_shards[index] = None; - rustfs_shards[index] = None; - } - let legacy = LegacyEcDecodeEngine::new(erasure.clone()); let rustfs = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created"); + for payload in [b"".as_slice(), b"insufficient shards must fail"] { + let mut original = encoded_shards(&erasure, payload); + original[..3].fill(None); + let mut legacy_shards = original.clone(); + let mut rustfs_shards = original.clone(); - assert!(reconstruct_with(&legacy, &mut legacy_shards).is_err()); - assert!(reconstruct_with(&rustfs, &mut rustfs_shards).is_err()); + let legacy_error = reconstruct_with(&legacy, &mut legacy_shards).expect_err("legacy needs quorum"); + let rustfs_error = reconstruct_with(&rustfs, &mut rustfs_shards).expect_err("native needs quorum"); + assert_eq!(legacy_error.kind(), io::ErrorKind::InvalidData); + assert_eq!(rustfs_error.kind(), io::ErrorKind::InvalidData); + assert_eq!(legacy_shards, original); + assert_eq!(rustfs_shards, original); + } + assert!(!rustfs.codec_is_initialized()); } #[test] @@ -653,12 +614,14 @@ mod tests { panic!("test parity shard should be present"); }; corrupt_parity[0] ^= 0x80; + let source_parity = shards[erasure.data_shards..].to_vec(); let engine = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created"); let err = reconstruct_with(&engine, &mut shards).expect_err("corrupt surviving parity must still be rejected"); assert_eq!(err.kind(), io::ErrorKind::InvalidData); assert!(err.to_string().contains("inconsistent read source shards")); + assert_eq!(&shards[erasure.data_shards..], source_parity); } #[test] @@ -774,19 +737,33 @@ mod tests { } #[test] - fn rustfs_codec_decode_engine_returns_called_without_parity_codec() { + fn streaming_decode_engines_reject_incomplete_zero_parity_shards() { + fn check(engine: &E) { + let mut workspace = engine.prepare_workspace(4).expect("workspace should be prepared"); + for malformed in [ + vec![None, Some(vec![2; 4])], + vec![Some(vec![2; 4]); 3], + vec![None, Some(Vec::new())], + ] { + let mut shards = malformed.clone(); + let error = engine + .reconstruct_into(&mut shards, &mut workspace) + .expect_err("invalid shard set"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(shards, malformed); + } + + let mut shards = vec![Some(vec![2; 4]); 2]; + let outcome = engine.reconstruct_into(&mut shards, &mut workspace).expect("complete data"); + assert_eq!(outcome, GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE); + assert_eq!(shards, vec![Some(vec![2; 4]); 2]); + } + let erasure = Erasure::new(2, 0, 16); let engine = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created"); - let mut workspace = engine.prepare_workspace(4).expect("workspace should be prepared"); - let mut shards = vec![None, Some(vec![2, 2, 2, 2])]; - - let outcome = engine - .reconstruct_into(&mut shards, &mut workspace) - .expect("zero parity engine should not allocate codec"); - - assert_eq!(outcome, GET_RECONSTRUCT_OUTCOME_RUSTFS_CALLED); - assert!(shards[0].is_none()); + check(&engine); assert!(!engine.codec_is_initialized()); + check(&LegacyEcDecodeEngine::new(erasure)); } #[test] diff --git a/crates/ecstore/src/erasure/coding/decode.rs b/crates/ecstore/src/erasure/coding/decode.rs index 29755fd7d7..1fa86bdae0 100644 --- a/crates/ecstore/src/erasure/coding/decode.rs +++ b/crates/ecstore/src/erasure/coding/decode.rs @@ -4396,6 +4396,37 @@ mod tests { } } + #[tokio::test] + async fn zero_parity_full_and_prefix_reads_reject_an_incomplete_stripe_before_output() { + let block_size = 64; + for data_shards in [1, 4] { + let erasure = Erasure::new(data_shards, 0, block_size); + let shard_size = erasure.shard_size(); + for length in [block_size, shard_size / 2] { + let mut output = Vec::new(); + let readers = make_test_readers(data_shards, shard_size, 1, &HashAlgorithm::HighwayHash256, &[], &[]).await; + let (written, error) = erasure.decode(&mut output, readers, 0, length, block_size).await; + assert!(error.is_none(), "complete stripe: {error:?}"); + assert_eq!(written, length); + assert_eq!(output.len(), length); + + let last = [data_shards - 1]; + for (missing, corrupt) in [(&last[..], &[][..]), (&[][..], &last[..])] { + output.clear(); + let readers = + make_test_readers(data_shards, shard_size, 1, &HashAlgorithm::HighwayHash256, missing, corrupt).await; + let (written, error) = erasure.decode(&mut output, readers, 0, length, block_size).await; + assert_eq!( + error.expect("incomplete stripe must fail").to_string(), + Error::ErasureReadQuorum.to_string() + ); + assert_eq!(written, 0); + assert!(output.is_empty()); + } + } + } + } + #[tokio::test] #[serial_test::serial] async fn copy_source_below_read_quorum_fails_before_output() { diff --git a/crates/ecstore/src/erasure/coding/erasure.rs b/crates/ecstore/src/erasure/coding/erasure.rs index da474630f8..81169496df 100644 --- a/crates/ecstore/src/erasure/coding/erasure.rs +++ b/crates/ecstore/src/erasure/coding/erasure.rs @@ -246,6 +246,22 @@ impl LegacyReedSolomonEncoder { return Ok(()); } let shard_len = shards[0].len(); + let (data, parity) = shards + .split_at_mut_checked(self.data_shards) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing data shards for SIMD encoding"))?; + self.with_encoded_parity(data.iter().map(|shard| &**shard), shard_len, |result| { + for (output, recovery) in parity.iter_mut().zip(result.recovery_iter()) { + output.copy_from_slice(recovery); + } + }) + } + + fn with_encoded_parity<'a, T>( + &self, + data: impl IntoIterator, + shard_len: usize, + use_parity: impl FnOnce(&reed_solomon_simd::EncoderResult<'_>) -> T, + ) -> io::Result { let cached_encoder = self .encoder_cache .write() @@ -274,7 +290,7 @@ impl LegacyReedSolomonEncoder { }, )?; let encoder = &mut workspace.codec; - for (i, shard) in shards.iter().enumerate().take(self.data_shards) { + for (i, shard) in data.into_iter().enumerate() { encoder .add_original_shard(shard) .map_err(|e| io::Error::other(format!("Failed to add shard {i}: {e:?}")))?; @@ -282,11 +298,7 @@ impl LegacyReedSolomonEncoder { let result = encoder .encode() .map_err(|e| io::Error::other(format!("SIMD encoding failed: {e:?}")))?; - for (i, recovery_shard) in result.recovery_iter().enumerate() { - if i + self.data_shards < shards.len() { - shards[i + self.data_shards].copy_from_slice(recovery_shard); - } - } + let output = use_parity(&result); drop(result); if self.should_cache_workspace(shard_len) { let mut cache = self @@ -297,20 +309,10 @@ impl LegacyReedSolomonEncoder { *cache = Some(workspace); } } - Ok(()) + Ok(output) } - fn reconstruct_data(&self, shards: &mut [Option]) -> io::Result<()> { - if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? { - return Ok(()); - } - // Every data shard present: nothing to rebuild. The conversions - // below would copy each shard out of its arena block and hand back - // heap buffers, which also defeats the zero-copy emit. - if shards.iter().take(self.data_shards).all(Option::is_some) { - return Ok(()); - } - + fn reconstruct_missing_data(&self, shards: &mut [Option]) -> io::Result<()> { let shard_len = shards .iter() .find_map(|s| s.as_ref().map(|v| v.len())) @@ -361,14 +363,12 @@ impl LegacyReedSolomonEncoder { .decode() .map_err(|e| io::Error::other(format!("SIMD decode error: {e:?}")))?; - for (i, shard_opt) in shards.iter_mut().enumerate() { - if shard_opt.is_none() && i < self.data_shards { - for (restored_index, restored_data) in result.restored_original_iter() { - if restored_index == i { - *shard_opt = Some(S::from(restored_data.to_vec())); - break; - } - } + for (index, shard) in shards[..self.data_shards].iter_mut().enumerate() { + if shard.is_none() { + let restored = result + .restored_original(index) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing data shard after SIMD reconstruction"))?; + *shard = Some(S::from(restored.to_vec())); } } @@ -387,11 +387,6 @@ impl LegacyReedSolomonEncoder { Ok(()) } - fn reconstruct(&self, shards: &mut [Option]) -> io::Result<()> { - self.reconstruct_data(shards)?; - self.encode_parity(shards) - } - fn verify(&self, shards: &[&[u8]]) -> io::Result { let expected_shards = self.data_shards + self.parity_shards; if shards.len() != expected_shards { @@ -430,6 +425,25 @@ impl LegacyReedSolomonEncoder { fn encode_parity(&self, shards: &mut [Option]) -> io::Result<()> { encode_parity_shards(shards, self.data_shards, self.parity_shards, |shards| self.encode(shards)) } + + fn verify_and_rebuild_parity(&self, shards: &mut [Option]) -> io::Result> { + verify_rebuilt_parity(shards, self.data_shards, |data, parity, shard_len| { + self.with_encoded_parity(data.iter().copied(), shard_len, |result| { + let mismatch = parity + .iter() + .zip(result.recovery_iter()) + .position(|(slot, rebuilt)| slot.as_ref().is_some_and(|source| source.as_slice() != rebuilt)); + if mismatch.is_none() { + for (slot, rebuilt) in parity.iter_mut().zip(result.recovery_iter()) { + if slot.is_none() { + *slot = Some(S::from(rebuilt.to_vec())); + } + } + } + mismatch + }) + }) + } } /// Reed-Solomon encoder using rustfs-erasure-codec @@ -485,31 +499,36 @@ impl ReedSolomonEncoder { } /// Reconstruct missing data shards. + /// + /// # Errors + /// Returns an error for incorrect shard counts, insufficient source + /// shards, or failed reconstruction. pub fn reconstruct_data(&self, shards: &mut [Option]) -> io::Result<()> { - if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? { + let sources = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)?; + if self.parity_shards == 0 { return Ok(()); } - // Every data shard present: nothing to rebuild. The conversions - // below would copy each shard out of its arena block and hand back - // heap buffers, which also defeats the zero-copy emit. - if shards.iter().take(self.data_shards).all(Option::is_some) { - return Ok(()); + let rs = self + .encoder + .as_deref() + .ok_or_else(|| io::Error::other("missing Reed-Solomon encoder"))?; + if sources.is_some() && !recover_empty_payload_data_shards(shards, self.data_shards) { + Self::reconstruct_missing_data(rs, shards)?; } + Ok(()) + } - if let Some(ref rs) = self.encoder { - // The codec works on plain vectors: a move for vectors, a copy out - // of arena blocks (reconstruction is the rare path). - let mut owned: Vec>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect(); - let result = rs - .reconstruct_data(owned.as_mut_slice()) - .map_err(|e| io::Error::other(format!("Reed-Solomon reconstruct failed: {e:?}"))); - for (slot, shard) in shards.iter_mut().zip(owned) { - *slot = shard.map(S::from); - } - result - } else { - Ok(()) + fn reconstruct_missing_data(rs: &ReedSolomon, shards: &mut [Option]) -> io::Result<()> { + // The codec works on plain vectors: a move for vectors, a copy out + // of arena blocks (reconstruction is the rare path). + let mut owned: Vec>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect(); + let result = rs + .reconstruct_data(owned.as_mut_slice()) + .map_err(|e| io::Error::other(format!("Reed-Solomon reconstruct failed: {e:?}"))); + for (slot, shard) in shards.iter_mut().zip(owned) { + *slot = shard.map(S::from); } + result } /// Reconstruct missing data shards and regenerate parity shards. @@ -544,6 +563,44 @@ impl ReedSolomonEncoder { fn encode_parity(&self, shards: &mut [Option]) -> io::Result<()> { encode_parity_shards(shards, self.data_shards, self.parity_shards, |shards| self.encode(shards)) } + + fn verify_and_rebuild_parity(&self, rs: &ReedSolomon, shards: &mut [Option]) -> io::Result> { + verify_rebuilt_parity(shards, self.data_shards, |data, parity, shard_len| { + let missing_count = parity.iter().filter(|slot| slot.is_none()).count(); + let source_count = parity.len() - missing_count; + let scratch_len = shard_len.checked_mul(source_count).ok_or(io::ErrorKind::OutOfMemory)?; + let mut scratch = vec![0; scratch_len]; + let mut rebuilt: SmallVec<[S; 16]> = (0..missing_count).map(|_| S::from(vec![0; shard_len])).collect(); + + let mut source_outputs = scratch.chunks_exact_mut(shard_len); + let mut missing_outputs = rebuilt.iter_mut().map(ShardBytes::as_mut_slice); + let mut outputs: SmallVec<[&mut [u8]; 16]> = SmallVec::with_capacity(parity.len()); + for slot in parity.iter() { + let output = if slot.is_some() { + source_outputs.next() + } else { + missing_outputs.next() + }; + outputs.push(output.ok_or_else(|| io::Error::other("missing parity verification output"))?); + } + rs.encode_sep(data, &mut outputs) + .map_err(|error| io::Error::other(format!("Reed-Solomon encode failed: {error:?}")))?; + drop(outputs); + + let mismatch = parity + .iter() + .enumerate() + .filter_map(|(index, slot)| slot.as_ref().map(|source| (index, source))) + .zip(scratch.chunks_exact(shard_len)) + .find_map(|((index, source), expected)| (source.as_slice() != expected).then_some(index)); + if mismatch.is_none() { + for (slot, shard) in parity.iter_mut().filter(|slot| slot.is_none()).zip(rebuilt) { + *slot = Some(shard); + } + } + Ok(mismatch) + }) + } } fn cached_modern_reed_solomon(data_shards: usize, parity_shards: usize) -> Result, rustfs_erasure_codec::Error> { @@ -666,29 +723,79 @@ where encode(shard_refs) } -fn recover_empty_payload_data_shards( +// Keep surviving parity read-only. Backends can compare against their own +// encoding workspace or generate into scratch without copying the sources. +fn verify_rebuilt_parity( shards: &mut [Option], data_shards: usize, - parity_shards: usize, -) -> io::Result { - let expected_shards = data_shards + parity_shards; - if shards.len() != expected_shards { - return Err(io::Error::other(format!( - "invalid shard count: got {}, expected {}", - shards.len(), - expected_shards - ))); - } - - let mut has_present_shard = false; - for shard in shards.iter().filter_map(|shard| shard.as_ref()) { - has_present_shard = true; - if !shard.is_empty() { - return Ok(false); + rebuild: impl FnOnce(&[&[u8]], &mut [Option], usize) -> io::Result>, +) -> io::Result> { + let (data, parity) = shards.split_at_mut(data_shards); + let shard_len = data + .first() + .and_then(Option::as_ref) + .map(ShardBytes::len) + .ok_or_else(|| io::Error::other("missing data shard after reconstruction"))?; + let mut inputs: SmallVec<[&[u8]; 16]> = SmallVec::with_capacity(data.len()); + for slot in data { + let shard = slot + .as_ref() + .ok_or_else(|| io::Error::other("missing data shard after reconstruction"))?; + if shard.len() != shard_len { + return Err(io::Error::other("inconsistent shard length after reconstruction")); } + inputs.push(shard.as_slice()); } - if !has_present_shard { - return Ok(false); + if parity.iter().flatten().any(|shard| shard.len() != shard_len) { + return Err(io::Error::other("inconsistent shard length after reconstruction")); + } + if shard_len == 0 { + for slot in parity { + slot.get_or_insert_with(|| S::from(Vec::new())); + } + return Ok(None); + } + rebuild(&inputs, parity, shard_len) +} + +/// Returns the available source count when any data shard needs reconstruction. +/// Complete data returns `None` without scanning the parity slots. +pub(crate) fn data_reconstruction_sources( + shards: &[Option], + data_shards: usize, + parity_shards: usize, +) -> io::Result> { + let expected = data_shards.checked_add(parity_shards).ok_or(io::ErrorKind::InvalidData)?; + if shards.len() != expected { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("invalid shard count: got {}, expected {expected}", shards.len()), + )); + } + if shards[..data_shards].iter().all(Option::is_some) { + return Ok(None); + } + if parity_shards == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "missing data shard with zero parity")); + } + let available = shards.iter().flatten().count(); + if available < data_shards { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "insufficient source shards to reconstruct data", + )); + } + Ok(Some(available)) +} + +/// Recovers an empty stripe after its source quorum has been established. +pub(crate) fn recover_empty_payload_data_shards(shards: &mut [Option], data_shards: usize) -> bool { + let mut present = shards.iter().flatten(); + let Some(first) = present.next() else { + return false; + }; + if !first.is_empty() || present.any(|shard| !shard.is_empty()) { + return false; } for shard in shards.iter_mut().take(data_shards) { @@ -696,7 +803,22 @@ fn recover_empty_payload_data_shards( *shard = Some(S::from(Vec::new())); } } - Ok(true) + true +} + +#[derive(Clone, Copy)] +enum DecodeMode { + Data, + All, + Verified, + VerifiedLockstep, +} + +fn validate_decoder_geometry(expected: (usize, usize), actual: (usize, usize)) -> io::Result<()> { + if expected != actual { + return Err(io::Error::new(io::ErrorKind::InvalidData, "erasure decoder geometry mismatch")); + } + Ok(()) } /// Erasure coding utility for data reliability using Reed-Solomon codes. @@ -1001,106 +1123,110 @@ impl Erasure { /// # Arguments /// * `shards` - Mutable slice of optional shard data. Missing shards should be `None`. /// - /// # Returns - /// Ok if reconstruction succeeds, error otherwise. + /// # Errors + /// Returns an error for an incorrect shard count, insufficient source + /// shards, or failed reconstruction. #[hotpath::measure(impl_type = "Erasure")] pub fn decode_data(&self, shards: &mut [Option]) -> io::Result<()> { - if self.parity_shards > 0 { - if self.uses_legacy { - if let Some(encoder) = self.legacy_encoder.as_ref() { - encoder.reconstruct_data(shards)?; - } else { - warn!("parity_shards > 0, uses_legacy but legacy_encoder is None"); - } - } else if let Some(encoder) = self.encoder.as_ref() { - encoder.reconstruct_data(shards)?; - } else { - warn!("parity_shards > 0, but encoder is None"); - } - } - - Ok(()) + self.decode_shards(shards, DecodeMode::Data).map(drop) } /// Decode and reconstruct missing data shards, then regenerate parity shards. + /// + /// # Errors + /// Returns an error for an incorrect shard count, failed reconstruction, + /// or failed parity generation. #[hotpath::measure(impl_type = "Erasure")] pub fn decode_data_and_parity(&self, shards: &mut [Option]) -> io::Result<()> { - if self.parity_shards > 0 { - if self.uses_legacy { - if let Some(encoder) = self.legacy_encoder.as_ref() { - encoder.reconstruct(shards)?; - } else { - warn!("parity_shards > 0, uses_legacy but legacy_encoder is None"); - } - } else if let Some(encoder) = self.encoder.as_ref() { - encoder.reconstruct(shards)?; - } else { - warn!("parity_shards > 0, but encoder is None"); - } - } - - Ok(()) + self.decode_shards(shards, DecodeMode::All).map(drop) } - pub(crate) fn decode_data_with_reconstruction_verification(&self, shards: &mut [Option]) -> io::Result<()> { - self.decode_data_with_reconstruction_verification_policy(shards, false) + /// Returns whether any data shard had to be reconstructed. + #[hotpath::measure(impl_type = "Erasure")] + pub(crate) fn decode_data_with_reconstruction_verification( + &self, + shards: &mut [Option], + ) -> io::Result { + self.decode_shards(shards, DecodeMode::Verified) } + #[hotpath::measure(impl_type = "Erasure")] pub(crate) fn decode_data_with_reconstruction_verification_for_lockstep( &self, shards: &mut [Option], - ) -> io::Result<()> { - self.decode_data_with_reconstruction_verification_policy(shards, true) + ) -> io::Result { + self.decode_shards(shards, DecodeMode::VerifiedLockstep) } - fn decode_data_with_reconstruction_verification_policy( - &self, - shards: &mut [Option], - require_surplus_source: bool, - ) -> io::Result<()> { - let missing_data_source = shards.iter().take(self.data_shards).any(|shard| shard.is_none()); - let available_shards = shards.iter().filter(|shard| shard.is_some()).count(); - if require_surplus_source && missing_data_source && available_shards == self.data_shards { + fn decode_shards(&self, shards: &mut [Option], mode: DecodeMode) -> io::Result { + let sources = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)?; + if self.parity_shards == 0 { + return Ok(false); + } + + if matches!(mode, DecodeMode::VerifiedLockstep) && sources == Some(self.data_shards) { return Err(io::Error::new( io::ErrorKind::InvalidData, "insufficient source shards to verify reconstructed data", )); } - let source_parity = if missing_data_source && available_shards > self.data_shards { - shards - .iter() - .enumerate() - .skip(self.data_shards) - .filter_map(|(index, shard)| shard.as_ref().map(|shard| (index, shard.as_slice().to_vec()))) - .collect::>() + let verify_parity = matches!(mode, DecodeMode::Verified | DecodeMode::VerifiedLockstep) + && sources.is_some_and(|available| available > self.data_shards); + let missing = sources.is_some(); + let needs_decode = |shards: &mut [Option]| missing && !recover_empty_payload_data_shards(shards, self.data_shards); + let geometry = (self.data_shards, self.parity_shards); + let mismatch = if self.uses_legacy { + let encoder = self + .legacy_encoder + .as_ref() + .ok_or_else(|| io::Error::other("missing legacy erasure encoder"))?; + validate_decoder_geometry(geometry, (encoder.data_shards, encoder.parity_shards))?; + if needs_decode(shards) { + encoder.reconstruct_missing_data(shards)?; + } + if verify_parity { + encoder.verify_and_rebuild_parity(shards)? + } else { + if matches!(mode, DecodeMode::All) { + encoder.encode_parity(shards)?; + } + None + } } else { - Vec::new() + let encoder = self + .encoder + .as_ref() + .ok_or_else(|| io::Error::other("missing erasure encoder"))?; + validate_decoder_geometry(geometry, (encoder.data_shards, encoder.parity_shards))?; + let rs = encoder + .encoder + .as_deref() + .ok_or_else(|| io::Error::other("missing Reed-Solomon encoder"))?; + if needs_decode(shards) { + ReedSolomonEncoder::reconstruct_missing_data(rs, shards)?; + } + if verify_parity { + encoder.verify_and_rebuild_parity(rs, shards)? + } else { + if matches!(mode, DecodeMode::All) { + encoder.encode_parity(shards)?; + } + None + } }; - if source_parity.is_empty() { - return self.decode_data(shards); + if let Some(index) = mismatch { + let index = self.data_shards + index; + warn!( + shard_index = index, + data_shards = self.data_shards, + parity_shards = self.parity_shards, + "erasure decode rejected inconsistent read source shards" + ); + return Err(io::Error::new(io::ErrorKind::InvalidData, "inconsistent read source shards")); } - self.decode_data_and_parity(shards)?; - for (index, source) in source_parity { - let Some(rebuilt) = shards[index].as_ref() else { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "missing rebuilt parity shard after read verification", - )); - }; - if rebuilt.as_slice() != source.as_slice() { - warn!( - shard_index = index, - data_shards = self.data_shards, - parity_shards = self.parity_shards, - "erasure decode rejected inconsistent read source shards" - ); - return Err(io::Error::new(io::ErrorKind::InvalidData, "inconsistent read source shards")); - } - } - - Ok(()) + Ok(missing) } pub(crate) fn verify_data_and_parity(&self, shards: &[Option]) -> io::Result { @@ -1341,7 +1467,7 @@ mod tests { let mut decoded = vec![None, Some(shards[1].clone()), Some(shards[2].clone())]; let (resources, _) = test_resource_units(1); with_optional_resource_unit(Some(resources.with_memory_budget(memory.clone())), async { - codec.reconstruct_data(&mut decoded).expect("accounted decoder"); + codec.reconstruct_missing_data(&mut decoded).expect("accounted decoder"); }) .await; assert_eq!(decoded[0].as_deref(), Some(shards[0].as_slice())); @@ -1896,10 +2022,7 @@ mod tests { assert!(err.to_string().contains("inconsistent shard length")); let mut no_present_empty_payload: Vec>> = vec![None, None, None]; - assert!( - !recover_empty_payload_data_shards(&mut no_present_empty_payload, 2, 1) - .expect("all-missing empty payload marker should not be synthesized") - ); + assert!(!recover_empty_payload_data_shards(&mut no_present_empty_payload, 2)); } #[test] @@ -2113,6 +2236,185 @@ mod tests { } } + #[test] + fn zero_parity_reconstruction_requires_exact_geometry_and_all_data() { + type Decode<'a> = (&'a str, &'a dyn Fn(&mut [Option>]) -> io::Result<()>); + + for data_shards in [1, 4] { + for uses_legacy in [false, true] { + let erasure = Erasure::new_with_options(data_shards, 0, 64, uses_legacy); + let encoder = ReedSolomonEncoder::new(data_shards, 0).expect("zero parity encoder"); + let decoders: [Decode<'_>; 6] = [ + ("data", &|shards| erasure.decode_data(shards)), + ("data and parity", &|shards| erasure.decode_data_and_parity(shards)), + ("verified", &|shards| { + erasure.decode_data_with_reconstruction_verification(shards).map(drop) + }), + ("lockstep", &|shards| { + erasure + .decode_data_with_reconstruction_verification_for_lockstep(shards) + .map(drop) + }), + ("direct data", &|shards| encoder.reconstruct_data(shards)), + ("direct data and parity", &|shards| encoder.reconstruct(shards)), + ]; + let complete = vec![Some(vec![42]); data_shards]; + let empty_payload = vec![Some(Vec::new()); data_shards]; + let mut missing = complete.clone(); + missing[data_shards - 1] = None; + let mut missing_from_empty = empty_payload.clone(); + missing_from_empty[data_shards - 1] = None; + let mut overlong = complete.clone(); + overlong.push(None); + for (name, decode) in decoders { + for malformed in [&complete[..data_shards - 1], &overlong, &missing, &missing_from_empty] { + let mut shards = malformed.to_vec(); + let error = decode(&mut shards).expect_err(name); + assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{name}: {error}"); + assert_eq!(shards, malformed, "{name} must reject before mutation"); + } + for expected in [&complete, &empty_payload] { + let mut shards = expected.clone(); + decode(&mut shards).expect(name); + assert_eq!(&shards, expected, "{name} must preserve complete data"); + } + } + } + } + } + + #[test] + fn complete_data_decode_does_not_read_payloads() { + struct Present; + + impl AsRef<[u8]> for Present { + fn as_ref(&self) -> &[u8] { + panic!("complete data must not enter payload inspection"); + } + } + impl AsMut<[u8]> for Present { + fn as_mut(&mut self) -> &mut [u8] { + panic!("complete data must not be rewritten"); + } + } + impl From> for Present { + fn from(_: Vec) -> Self { + panic!("complete data must not allocate replacement shards"); + } + } + impl ShardBytes for Present { + fn into_vec(self) -> Vec { + panic!("complete data must not be copied"); + } + } + + for uses_legacy in [false, true] { + let erasure = Erasure::new_with_options(2, 2, 64, uses_legacy); + let mut shards = [Some(Present), Some(Present), None, Some(Present)]; + erasure.decode_data(&mut shards).expect("complete data"); + assert!( + !erasure + .decode_data_with_reconstruction_verification(&mut shards) + .expect("complete data"), + "missing parity must not trigger data reconstruction" + ); + } + } + + #[test] + fn reconstruction_errors_when_selected_encoder_is_absent() { + for uses_legacy in [false, true] { + let mut erasure = Erasure::new_with_options(2, 1, 64, uses_legacy); + let mut shards = vec![Some(vec![1]); 3]; + erasure.encoder = None; + erasure.legacy_encoder = None; + assert_eq!( + erasure.decode_data(&mut shards).expect_err("missing encoder").kind(), + io::ErrorKind::Other + ); + assert_eq!( + erasure + .decode_data_and_parity(&mut shards) + .expect_err("missing encoder") + .kind(), + io::ErrorKind::Other + ); + assert_eq!( + erasure + .decode_data_with_reconstruction_verification(&mut shards) + .expect_err("missing encoder") + .kind(), + io::ErrorKind::Other + ); + } + } + + #[test] + fn reconstruction_rejects_mismatched_decoder_geometry() { + for uses_legacy in [false, true] { + let mut erasure = Erasure::new_with_options(2, 2, 64, uses_legacy); + erasure.data_shards = 3; + erasure.parity_shards = 1; + let original = [Some(vec![1]), Some(vec![2]), Some(vec![3]), Some(vec![4])]; + let mut shards = original.clone(); + let error = erasure + .decode_data_and_parity(&mut shards) + .expect_err("encoder dimensions differ"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(shards, original); + } + } + + #[test] + fn reconstruction_requires_read_quorum_even_for_empty_shards() { + let below_quorum = [Some(Vec::new()), None, None]; + let exact_quorum = [None, Some(Vec::new()), Some(Vec::new())]; + for uses_legacy in [false, true] { + let erasure = Erasure::new_with_options(2, 1, 64, uses_legacy); + for mode in [ + DecodeMode::Data, + DecodeMode::All, + DecodeMode::Verified, + DecodeMode::VerifiedLockstep, + ] { + let mut shards = below_quorum.clone(); + let error = erasure + .decode_shards(&mut shards, mode) + .expect_err("one empty source is below quorum"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(shards, below_quorum); + } + for mode in [DecodeMode::Data, DecodeMode::All, DecodeMode::Verified] { + let mut shards = exact_quorum.clone(); + assert!( + erasure + .decode_shards(&mut shards, mode) + .expect("two empty sources meet quorum") + ); + assert_eq!(shards, [Some(Vec::new()), Some(Vec::new()), Some(Vec::new())]); + } + let mut shards = exact_quorum.clone(); + let error = erasure + .decode_data_with_reconstruction_verification_for_lockstep(&mut shards) + .expect_err("lockstep requires a surplus source for reconstruction"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(shards, exact_quorum); + } + let encoder = ReedSolomonEncoder::new(2, 1).expect("2+1 encoder"); + let mut shards = below_quorum.clone(); + let error = encoder + .reconstruct_data(&mut shards) + .expect_err("a direct reconstruction also needs quorum"); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert_eq!(shards, below_quorum); + + let mut shards = exact_quorum; + encoder + .reconstruct_data(&mut shards) + .expect("direct empty reconstruction at quorum"); + assert_eq!(shards, [Some(Vec::new()), Some(Vec::new()), Some(Vec::new())]); + } + #[test] fn decode_data_and_parity_rejects_wrong_shard_count() { for uses_legacy in [false, true] { @@ -2132,18 +2434,44 @@ mod tests { #[test] fn decode_data_with_verification_rejects_corrupt_surplus_parity() { - let erasure = Erasure::new(3, 2, 128); - let data = b"verified reads must fail closed on stale surplus parity"; - let encoded = erasure.encode_data(data).expect("encode should succeed"); - let mut shards = optional_shards(&encoded); - shards[1] = None; - shards[erasure.data_shards].as_mut().expect("parity shard should be present")[0] ^= 0x7d; + for uses_legacy in [false, true] { + let erasure = Erasure::new_with_options(3, 3, 128, uses_legacy); + let data = b"verified reads must fail closed on stale surplus parity"; + let encoded = erasure.encode_data(data).expect("encode should succeed"); + let mut shards = optional_shards(&encoded); + shards[1] = None; + shards[erasure.data_shards] = None; + shards[erasure.data_shards + 1].as_mut().expect("source parity")[0] ^= 0x7d; + let source_parity = shards[erasure.data_shards..].to_vec(); - let err = erasure - .decode_data_with_reconstruction_verification(&mut shards) - .expect_err("verified decode must reject inconsistent parity"); + let err = erasure + .decode_data_with_reconstruction_verification(&mut shards) + .expect_err("verified decode must reject inconsistent parity"); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert_eq!(&shards[erasure.data_shards..], source_parity); + } + } - assert_eq!(err.kind(), io::ErrorKind::InvalidData); + #[test] + fn verified_decode_restores_missing_parity_with_surplus_sources() { + for uses_legacy in [false, true] { + let erasure = Erasure::new_with_options(4, 3, 128, uses_legacy); + for payload in [b"".as_slice(), b"reconstruct both a data shard and a parity shard"] { + let encoded = erasure.encode_data(payload).expect("encode should succeed"); + let expected = optional_shards(&encoded); + let mut shards = expected.clone(); + shards[1] = None; + shards[erasure.data_shards + 1] = None; + + assert!( + erasure + .decode_data_with_reconstruction_verification(&mut shards) + .expect("enough sources"), + "data reconstruction must be reported" + ); + assert_eq!(shards, expected); + } + } } #[test] diff --git a/crates/ecstore/src/lib.rs b/crates/ecstore/src/lib.rs index 99a7ef35b0..3adf41d657 100644 --- a/crates/ecstore/src/lib.rs +++ b/crates/ecstore/src/lib.rs @@ -93,6 +93,12 @@ pub fn mark_get_metadata_read_version_coalescing_service_ready() { runtime::global::mark_get_metadata_read_version_coalescing_service_ready(); } +#[cfg(feature = "fuzzing")] +pub mod fuzz_exports { + pub use crate::erasure::coding::{BitrotReader, BitrotWriter, ShardChunkRead, ShardSource, bitrot_verify}; + pub use rustfs_gateway_types::{cors_tagging, persistence}; +} + #[cfg(test)] mod rio_tests { #[test] diff --git a/crates/ecstore/src/runtime/global.rs b/crates/ecstore/src/runtime/global.rs index 233385fcad..5993911799 100644 --- a/crates/ecstore/src/runtime/global.rs +++ b/crates/ecstore/src/runtime/global.rs @@ -21,6 +21,7 @@ use crate::{ services::tier::tier::TierConfigMgr, store::ECStore, }; +use arc_swap::ArcSwapOption; use lazy_static::lazy_static; use rustfs_lock::client::LockClient; use std::{ @@ -64,7 +65,7 @@ pub(crate) fn get_metadata_read_version_coalescing_service_ready() -> bool { // forward to the current instance's context. lazy_static! { static ref GLOBAL_RUSTFS_PORT: OnceLock = OnceLock::new(); - pub static ref GLOBAL_OBJECT_API: OnceLock> = OnceLock::new(); + pub static ref GLOBAL_OBJECT_API: ArcSwapOption = ArcSwapOption::empty(); pub static ref GLOBAL_ROOT_DISK_THRESHOLD: RwLock = RwLock::new(0); pub static ref GLOBAL_LIFECYCLE_SYS: Arc = LifecycleSys::new(); pub static ref GLOBAL_BOOT_TIME: OnceCell = OnceCell::new(); @@ -72,7 +73,7 @@ lazy_static! { pub static ref GLOBAL_LOCAL_NODE_NAME_HEX_FALLBACK: String = rustfs_utils::crypto::hex(GLOBAL_LOCAL_NODE_NAME_FALLBACK.as_bytes()); pub static ref GLOBAL_LOCAL_LOCK_CLIENT: OnceLock> = OnceLock::new(); - pub static ref GLOBAL_LOCK_CLIENTS: OnceLock>> = OnceLock::new(); + pub static ref GLOBAL_LOCK_CLIENTS: ArcSwapOption>> = ArcSwapOption::empty(); } pub fn init_global_bucket_monitor(num_nodes: u64) { @@ -176,7 +177,7 @@ pub fn get_global_tier_config_mgr() -> Arc> { /// * `Option>` - The global object layer instance, if set /// pub fn new_object_layer_fn() -> Option> { - GLOBAL_OBJECT_API.get().cloned() + GLOBAL_OBJECT_API.load_full() } pub type ObjectStoreResolver = dyn Fn() -> Option> + Send + Sync + 'static; @@ -215,9 +216,17 @@ pub(crate) fn current_ctx() -> Arc { /// # Returns /// * None pub async fn set_object_layer(o: Arc) { - if GLOBAL_OBJECT_API.set(o).is_err() { + if GLOBAL_OBJECT_API.load().is_some() { warn!("global object layer already initialized, ignoring re-initialization"); + return; } + GLOBAL_OBJECT_API.store(Some(o)); +} + +/// Atomically replace the process-global object store during a live topology +/// hot-reload, returning the previous generation if one was published. +pub fn replace_object_layer(o: Arc) -> Option> { + GLOBAL_OBJECT_API.swap(Some(o)) } /// Check if the setup type is distributed erasure coding @@ -348,14 +357,25 @@ pub fn get_global_lock_client() -> Option> { pub fn set_global_lock_clients( clients: HashMap>, ) -> Result<(), HashMap>> { - GLOBAL_LOCK_CLIENTS.set(clients) + if GLOBAL_LOCK_CLIENTS.load().is_some() { + return Err(clients); + } + GLOBAL_LOCK_CLIENTS.store(Some(Arc::new(clients))); + Ok(()) +} + +/// Atomically replace the global lock clients map during a live topology reload. +pub fn replace_global_lock_clients( + clients: HashMap>, +) -> Option>>> { + GLOBAL_LOCK_CLIENTS.swap(Some(Arc::new(clients))) } /// Get the global lock clients map /// /// # Returns -/// * `Option<&HashMap>>` - The global lock clients map, if set +/// * `Option>>>` - The global lock clients map, if set /// -pub fn get_global_lock_clients() -> Option<&'static HashMap>> { - GLOBAL_LOCK_CLIENTS.get() +pub fn get_global_lock_clients() -> Option>>> { + GLOBAL_LOCK_CLIENTS.load_full() } diff --git a/crates/ecstore/src/runtime/instance.rs b/crates/ecstore/src/runtime/instance.rs index 868d135968..f3f20f669c 100644 --- a/crates/ecstore/src/runtime/instance.rs +++ b/crates/ecstore/src/runtime/instance.rs @@ -51,6 +51,7 @@ use crate::object_api::ObjectEncryptionResolver; use crate::services::event_notification::EventNotifier; use crate::services::tier::tier::TierConfigMgr; use crate::store::delete_recovery_runtime::DeleteRecoveryHints; +use arc_swap::ArcSwapOption; use rustfs_lock::{GlobalLockManager, get_global_lock_manager}; use rustfs_s3_types::Region; use std::collections::{HashMap, HashSet}; @@ -263,9 +264,35 @@ pub struct InstanceContext { deployment_id: OnceLock, /// This instance's endpoint topology (Phase 5 Slice 6, backlog#939). /// - /// Write-once: storage startup publishes the server pools exactly once. - /// Replaces the process-global endpoints static. - endpoints: OnceLock, + /// Published once during startup via [`Self::set_endpoints`] and atomically + /// swapped on live pool topology hot-reload via [`Self::replace_endpoints`]. + endpoints: ArcSwapOption, + /// Monotonic topology generation counter incremented on each live hot-reload. + topology_generation: AtomicU64, + /// Weak pointer to the currently active `ECStore` generation for this + /// instance context, updated on startup and on every live hot-reload so + /// long-lived background subsystems resolve the live generation without + /// pinning retired `ECStore` generations in memory. + live_store: std::sync::RwLock>, + /// Weak registry of external `DynamicECStoreHandle` cells eagerly rebound + /// to each newly published `ECStore` generation at cutover so retired + /// generations are released immediately even when subsystems are idle. + rebindable_store_cells: std::sync::Mutex>>>>, + /// Raw pointer address of the currently active `ECStore` generation (0 before + /// publication), used to reject deferred movement starts on retired generations. + active_store_ptr: std::sync::atomic::AtomicUsize, + /// Per-generation cancellation token cancelled and rotated on each hot-reload. + active_generation_cancel: std::sync::Mutex>, + /// Shared across `ECStore` generations of this instance so rebalance, + /// decommission, and topology hot-reload starts serialize even across + /// generation retirement. + movement_start_gate: Arc>, + /// Set once startup disk format discovery/creation and local disk-ID map + /// prewarming have completed (before entering `pool_join_standby`). + startup_formats_ready: AtomicBool, + /// Instant wakeup notifier for a node waiting in `pool_join_standby` once + /// the elected pool writer commits `pool.bin`. + pool_join_wakeup: Notify, /// Only a complete validated topology may enable native local proof origin. multipart_proof_topology: OnceLock<([u8; 32], ProofVerificationContext)>, /// This instance's tier configuration manager (Phase 5 Slice 7, backlog#939). @@ -293,9 +320,9 @@ pub struct InstanceContext { /// This instance's bucket bandwidth monitor (Phase 5 Slice 10, backlog#939). /// /// Set once at startup with the cluster node count (see - /// [`InstanceContext::init_bucket_monitor`]); read as `None` until then. - /// Replaces the process-global bucket-monitor static. - bucket_monitor: OnceLock>, + /// [`InstanceContext::init_bucket_monitor`]) and atomically refreshed when + /// cluster membership changes on live topology hot-reload. + bucket_monitor: ArcSwapOption, /// This instance's background replication stats (Phase 5 Slice 11, backlog#939). /// /// Async set-once (workers are spawned during init); read as `None` until @@ -328,6 +355,7 @@ pub struct InstanceContext { /// their own `ECStore` without panicking. Production startup still sets /// this exactly once. bucket_metadata_sys: std::sync::Mutex>>>, + bucket_metadata_store_cell: std::sync::Mutex>>>>, /// This instance's background-services cancellation token (Phase 5 Slice 13, /// backlog#939). /// @@ -339,6 +367,10 @@ pub struct InstanceContext { /// Readers are held across one publication commit; movement transitions /// take the writer at their durable state commit boundary. data_movement_operation_gate: Arc>, + /// Serializes `CreateBucket` execution with live topology hot-reload cutover + /// so in-flight bucket creations never straddle old/new pool generations or + /// miss physical directory propagation onto newly expanded pools. + bucket_topology_gate: Arc>, /// Set while an operator decommission start runs on this instance. A /// start runs detached from its caller, so this keeps abandoned requests /// and their retries from stacking concurrent starts and preflight heals. @@ -475,21 +507,31 @@ impl InstanceContext { region: OnceLock::new(), additional_regions: OnceLock::new(), deployment_id: OnceLock::new(), - endpoints: OnceLock::new(), + endpoints: ArcSwapOption::empty(), + topology_generation: AtomicU64::new(0), + live_store: std::sync::RwLock::new(std::sync::Weak::new()), + rebindable_store_cells: std::sync::Mutex::new(Vec::new()), + active_store_ptr: std::sync::atomic::AtomicUsize::new(0), + active_generation_cancel: std::sync::Mutex::new(None), + movement_start_gate: Arc::new(Mutex::new(())), + startup_formats_ready: AtomicBool::new(false), + pool_join_wakeup: Notify::new(), multipart_proof_topology: OnceLock::new(), tier_config_mgr: OnceLock::new(), event_notifier: OnceLock::new(), expiry_state: OnceLock::new(), transition_state: OnceLock::new(), - bucket_monitor: OnceLock::new(), + bucket_monitor: ArcSwapOption::empty(), replication_stats: OnceCell::new(), replication_pool: OnceCell::new(), local_disk_map: Arc::new(RwLock::new(HashMap::new())), local_disk_id_map: Arc::new(RwLock::new(HashMap::new())), local_disk_set_drives: Arc::new(RwLock::new(Vec::new())), bucket_metadata_sys: std::sync::Mutex::new(None), + bucket_metadata_store_cell: std::sync::Mutex::new(None), background_cancel_token: OnceLock::new(), data_movement_operation_gate: Arc::new(RwLock::new(())), + bucket_topology_gate: Arc::new(RwLock::new(())), decommission_start_in_flight: AtomicBool::new(false), decommission_pauses: std::sync::Mutex::new(HashMap::new()), decommission_count_ledgers: std::sync::Mutex::new(HashMap::new()), @@ -567,6 +609,10 @@ impl InstanceContext { Arc::clone(&self.data_movement_operation_gate) } + pub(crate) fn bucket_topology_gate(&self) -> Arc> { + Arc::clone(&self.bucket_topology_gate) + } + /// Claim the single decommission start slot; `false` when a start is /// already running. Release it with [`Self::end_decommission_start`]. pub(crate) fn try_begin_decommission_start(&self) -> bool { @@ -629,6 +675,36 @@ impl InstanceContext { .cloned() } + /// Remap positional per-pool decommission pauses and count ledgers across a + /// committed topology hot-reload (`old_pool_idx -> new_pool_idx`), pruning + /// removed pools and shifting retained pools when an earlier pool is removed. + pub(crate) fn reconcile_positional_pool_state(&self, old_to_new_pool: &HashMap) { + { + let mut pauses = self + .decommission_pauses + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let old_pauses = std::mem::take(&mut *pauses); + for (old_idx, record) in old_pauses { + if let Some(&new_idx) = old_to_new_pool.get(&old_idx) { + pauses.insert(new_idx, record); + } + } + } + { + let mut ledgers = self + .decommission_count_ledgers + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let old_ledgers = std::mem::take(&mut *ledgers); + for (old_idx, ledger) in old_ledgers { + if let Some(&new_idx) = old_to_new_pool.get(&old_idx) { + ledgers.insert(new_idx, ledger); + } + } + } + } + pub(crate) async fn install_scanner_publication_lease( &self, token: Uuid, @@ -940,17 +1016,135 @@ impl InstanceContext { /// Set this instance's endpoint topology. /// - /// Write-once: panics on a second write, preserving the startup fail-fast - /// contract of the process global it replaces. + /// Write-once during startup: panics on a second write, preserving the + /// startup fail-fast contract. Live topology hot-reload uses + /// [`Self::replace_endpoints`]. pub fn set_endpoints(&self, endpoints: EndpointServerPools) { + assert!( + self.endpoints.load().is_none(), + "instance endpoints should be initialized once during storage startup" + ); + self.endpoints.store(Some(Arc::new(endpoints))); + } + + /// Atomically replace this instance's endpoint topology during a live + /// hot-reload, returning the previous topology if one was set. + pub fn replace_endpoints(&self, endpoints: EndpointServerPools) -> Option { self.endpoints - .set(endpoints) - .expect("instance endpoints should be initialized once during storage startup"); + .swap(Some(Arc::new(endpoints))) + .map(|prev| prev.as_ref().clone()) + } + + /// Current topology reload generation (0 at initial boot, incremented per hot-reload). + pub fn topology_generation(&self) -> u64 { + self.topology_generation.load(Ordering::Acquire) + } + + /// Increment and return the new topology generation after a live hot-reload commit. + pub(crate) fn advance_topology_generation(&self) -> u64 { + self.topology_generation.fetch_add(1, Ordering::AcqRel).saturating_add(1) + } + + pub(crate) fn sync_topology_generation_at_least(&self, min_generation: u64) -> u64 { + let mut current = self.topology_generation.load(Ordering::Acquire); + while current < min_generation { + match self + .topology_generation + .compare_exchange_weak(current, min_generation, Ordering::AcqRel, Ordering::Acquire) + { + Ok(_) => return min_generation, + Err(observed) => current = observed, + } + } + current + } + + /// Publish the currently active `ECStore` generation for this instance context. + pub(crate) fn set_live_store(&self, store: &Arc) { + let new_ptr = Arc::as_ptr(store) as usize; + self.active_store_ptr.store(new_ptr, Ordering::Release); + *self.live_store.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::downgrade(store); + let mut cells = self + .rebindable_store_cells + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + cells.retain(|weak_cell| { + let Some(cell) = weak_cell.upgrade() else { + return false; + }; + *cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::clone(store); + true + }); + } + + pub(crate) fn register_rebindable_store_cell(&self, cell: &Arc>>) { + if let Some(live) = self.live_store() { + *cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = live; + } + self.rebindable_store_cells + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(Arc::downgrade(cell)); + } + + pub(crate) fn active_store_ptr(&self) -> usize { + self.active_store_ptr.load(Ordering::Acquire) + } + + /// Cancel any previous generation's background worker token and install a + /// fresh child token of `parent` for the newly active generation. + pub(crate) fn rotate_generation_cancel(&self, parent: &CancellationToken) -> CancellationToken { + let next = parent.child_token(); + let prev = self + .active_generation_cancel + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .replace(next.clone()); + if let Some(prev) = prev { + prev.cancel(); + } + next + } + + /// Resolve the currently active `ECStore` generation for this instance context, + /// if still alive. + pub fn live_store(&self) -> Option> { + self.live_store + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .upgrade() + } + + /// Shared start-gate mutex serializing rebalance, decommission, and topology + /// hot-reload start transitions across `ECStore` generations. + pub(crate) fn movement_start_gate(&self) -> Arc> { + Arc::clone(&self.movement_start_gate) + } + + /// Record that local disk formats and disk-ID maps are initialized and ready + /// to serve remote I/O during standby pool join. + pub(crate) fn mark_startup_formats_ready(&self) { + self.startup_formats_ready.store(true, Ordering::Release); + } + + /// Whether startup disk format discovery and disk-ID prewarming have completed. + pub fn is_startup_formats_ready(&self) -> bool { + self.startup_formats_ready.load(Ordering::Acquire) + } + + /// Wake a standby joining node immediately after the elected writer commits `pool.bin`. + pub fn notify_pool_join_wakeup(&self) { + self.pool_join_wakeup.notify_one(); + } + + /// Wait until notified that `pool.bin` was committed during standby pool join. + pub(crate) async fn wait_pool_join_wakeup(&self) { + self.pool_join_wakeup.notified().await; } /// This instance's endpoint topology, if it has been set. pub fn endpoints(&self) -> Option { - self.endpoints.get().cloned() + self.endpoints.load_full().map(|eps| eps.as_ref().clone()) } /// Keep one authority identity across complete local registry reinitializations. @@ -978,6 +1172,27 @@ impl InstanceContext { Ok(stored.1.clone()) } + /// Atomically replace the multipart proof topology's active endpoint set + /// during a committed live hot-reload (pruning removed local endpoints). + pub(crate) fn replace_multipart_proof_topology( + &self, + endpoints: &EndpointServerPools, + ) -> crate::disk::error::Result { + if endpoints.as_ref().iter().enumerate().any(|(pool, entry)| { + entry + .endpoints + .as_ref() + .iter() + .any(|endpoint| usize::try_from(endpoint.pool_idx).ok() != Some(pool)) + }) { + return Err(crate::disk::error::DiskError::InconsistentDisk); + } + let (identity, authority) = ProofVerificationContext::for_topology(endpoints)?; + let stored = self.multipart_proof_topology.get_or_init(|| (identity, authority.clone())); + stored.1.replace_topology(&authority)?; + Ok(stored.1.clone()) + } + pub(crate) fn multipart_proof_verification_context(&self) -> ProofVerificationContext { self.multipart_proof_topology .get() @@ -1013,12 +1228,31 @@ impl InstanceContext { /// node count. Returns `false` if it was already initialized (the caller /// logs; matches the process global's ignore-and-warn behavior). pub fn init_bucket_monitor(&self, num_nodes: u64) -> bool { - self.bucket_monitor.set(Monitor::new(num_nodes)).is_ok() + if self.bucket_monitor.load().is_some() { + return false; + } + self.bucket_monitor.store(Some(Monitor::new(num_nodes))); + true + } + + /// Atomically replace this instance's bucket bandwidth monitor for a live + /// topology reload with an updated node count, preserving configured bucket + /// bandwidth limits. + pub fn replace_bucket_monitor(&self, num_nodes: u64) { + let normalized = num_nodes.max(1); + if let Some(existing) = self.bucket_monitor.load_full() { + if existing.node_count == normalized { + return; + } + self.bucket_monitor.store(Some(existing.with_inherited_limits(normalized))); + } else { + self.bucket_monitor.store(Some(Monitor::new(normalized))); + } } /// This instance's bucket bandwidth monitor, if it has been initialized. pub fn bucket_monitor(&self) -> Option> { - self.bucket_monitor.get().cloned() + self.bucket_monitor.load_full() } /// This instance's background replication stats, if initialized. @@ -1078,6 +1312,25 @@ impl InstanceContext { let mut guard = self.bucket_metadata_sys.lock().expect("bucket_metadata_sys lock poisoned"); let is_first = guard.is_none(); *guard = Some(sys); + *self + .bucket_metadata_store_cell + .lock() + .expect("bucket_metadata_store_cell lock poisoned") = None; + is_first + } + + pub(crate) fn init_bucket_metadata_sys_with_store_cell( + &self, + sys: Arc>, + store_cell: Arc>>, + ) -> bool { + let mut guard = self.bucket_metadata_sys.lock().expect("bucket_metadata_sys lock poisoned"); + let is_first = guard.is_none(); + *guard = Some(sys); + *self + .bucket_metadata_store_cell + .lock() + .expect("bucket_metadata_store_cell lock poisoned") = Some(store_cell); is_first } @@ -1089,28 +1342,68 @@ impl InstanceContext { .clone() } + /// Rebind this instance's bucket metadata system to a newly hot-reloaded + /// `ECStore` generation wait-free without contending on outer async + /// `BucketMetadataSys` read/write locks. + pub fn rebind_bucket_metadata_store_sync(&self, store: &Arc) { + if let Some(cell) = self + .bucket_metadata_store_cell + .lock() + .expect("bucket_metadata_store_cell lock poisoned") + .clone() + { + *cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::downgrade(store); + return; + } + if let Some(sys) = self.bucket_metadata_sys() + && let Ok(guard) = sys.try_read() + { + guard.rebind_store(store.clone()); + } + } + + /// Async-compatible wrapper around [`Self::rebind_bucket_metadata_store_sync`]. + pub async fn rebind_bucket_metadata_store(&self, store: Arc) { + if let Some(cell) = self + .bucket_metadata_store_cell + .lock() + .expect("bucket_metadata_store_cell lock poisoned") + .clone() + { + *cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::downgrade(&store); + return; + } + if let Some(sys) = self.bucket_metadata_sys() { + sys.read().await.rebind_store(store); + } + } + /// Remove the `BucketMetadataSys` when its backing `ECStore` is gone. - /// - /// Called from `ECStore::drop`. When test fixtures share the bootstrap - /// context, the `BucketMetadataSys` stores a `Weak` to prevent a - /// reference cycle; once the store drops the weak is dangling and any - /// `object_store()` call panics. Clearing the slot here lets the next - /// fixture install a fresh `BucketMetadataSys` without hitting the stale one. pub fn clear_bucket_metadata_sys_if_stale(&self) { let mut guard = self.bucket_metadata_sys.lock().expect("bucket_metadata_sys lock poisoned"); if let Some(sys) = guard.as_ref() { - // `read()` may block briefly; the async RwLock is acceptable here - // because Drop is sync and the lock is held only long enough to - // check the weak reference. - let is_stale = { - let s = sys.try_read(); - match s { + let cell_opt = self + .bucket_metadata_store_cell + .lock() + .expect("bucket_metadata_store_cell lock poisoned") + .clone(); + let is_stale = if let Some(cell) = cell_opt { + cell.read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .upgrade() + .is_none() + } else { + match sys.try_read() { Ok(s) => s.is_store_stale(), - Err(_) => true, // contended: treat as stale-safe to clear + Err(_) => false, } }; if is_stale { *guard = None; + *self + .bucket_metadata_store_cell + .lock() + .expect("bucket_metadata_store_cell lock poisoned") = None; } } } @@ -1209,7 +1502,7 @@ impl std::fmt::Debug for InstanceContext { .field("event_notifier_set", &self.event_notifier.get().is_some()) .field("expiry_state_set", &self.expiry_state.get().is_some()) .field("transition_state_set", &self.transition_state.get().is_some()) - .field("bucket_monitor_set", &self.bucket_monitor.get().is_some()) + .field("bucket_monitor_set", &self.bucket_monitor.load().is_some()) .field( "bucket_metadata_sys_set", &self.bucket_metadata_sys.lock().map(|g| g.is_some()).unwrap_or(false), diff --git a/crates/ecstore/src/runtime/sources.rs b/crates/ecstore/src/runtime/sources.rs index 94c83aae48..9de2ca8335 100644 --- a/crates/ecstore/src/runtime/sources.rs +++ b/crates/ecstore/src/runtime/sources.rs @@ -34,7 +34,8 @@ use crate::{ get_background_services_cancel_token, get_global_bucket_monitor, get_global_deployment_id, get_global_endpoints, get_global_endpoints_opt, get_global_lock_client, get_global_lock_clients, get_global_region, get_global_tier_config_mgr, global_rustfs_port, init_global_bucket_monitor, is_dist_erasure, is_erasure, is_erasure_sd, is_first_cluster_node_local, - resolve_object_store_handle, set_global_lock_client, set_global_lock_clients, set_object_layer, update_erasure_type, + replace_global_lock_clients, replace_object_layer, resolve_object_store_handle, set_global_lock_client, + set_global_lock_clients, set_object_layer, update_erasure_type, }, services::batch_processor::{GlobalBatchProcessors, get_global_processors}, services::notification_sys::{NotificationSys, get_global_notification_sys}, @@ -307,7 +308,7 @@ pub fn global_lock_client() -> Option> { get_global_lock_client() } -pub fn global_lock_clients() -> Option<&'static HashMap>> { +pub fn global_lock_clients() -> Option>>> { get_global_lock_clients() } @@ -326,10 +327,20 @@ pub(crate) fn set_lock_clients( set_global_lock_clients(clients) } +pub(crate) fn replace_lock_clients( + clients: HashMap>, +) -> Option>>> { + replace_global_lock_clients(clients) +} + pub(crate) async fn publish_object_store(store: Arc) { set_object_layer(store).await; } +pub(crate) fn replace_object_store(store: Arc) -> Option> { + replace_object_layer(store) +} + pub(crate) fn notification_sys() -> Option> { get_global_notification_sys() } @@ -631,6 +642,228 @@ pub(crate) async fn initialize_local_disk_maps( Ok(()) } +pub(crate) struct StagedLocalDiskTopology { + pub(crate) set_drives: crate::runtime::global::TypeLocalDiskSetDrives, + pub(crate) local_disk_map: HashMap>, + pub(crate) newly_opened: Vec, + pub(crate) pool_index_updates: Vec<(DiskStore, i32)>, + pub(crate) removed_local_disks: Vec, + pub(crate) endpoint_pools: EndpointServerPools, +} + +fn canonical_local_disk_path(ep: &Endpoint) -> std::path::PathBuf { + let raw = std::path::PathBuf::from(ep.get_file_path()); + std::fs::canonicalize(&raw).unwrap_or(raw) +} + +/// Stage local disk handles for a candidate topology WITHOUT mutating any live +/// registry (`local_disk_map`, `local_disk_set_drives`, `local_disk_id_map`) +/// or live `LocalDisk` pool indices until atomic cutover. +pub(crate) async fn prepare_staged_local_disks_for_reload( + instance_ctx: &Arc, + endpoint_pools: EndpointServerPools, +) -> Result { + let reload_opt = DiskOption { + cleanup: false, + health_check: true, + }; + + let existing_by_endpoint = instance_ctx.local_disk_map().read().await.clone(); + let mut existing_by_path: HashMap = HashMap::new(); + let mut all_existing_disks: Vec = Vec::new(); + for disk in existing_by_endpoint.values().flatten() { + existing_by_path.insert(canonical_local_disk_path(&disk.endpoint()), disk.clone()); + all_existing_disks.push(disk.clone()); + } + + let mut next_set_drives = Vec::with_capacity(endpoint_pools.as_ref().len()); + for pool_eps in endpoint_pools.as_ref().iter() { + let mut set_count_drives = Vec::with_capacity(pool_eps.set_count); + for _ in 0..pool_eps.set_count { + set_count_drives.push(vec![None; pool_eps.drives_per_set]); + } + next_set_drives.push(set_count_drives); + } + + let mut next_local_disk_map = HashMap::new(); + let mut newly_opened = Vec::new(); + let mut pool_index_updates = Vec::new(); + let mut retained_ptrs: HashSet = HashSet::new(); + + for pool_eps in endpoint_pools.as_ref().iter() { + for ep in pool_eps.endpoints.as_ref().iter() { + if !ep.is_local { + continue; + } + let ep_key = ep.to_string(); + let existing = existing_by_endpoint + .get(&ep_key) + .cloned() + .flatten() + .or_else(|| existing_by_path.get(&canonical_local_disk_path(ep)).cloned()); + let disk = if let Some(live_disk) = existing { + retained_ptrs.insert(Arc::as_ptr(&live_disk) as usize); + if live_disk.endpoint().pool_idx != ep.pool_idx { + pool_index_updates.push((live_disk.clone(), ep.pool_idx)); + } + live_disk + } else { + match new_disk(ep, &reload_opt).await { + Ok(disk) => { + newly_opened.push(disk.clone()); + disk + } + Err(crate::disk::error::DiskError::FileAccessDenied | crate::disk::error::DiskError::VolumeNotFound) => { + next_local_disk_map.insert(ep_key, None); + continue; + } + Err(err) => { + for opened in newly_opened { + if let crate::disk::Disk::Local(wrapper) = opened.as_ref() { + wrapper.retire_handle(); + } + let _ = opened.close().await; + } + return Err(err.into()); + } + } + }; + let pool_idx = usize::try_from(ep.pool_idx).map_err(|err| { + crate::error::Error::other_with_context( + "topology reload failed to convert pool index", + format!("pool_idx={}: {err}", ep.pool_idx), + ) + })?; + let set_idx = usize::try_from(ep.set_idx).map_err(|err| { + crate::error::Error::other_with_context( + "topology reload failed to convert set index", + format!("set_idx={}: {err}", ep.set_idx), + ) + })?; + let disk_idx = usize::try_from(ep.disk_idx).map_err(|err| { + crate::error::Error::other_with_context( + "topology reload failed to convert disk index", + format!("disk_idx={}: {err}", ep.disk_idx), + ) + })?; + next_local_disk_map.insert(ep_key, Some(disk.clone())); + next_set_drives[pool_idx][set_idx][disk_idx] = Some(disk); + } + } + + let removed_local_disks = all_existing_disks + .into_iter() + .filter(|d| !retained_ptrs.contains(&(Arc::as_ptr(d) as usize))) + .collect(); + + Ok(StagedLocalDiskTopology { + set_drives: next_set_drives, + local_disk_map: next_local_disk_map, + newly_opened, + pool_index_updates, + removed_local_disks, + endpoint_pools, + }) +} + +/// Synchronize post-quorum format quarantine decisions into the staged local +/// disk structures before atomic cutover. +pub(crate) fn sync_staged_local_disks_with_quorum( + staged: &mut StagedLocalDiskTopology, + pool_idx: usize, + pool_eps: &crate::layout::endpoints::PoolEndpoints, + quorum_disks: &[Option], +) { + if pool_eps.drives_per_set == 0 { + return; + } + for (flat_idx, ep) in pool_eps.endpoints.as_ref().iter().enumerate() { + if !ep.is_local { + continue; + } + let set_idx = flat_idx / pool_eps.drives_per_set; + let disk_idx = flat_idx % pool_eps.drives_per_set; + let selected = quorum_disks.get(flat_idx).cloned().flatten(); + staged.local_disk_map.insert(ep.to_string(), selected.clone()); + if let Some(slot) = staged + .set_drives + .get_mut(pool_idx) + .and_then(|sets| sets.get_mut(set_idx)) + .and_then(|drives| drives.get_mut(disk_idx)) + { + *slot = selected; + } + } +} + +/// Discard newly opened candidate local disks when a staged reload aborts before cutover. +pub(crate) async fn abort_staged_local_disks_for_reload(staged: StagedLocalDiskTopology) { + for disk in staged.newly_opened { + if let crate::disk::Disk::Local(wrapper) = disk.as_ref() { + wrapper.retire_handle(); + } + let _ = disk.close().await; + } +} + +/// Commit staged local disk registries, updated `pool_idx` locations, multipart +/// proof topology, and pruned `local_disk_id_map` atomically at cutover. +pub(crate) async fn commit_staged_local_disks_for_reload( + instance_ctx: &Arc, + staged: StagedLocalDiskTopology, +) -> Result> { + let multipart_authority = instance_ctx.replace_multipart_proof_topology(&staged.endpoint_pools)?; + for (disk, new_pool_idx) in &staged.pool_index_updates { + if let crate::disk::Disk::Local(wrapper) = disk.as_ref() { + wrapper.get_disk().set_pool_index(*new_pool_idx); + } + } + + let mut active_disk_ids: HashMap = HashMap::new(); + for (ep_key, maybe_disk) in &staged.local_disk_map { + let Some(disk) = maybe_disk else { continue }; + if let crate::disk::Disk::Local(wrapper) = disk.as_ref() { + wrapper.get_disk().usage_watch_binding.bind(&instance_ctx.usage_watches); + wrapper.get_disk().bind_multipart_proof_authority(&multipart_authority)?; + } + if let Ok(Some(disk_id)) = disk.get_disk_id().await { + active_disk_ids.insert(disk_id, ep_key.clone()); + } + } + + let set_drives = instance_ctx.local_disk_set_drives(); + let map = instance_ctx.local_disk_map(); + let id_map = instance_ctx.local_disk_id_map(); + let mut global_set_drives = set_drives.write().await; + let mut global_local_disk_map = map.write().await; + let mut global_id_map = id_map.write().await; + *global_set_drives = staged.set_drives; + *global_local_disk_map = staged.local_disk_map; + *global_id_map = active_disk_ids; + Ok(staged.removed_local_disks) +} + +/// Refresh local disk registries for a live topology hot-reload. +/// +/// Retains existing live `DiskStore` handles for unchanged local paths without +/// running destructive startup `cleanup`, opens only newly added local disks +/// with `cleanup = false`, and re-indexes `(pool_idx, set_idx, disk_idx)` to +/// match `endpoint_pools`. +pub(crate) async fn refresh_local_disk_maps_for_reload( + instance_ctx: &Arc, + endpoint_pools: EndpointServerPools, +) -> Result<()> { + let staged = prepare_staged_local_disks_for_reload(instance_ctx, endpoint_pools).await?; + let removed = commit_staged_local_disks_for_reload(instance_ctx, staged).await?; + for disk in removed { + if let crate::disk::Disk::Local(wrapper) = disk.as_ref() { + wrapper.retire_handle(); + } + let _ = disk.close().await; + } + Ok(()) +} + pub(crate) async fn init_tier_config_mgr(store: Arc) -> Result<()> { init_tier_config_mgr_handle(get_global_tier_config_mgr(), store).await } diff --git a/crates/ecstore/src/services/notification_sys.rs b/crates/ecstore/src/services/notification_sys.rs index 556f9b2842..dd7475f96f 100644 --- a/crates/ecstore/src/services/notification_sys.rs +++ b/crates/ecstore/src/services/notification_sys.rs @@ -24,6 +24,7 @@ use crate::layout::endpoints::EndpointServerPools; use crate::runtime::sources as runtime_sources; use crate::services::metrics_realtime::{CollectMetricsOpts, MetricType}; use crate::storage_api_contracts::admin::StorageAdminApi; +use arc_swap::ArcSwapOption; use bytes::Bytes; use futures::future::join_all; use lazy_static::lazy_static; @@ -202,7 +203,7 @@ const SERVER_INFO_CACHE_MAX_AGE: Duration = Duration::from_secs(60); const STORAGE_INFO_CACHE_MAX_AGE: Duration = Duration::from_secs(60); lazy_static! { - pub static ref GLOBAL_NOTIFICATION_SYS: OnceLock> = OnceLock::new(); + pub static ref GLOBAL_NOTIFICATION_SYS: ArcSwapOption = ArcSwapOption::empty(); } #[derive(Clone)] @@ -361,7 +362,32 @@ static ILM_RECOVERY_EXPORT_FLEET_PROOF: OnceLock> = OnceLock::new(); static MRF_LIFECYCLE_WRITER_FLEET_PROOF: OnceLock> = OnceLock::new(); static MRF_LIFECYCLE_READER_LOCAL_PROCESS_EPOCH: LazyLock = LazyLock::new(Uuid::new_v4); -static REMOTE_VERSION_STATE_PROBE_TOPOLOGY: OnceLock = OnceLock::new(); +static REMOTE_VERSION_STATE_PROBE_TOPOLOGY: LazyLock> = LazyLock::new(ArcSwapOption::empty); + +fn current_probe_topology() -> Option> { + REMOTE_VERSION_STATE_PROBE_TOPOLOGY.load_full() +} + +fn set_probe_topology_once(topology_fingerprint: String) -> std::result::Result<(), String> { + if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.load().is_some() { + return Err(topology_fingerprint); + } + REMOTE_VERSION_STATE_PROBE_TOPOLOGY.store(Some(Arc::new(topology_fingerprint))); + Ok(()) +} + +/// Atomically replace the active fleet probe topology during a live pool +/// topology hot-reload, revoking stale generation proofs and waking the probe +/// loop to re-establish fleet proofs for the new membership immediately. +pub fn replace_remote_version_state_probe_topology(topology_fingerprint: String) { + REMOTE_VERSION_STATE_PROBE_TOPOLOGY.store(Some(Arc::new(topology_fingerprint))); + for slot in all_fleet_capability_proof_slots() { + let mut state = slot.write().unwrap_or_else(std::sync::PoisonError::into_inner); + state.topology_conflict = false; + revoke_fleet_capability_proof_state(&mut state); + } + NOTIFICATION_SYS_PUBLISHED.notify_one(); +} /// Signalled once `GLOBAL_NOTIFICATION_SYS` is published so the fleet probe can /// run its first real pass without waiting for the bootstrap poll. static NOTIFICATION_SYS_PUBLISHED: Notify = Notify::const_new(); @@ -494,11 +520,11 @@ fn publish_fleet_capability_probe_result( } pub(crate) fn acquire_remote_version_state_fleet_proof() -> Option { - let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?; + let expected_topology = current_probe_topology()?; let state = remote_version_state_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now()).map(RemoteVersionStateFleetProofToken) + acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now()).map(RemoteVersionStateFleetProofToken) } pub(crate) fn acquire_remote_version_state_writer_fleet_proof() -> Option { @@ -531,11 +557,11 @@ pub(crate) fn remote_version_state_fleet_proof_matches(proof: &RemoteVersionStat } pub(crate) fn acquire_transition_transaction_compaction_fleet_proof() -> Option { - let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?; + let expected_topology = current_probe_topology()?; let state = transition_transaction_compaction_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - let token = acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now())?; + let token = acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now())?; let permit = state.proof.as_ref()?.generation.try_acquire()?; Some(TransitionTransactionCompactionFleetProofToken { token, _permit: permit }) } @@ -543,14 +569,14 @@ pub(crate) fn acquire_transition_transaction_compaction_fleet_proof() -> Option< pub(crate) fn transition_transaction_compaction_fleet_proof_matches( proof: &TransitionTransactionCompactionFleetProofToken, ) -> bool { - let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { + let Some(expected_topology) = current_probe_topology() else { return false; }; let state = transition_transaction_compaction_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); proof._permit.generation.is_accepting() - && fleet_capability_proof_matches_at(&state, &proof.token, expected_topology, Instant::now()) + && fleet_capability_proof_matches_at(&state, &proof.token, expected_topology.as_str(), Instant::now()) && state .proof .as_ref() @@ -558,11 +584,11 @@ pub(crate) fn transition_transaction_compaction_fleet_proof_matches( } pub fn acquire_cross_pool_fence_fleet_proof() -> Option { - let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?; + let expected_topology = current_probe_topology()?; let state = cross_pool_fence_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now()).map(CrossPoolFenceFleetProofToken) + acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now()).map(CrossPoolFenceFleetProofToken) } async fn wait_for_fleet_capability_proof( @@ -603,14 +629,14 @@ pub(crate) async fn wait_for_cross_pool_fence_fleet_proof(rx: CancellationToken) } /// Startup layout identity remains available when peers or the live fleet proof are unavailable. -pub fn configured_fleet_topology_fingerprint() -> Option<&'static str> { +pub fn configured_fleet_topology_fingerprint() -> Option { let state = cross_pool_fence_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); if state.topology_conflict { return None; } - REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get().map(String::as_str) + current_probe_topology().map(|topology| topology.as_ref().clone()) } pub fn cross_pool_fence_fleet_proof_matches(proof: &CrossPoolFenceFleetProofToken) -> bool { @@ -618,11 +644,12 @@ pub fn cross_pool_fence_fleet_proof_matches(proof: &CrossPoolFenceFleetProofToke } pub(crate) fn acquire_decommission_target_fence_fleet_proof() -> Option { - let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?; + let expected_topology = current_probe_topology()?; let state = decommission_target_fence_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now()).map(DecommissionTargetFenceFleetProofToken) + acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now()) + .map(DecommissionTargetFenceFleetProofToken) } pub(crate) fn decommission_target_fence_fleet_proof_matches(proof: &DecommissionTargetFenceFleetProofToken) -> bool { @@ -630,11 +657,11 @@ pub(crate) fn decommission_target_fence_fleet_proof_matches(proof: &Decommission } pub(crate) fn acquire_tier_delete_journal_fleet_proof() -> Option { - let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?; + let expected_topology = current_probe_topology()?; let state = tier_delete_journal_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - acquire_tier_delete_journal_fleet_proof_from(&state, expected_topology, Instant::now()) + acquire_tier_delete_journal_fleet_proof_from(&state, expected_topology.as_str(), Instant::now()) } fn acquire_tier_delete_journal_fleet_proof_from( @@ -648,13 +675,13 @@ fn acquire_tier_delete_journal_fleet_proof_from( } pub(crate) fn tier_delete_journal_fleet_proof_matches(proof: &TierDeleteJournalFleetProofToken) -> bool { - let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { + let Some(expected_topology) = current_probe_topology() else { return false; }; let state = tier_delete_journal_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - tier_delete_journal_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now()) + tier_delete_journal_fleet_proof_matches_at(&state, proof, expected_topology.as_str(), Instant::now()) } fn tier_delete_journal_fleet_proof_matches_at( @@ -682,21 +709,21 @@ pub(crate) fn cross_pool_fence_topology_generation(proof: &CrossPoolFenceFleetPr /// Acquire one non-cloneable authority that must span the complete reconcile /// effect window, including its final strong readback. pub async fn acquire_legacy_transition_state_reconcile_fleet_proof() -> Option { - let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?; + let expected_topology = current_probe_topology()?; let proof = { let state = legacy_transition_state_reconcile_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - acquire_legacy_transition_state_reconcile_fleet_proof_from(&state, expected_topology, Instant::now())? + acquire_legacy_transition_state_reconcile_fleet_proof_from(&state, expected_topology.as_str(), Instant::now())? }; - let observed_peer_epochs = observe_legacy_transition_state_reconcile_fleet(expected_topology).await?; + let observed_peer_epochs = observe_legacy_transition_state_reconcile_fleet(expected_topology.as_str()).await?; let state = legacy_transition_state_reconcile_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); legacy_transition_state_reconcile_fleet_proof_matches_observation_at( &state, &proof, - expected_topology, + expected_topology.as_str(), &observed_peer_epochs, Instant::now(), ) @@ -704,7 +731,7 @@ pub async fn acquire_legacy_transition_state_reconcile_fleet_proof() -> Option Result<()> { - let Some(topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { + let Some(topology) = current_probe_topology() else { #[cfg(any(test, feature = "test-util"))] return Ok(()); #[cfg(not(any(test, feature = "test-util")))] @@ -718,7 +745,7 @@ pub async fn require_restore_copyback_fleet_capability() -> Result<()> { }; timeout( REMOTE_VERSION_STATE_PROBE_TIMEOUT, - notification_sys.probe_restore_copyback_fleet(topology), + notification_sys.probe_restore_copyback_fleet(topology.as_str()), ) .await .map_err(|_| Error::other("restore copy-back capability fleet probe timed out"))??; @@ -765,11 +792,11 @@ pub(crate) async fn with_legacy_transition_state_fleet_proof_for_test bool { - let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { + let Some(expected_topology) = current_probe_topology() else { return false; }; legacy_transition_state_reconcile_fleet_proof_matches_with_observer( legacy_transition_state_reconcile_fleet_proof_slot(), proof, - expected_topology, - || observe_legacy_transition_state_reconcile_fleet(expected_topology), + expected_topology.as_str(), + || observe_legacy_transition_state_reconcile_fleet(expected_topology.as_str()), ) .await } @@ -803,26 +830,26 @@ pub async fn legacy_transition_state_reconcile_fleet_proof_matches( pub(crate) fn legacy_transition_state_reconcile_fleet_proof_current( proof: &LegacyTransitionStateReconcileFleetProofToken, ) -> bool { - let Some(topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { return false }; + let Some(topology) = current_probe_topology() else { return false }; let state = legacy_transition_state_reconcile_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - legacy_transition_state_reconcile_fleet_proof_matches_at(&state, proof, topology, Instant::now()) + legacy_transition_state_reconcile_fleet_proof_matches_at(&state, proof, topology.as_str(), Instant::now()) } pub async fn acquire_ilm_recovery_export_fleet_proof() -> Option { - let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?; + let expected_topology = current_probe_topology()?; let proof = { let state = ilm_recovery_export_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - acquire_ilm_recovery_export_fleet_proof_from(&state, expected_topology, Instant::now())? + acquire_ilm_recovery_export_fleet_proof_from(&state, expected_topology.as_str(), Instant::now())? }; - let observed = observe_ilm_recovery_export_fleet(expected_topology).await?; + let observed = observe_ilm_recovery_export_fleet(expected_topology.as_str()).await?; let state = ilm_recovery_export_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - ilm_recovery_export_fleet_proof_matches_observation_at(&state, &proof, expected_topology, &observed, Instant::now()) + ilm_recovery_export_fleet_proof_matches_observation_at(&state, &proof, expected_topology.as_str(), &observed, Instant::now()) .then_some(proof) } @@ -837,24 +864,24 @@ fn acquire_ilm_recovery_export_fleet_proof_from( } pub async fn ilm_recovery_export_fleet_proof_matches(proof: &IlmRecoveryExportFleetProofToken) -> bool { - let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { + let Some(expected_topology) = current_probe_topology() else { return false; }; { let state = ilm_recovery_export_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - if !ilm_recovery_export_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now()) { + if !ilm_recovery_export_fleet_proof_matches_at(&state, proof, expected_topology.as_str(), Instant::now()) { return false; } } - let Some(observed) = observe_ilm_recovery_export_fleet(expected_topology).await else { + let Some(observed) = observe_ilm_recovery_export_fleet(expected_topology.as_str()).await else { return false; }; let state = ilm_recovery_export_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - ilm_recovery_export_fleet_proof_matches_observation_at(&state, proof, expected_topology, &observed, Instant::now()) + ilm_recovery_export_fleet_proof_matches_observation_at(&state, proof, expected_topology.as_str(), &observed, Instant::now()) } pub fn ilm_recovery_export_topology_generation(proof: &IlmRecoveryExportFleetProofToken) -> String { @@ -996,11 +1023,10 @@ fn stable_tier_delete_journal_topology_generation(topology_fingerprint: &str) -> #[cfg(any(test, feature = "test-util"))] pub(crate) fn install_cross_pool_fence_fleet_proof_for_test() { - let topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY - .get() - .cloned() + let topology = current_probe_topology() + .map(|value| value.as_ref().clone()) .unwrap_or_else(|| "pool-activation-test-topology".to_string()); - let _ = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology.clone()); + let _ = set_probe_topology_once(topology.clone()); let mut state = cross_pool_fence_fleet_proof_slot() .write() .unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1250,11 +1276,11 @@ fn fleet_capability_proof_matches( slot: &std::sync::RwLock, proof: &FleetCapabilityProofToken, ) -> bool { - let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { + let Some(expected_topology) = current_probe_topology() else { return false; }; let state = slot.read().unwrap_or_else(std::sync::PoisonError::into_inner); - fleet_capability_proof_matches_at(&state, proof, expected_topology, Instant::now()) + fleet_capability_proof_matches_at(&state, proof, expected_topology.as_str(), Instant::now()) } fn fleet_capability_proof_matches_at( @@ -1288,12 +1314,9 @@ impl Drop for RemoteVersionStateFleetProofGuard { #[cfg(test)] pub(crate) fn install_remote_version_state_fleet_proof_for_test(topology_fingerprint: &str) -> RemoteVersionStateFleetProofGuard { - match REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology_fingerprint.to_string()) { + match set_probe_topology_once(topology_fingerprint.to_string()) { Ok(()) => {} - Err(_) - if REMOTE_VERSION_STATE_PROBE_TOPOLOGY - .get() - .is_some_and(|current| current == topology_fingerprint) => {} + Err(_) if current_probe_topology().is_some_and(|current| current.as_str() == topology_fingerprint) => {} Err(_) => panic!("remote version state test topology is already bound to another fingerprint"), } let peer_epochs = BTreeMap::new(); @@ -1310,10 +1333,9 @@ pub(crate) fn install_remote_version_state_fleet_proof_for_test(topology_fingerp #[cfg(all(test, feature = "test-util"))] pub(crate) fn install_current_remote_version_state_fleet_proof_for_test() -> RemoteVersionStateFleetProofGuard { - let topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY - .get() - .expect("the test store must bind its fleet topology before installing a writer proof"); - install_remote_version_state_fleet_proof_for_test(topology) + let topology = + current_probe_topology().expect("the test store must bind its fleet topology before installing a writer proof"); + install_remote_version_state_fleet_proof_for_test(topology.as_str()) } #[cfg(all(test, feature = "test-util"))] @@ -1330,13 +1352,12 @@ impl Drop for TransitionTransactionCompactionFleetProofGuard { pub(crate) fn install_transition_transaction_compaction_fleet_proof_for_test( topology_fingerprint: &str, ) -> TransitionTransactionCompactionFleetProofGuard { - let _ = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology_fingerprint.to_string()); - let effective_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY - .get() - .expect("transition transaction compaction test topology should be initialized"); + let _ = set_probe_topology_once(topology_fingerprint.to_string()); + let effective_topology = + current_probe_topology().expect("transition transaction compaction test topology should be initialized"); if let Some(err) = publish_fleet_capability_probe_result( transition_transaction_compaction_fleet_proof_slot(), - effective_topology, + effective_topology.as_str(), Ok(BTreeMap::new()), Instant::now(), ) { @@ -1385,7 +1406,7 @@ pub fn mrf_lifecycle_writer_fleet_proof_current(proof: &MrfLifecycleWriterFleetP let state = mrf_lifecycle_writer_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, topology, Instant::now()) + mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, &topology, Instant::now()) } fn mrf_lifecycle_writer_fleet_proof_slot() -> &'static std::sync::RwLock { @@ -1401,8 +1422,8 @@ pub fn mrf_lifecycle_reader_local_process_epoch() -> Uuid { pub async fn acquire_mrf_lifecycle_writer_fleet_proof(local_reader_max_format: u8) -> Option { let expected_topology = configured_fleet_topology_fingerprint()?; let observed_at = Instant::now(); - let observed = observe_mrf_lifecycle_reader_fleet(expected_topology, local_reader_max_format).await; - if publish_fleet_capability_probe_result(mrf_lifecycle_writer_fleet_proof_slot(), expected_topology, observed, observed_at) + let observed = observe_mrf_lifecycle_reader_fleet(&expected_topology, local_reader_max_format).await; + if publish_fleet_capability_probe_result(mrf_lifecycle_writer_fleet_proof_slot(), &expected_topology, observed, observed_at) .is_some() { return None; @@ -1410,7 +1431,7 @@ pub async fn acquire_mrf_lifecycle_writer_fleet_proof(local_reader_max_format: u let state = mrf_lifecycle_writer_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - acquire_mrf_lifecycle_writer_fleet_proof_from(&state, expected_topology, local_reader_max_format, Instant::now()) + acquire_mrf_lifecycle_writer_fleet_proof_from(&state, &expected_topology, local_reader_max_format, Instant::now()) } fn acquire_mrf_lifecycle_writer_fleet_proof_from( @@ -1457,11 +1478,11 @@ pub async fn mrf_lifecycle_writer_fleet_proof_matches(proof: &MrfLifecycleWriter let state = mrf_lifecycle_writer_fleet_proof_slot() .read() .unwrap_or_else(std::sync::PoisonError::into_inner); - if !mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now()) { + if !mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, &expected_topology, Instant::now()) { return false; } } - let observed = observe_mrf_lifecycle_reader_fleet(expected_topology, proof.local_reader_max_format).await; + let observed = observe_mrf_lifecycle_reader_fleet(&expected_topology, proof.local_reader_max_format).await; let mut state = mrf_lifecycle_writer_fleet_proof_slot() .write() .unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1469,7 +1490,7 @@ pub async fn mrf_lifecycle_writer_fleet_proof_matches(proof: &MrfLifecycleWriter revoke_fleet_capability_proof_state(&mut state); return false; } - mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now()) + mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, &expected_topology, Instant::now()) } async fn observe_mrf_lifecycle_reader_fleet( @@ -1508,8 +1529,8 @@ fn mrf_lifecycle_reader_epoch_map( } pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { - if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology_fingerprint.clone()).is_err() { - if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() != Some(&topology_fingerprint) { + if set_probe_topology_once(topology_fingerprint.clone()).is_err() { + if current_probe_topology().as_deref().map(String::as_str) != Some(topology_fingerprint.as_str()) { for slot in all_fleet_capability_proof_slots() { mark_fleet_capability_topology_conflict(slot); } @@ -1520,6 +1541,12 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { tokio::spawn(async move { let mut notification_sys_unavailable_logged = false; loop { + let Some(active_topology) = current_probe_topology() else { + revoke_all_fleet_capability_proofs(); + let _ = timeout(REMOTE_VERSION_STATE_PROBE_BOOTSTRAP_INTERVAL, NOTIFICATION_SYS_PUBLISHED.notified()).await; + continue; + }; + let topology_fingerprint = active_topology.as_ref(); let Some(notification_sys) = get_global_notification_sys() else { // Startup publishes the notification system after this probe // is started. Stay failed closed, but retry on the bootstrap @@ -1543,7 +1570,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { let remote_version_state_probe = async { timeout( REMOTE_VERSION_STATE_PROBE_TIMEOUT, - notification_sys.probe_remote_version_state_fleet(&topology_fingerprint), + notification_sys.probe_remote_version_state_fleet(topology_fingerprint), ) .await .unwrap_or_else(|_| Err(Error::other("remote version state fleet capability probe timed out"))) @@ -1551,7 +1578,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { let cross_pool_fence_probe = async { timeout( REMOTE_VERSION_STATE_PROBE_TIMEOUT, - notification_sys.probe_cross_pool_fence_fleet(&topology_fingerprint), + notification_sys.probe_cross_pool_fence_fleet(topology_fingerprint), ) .await .unwrap_or_else(|_| Err(Error::other("cross-pool fence fleet capability probe timed out"))) @@ -1559,7 +1586,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { let recovery_export_probe = async { timeout( REMOTE_VERSION_STATE_PROBE_TIMEOUT, - notification_sys.probe_ilm_recovery_export_fleet(&topology_fingerprint), + notification_sys.probe_ilm_recovery_export_fleet(topology_fingerprint), ) .await .unwrap_or_else(|_| Err(Error::other("ILM recovery export fleet capability probe timed out"))) @@ -1567,7 +1594,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { let transition_transaction_compaction_probe = async { timeout( REMOTE_VERSION_STATE_PROBE_TIMEOUT, - notification_sys.probe_transition_transaction_compaction_fleet(&topology_fingerprint), + notification_sys.probe_transition_transaction_compaction_fleet(topology_fingerprint), ) .await .unwrap_or_else(|_| Err(Error::other("transition transaction compaction fleet capability probe timed out"))) @@ -1598,7 +1625,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { revoke_all_fleet_capability_proofs(); } else if let Some(err) = publish_fleet_capability_probe_result( remote_version_state_fleet_proof_slot(), - &topology_fingerprint, + topology_fingerprint, result, Instant::now(), ) { @@ -1607,7 +1634,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { if !topology_conflict && let Some(err) = publish_fleet_capability_probe_result( cross_pool_fence_fleet_proof_slot(), - &topology_fingerprint, + topology_fingerprint, fence_result, Instant::now(), ) @@ -1625,7 +1652,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { if !topology_conflict && let Some(err) = publish_fleet_capability_probe_result( ilm_recovery_export_fleet_proof_slot(), - &topology_fingerprint, + topology_fingerprint, recovery_export_result, Instant::now(), ) @@ -1643,7 +1670,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { if !topology_conflict && let Some(err) = publish_fleet_capability_probe_result( transition_transaction_compaction_fleet_proof_slot(), - &topology_fingerprint, + topology_fingerprint, transition_transaction_compaction_result, Instant::now(), ) @@ -1661,7 +1688,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { if !topology_conflict && let Some(err) = publish_fleet_capability_probe_result( tier_delete_journal_fleet_proof_slot(), - &topology_fingerprint, + topology_fingerprint, journal_result, Instant::now(), ) @@ -1679,7 +1706,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { if !topology_conflict && let Some(err) = publish_fleet_capability_probe_result( decommission_target_fence_fleet_proof_slot(), - &topology_fingerprint, + topology_fingerprint, decommission_target_fence_result, Instant::now(), ) @@ -1697,7 +1724,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { if !topology_conflict && let Some(err) = publish_fleet_capability_probe_result( legacy_transition_state_reconcile_fleet_proof_slot(), - &topology_fingerprint, + topology_fingerprint, reconcile_result, Instant::now(), ) @@ -1712,13 +1739,37 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) { "notification capability probe" ); } - sleep(REMOTE_VERSION_STATE_PROBE_INTERVAL).await; + let probe_degraded = topology_conflict + || decommission_target_fence_fleet_proof_slot() + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .proof + .is_none(); + let sleep_interval = if probe_degraded { + Duration::from_millis(250) + } else { + REMOTE_VERSION_STATE_PROBE_INTERVAL + }; + let _ = timeout(sleep_interval, NOTIFICATION_SYS_PUBLISHED.notified()).await; } }); } +/// Immediately wake the fleet capability probe loop (for example, once all peers +/// have committed a live pool topology hot-reload). +pub fn trigger_fleet_capability_probe_refresh() { + NOTIFICATION_SYS_PUBLISHED.notify_one(); +} + +/// Returns whether this node currently holds a valid fleet capability proof for +/// cross-pool decommission target fencing on the active topology. +pub fn has_decommission_target_fence_fleet_proof() -> bool { + acquire_decommission_target_fence_fleet_proof().is_some() +} + pub async fn new_global_notification_sys(eps: EndpointServerPools) -> Result<()> { - if GLOBAL_NOTIFICATION_SYS.set(Arc::new(NotificationSys::new(eps).await)).is_ok() { + if GLOBAL_NOTIFICATION_SYS.load().is_none() { + GLOBAL_NOTIFICATION_SYS.store(Some(Arc::new(NotificationSys::new(eps).await))); // `notify_one` stores a permit, so a probe that checks availability // just before this publication still wakes without losing the signal. NOTIFICATION_SYS_PUBLISHED.notify_one(); @@ -1726,11 +1777,28 @@ pub async fn new_global_notification_sys(eps: EndpointServerPools) -> Result<()> Ok(()) } +/// Atomically replace the global notification system during a live pool +/// topology hot-reload, optionally updating the active fleet probe topology +/// fingerprint and waking the fleet capability probe immediately. +pub async fn replace_global_notification_sys( + eps: EndpointServerPools, + topology_fingerprint: Option, +) -> Arc { + let next = Arc::new(NotificationSys::new(eps).await); + GLOBAL_NOTIFICATION_SYS.store(Some(next.clone())); + if let Some(fingerprint) = topology_fingerprint { + replace_remote_version_state_probe_topology(fingerprint); + } else { + NOTIFICATION_SYS_PUBLISHED.notify_one(); + } + next +} + // Owned handle rather than `&'static` (backlog#1052 S3): per-server contexts // need to hold their own notification system, which a process-lifetime // borrow cannot express. pub fn get_global_notification_sys() -> Option> { - GLOBAL_NOTIFICATION_SYS.get().cloned() + GLOBAL_NOTIFICATION_SYS.load_full() } pub struct NotificationSys { @@ -4383,7 +4451,7 @@ mod tests { /// to publish the notification system. #[tokio::test] async fn fleet_probe_publishes_promptly_once_the_notification_system_appears() { - if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get().is_some() || GLOBAL_NOTIFICATION_SYS.get().is_some() { + if current_probe_topology().is_some() || GLOBAL_NOTIFICATION_SYS.load().is_some() { // Process-wide state was bound by another test in this binary. The // startup ordering under test needs a fresh process; nextest // (the authoritative runner) always provides one. @@ -4634,7 +4702,8 @@ mod tests { use crate::layout::endpoint::Endpoint; temp_env::async_with_vars([(rustfs_config::ENV_DRIVE_MAX_TIMEOUT_DURATION, Some("60"))], async { - let topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get_or_init(|| "mrf-cas-test".to_owned()); + let _ = set_probe_topology_once("mrf-cas-test".to_owned()); + let topology = current_probe_topology().expect("mrf-cas-test topology should be initialized"); let slot = mrf_lifecycle_writer_fleet_proof_slot(); for cancel_waiter in [true, false] { let root = tempfile::tempdir().expect("isolated CAS fixture"); @@ -4651,11 +4720,11 @@ mod tests { .expect("native CAS publication path"); std::fs::write(&path, b"old").expect("old committed file"); let peers = BTreeMap::from([("local".to_owned(), Uuid::new_v4())]); - assert!(publish_fleet_capability_probe_result(slot, topology, Ok(peers), Instant::now()).is_none()); + assert!(publish_fleet_capability_probe_result(slot, topology.as_str(), Ok(peers), Instant::now()).is_none()); let proof = Arc::new( acquire_mrf_lifecycle_writer_fleet_proof_from( &slot.read().expect("proof state"), - topology, + &topology, 2, Instant::now(), ) @@ -4700,7 +4769,7 @@ mod tests { } assert!(weak.upgrade().is_some(), "the native worker still owns the permit"); let restarted = BTreeMap::from([("local".to_owned(), Uuid::new_v4())]); - assert!(publish_fleet_capability_probe_result(slot, topology, Ok(restarted.clone()), Instant::now()).is_some()); + assert!(publish_fleet_capability_probe_result(slot, &topology, Ok(restarted.clone()), Instant::now()).is_some()); assert_eq!(std::fs::read(&path).expect("old file retained while blocked"), b"old"); drop(release_tx); timeout(Duration::from_secs(5), async { @@ -4711,7 +4780,7 @@ mod tests { .await .expect("native worker drains"); assert_eq!(std::fs::read(&path).expect("revoked writer cannot publish"), b"old"); - assert!(publish_fleet_capability_probe_result(slot, topology, Ok(restarted), Instant::now()).is_none()); + assert!(publish_fleet_capability_probe_result(slot, &topology, Ok(restarted), Instant::now()).is_none()); revoke_fleet_capability_proof(slot); } }) diff --git a/crates/ecstore/src/services/rebalance/control.rs b/crates/ecstore/src/services/rebalance/control.rs index a1361b2885..946cb92a43 100644 --- a/crates/ecstore/src/services/rebalance/control.rs +++ b/crates/ecstore/src/services/rebalance/control.rs @@ -1080,7 +1080,10 @@ impl ECStore { #[tracing::instrument(skip(self, bucktes))] pub async fn init_rebalance_start(self: &Arc, bucktes: Vec) -> Result { + let movement_start_gate = self.ctx.movement_start_gate(); + let _instance_start_guard = movement_start_gate.lock().await; let _start_guard = self.start_gate.lock().await; + self.ensure_not_retired()?; { let decommission_running = self.is_decommission_running().await; let rebalance_meta = self.rebalance_meta.read().await; @@ -1099,7 +1102,10 @@ impl ECStore { #[tracing::instrument(skip(self))] pub async fn start_rebalance_for_id(self: &Arc, expected_id: &str) -> Result<()> { + let movement_start_gate = self.ctx.movement_start_gate(); + let _instance_start_guard = movement_start_gate.lock().await; let _start_guard = self.start_gate.lock().await; + self.ensure_not_retired()?; let _activation_guard = self .rebalance_activation_write_guard(Some(expected_id), "start rebalance") .await?; diff --git a/crates/ecstore/src/services/rebalance/runtime.rs b/crates/ecstore/src/services/rebalance/runtime.rs index 70efd297d9..cec96031a1 100644 --- a/crates/ecstore/src/services/rebalance/runtime.rs +++ b/crates/ecstore/src/services/rebalance/runtime.rs @@ -177,7 +177,10 @@ pub(super) fn rollback_local_rebalance_worker_activation( impl ECStore { #[tracing::instrument(skip_all)] pub async fn start_rebalance(self: &Arc) -> Result<()> { + let movement_start_gate = self.ctx.movement_start_gate(); + let _instance_start_guard = movement_start_gate.lock().await; let _start_guard = self.start_gate.lock().await; + self.ensure_not_retired()?; let _activation_guard = self.rebalance_activation_write_guard(None, "start rebalance").await?; let movement_gate = self.ctx.data_movement_operation_gate(); let _movement_guard = movement_gate.write().await; diff --git a/crates/ecstore/src/services/tier/tier.rs b/crates/ecstore/src/services/tier/tier.rs index 0d10c6fe73..ee3bafd65e 100644 --- a/crates/ecstore/src/services/tier/tier.rs +++ b/crates/ecstore/src/services/tier/tier.rs @@ -6898,10 +6898,15 @@ impl TierConfigMgr { } pub(crate) async fn refresh_tier_config_handle(handle: Arc>, api: Arc) { - Self::refresh_tier_config_handle_with_weak(handle, Arc::downgrade(&api)).await; + let instance_ctx = api.ctx.clone(); + Self::refresh_tier_config_handle_with_weak(handle, instance_ctx, Arc::downgrade(&api)).await; } - async fn refresh_tier_config_handle_with_weak(handle: Arc>, api: Weak) { + async fn refresh_tier_config_handle_with_weak( + handle: Arc>, + instance_ctx: Arc, + api: Weak, + ) { // The periodic refresh remains the recovery fallback; committed mutations // notify this worker so a successful peer commit converges immediately. let mutation_refresh = Self::mutation_refresh_notifier(&handle).await; @@ -6913,7 +6918,7 @@ impl TierConfigMgr { loop { select! { _ = t.tick() => { - let Some(api) = Weak::upgrade(&api) else { + let Some(api) = instance_ctx.live_store().or_else(|| Weak::upgrade(&api)) else { return; }; if let Err(err) = Self::reload_handle_with(&handle, api).await { @@ -6929,7 +6934,7 @@ impl TierConfigMgr { } } _ = mutation_refresh.notified() => { - let Some(api) = Weak::upgrade(&api) else { + let Some(api) = instance_ctx.live_store().or_else(|| Weak::upgrade(&api)) else { return; }; Self::reload_after_committed_mutation(&handle, api).await; @@ -7625,7 +7630,10 @@ mod tests { Ok(_) => panic!("an older generic S3 driver must not operate a Wasabi compatibility envelope"), Err(err) => err, }; - assert!(err.to_string().contains("missing a host"), "{err}"); + assert_eq!( + err.to_string(), + format!("tier endpoint is not allowed: outbound URL scheme '{EXTERNAL_TIER_VERSION_WASABI_V1}' is not allowed") + ); let mut generic_s3 = old_node_rewrite.clone(); generic_s3 diff --git a/crates/ecstore/src/set_disk/core/io_primitives.rs b/crates/ecstore/src/set_disk/core/io_primitives.rs index 210c63e238..1c391bd7e0 100644 --- a/crates/ecstore/src/set_disk/core/io_primitives.rs +++ b/crates/ecstore/src/set_disk/core/io_primitives.rs @@ -5015,6 +5015,8 @@ impl SetDisks { .await } Disk::Local(_) => Err(RenameBatchStartError::NotDispatched(DiskError::Unexpected)), + #[cfg(feature = "dst")] + Disk::Sim(_) => Err(RenameBatchStartError::NotDispatched(DiskError::Unexpected)), } }; match start { diff --git a/crates/ecstore/src/set_disk/core/multipart_source.rs b/crates/ecstore/src/set_disk/core/multipart_source.rs index 508a806731..cec4e0a04f 100644 --- a/crates/ecstore/src/set_disk/core/multipart_source.rs +++ b/crates/ecstore/src/set_disk/core/multipart_source.rs @@ -60,6 +60,11 @@ async fn recover_on_disk( let _namespace_owner = namespace_owner; remote.recover_multipart_source(request).await } + #[cfg(feature = "dst")] + crate::disk::Disk::Sim(sim) => { + let _namespace_owner = namespace_owner; + sim.recover_multipart_source(request).await + } } } diff --git a/crates/ecstore/src/set_disk/mod.rs b/crates/ecstore/src/set_disk/mod.rs index e41a991da7..1b4d07b017 100644 --- a/crates/ecstore/src/set_disk/mod.rs +++ b/crates/ecstore/src/set_disk/mod.rs @@ -301,6 +301,17 @@ fn rename_tail_heal_suppressed_for_e2e(bucket: &str, object: Option<&str>) -> bo } impl SetDisks { + #[cfg(feature = "dst")] + pub fn invalidate_metadata_cache_for_dst(&self) { + self.get_object_metadata_cache.invalidate_all(); + for g in self.get_object_metadata_cache_generations.iter() { + g.fetch_add(1, Ordering::AcqRel); + } + if let Ok(mut hc) = self.disk_health_cache.try_write() { + hc.clear(); + } + } + pub(super) async fn require_current_restore_operation_id( &self, bucket: &str, @@ -4816,7 +4827,10 @@ pub struct SetDisks { /// Hermetic sets may retain shared services while owning isolated proof scopes. #[cfg(test)] multipart_proof_authority_override: Arc>>, - #[cfg(test)] + /// Optional per-set storage class override used during live topology + /// hot-reload staging (so the candidate generation validates/writes metadata + /// against its own pool layout while the previous generation serves traffic) + /// and in hermetic unit tests. storage_class_config_override: Arc>>>, #[cfg(test)] rename_tail_heal_capture: Arc< @@ -5461,11 +5475,10 @@ impl SetDisks { } fn storage_class_config_snapshot(&self) -> Arc { - #[cfg(test)] if let Some(config) = self .storage_class_config_override .read() - .expect("test storage class override lock should not be poisoned") + .unwrap_or_else(std::sync::PoisonError::into_inner) .as_ref() { return config.clone(); @@ -5474,12 +5487,20 @@ impl SetDisks { runtime_sources::storage_class_config_snapshot() } - #[cfg(test)] - pub(crate) fn set_test_storage_class_config(&self, config: storageclass::Config) { + /// Pin or clear an explicit storage class snapshot on this erasure set. + /// Used during zero-downtime topology hot-reload so candidate sets write + /// pool metadata against the target pool layout and retiring sets keep + /// serving in-flight requests against the previous layout. + pub(crate) fn set_storage_class_config_override(&self, config: Option>) { *self .storage_class_config_override .write() - .expect("test storage class override lock should not be poisoned") = Some(Arc::new(config)); + .unwrap_or_else(std::sync::PoisonError::into_inner) = config; + } + + #[cfg(test)] + pub(crate) fn set_test_storage_class_config(&self, config: storageclass::Config) { + self.set_storage_class_config_override(Some(Arc::new(config))); } fn get_object_metadata_cache_hash(&self, bucket: &str, object: &str) -> u64 { @@ -5776,7 +5797,6 @@ impl SetDisks { orphan_purge_backoff: Arc::new(std::sync::Mutex::new(HashMap::new())), #[cfg(test)] multipart_proof_authority_override: Arc::new(std::sync::RwLock::new(None)), - #[cfg(test)] storage_class_config_override: Arc::new(std::sync::RwLock::new(None)), #[cfg(test)] rename_tail_heal_capture: Arc::new(std::sync::Mutex::new(None)), diff --git a/crates/ecstore/src/set_disk/ops/bitrot_self_verify.rs b/crates/ecstore/src/set_disk/ops/bitrot_self_verify.rs index 5f10921eda..423fdd931a 100644 --- a/crates/ecstore/src/set_disk/ops/bitrot_self_verify.rs +++ b/crates/ecstore/src/set_disk/ops/bitrot_self_verify.rs @@ -139,6 +139,12 @@ impl WrittenBitrotShards<'_> { let reader = local.read_file(RUSTFS_META_TMP_BUCKET, &path).await?; coding::bitrot_verify(reader, encoded_size, target.logical_shard_size, algo, target.shard_size).await?; } + #[cfg(feature = "dst")] + Disk::Sim(sim) => { + let path = format!("{directory}/part.{number}"); + let reader = sim.read_file(RUSTFS_META_TMP_BUCKET, &path).await?; + coding::bitrot_verify(reader, encoded_size, target.logical_shard_size, algo, target.shard_size).await?; + } Disk::Remote(peer) => { let fi = staged_part_file_info(layout, index + 1, number, *part_size, target.shard_size)?; let response = peer.verify_staged_part(directory, &fi, encoded_size).await?; diff --git a/crates/ecstore/src/set_disk/ops/object.rs b/crates/ecstore/src/set_disk/ops/object.rs index 962ea75f3a..17fdf7d86d 100644 --- a/crates/ecstore/src/set_disk/ops/object.rs +++ b/crates/ecstore/src/set_disk/ops/object.rs @@ -25944,6 +25944,8 @@ mod put_object_tmp_cleanup_tests { .map(|disk| match disk.as_ref() { disk::Disk::Local(local) => local, disk::Disk::Remote(_) => panic!("hermetic fixture must use local disks"), + #[cfg(feature = "dst")] + disk::Disk::Sim(_) => panic!("hermetic fixture must use local disks"), }) .collect(); let before: Vec<_> = local_disks diff --git a/crates/ecstore/src/store/bucket.rs b/crates/ecstore/src/store/bucket.rs index 45cdace2bc..c15f40e8d9 100644 --- a/crates/ecstore/src/store/bucket.rs +++ b/crates/ecstore/src/store/bucket.rs @@ -521,6 +521,16 @@ async fn bucket_delete_local_blocker( Ok(None) } +// Keep the large `handle_make_bucket_inner` state machine out of unoptimized +// caller poll frames when both `live_store()` and `self` branches are present. +#[inline(never)] +fn box_make_bucket_future(make_future: impl FnOnce() -> F) -> std::pin::Pin> +where + F: Future, +{ + Box::pin(make_future()) +} + impl ECStore { /// Fail the next real creation of this bucket after persisting its intent. #[cfg(any(test, feature = "test-util"))] @@ -1686,9 +1696,19 @@ impl ECStore { #[instrument(level = "trace", skip(self))] pub(super) async fn handle_make_bucket(&self, bucket: &str, opts: &MakeBucketOptions) -> Result<()> { + // Serialize against live topology hot-reload cutover so a concurrent + // `CreateBucket` never straddles two store generations or misses physical + // bucket directory propagation onto newly expanded pools. + let gate = self.ctx.bucket_topology_gate(); + let _topology_guard = gate.read().await; + if let Some(live) = self.ctx.live_store() + && !std::ptr::eq(Arc::as_ptr(&live), self as *const Self) + { + return box_make_bucket_future(|| live.handle_make_bucket_inner(bucket, opts, None)).await; + } // Metadata persistence re-enters native PUT/GET. Keep its full state // out of the tracing wrapper's poll frame on bounded runtime stacks. - Box::pin(self.handle_make_bucket_inner(bucket, opts, None)).await + box_make_bucket_future(|| self.handle_make_bucket_inner(bucket, opts, None)).await } /// Create a managed bucket with its complete identity and encryption in the creation intent. @@ -1710,12 +1730,16 @@ impl ECStore { { return Err(Error::PreconditionFailed); } - Box::pin(self.handle_make_bucket_inner( - identity.storage_bucket_id().as_str(), - opts, - Some((identity, encryption_config_xml, tagging_config_xml)), - )) - .await + let gate = self.ctx.bucket_topology_gate(); + let _topology_guard = gate.read().await; + let managed = Some((identity, encryption_config_xml, tagging_config_xml)); + let bucket = identity.storage_bucket_id().as_str(); + if let Some(live) = self.ctx.live_store() + && !std::ptr::eq(Arc::as_ptr(&live), self as *const Self) + { + return box_make_bucket_future(|| live.handle_make_bucket_inner(bucket, opts, managed)).await; + } + box_make_bucket_future(|| self.handle_make_bucket_inner(bucket, opts, managed)).await } async fn handle_make_bucket_inner( diff --git a/crates/ecstore/src/store/delete_recovery_runtime.rs b/crates/ecstore/src/store/delete_recovery_runtime.rs index ec62b78b61..eca5f98ba0 100644 --- a/crates/ecstore/src/store/delete_recovery_runtime.rs +++ b/crates/ecstore/src/store/delete_recovery_runtime.rs @@ -410,6 +410,54 @@ impl DeleteRecoveryHints { .started .insert(store) } + + /// Remap positional `(pool, set)` delete recovery hints across a committed + /// topology hot-reload (`old_pool_idx -> new_pool_idx`), pruning removed + /// pools, resetting worker start registration so the successor generation + /// spawns its recovery task, and scheduling a rescan for added pools. + pub(crate) fn reset_on_topology_reload(&self, old_to_new_pool: &HashMap) { + let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + state.started.clear(); + state.rescan = Some(Uuid::new_v4()); + + let old_drive_returns = std::mem::take(&mut state.drive_returns); + for ((old_pool, set), gen_id) in old_drive_returns { + if let Some(&new_pool) = old_to_new_pool.get(&old_pool) { + state.drive_returns.insert((new_pool, set), gen_id); + } + } + + let old_evicted = std::mem::take(&mut state.evicted_retries); + for (old_key, retry) in old_evicted { + if let Some(&new_pool) = old_to_new_pool.get(&old_key.pool) { + let mut remapped = (*old_key).clone(); + remapped.pool = new_pool; + state.evicted_retries.insert(Arc::new(remapped), retry); + } + } + + let old_pending = std::mem::take(&mut state.pending); + let old_order = std::mem::take(&mut state.order); + let mut key_map: HashMap, Arc> = HashMap::with_capacity(old_pending.len()); + for (old_key, entry) in old_pending { + if let Some(&new_pool) = old_to_new_pool.get(&old_key.pool) { + let new_key = if new_pool == old_key.pool { + old_key.clone() + } else { + let mut remapped = (*old_key).clone(); + remapped.pool = new_pool; + Arc::new(remapped) + }; + key_map.insert(old_key, new_key.clone()); + state.pending.insert(new_key, entry); + } + } + for (old_key, slot) in old_order { + if let Some(new_key) = key_map.get(&old_key) { + state.order.push_back((new_key.clone(), slot)); + } + } + } } #[derive(Clone)] @@ -660,6 +708,8 @@ impl RecoveryPass { let renewed = match scan.source.disk.as_ref() { crate::disk::Disk::Local(local) => local.get_disk().renew_delete_recovery_cursor(&bucket.bucket, cursor), crate::disk::Disk::Remote(_) => false, + #[cfg(feature = "dst")] + crate::disk::Disk::Sim(_) => false, }; if !renewed { bucket.cursor = None; diff --git a/crates/ecstore/src/store/format_bootstrap.rs b/crates/ecstore/src/store/format_bootstrap.rs index fe348ad6b1..a70f3142a8 100644 --- a/crates/ecstore/src/store/format_bootstrap.rs +++ b/crates/ecstore/src/store/format_bootstrap.rs @@ -14,7 +14,7 @@ use super::init_format::{ check_format_erasure_values, formats_match_reference_slots, legacy_format_max_bytes, read_legacy_format_bytes, - retain_format_quorum_members, write_format_file, + retain_format_quorum_members_with_mode, write_format_file, }; use crate::disk::{DiskAPI, DiskStore, RUSTFS_META_BUCKET, error::DiskError, format::FormatV3}; use crate::error::{Error, Result}; @@ -105,6 +105,7 @@ pub(super) async fn write_format_bootstrap_intents(disks: &[Option], /// Completes an anchored plan before its first format publication, or restores /// explicitly unformatted slots from a complete durable intent set. Partial /// intent sets grant no authority once any format has been published. +#[allow(clippy::too_many_arguments)] pub(super) async fn resume_format_bootstrap( instance_ctx: &Arc, disks: &mut [Option], @@ -113,6 +114,7 @@ pub(super) async fn resume_format_bootstrap( set_count: usize, set_drive_count: usize, deployment_id: Option, + staged_mode: bool, ) -> Result> { if disks.is_empty() || disks.len() != formats.len() @@ -220,7 +222,7 @@ pub(super) async fn resume_format_bootstrap( format.erasure.this = Uuid::nil(); format.disk_info = None; let members = vec![true; disks.len()]; - retain_format_quorum_members(instance_ctx, disks, &format, &members, None, set_drive_count).await?; + retain_format_quorum_members_with_mode(instance_ctx, disks, &format, &members, None, set_drive_count, staged_mode).await?; Ok(Some(format)) } diff --git a/crates/ecstore/src/store/init.rs b/crates/ecstore/src/store/init.rs index 650bd5be72..730ca09894 100644 --- a/crates/ecstore/src/store/init.rs +++ b/crates/ecstore/src/store/init.rs @@ -32,7 +32,7 @@ const EVENT_STORE_FORMAT_RETRY: &str = "store_format_retry"; const EVENT_ECSTORE_INIT_STATUS: &str = "ecstore_init_status"; const EVENT_STORE_RPC_SECRET_PREFLIGHT_FAILED: &str = "store_rpc_secret_preflight_failed"; -fn pool_first_endpoint_is_local(pool: &crate::layout::endpoints::PoolEndpoints) -> bool { +pub(super) fn pool_first_endpoint_is_local(pool: &crate::layout::endpoints::PoolEndpoints) -> bool { pool.endpoints.as_ref().first().is_some_and(|endpoint| endpoint.is_local) } @@ -40,7 +40,7 @@ fn startup_pool_drive_counts(endpoint_pools: &EndpointServerPools) -> Vec endpoint_pools.as_ref().iter().map(|pool| pool.drives_per_set).collect() } -fn resolve_startup_pool_defaults(endpoint_pools: &EndpointServerPools) -> Result> { +pub(super) fn resolve_startup_pool_defaults(endpoint_pools: &EndpointServerPools) -> Result> { resolve_startup_pool_defaults_with(endpoint_pools, ECStore::validate_startup_storage_class) } @@ -57,7 +57,7 @@ fn resolve_startup_pool_defaults_with( /// resolves. Every remote format read would otherwise fail client-side with /// "No valid auth token" and startup would retry for minutes before dying with /// a misleading "erasure read quorum" error (issues #4939, #5153). -fn preflight_startup_rpc_secret(endpoint_pools: &EndpointServerPools) -> Result<()> { +pub(super) fn preflight_startup_rpc_secret(endpoint_pools: &EndpointServerPools) -> Result<()> { preflight_startup_rpc_secret_with(endpoint_pools, try_get_rpc_token) } @@ -101,14 +101,14 @@ const LOCAL_DECOMMISSION_WATCHDOG_MAX_RETRY_DELAY: Duration = Duration::from_sec const REBALANCE_INITIAL_RESUME_DELAY: Duration = Duration::from_secs(10); const REBALANCE_RESUME_RETRY_DELAY: Duration = Duration::from_secs(10); -fn should_retry_format_load(err: &Error) -> bool { +pub(super) fn should_retry_format_load(err: &Error) -> bool { !matches!( err, Error::CorruptedFormat | Error::UnsupportedSnsdExpansion { .. } | Error::PoolTopologyMismatch { .. } ) } -fn format_load_retry_exhausted(err: &Error, retries: u32) -> bool { +pub(super) fn format_load_retry_exhausted(err: &Error, retries: u32) -> bool { retries >= 10 && !matches!(err, Error::ErasureReadQuorum | Error::FirstDiskWait | Error::NotFirstDisk) } @@ -480,8 +480,64 @@ impl ECStore { /// Validate topology and process storage-class overrides before any disk is opened. pub fn validate_startup_storage_class(endpoint_pools: &EndpointServerPools) -> Result<()> { + Self::validate_storage_class_with_kvs(endpoint_pools, None).map(|_| ()) + } + + /// Validate storage-class parity settings against `endpoint_pools`, merging + /// persisted `server_config` storage-class KVS with optional candidate overrides. + pub fn validate_storage_class_with_kvs( + endpoint_pools: &EndpointServerPools, + extra_kvs: Option<&KVS>, + ) -> Result { let drive_counts = startup_pool_drive_counts(endpoint_pools); - storageclass::lookup_config_for_pools(&KVS::new(), &drive_counts).map(|_| ()) + let mut merged = runtime_sources::server_config() + .and_then(|cfg| cfg.get_value(crate::config::com::STORAGE_CLASS_SUB_SYS, rustfs_config::DEFAULT_DELIMITER)) + .unwrap_or_default(); + if let Some(extra) = extra_kvs { + for kv in &extra.0 { + merged.insert(kv.key.clone(), kv.value.clone()); + } + } + storageclass::lookup_config_for_pools(&merged, &drive_counts) + } + + /// Validate storage-class parity settings against `endpoint_pools`, applying + /// optional staged `STANDARD` and `RRS` overrides from a candidate env file. + pub fn validate_storage_class_with_overrides( + endpoint_pools: &EndpointServerPools, + standard_override: Option<&str>, + rrs_override: Option<&str>, + ) -> Result<()> { + let drive_counts = startup_pool_drive_counts(endpoint_pools); + let merged = runtime_sources::server_config() + .and_then(|cfg| cfg.get_value(crate::config::com::STORAGE_CLASS_SUB_SYS, rustfs_config::DEFAULT_DELIMITER)) + .unwrap_or_default(); + storageclass::lookup_config_for_pools_with_overrides( + &merged, + &drive_counts, + standard_override + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(ToOwned::to_owned), + rrs_override.map(str::trim).filter(|s| !s.is_empty()).map(ToOwned::to_owned), + ) + .map(|_| ()) + } + + /// Whether this `ECStore` generation has been superseded by a newer live + /// topology hot-reload generation on the same [`InstanceContext`]. + pub fn is_retired(&self) -> bool { + let active = self.ctx.active_store_ptr(); + active != 0 && active != std::ptr::from_ref(self) as usize + } + + pub(crate) fn ensure_not_retired(&self) -> Result<()> { + if self.is_retired() { + return Err(Error::other( + "storage topology generation has been hot-reloaded; retry against active store", + )); + } + Ok(()) } #[allow(clippy::new_ret_no_self)] @@ -690,6 +746,11 @@ impl ECStore { if !instance_ctx.is_dist_erasure().await { runtime_sources::record_local_disks(&instance_ctx, local_disks).await; } + // Populate the local disk-ID lookup map now that all pools have loaded or + // created their `format.json`, so standby joining nodes immediately accept + // disk-ID-addressed RPCs without missing-disk races during hot-reload. + crate::store::peer::prewarm_local_disk_id_map_with_instance_ctx(&instance_ctx).await; + instance_ctx.mark_startup_formats_ready(); let deployment_id = deployment_id.ok_or_else(|| Error::other("store init failed: deployment id is not initialized"))?; let peer_sys = S3PeerSys::new_with_instance_ctx(&endpoint_pools, instance_ctx.clone()); @@ -726,14 +787,62 @@ impl ECStore { if instance_ctx.deployment_id().is_none() { instance_ctx.set_deployment_id(deployment_id); } + instance_ctx.set_live_store(&ec); let wait_sec = 5; + let join_wait_timeout = Duration::from_secs(rustfs_utils::get_env_u64("RUSTFS_POOL_JOIN_WAIT_TIMEOUT_SECS", 1800)); + let join_wait_started = tokio::time::Instant::now(); let mut exit_count = 0; + let mut standby_iters = 0_u64; loop { if let Err(err) = ec.init(ctx.clone()).await { + let bootstrap_pending = err.to_string().contains("pool metadata bootstrap pending"); + if bootstrap_pending && join_wait_started.elapsed() < join_wait_timeout { + let standby_poll = Duration::from_secs(2); + if standby_iters == 0 { + info!( + event = EVENT_ECSTORE_INIT_STATUS, + component = LOG_COMPONENT_ECSTORE, + subsystem = LOG_SUBSYSTEM_STORE_INIT, + stage = "pool_join_standby", + retry_delay_ms = standby_poll.as_millis() as u64, + "Waiting in standby for elected pool writer to commit hot-reloaded topology" + ); + } else if standby_iters.is_multiple_of(15) { + debug!( + event = EVENT_ECSTORE_INIT_STATUS, + component = LOG_COMPONENT_ECSTORE, + subsystem = LOG_SUBSYSTEM_STORE_INIT, + stage = "pool_join_standby", + standby_iters, + elapsed_secs = join_wait_started.elapsed().as_secs(), + "Still waiting in standby for elected pool writer to commit hot-reloaded topology" + ); + } + standby_iters = standby_iters.saturating_add(1); + select! { + _ = ctx.cancelled() => { + return Err(Error::other(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "storage initialization cancelled while awaiting pool topology commit", + ))); + } + _ = instance_ctx.wait_pool_join_wakeup() => {} + _ = sleep(standby_poll) => {} + } + continue; + } error!("init err: {}", err); error!("retry after {} second", wait_sec); - sleep(Duration::from_secs(wait_sec)).await; + select! { + _ = ctx.cancelled() => { + return Err(Error::other(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "storage initialization cancelled", + ))); + } + _ = sleep(Duration::from_secs(wait_sec)) => {} + } if exit_count > 10 { return Err(Error::other("store init failed: init retry budget exhausted")); @@ -752,7 +861,7 @@ impl ECStore { Ok(ec) } - async fn init_pool_metadata_for_startup(self: &Arc) -> Result<(PoolMeta, PoolMetaReplicaState)> { + pub(super) async fn init_pool_metadata_for_startup(self: &Arc) -> Result<(PoolMeta, PoolMetaReplicaState)> { let should_persist_pool_meta = self .pools .first() @@ -1024,7 +1133,6 @@ impl ECStore { } let local_pool_indices = local_decommission_queue_prefix(&endpoints, &pool_indices)?; - let has_local_decommission_leadership = endpoints.as_ref().iter().any(pool_first_endpoint_is_local); let pool_meta_write_safe = self .ensure_pool_meta_side_effects_safe("decommission resume blocked while pool metadata requires recovery") .await @@ -1040,14 +1148,47 @@ impl ECStore { "Decommission watchdog waiting for pool metadata recovery" ); } + let gen_rx = self.spawn_generation_background_workers(&endpoints, &rx); + + runtime_sources::init_bucket_monitor_for_current_endpoints(); + crate::bucket::bucket_target_sys::BucketTargetSys::get().start_heartbeat(); + + init_background_expiry(self.clone()).await; + crate::bucket::lifecycle::bucket_lifecycle_ops::init_background_stale_multipart_upload_cleanup(self.clone()); + + TransitionState::init(self.clone()).await; + crate::services::tier::tier::try_migrate_tiering_config(self.clone()).await; + + if let Err(err) = runtime_sources::init_tier_config_mgr(self.clone()).await { + info!("TierConfigMgr init error: {}", err); + } + + if rebalance_auto_start_deferred { + let store = self.clone(); + tokio::spawn(resume_rebalance_after_init(store, gen_rx)); + } + + Ok(()) + } + + /// Rotate the per-generation worker cancellation token (cancelling any retired + /// generation's loops) and spawn generation-bound supervisors (`decommission` + /// watchdog, `pool.bin` transaction recovery, and `delete_recovery`) onto `self`. + pub(super) fn spawn_generation_background_workers( + self: &Arc, + endpoints: &EndpointServerPools, + parent_rx: &CancellationToken, + ) -> CancellationToken { + let gen_rx = self.ctx.rotate_generation_cancel(parent_rx); + let has_local_decommission_leadership = endpoints.as_ref().iter().any(pool_first_endpoint_is_local); if has_local_decommission_leadership { // The watchdog checks recovery safety and retries transient failures. // Resume persisted work without an unconditional cold-start delay. - tokio::spawn(supervise_local_decommission_after_init(self.clone(), rx.clone())); + tokio::spawn(supervise_local_decommission_after_init(self.clone(), gen_rx.clone())); } let recovery_store = self.clone(); - let recovery_rx = rx.clone(); + let recovery_rx = gen_rx.clone(); tokio::spawn(async move { let mut delay = std::time::Duration::from_secs(5); loop { @@ -1073,27 +1214,8 @@ impl ECStore { } }); - super::delete_recovery_runtime::start_delete_recovery(self.clone(), rx.clone()); - - runtime_sources::init_bucket_monitor_for_current_endpoints(); - crate::bucket::bucket_target_sys::BucketTargetSys::get().start_heartbeat(); - - init_background_expiry(self.clone()).await; - crate::bucket::lifecycle::bucket_lifecycle_ops::init_background_stale_multipart_upload_cleanup(self.clone()); - - TransitionState::init(self.clone()).await; - crate::services::tier::tier::try_migrate_tiering_config(self.clone()).await; - - if let Err(err) = runtime_sources::init_tier_config_mgr(self.clone()).await { - info!("TierConfigMgr init error: {}", err); - } - - if rebalance_auto_start_deferred { - let store = self.clone(); - tokio::spawn(resume_rebalance_after_init(store, rx)); - } - - Ok(()) + super::delete_recovery_runtime::start_delete_recovery(self.clone(), gen_rx.clone()); + gen_rx } pub fn init_local_disks() {} @@ -2095,6 +2217,147 @@ mod tests { .expect("no latch remains after convergence"); } + #[tokio::test] + async fn test_single_pool_non_elected_follower_converges_without_latching_write_gate() { + let deployment_id = Uuid::new_v4(); + let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new())); + let pools = vec![pool0.clone()]; + let mut elected = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities( + deployment_id, + vec![PoolMetaBootstrapAuthority::Fresh], + true, + ); + let mut follower = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities( + deployment_id, + vec![PoolMetaBootstrapAuthority::None], + false, + ); + assert!(!follower.bootstrap_identity_proven()); + + // Stage 1: before the elected writer mints a pending identity, the + // non-elected follower waits without writing or latching write_blocked. + establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut follower, false) + .await + .expect("single-pool follower writes no identity before bootstrap"); + let err = load_pool_meta_for_startup(pools.clone(), &mut follower) + .await + .expect_err("follower waits for elected writer to establish cluster identity"); + assert!( + err.to_string() + .contains("waiting for the elected writer to establish the cluster identity"), + "{err}" + ); + follower + .ensure_write_safe("single-pool follower before identity") + .expect("waiting for initial identity must not latch the write gate"); + assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), 0); + assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), 0); + + // Stage 2: elected writer mints the nonce-bound pending identity, but + // has not yet published pool.bin; follower still waits unlatched. + establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut elected, true) + .await + .expect("elected writer mints single-pool pending identity"); + let minted_writes = pool0.identity_write_attempts.load(Ordering::SeqCst); + assert_eq!(minted_writes, 1); + establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut follower, false) + .await + .expect("single-pool follower does not overwrite pending identity"); + assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), minted_writes); + let err = load_pool_meta_for_startup(pools.clone(), &mut follower) + .await + .expect_err("follower waits for elected writer to publish pool.bin"); + assert!( + err.to_string() + .contains("waiting for the elected writer to publish the initial pool.bin"), + "{err}" + ); + follower + .ensure_write_safe("single-pool follower during pending identity") + .expect("waiting for initial pool.bin must not latch the write gate"); + assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), 0); + + // Stage 3: elected writer commits V3 pool.bin and initialized identity; + // the same follower converges to write-ready with zero writes. + let (_, replica_state) = load_pool_meta_for_startup(pools.clone(), &mut elected) + .await + .expect("elected writer loads proven single-pool bootstrap"); + persist_pool_meta_for_startup_if_safe(&init_test_pool_meta(None), pools.clone(), replica_state, &mut elected, true, true) + .await + .expect("elected writer commits V3 pool.bin and initialized identity"); + let committed_identity_writes = pool0.identity_write_attempts.load(Ordering::SeqCst); + let committed_meta_writes = pool0.pool_meta_write_attempts.load(Ordering::SeqCst); + + establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut follower, false) + .await + .expect("converged follower leaves initialized identity untouched"); + load_pool_meta_for_startup(pools.clone(), &mut follower) + .await + .expect("published pool.bin admits single-pool follower"); + complete_pool_meta_for_startup(pools, &mut follower, false, None, async { + panic!("converged follower must never execute intent retirement") + }) + .await + .expect("converged single-pool follower completes startup read-only"); + follower + .ensure_write_safe("converged single-pool follower") + .expect("converged follower remains write-ready"); + assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), committed_identity_writes); + assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), committed_meta_writes); + } + + #[tokio::test] + async fn test_single_pool_non_elected_follower_escalates_hard_faults_to_latched_recovery() { + let deployment_id = Uuid::new_v4(); + let initialized = initialized_pool_meta_identity_for_test(deployment_id, 1).expect("encode initialized identity"); + let mut corrupt = pending_pool_meta_identity_for_test(deployment_id, 1, Uuid::new_v4()).expect("encode pending identity"); + corrupt.truncate(4); + corrupt.extend_from_slice(b"corrupt single-pool identity"); + + for (label, bad_identity, expected_msg) in [ + ( + "initialized_missing_pool_meta", + initialized.clone(), + "initialized cluster identity exists", + ), + ("corrupt_identity_missing_pool_meta", corrupt, "corrupt"), + ] { + let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new())); + inject_startup_object(&pool0, POOL_META_IDENTITY_NAME, bad_identity); + let pools = vec![pool0.clone()]; + let mut follower = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities( + deployment_id, + vec![PoolMetaBootstrapAuthority::None], + false, + ); + + let err = load_pool_meta_for_startup(pools.clone(), &mut follower) + .await + .expect_err("hard fault on single-pool follower must fail closed"); + assert!(error_chain_text(&err).contains(expected_msg), "case={label} err={err}"); + let latch = follower + .ensure_write_safe("single-pool follower hard fault") + .expect_err("hard fault must latch the write gate"); + assert_eq!( + latch.pool_metadata_failure().expect("typed recovery latch").kind, + crate::error::PoolMetadataFailure::RecoveryRequired, + "case={label} latch={latch}" + ); + + // A later healthy snapshot must not silently clear the recovery latch. + inject_startup_object(&pool0, POOL_META_IDENTITY_NAME, initialized.clone()); + inject_startup_object(&pool0, POOL_META_NAME, startup_pool_meta_payload(&init_test_pool_meta(None))); + load_pool_meta_for_startup(pools, &mut follower) + .await + .expect("repaired snapshot remains readable for diagnostics"); + follower + .ensure_write_safe("single-pool follower after later healthy replica") + .expect_err("recovery latch must remain active after hard fault"); + assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), 0); + assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), 0); + } + } + #[tokio::test] async fn test_two_pool_bootstrap_rejects_pending_replicas_from_different_bootstraps() { let deployment_id = Uuid::new_v4(); diff --git a/crates/ecstore/src/store/init_format.rs b/crates/ecstore/src/store/init_format.rs index a6cdc39f50..3c207ddbcc 100644 --- a/crates/ecstore/src/store/init_format.rs +++ b/crates/ecstore/src/store/init_format.rs @@ -93,6 +93,55 @@ pub async fn init_disks( (res, errors) } +/// Initialize pool disk handles during staged topology reload without reading +/// or mutating live `instance_ctx.local_disk_map`. +pub(crate) async fn init_disks_with_staged_locals( + instance_ctx: &InstanceContext, + eps: &Endpoints, + opt: &DiskOption, + staged_locals: &std::collections::HashMap>, +) -> (Vec>, Vec>) { + let mut futures = Vec::with_capacity(eps.as_ref().len()); + + for ep in eps.as_ref().iter() { + let staged = if ep.is_local { + staged_locals.get(&ep.to_string()).cloned() + } else { + None + }; + futures.push(async move { + if ep.is_local { + match staged { + Some(Some(disk)) => Ok(disk), + Some(None) => Err(DiskError::VolumeNotFound), + None => Err(DiskError::DiskNotFound), + } + } else { + crate::disk::new_disk_for_instance(instance_ctx, ep, opt).await + } + }); + } + + let mut res = Vec::with_capacity(eps.as_ref().len()); + let mut errors = Vec::with_capacity(eps.as_ref().len()); + + let results = join_all(futures).await; + for result in results { + match result { + Ok(s) => { + res.push(Some(s)); + errors.push(None); + } + Err(e) => { + res.push(None); + errors.push(Some(e)); + } + } + } + + (res, errors) +} + #[cfg(test)] pub async fn connect_load_init_formats( first_disk: bool, @@ -119,6 +168,29 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx( set_count: usize, set_drive_count: usize, deployment_id: Option, +) -> Result { + connect_load_init_formats_inner(instance_ctx, first_disk, disks, set_count, set_drive_count, deployment_id, false).await +} + +pub(crate) async fn connect_load_init_formats_staged( + instance_ctx: &Arc, + first_disk: bool, + disks: &mut [Option], + set_count: usize, + set_drive_count: usize, + deployment_id: Option, +) -> Result { + connect_load_init_formats_inner(instance_ctx, first_disk, disks, set_count, set_drive_count, deployment_id, true).await +} + +async fn connect_load_init_formats_inner( + instance_ctx: &Arc, + first_disk: bool, + disks: &mut [Option], + set_count: usize, + set_drive_count: usize, + deployment_id: Option, + staged_mode: bool, ) -> Result { let (formats, errs, unformatted_bootstrap_routes) = load_format_erasure_all_observing_bootstrap_routes(disks, false).await; @@ -126,8 +198,17 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx( // Only the elected pool creator may replay a complete durable format plan. // Absence of pool metadata or an orphaned format temp file grants no authority. if first_disk - && let Some(format) = - resume_format_bootstrap(instance_ctx, disks, &formats, &errs, set_count, set_drive_count, deployment_id).await? + && let Some(format) = resume_format_bootstrap( + instance_ctx, + disks, + &formats, + &errs, + set_count, + set_drive_count, + deployment_id, + staged_mode, + ) + .await? { return Ok(LoadedFormat { format, @@ -199,7 +280,16 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx( match try_migrate_format(disks, &formats, set_count, set_drive_count, mode).await { Ok(LegacyFormatOutcome::Migrated { format, quorum_members }) => { info!("Migrated format from MinIO config"); - retain_format_quorum_members(instance_ctx, disks, &format, &quorum_members, None, set_drive_count).await?; + retain_format_quorum_members_with_mode( + instance_ctx, + disks, + &format, + &quorum_members, + None, + set_drive_count, + staged_mode, + ) + .await?; return Ok(LoadedFormat { format: *format, pool_meta_bootstrap_authority: PoolMetaBootstrapAuthority::LegacyAdoption, @@ -219,7 +309,8 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx( Err(e) => return Err(e), } if first_disk && fresh_bootstrap_proven { - let fm = init_format_erasure(instance_ctx, disks, set_count, set_drive_count, deployment_id).await?; + let fm = init_format_erasure_with_mode(instance_ctx, disks, set_count, set_drive_count, deployment_id, staged_mode) + .await?; return Ok(LoadedFormat { format: fm, pool_meta_bootstrap_authority: PoolMetaBootstrapAuthority::Fresh, @@ -230,13 +321,14 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx( // Resolve legacy migration before admitting native reads. Blank replacement // slots contribute no votes and receive no formatting/bootstrap authority. if let Some((format, members)) = native_read_candidate { - retain_format_quorum_members( + retain_format_quorum_members_with_mode( instance_ctx, disks, &format, &members, Some(&unformatted_bootstrap_routes), set_drive_count, + staged_mode, ) .await?; // Loading an existing format grants no authority to initialize pool @@ -267,13 +359,14 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx( None => select_format_erasure_in_quorum(&formats, 0)?, }; check_format_erasure_value_for_topology(&fm, formats.len(), set_drive_count)?; - retain_format_quorum_members( + retain_format_quorum_members_with_mode( instance_ctx, disks, &fm, &quorum_members, Some(&unformatted_bootstrap_routes), set_drive_count, + staged_mode, ) .await?; @@ -304,6 +397,7 @@ async fn verified_legacy_adoption_source( } } +#[allow(dead_code)] pub(super) async fn retain_format_quorum_members( instance_ctx: &Arc, disks: &mut [Option], @@ -311,6 +405,27 @@ pub(super) async fn retain_format_quorum_members( quorum_members: &[bool], unformatted_bootstrap_routes: Option<&[bool]>, set_drive_count: usize, +) -> Result<()> { + retain_format_quorum_members_with_mode( + instance_ctx, + disks, + format, + quorum_members, + unformatted_bootstrap_routes, + set_drive_count, + false, + ) + .await +} + +pub(super) async fn retain_format_quorum_members_with_mode( + instance_ctx: &Arc, + disks: &mut [Option], + format: &FormatV3, + quorum_members: &[bool], + unformatted_bootstrap_routes: Option<&[bool]>, + set_drive_count: usize, + staged_mode: bool, ) -> Result<()> { if set_drive_count == 0 || quorum_members.len() != disks.len() @@ -319,11 +434,15 @@ pub(super) async fn retain_format_quorum_members( return Err(Error::CorruptedFormat); } - let pool_idx = disks - .iter() - .flatten() - .map(|disk| disk.endpoint().pool_idx) - .find_map(|pool_idx| usize::try_from(pool_idx).ok()); + let pool_idx = if staged_mode { + None + } else { + disks + .iter() + .flatten() + .map(|disk| disk.endpoint().pool_idx) + .find_map(|pool_idx| usize::try_from(pool_idx).ok()) + }; let registered_endpoints = if let Some(pool_idx) = pool_idx { instance_ctx .local_disk_set_drives() @@ -384,18 +503,28 @@ pub(super) async fn retain_format_quorum_members( selected_local_disk_ids.push((disk_id, disk.endpoint().to_string())); } } - if bootstrap_routes.is_empty() { - quarantine_local_disks(instance_ctx, &quarantined_endpoints).await?; - } else { - quarantine_local_disks_preserving_bootstrap_routes(instance_ctx, &quarantined_endpoints, &bootstrap_routes).await?; + if !staged_mode { + if bootstrap_routes.is_empty() { + quarantine_local_disks(instance_ctx, &quarantined_endpoints).await?; + } else { + quarantine_local_disks_preserving_bootstrap_routes(instance_ctx, &quarantined_endpoints, &bootstrap_routes).await?; + } } for (disk, disk_id) in disks.iter().zip(member_disk_ids) { if let Some(disk) = disk { - disk.set_disk_id_state(disk_id).await?; + if staged_mode { + // During staged reload, update only the wrapper's in-memory ID + // without mutating `instance_ctx.local_disk_id_map` before cutover. + disk.set_disk_id(disk_id).await?; + } else { + disk.set_disk_id_state(disk_id).await?; + } } } - reconcile_local_disk_ids(instance_ctx, &local_pool_endpoints, &selected_local_disk_ids).await; + if !staged_mode { + reconcile_local_disk_ids(instance_ctx, &local_pool_endpoints, &selected_local_disk_ids).await; + } for (disk, belongs_to_quorum) in disks.iter_mut().zip(quorum_members) { if !belongs_to_quorum { *disk = None; @@ -430,12 +559,24 @@ pub fn check_disk_fatal_errs(errs: &[Option]) -> disk::error::Result< Ok(()) } +#[allow(dead_code)] async fn init_format_erasure( instance_ctx: &Arc, disks: &mut [Option], set_count: usize, set_drive_count: usize, deployment_id: Option, +) -> Result { + init_format_erasure_with_mode(instance_ctx, disks, set_count, set_drive_count, deployment_id, false).await +} + +async fn init_format_erasure_with_mode( + instance_ctx: &Arc, + disks: &mut [Option], + set_count: usize, + set_drive_count: usize, + deployment_id: Option, + staged_mode: bool, ) -> Result { let mut fm = FormatV3::new(set_count, set_drive_count); if let Some(id) = deployment_id { @@ -447,7 +588,8 @@ async fn init_format_erasure( write_format_file_all(disks, &fms).await?; let format = get_format_erasure_in_quorum(&fms, 0)?; let quorum_members = vec![true; disks.len()]; - retain_format_quorum_members(instance_ctx, disks, &format, &quorum_members, None, set_drive_count).await?; + retain_format_quorum_members_with_mode(instance_ctx, disks, &format, &quorum_members, None, set_drive_count, staged_mode) + .await?; Ok(format) } diff --git a/crates/ecstore/src/store/mod.rs b/crates/ecstore/src/store/mod.rs index 1fbe17c904..41b671c6a1 100644 --- a/crates/ecstore/src/store/mod.rs +++ b/crates/ecstore/src/store/mod.rs @@ -458,6 +458,7 @@ pub use object::{ }; mod peer; mod rebalance; +pub mod reload; #[cfg(test)] mod usage_watch_tests; #[cfg(all(test, feature = "test-util"))] @@ -471,6 +472,12 @@ pub use peer::{ BootstrapLocalTarget, all_local_disk, all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc, get_disk_infos, init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map, prewarm_local_disk_id_map_with_instance_ctx, + refresh_local_disks_for_topology_reload, refresh_lock_clients, +}; +pub use reload::{ + CandidateDiskFormatState, CandidateDiskProbe, CandidateDiskProbeReport, DynamicECStoreHandle, PoolGeometrySummary, + TopologyDiff, TopologyReloadMode, TopologyReloadOutcome, TopologyTransitionKind, analyze_topology_transition, + summarize_endpoint_pools, summarize_pool_geometry, }; pub struct ECStore { @@ -950,6 +957,8 @@ impl ECStore { disk.as_ref().is_some_and(|disk| match disk.as_ref() { crate::disk::Disk::Local(wrapper) => wrapper.get_disk().usage_watch_binding.matches(&self.ctx.usage_watches), crate::disk::Disk::Remote(_) => false, + #[cfg(feature = "dst")] + crate::disk::Disk::Sim(_) => false, }) }); drop(local_disks); diff --git a/crates/ecstore/src/store/peer.rs b/crates/ecstore/src/store/peer.rs index 17fd9b4d2a..40397a11dd 100644 --- a/crates/ecstore/src/store/peer.rs +++ b/crates/ecstore/src/store/peer.rs @@ -46,6 +46,15 @@ impl BootstrapLocalTarget { Arc::ptr_eq(&self.ctx, &store.ctx) } + pub fn is_startup_formats_ready(&self) -> bool { + self.ctx.is_startup_formats_ready() + } + + /// Wake the standby pool-join loop immediately once `pool.bin` has been committed. + pub fn notify_pool_join_wakeup(&self) { + self.ctx.notify_pool_join_wakeup(); + } + /// Atomically publish a format control file on this bootstrap instance. /// /// # Errors @@ -676,7 +685,16 @@ pub async fn init_local_disks_with_instance_ctx( runtime_sources::initialize_local_disk_maps(instance_ctx, endpoint_pools, opt).await } -pub fn init_lock_clients(endpoint_pools: EndpointServerPools) { +/// Refresh local disks for a live topology hot-reload without running +/// destructive startup cleanup on active disks. +pub async fn refresh_local_disks_for_topology_reload( + instance_ctx: &Arc, + endpoint_pools: EndpointServerPools, +) -> Result<()> { + runtime_sources::refresh_local_disk_maps_for_reload(instance_ctx, endpoint_pools).await +} + +fn build_lock_clients_map(endpoint_pools: &EndpointServerPools) -> HashMap> { let mut unique_endpoints: HashMap = HashMap::new(); for pool_eps in endpoint_pools.as_ref().iter() { @@ -686,35 +704,49 @@ pub fn init_lock_clients(endpoint_pools: EndpointServerPools) { } let mut clients = HashMap::new(); - let mut first_local_client_set = false; + let existing_map = runtime_sources::global_lock_clients(); + let existing_local = runtime_sources::global_lock_client(); + let mut local_client_handle = existing_local.clone(); for (key, endpoint) in unique_endpoints { if endpoint.is_local { - let local_client = Arc::new(LocalClient::new()) as Arc; + let local_client = local_client_handle + .get_or_insert_with(|| Arc::new(LocalClient::new()) as Arc) + .clone(); - // Store the first LocalClient globally for use by other modules - if !first_local_client_set { - if let Err(e) = runtime_sources::set_primary_lock_client(local_client.clone()) { - // If already set, ignore the error (another thread may have set it) - debug!( - event = EVENT_LOCK_CLIENT_INITIALIZATION_FAILED, - component = LOG_COMPONENT_ECSTORE, - subsystem = LOG_SUBSYSTEM_DISK_STARTUP, - error = ?e, - reason = "global_lock_client_already_set", - "Skipped global lock client publication" - ); - } else { - first_local_client_set = true; - } + if existing_local.is_none() + && let Err(e) = runtime_sources::set_primary_lock_client(local_client.clone()) + { + debug!( + event = EVENT_LOCK_CLIENT_INITIALIZATION_FAILED, + component = LOG_COMPONENT_ECSTORE, + subsystem = LOG_SUBSYSTEM_DISK_STARTUP, + error = ?e, + reason = "global_lock_client_already_set", + "Skipped global lock client publication" + ); } clients.insert(key, local_client); + } else if let Some(existing_remote) = existing_map.as_ref().and_then(|map| map.get(&key)).cloned() { + clients.insert(key, existing_remote); } else { clients.insert(key, Arc::new(RemoteClient::new(endpoint.url.to_string())) as Arc); } } + clients +} + +/// Build a staged lock-client map for `endpoint_pools` without mutating +/// the active lock-client registry until atomic hot-reload cutover. +pub(super) fn build_staged_lock_clients_map(endpoint_pools: &EndpointServerPools) -> HashMap> { + build_lock_clients_map(endpoint_pools) +} + +pub fn init_lock_clients(endpoint_pools: EndpointServerPools) { + let clients = build_lock_clients_map(&endpoint_pools); + // Store the lock clients map globally if runtime_sources::set_lock_clients(clients).is_err() { error!( @@ -727,6 +759,14 @@ pub fn init_lock_clients(endpoint_pools: EndpointServerPools) { } } +/// Atomically refresh the global lock clients map during a live topology reload, +/// preserving the existing primary `LocalClient` so active local locks remain +/// visible across the topology transition. +pub fn refresh_lock_clients(endpoint_pools: EndpointServerPools) { + let clients = build_lock_clients_map(&endpoint_pools); + runtime_sources::replace_lock_clients(clients); +} + fn endpoint_rpc_authority(endpoint: &Endpoint) -> Option { let host = endpoint.url.host_str()?; let host = if host.contains(':') && !host.starts_with('[') { @@ -740,30 +780,28 @@ fn endpoint_rpc_authority(endpoint: &Endpoint) -> Option { }) } -pub(super) async fn init_local_peer(endpoint_pools: &EndpointServerPools, host: &String, port: &String) { - let mut peer_set = Vec::new(); - endpoint_pools.as_ref().iter().for_each(|endpoints| { - endpoints.endpoints.as_ref().iter().for_each(|endpoint| { +pub(super) fn resolve_local_peer_name(endpoint_pools: &EndpointServerPools, host: &str, port: &str) -> String { + for endpoints in endpoint_pools.as_ref() { + for endpoint in endpoints.endpoints.as_ref() { if endpoint.get_type() == EndpointType::Url && endpoint.is_local && let Some(authority) = endpoint_rpc_authority(endpoint) { - peer_set.push(authority); + return authority; } - }); - }); - - if peer_set.is_empty() { - if !host.is_empty() { - runtime_sources::set_local_node_name(format!("{host}:{port}")).await; - return; } - - runtime_sources::set_local_node_name(format!("127.0.0.1:{port}")).await; - return; } - runtime_sources::set_local_node_name(peer_set[0].clone()).await; + if !host.is_empty() { + return format!("{host}:{port}"); + } + + format!("127.0.0.1:{port}") +} + +pub(super) async fn init_local_peer(endpoint_pools: &EndpointServerPools, host: &str, port: &str) { + let resolved = resolve_local_peer_name(endpoint_pools, host, port); + runtime_sources::set_local_node_name(resolved).await; } pub async fn get_disk_infos(disks: &[Option]) -> Vec> { diff --git a/crates/ecstore/src/store/reload.rs b/crates/ecstore/src/store/reload.rs new file mode 100644 index 0000000000..cbf9537961 --- /dev/null +++ b/crates/ecstore/src/store/reload.rs @@ -0,0 +1,2236 @@ +// Copyright 2024 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Live zero-downtime pool topology validation, disk/format preflight probing, +//! and RCU generation hot-reload for [`ECStore`]. + +use super::ECStore; +use super::init::{ + format_load_retry_exhausted, pool_first_endpoint_is_local, preflight_startup_rpc_secret, resolve_startup_pool_defaults, + should_retry_format_load, +}; +use super::init_format::{self, check_disk_fatal_errs}; +use super::peer::{build_staged_lock_clients_map, resolve_local_peer_name}; +use crate::cluster::rpc::S3PeerSys; +use crate::core::pools::{PoolMeta, PoolMetaBootstrapAuthority, PoolMetaWriteState}; +use crate::core::sets::Sets; +use crate::disk::error::DiskError; +use crate::disk::{DiskAPI, DiskInfoOptions, DiskOption, DiskStore, FORMAT_CONFIG_FILE, RUSTFS_META_BUCKET, format::FormatV3}; +use crate::error::{Error, Result}; +use crate::layout::endpoints::{EndpointServerPools, PoolEndpoints, SetupType}; +use crate::runtime::instance::InstanceContext; +use crate::runtime::sources as runtime_sources; +use crate::services::notification_sys::replace_global_notification_sys; +use crate::storage_api_contracts::bucket::{BucketInfo, BucketOperations, MakeBucketOptions}; +use futures::stream::{self, StreamExt}; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::net::SocketAddr; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::sync::{Mutex, RwLock}; +use tokio::time::sleep; +use tokio_util::sync::CancellationToken; +use tracing::{debug, info, warn}; + +const LOG_COMPONENT_ECSTORE: &str = "ecstore"; +const LOG_SUBSYSTEM_TOPOLOGY_RELOAD: &str = "topology_reload"; +const EVENT_TOPOLOGY_RELOAD_STAGE: &str = "topology_reload_stage"; +const POOL_META_BOOTSTRAP_PENDING_MARKER: &str = "pool metadata bootstrap pending"; +const NON_WRITER_POOL_META_WAIT_ATTEMPTS: usize = 60; +const NON_WRITER_POOL_META_WAIT_INTERVAL: Duration = Duration::from_millis(500); +const MIN_RECOMMENDED_FREE_INODES: u64 = 1_000; + +/// Intended maintenance operation mode for a live topology reload. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TopologyReloadMode { + Expand, + Decommission, +} + +impl TopologyReloadMode { + pub const fn as_str(self) -> &'static str { + match self { + Self::Expand => "expand", + Self::Decommission => "decommission", + } + } +} + +/// Classification of the diff between active and candidate endpoint topologies. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TopologyTransitionKind { + Expand, + Decommission, + Noop, + Invalid, +} + +impl TopologyTransitionKind { + pub const fn as_str(self) -> &'static str { + match self { + Self::Expand => "expand", + Self::Decommission => "decommission", + Self::Noop => "noop", + Self::Invalid => "invalid", + } + } +} + +/// Geometry and host distribution summary of one storage pool. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PoolGeometrySummary { + pub pool_index: usize, + pub cmd_line: String, + pub set_count: usize, + pub drives_per_set: usize, + pub parity_drives: usize, + pub data_drives: usize, + pub endpoint_count: usize, + pub local_endpoint_count: usize, + pub hosts: Vec, + pub decommissioned: bool, + pub decommission_complete: bool, + pub unresolved_entries: usize, + pub host_failure_risk: bool, +} + +/// Structured diff between the active in-memory pool topology and a candidate topology. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TopologyDiff { + pub kind: TopologyTransitionKind, + pub current_pools: Vec, + pub target_pools: Vec, + pub added_pools: Vec, + pub removed_pools: Vec, + pub retained_pools: Vec, + pub errors: Vec, + pub warnings: Vec, +} + +/// Format state observed on a single disk during preflight probing. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CandidateDiskFormatState { + Unformatted, + MatchingCluster, + ForeignCluster, + TopologyMismatch, + Corrupt, + Offline, +} + +/// Per-endpoint disk probe report collected during expansion/decommission preflight. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CandidateDiskProbe { + pub pool_index: usize, + pub endpoint: String, + pub host: String, + pub is_local: bool, + pub reachable: bool, + pub format_state: CandidateDiskFormatState, + pub deployment_id: Option, + pub total_bytes: u64, + pub free_bytes: u64, + pub free_inodes: u64, + pub fs_type: String, + pub error: Option, +} + +/// Aggregated disk & quorum probe report for candidate topology preflight. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CandidateDiskProbeReport { + pub ok: bool, + pub disks: Vec, + pub errors: Vec, + pub warnings: Vec, +} + +/// Outcome of a committed live topology hot-reload. +#[derive(Clone)] +pub struct TopologyReloadOutcome { + pub store: Arc, + pub generation: u64, + pub mode: TopologyReloadMode, + pub previous_pool_count: usize, + pub new_pool_count: usize, + pub added_pools: Vec, + pub removed_pools: Vec, + pub buckets_propagated: usize, + pub duration_ms: u64, +} + +/// Lightweight, generation-aware handle to an instance's live [`ECStore`]. +/// +/// Resolves the active `ECStore` generation published on [`InstanceContext`] +/// without retaining superseded generations after a live topology hot-reload. +#[derive(Clone)] +pub struct DynamicECStoreHandle { + ctx: Arc, + cell: Arc>>, +} + +impl std::fmt::Debug for DynamicECStoreHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DynamicECStoreHandle") + .field("generation", &self.ctx.topology_generation()) + .finish() + } +} + +impl DynamicECStoreHandle { + /// Return the currently active [`ECStore`] generation for this instance. + pub fn current(&self) -> Arc { + if let Some(live) = self.ctx.live_store() { + return live; + } + self.cell.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone() + } + + fn require_live(&self) -> Result> { + Ok(self.current()) + } +} + +#[async_trait::async_trait] +impl crate::storage_api_contracts::object::ObjectIO for DynamicECStoreHandle { + type Error = Error; + type RangeSpec = crate::storage_api_contracts::range::HTTPRangeSpec; + type HeaderMap = http::HeaderMap; + type ObjectOptions = crate::object_api::ObjectOptions; + type ObjectInfo = crate::object_api::ObjectInfo; + type GetObjectReader = crate::object_api::GetObjectReader; + type PutObjectReader = crate::object_api::PutObjReader; + + async fn get_object_reader( + &self, + bucket: &str, + object: &str, + range: Option, + h: Self::HeaderMap, + opts: &Self::ObjectOptions, + ) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectIO::get_object_reader(store.as_ref(), bucket, object, range, h, opts).await + } + + async fn put_object( + &self, + bucket: &str, + object: &str, + data: &mut Self::PutObjectReader, + opts: &Self::ObjectOptions, + ) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectIO::put_object(store.as_ref(), bucket, object, data, opts).await + } +} + +#[async_trait::async_trait] +impl crate::storage_api_contracts::bucket::BucketOperations for DynamicECStoreHandle { + type Error = Error; + + async fn make_bucket(&self, bucket: &str, opts: &MakeBucketOptions) -> Result<()> { + let store = self.require_live()?; + BucketOperations::make_bucket(store.as_ref(), bucket, opts).await + } + + async fn get_bucket_info( + &self, + bucket: &str, + opts: &crate::storage_api_contracts::bucket::BucketOptions, + ) -> Result { + let store = self.require_live()?; + BucketOperations::get_bucket_info(store.as_ref(), bucket, opts).await + } + + async fn list_bucket(&self, opts: &crate::storage_api_contracts::bucket::BucketOptions) -> Result> { + let store = self.require_live()?; + BucketOperations::list_bucket(store.as_ref(), opts).await + } + + async fn delete_bucket(&self, bucket: &str, opts: &crate::storage_api_contracts::bucket::DeleteBucketOptions) -> Result<()> { + let store = self.require_live()?; + BucketOperations::delete_bucket(store.as_ref(), bucket, opts).await + } +} + +#[async_trait::async_trait] +impl crate::storage_api_contracts::object::ObjectOperations for DynamicECStoreHandle { + type Error = Error; + type ObjectInfo = crate::object_api::ObjectInfo; + type ObjectOptions = crate::object_api::ObjectOptions; + type FileInfo = rustfs_filemeta::FileInfo; + type ObjectToDelete = crate::storage_api_contracts::object::ObjectToDelete; + type DeletedObject = crate::storage_api_contracts::object::DeletedObject; + + async fn get_object_info(&self, bucket: &str, object: &str, opts: &Self::ObjectOptions) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::get_object_info(store.as_ref(), bucket, object, opts).await + } + + async fn get_object_info_for_delete( + &self, + bucket: &str, + object: &str, + opts: &Self::ObjectOptions, + ) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::get_object_info_for_delete(store.as_ref(), bucket, object, opts) + .await + } + + async fn verify_object_integrity(&self, bucket: &str, object: &str, opts: &Self::ObjectOptions) -> Result<()> { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::verify_object_integrity(store.as_ref(), bucket, object, opts) + .await + } + + async fn copy_object( + &self, + src_bucket: &str, + src_object: &str, + dst_bucket: &str, + dst_object: &str, + src_info: &mut Self::ObjectInfo, + src_opts: &Self::ObjectOptions, + dst_opts: &Self::ObjectOptions, + ) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::copy_object( + store.as_ref(), + src_bucket, + src_object, + dst_bucket, + dst_object, + src_info, + src_opts, + dst_opts, + ) + .await + } + + async fn delete_object_version(&self, bucket: &str, object: &str, fi: &Self::FileInfo, force_del_marker: bool) -> Result<()> { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::delete_object_version( + store.as_ref(), + bucket, + object, + fi, + force_del_marker, + ) + .await + } + + async fn delete_object(&self, bucket: &str, object: &str, opts: Self::ObjectOptions) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::delete_object(store.as_ref(), bucket, object, opts).await + } + + async fn delete_objects( + &self, + bucket: &str, + objects: Vec, + opts: Self::ObjectOptions, + ) -> (Vec, Vec>) { + let Ok(store) = self.require_live() else { + let errs = (0..objects.len()) + .map(|_| Some(Error::other("storage not initialized"))) + .collect(); + return (Vec::new(), errs); + }; + crate::storage_api_contracts::object::ObjectOperations::delete_objects(store.as_ref(), bucket, objects, opts).await + } + + async fn put_object_metadata(&self, bucket: &str, object: &str, opts: &Self::ObjectOptions) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::put_object_metadata(store.as_ref(), bucket, object, opts).await + } + + async fn get_object_tags(&self, bucket: &str, object: &str, opts: &Self::ObjectOptions) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::get_object_tags(store.as_ref(), bucket, object, opts).await + } + + async fn put_object_tags( + &self, + bucket: &str, + object: &str, + tags: &str, + opts: &Self::ObjectOptions, + ) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::put_object_tags(store.as_ref(), bucket, object, tags, opts).await + } + + async fn delete_object_tags(&self, bucket: &str, object: &str, opts: &Self::ObjectOptions) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::delete_object_tags(store.as_ref(), bucket, object, opts).await + } + + async fn add_partial(&self, bucket: &str, object: &str, version_id: &str) -> Result<()> { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::add_partial(store.as_ref(), bucket, object, version_id).await + } + + async fn transition_object(&self, bucket: &str, object: &str, opts: &Self::ObjectOptions) -> Result<()> { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::transition_object(store.as_ref(), bucket, object, opts).await + } + + async fn restore_transitioned_object(self: Arc, bucket: &str, object: &str, opts: &Self::ObjectOptions) -> Result<()> { + let store = self.require_live()?; + crate::storage_api_contracts::object::ObjectOperations::restore_transitioned_object(store, bucket, object, opts).await + } +} + +#[async_trait::async_trait] +impl crate::storage_api_contracts::list::ListOperations for DynamicECStoreHandle { + type Error = Error; + type ListObjectsV2Info = crate::storage_api_contracts::list::StorageListObjectsV2Info; + type ListObjectVersionsInfo = + crate::storage_api_contracts::list::StorageListObjectVersionsInfo; + type ObjectInfoOrErr = crate::storage_api_contracts::list::StorageObjectInfoOrErr; + type WalkOptions = crate::storage_api_contracts::list::StorageWalkOptions bool>; + type WalkCancellation = CancellationToken; + type WalkResultSender = tokio::sync::mpsc::Sender; + + async fn list_objects_v2( + self: Arc, + bucket: &str, + prefix: &str, + continuation_token: Option, + delimiter: Option, + max_keys: i32, + fetch_owner: bool, + start_after: Option, + incl_deleted: bool, + ) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::list::ListOperations::list_objects_v2( + store, + bucket, + prefix, + continuation_token, + delimiter, + max_keys, + fetch_owner, + start_after, + incl_deleted, + ) + .await + } + + async fn list_object_versions( + self: Arc, + bucket: &str, + prefix: &str, + marker: Option, + version_marker: Option, + delimiter: Option, + max_keys: i32, + ) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::list::ListOperations::list_object_versions( + store, + bucket, + prefix, + marker, + version_marker, + delimiter, + max_keys, + ) + .await + } + + async fn walk( + self: Arc, + rx: CancellationToken, + bucket: &str, + prefix: &str, + result: Self::WalkResultSender, + opts: Self::WalkOptions, + ) -> Result<()> { + let store = self.require_live()?; + crate::storage_api_contracts::list::ListOperations::walk(store, rx, bucket, prefix, result, opts).await + } +} + +#[async_trait::async_trait] +impl crate::storage_api_contracts::namespace::NamespaceLocking for DynamicECStoreHandle { + type Error = Error; + type NamespaceLock = rustfs_lock::NamespaceLockWrapper; + + async fn new_ns_lock(&self, bucket: &str, object: &str) -> Result { + let store = self.require_live()?; + crate::storage_api_contracts::namespace::NamespaceLocking::new_ns_lock(store.as_ref(), bucket, object).await + } +} + +fn pool_hosts(pool: &PoolEndpoints) -> Vec { + let mut hosts = BTreeSet::new(); + for ep in pool.endpoints.as_ref() { + let host = ep.host_port(); + if !host.is_empty() { + hosts.insert(host); + } + } + hosts.into_iter().collect() +} + +fn max_drives_per_host_in_set(pool: &PoolEndpoints) -> usize { + if pool.drives_per_set == 0 { + return 0; + } + let mut max_per_host = 0usize; + for set_slice in pool.endpoints.as_ref().chunks(pool.drives_per_set) { + let mut host_counts: BTreeMap = BTreeMap::new(); + for ep in set_slice { + let host = ep.host_port(); + if !host.is_empty() { + let count = host_counts.entry(host).or_insert(0); + *count = count.saturating_add(1); + max_per_host = max_per_host.max(*count); + } + } + } + max_per_host +} + +/// Summarize a single [`PoolEndpoints`] geometry combined with optional persisted [`PoolMeta`]. +pub fn summarize_pool_geometry( + pool_index: usize, + pool: &PoolEndpoints, + parity_drives: usize, + pool_meta: Option<&PoolMeta>, +) -> PoolGeometrySummary { + let status = pool_meta.and_then(|meta| meta.pools.iter().find(|entry| entry.cmd_line == pool.cmd_line)); + let decom = status.and_then(|entry| entry.decommission.as_ref()); + let decommissioned = decom.is_some(); + let decommission_complete = decom.is_some_and(|info| info.complete); + let unresolved_entries = decom.map_or(0, |info| info.unresolved_entries.len()); + let local_endpoint_count = pool.endpoints.as_ref().iter().filter(|ep| ep.is_local).count(); + let hosts = pool_hosts(pool); + let max_per_host = max_drives_per_host_in_set(pool); + // In a multi-host pool, losing one host loses availability if that host holds + // more drives in a single erasure set than the set's parity tolerance. + let host_failure_risk = if hosts.len() > 1 { + max_per_host > parity_drives + } else { + pool.drives_per_set > 1 && parity_drives == 0 + }; + + PoolGeometrySummary { + pool_index, + cmd_line: pool.cmd_line.clone(), + set_count: pool.set_count, + drives_per_set: pool.drives_per_set, + parity_drives, + data_drives: pool.drives_per_set.saturating_sub(parity_drives), + endpoint_count: pool.endpoints.as_ref().len(), + local_endpoint_count, + hosts, + decommissioned, + decommission_complete, + unresolved_entries, + host_failure_risk, + } +} + +/// Summarize all pools in an [`EndpointServerPools`]. +pub fn summarize_endpoint_pools(endpoints: &EndpointServerPools, pool_meta: Option<&PoolMeta>) -> Vec { + let sc_parities: Option> = ECStore::validate_storage_class_with_kvs(endpoints, None).ok().map(|sc| { + endpoints + .as_ref() + .iter() + .enumerate() + .map(|(idx, pool)| { + sc.parity_for_pool(crate::config::storageclass::STANDARD, idx, pool.drives_per_set) + .filter(|&p| p > 0) + .unwrap_or_else(|| crate::store::init_format::ec_drives_no_config(pool.drives_per_set).unwrap_or(0)) + }) + .collect() + }); + let fallback_parities = resolve_startup_pool_defaults(endpoints).ok(); + endpoints + .as_ref() + .iter() + .enumerate() + .map(|(idx, pool)| { + let parity = sc_parities + .as_ref() + .and_then(|list| list.get(idx).copied()) + .or_else(|| fallback_parities.as_ref().and_then(|list| list.get(idx).copied())) + .unwrap_or_else(|| crate::store::init_format::ec_drives_no_config(pool.drives_per_set).unwrap_or(0)); + summarize_pool_geometry(idx, pool, parity, pool_meta) + }) + .collect() +} + +/// Analyze and validate the transition from `current` active topology to `target` candidate topology. +/// +/// Enforces distributed storage safety invariants: +/// - Target topology must be non-empty and satisfy storage class / erasure parity rules. +/// - No duplicate endpoints across pools, no mixed schemes or endpoint types. +/// - An expansion must preserve all existing pools intact and add at least one new pool. +/// - A decommission removal must remove only pools with `decommission.complete == true`, +/// zero unresolved entries, and no active capacity reservation, leaving at least one healthy pool. +/// - Simultaneous expansion and pool removal in one step is rejected. +pub fn analyze_topology_transition( + current: &EndpointServerPools, + target: &EndpointServerPools, + pool_meta: &PoolMeta, + expected_mode: Option, +) -> TopologyDiff { + let current_pools = summarize_endpoint_pools(current, Some(pool_meta)); + let target_pools = summarize_endpoint_pools(target, Some(pool_meta)); + + let mut errors = Vec::new(); + let mut warnings = Vec::new(); + + if target.as_ref().is_empty() { + errors.push("target configuration contains no storage pools".to_string()); + } + + if let Err(err) = ECStore::validate_storage_class_with_kvs(target, None) { + errors.push(format!("storage class / erasure stripe validation failed: {err}")); + } + + if !current.as_ref().is_empty() && !target.as_ref().is_empty() { + let current_has_remote = current + .as_ref() + .iter() + .any(|p| p.endpoints.as_ref().iter().any(|ep| !ep.is_local)); + let target_has_remote = target + .as_ref() + .iter() + .any(|p| p.endpoints.as_ref().iter().any(|ep| !ep.is_local)); + if current_has_remote != target_has_remote { + errors.push( + "cannot transition between single-node local topology and distributed multi-node RPC topology via live hot-reload; restart the cluster to change deployment mode" + .to_string(), + ); + } + } + + // Check cross-pool endpoint collisions, scheme uniformity, and stripe sanity. + let mut seen_endpoints: HashMap = HashMap::new(); + let mut global_scheme: Option = None; + let mut global_type = None; + for (pool_idx, pool) in target.as_ref().iter().enumerate() { + if pool.set_count == 0 || pool.drives_per_set == 0 { + errors.push(format!( + "pool {pool_idx} (`{}`) has invalid erasure geometry: sets={}, drives_per_set={}", + pool.cmd_line, pool.set_count, pool.drives_per_set + )); + } else if !target.legacy() && pool.drives_per_set < 4 { + errors.push(format!( + "pool {pool_idx} (`{}`) has {} drive(s) per erasure set; minimum for erasure coding is 4", + pool.cmd_line, pool.drives_per_set + )); + } + if pool.endpoints.as_ref().len() != pool.set_count.saturating_mul(pool.drives_per_set) { + errors.push(format!( + "pool {pool_idx} (`{}`) endpoint count {} does not equal sets({}) * drives_per_set({})", + pool.cmd_line, + pool.endpoints.as_ref().len(), + pool.set_count, + pool.drives_per_set + )); + } + for ep in pool.endpoints.as_ref() { + let scheme = ep.url.scheme().to_string(); + if let Some(ref expected) = global_scheme { + if expected != &scheme { + errors.push(format!( + "mixed endpoint URL schemes detected: expected `{expected}` but pool {pool_idx} uses `{scheme}`" + )); + } + } else { + global_scheme = Some(scheme); + } + let ep_type = ep.get_type(); + if let Some(ref expected_type) = global_type { + if expected_type != &ep_type { + errors.push(format!("mixed endpoint styles detected in pool {pool_idx}")); + } + } else { + global_type = Some(ep_type); + } + let key = ep.to_string(); + if let Some(prev_pool) = seen_endpoints.insert(key.clone(), pool_idx) { + errors.push(format!("duplicate endpoint `{key}` appears in both pool {prev_pool} and pool {pool_idx}")); + } + } + } + + let current_by_cmd: HashMap<&str, &PoolGeometrySummary> = current_pools.iter().map(|p| (p.cmd_line.as_str(), p)).collect(); + let target_by_cmd: HashMap<&str, &PoolGeometrySummary> = target_pools.iter().map(|p| (p.cmd_line.as_str(), p)).collect(); + + let mut added_pools = Vec::new(); + let mut removed_pools = Vec::new(); + let mut retained_pools = Vec::new(); + + for pool in &target_pools { + if current_by_cmd.contains_key(pool.cmd_line.as_str()) { + retained_pools.push(pool.clone()); + } else { + added_pools.push(pool.clone()); + } + } + + for pool in ¤t_pools { + if !target_by_cmd.contains_key(pool.cmd_line.as_str()) { + removed_pools.push(pool.clone()); + } + } + + // Detect forbidden in-place mutation of an existing pool (e.g., resizing drives on same hosts/paths). + let current_endpoints: HashMap = current + .as_ref() + .iter() + .flat_map(|pool| { + pool.endpoints + .as_ref() + .iter() + .map(move |ep| (ep.to_string(), pool.cmd_line.as_str())) + }) + .collect(); + for added in &added_pools { + if let Some(target_pool) = target.as_ref().get(added.pool_index) { + for ep in target_pool.endpoints.as_ref() { + if let Some(old_cmd) = current_endpoints.get(&ep.to_string()) { + errors.push(format!( + "endpoint `{ep}` already belongs to active pool `{old_cmd}`; in-place modification of an existing pool is forbidden — add a new pool instead" + )); + break; + } + } + } + } + + // Check host failure domain warnings on added/target pools. + for pool in &target_pools { + if pool.host_failure_risk { + warnings.push(format!( + "pool {} (`{}`) places more drives per host in a single erasure set than its parity tolerance ({} parity drives); a single host failure could impact availability", + pool.pool_index, pool.cmd_line, pool.parity_drives + )); + } + if pool.parity_drives == 0 { + warnings.push(format!( + "pool {} (`{}`) has 0 parity drives (no drive failure redundancy)", + pool.pool_index, pool.cmd_line + )); + } + } + + // Classify transition kind. + let kind = match (added_pools.is_empty(), removed_pools.is_empty()) { + (true, true) => { + // Check whether pool ordering changed. + let order_changed = current_pools + .iter() + .zip(target_pools.iter()) + .any(|(a, b)| a.cmd_line != b.cmd_line); + if order_changed { + errors.push("reordering existing pools without expansion or decommission is not permitted".to_string()); + TopologyTransitionKind::Invalid + } else { + warnings.push("target configuration is identical to the active in-memory pool topology".to_string()); + TopologyTransitionKind::Noop + } + } + (false, true) => TopologyTransitionKind::Expand, + (true, false) => TopologyTransitionKind::Decommission, + (false, false) => { + errors.push( + "cannot simultaneously add new pools and remove existing pools in a single maintenance reload; execute expansion and decommission as separate operations" + .to_string(), + ); + TopologyTransitionKind::Invalid + } + }; + + // Verify expected maintenance mode matches detected transition. + if let Some(mode) = expected_mode { + match (mode, kind) { + (TopologyReloadMode::Expand, TopologyTransitionKind::Decommission) => { + errors.push( + "maintenance mode is `expand`, but target configuration removes existing pools instead of adding new pools" + .to_string(), + ); + } + (TopologyReloadMode::Decommission, TopologyTransitionKind::Expand) => { + errors.push( + "maintenance mode is `decommission`, but target configuration adds new pools instead of removing a decommissioned pool" + .to_string(), + ); + } + (_, TopologyTransitionKind::Noop) => { + errors.push(format!( + "target configuration introduces no topology change for `{}` maintenance mode", + mode.as_str() + )); + } + _ => {} + } + } + + // Expansion-specific invariants: existing pools must remain in their original order prefix. + if kind == TopologyTransitionKind::Expand { + for (idx, current_pool) in current_pools.iter().enumerate() { + if target_pools + .get(idx) + .is_none_or(|target_pool| target_pool.cmd_line != current_pool.cmd_line) + { + errors.push(format!( + "existing pool {idx} (`{}`) must remain at index {idx}; new pools must be appended after existing pools", + current_pool.cmd_line + )); + } + } + // Reject expansion if any already-completed decommissioned pool is still present + // in the configuration (`PoolMeta::validate` forbids expanding over completed decommissions). + for pool in &target_pools { + if pool.decommission_complete { + errors.push(format!( + "pool {} (`{}`) has already completed decommission; remove completed decommissioned pools in a `decommission` maintenance reload before expanding", + pool.pool_index, pool.cmd_line + )); + } + } + } + + // Decommission-specific invariants: every removed pool MUST have completed decommission cleanly, + // and surviving pools must retain their exact relative ordering. + if kind == TopologyTransitionKind::Decommission { + let current_retained_order: Vec<&str> = current_pools + .iter() + .filter(|p| target_by_cmd.contains_key(p.cmd_line.as_str())) + .map(|p| p.cmd_line.as_str()) + .collect(); + let target_retained_order: Vec<&str> = target_pools.iter().map(|p| p.cmd_line.as_str()).collect(); + if current_retained_order != target_retained_order { + errors.push( + "reordering surviving pools during decommission hot-reload is not permitted; keep surviving pools in their original relative order" + .to_string(), + ); + } + if retained_pools.is_empty() { + errors.push("cannot remove all storage pools; at least one active pool must remain".to_string()); + } + let all_retained_decommissioned = !retained_pools.is_empty() && retained_pools.iter().all(|pool| pool.decommissioned); + if all_retained_decommissioned { + errors.push("cannot remove pool when every remaining pool is also being decommissioned".to_string()); + } + for removed in &removed_pools { + let status = pool_meta.pools.iter().find(|entry| entry.cmd_line == removed.cmd_line); + match status.and_then(|entry| entry.decommission.as_ref()) { + None => { + errors.push(format!( + "pool {} (`{}`) has not been decommissioned; drain the pool before removing it from configuration", + removed.pool_index, removed.cmd_line + )); + } + Some(info) => { + if !info.complete { + errors.push(format!( + "pool {} (`{}`) decommission is not complete (failed={}, canceled={}, objects_failed={})", + removed.pool_index, removed.cmd_line, info.failed, info.canceled, info.items_decommission_failed + )); + } + if !info.unresolved_entries.is_empty() { + errors.push(format!( + "pool {} (`{}`) still has {} unresolved decommission entries", + removed.pool_index, + removed.cmd_line, + info.unresolved_entries.len() + )); + } + if info + .capacity_reservation + .as_ref() + .is_some_and(|reservation| reservation.released_at.is_none()) + { + errors.push(format!( + "pool {} (`{}`) still holds an active decommission capacity reservation", + removed.pool_index, removed.cmd_line + )); + } + } + } + } + } + + let final_kind = if errors.is_empty() { + kind + } else { + TopologyTransitionKind::Invalid + }; + + TopologyDiff { + kind: final_kind, + current_pools, + target_pools, + added_pools, + removed_pools, + retained_pools, + errors, + warnings, + } +} + +fn is_pool_meta_bootstrap_pending(err: &Error) -> bool { + err.to_string().contains(POOL_META_BOOTSTRAP_PENDING_MARKER) +} + +fn probe_local_unregistered_disk_sync( + pool_idx: usize, + ep_str: String, + host: String, + file_path: String, + cluster_id: uuid::Uuid, + expected_sets: usize, + expected_drives_per_set: usize, +) -> CandidateDiskProbe { + let root = std::path::PathBuf::from(&file_path); + let meta = match std::fs::metadata(&root) { + Ok(meta) => meta, + Err(err) => { + return CandidateDiskProbe { + pool_index: pool_idx, + endpoint: ep_str, + host, + is_local: true, + reachable: false, + format_state: CandidateDiskFormatState::Offline, + deployment_id: None, + total_bytes: 0, + free_bytes: 0, + free_inodes: 0, + fs_type: String::new(), + error: Some(format!("local drive path `{file_path}` unavailable: {err}")), + }; + } + }; + if !meta.is_dir() { + return CandidateDiskProbe { + pool_index: pool_idx, + endpoint: ep_str, + host, + is_local: true, + reachable: false, + format_state: CandidateDiskFormatState::Offline, + deployment_id: None, + total_bytes: 0, + free_bytes: 0, + free_inodes: 0, + fs_type: String::new(), + error: Some(format!("local drive path `{file_path}` is not a directory")), + }; + } + + let (total_bytes, free_bytes, free_inodes, fs_type, info_err) = match rustfs_utils::os::get_info(&file_path) { + Ok(info) => (info.total, info.free, info.ffree, info.fstype, None), + Err(err) => (0, 0, 0, String::new(), Some(err.to_string())), + }; + + let fmt_path = root.join(RUSTFS_META_BUCKET).join(FORMAT_CONFIG_FILE); + let (format_state, dep_id, fmt_err) = match std::fs::read(&fmt_path) { + Ok(raw) => classify_probed_format(&raw, cluster_id, expected_sets, expected_drives_per_set), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => (CandidateDiskFormatState::Unformatted, None, None), + Err(err) => ( + CandidateDiskFormatState::Offline, + None, + Some(format!("failed to read disk format: {err}")), + ), + }; + + CandidateDiskProbe { + pool_index: pool_idx, + endpoint: ep_str, + host, + is_local: true, + reachable: info_err.is_none() && format_state != CandidateDiskFormatState::Offline, + format_state, + deployment_id: dep_id, + total_bytes, + free_bytes, + free_inodes, + fs_type, + error: fmt_err.or(info_err), + } +} + +fn classify_probed_format( + raw: &[u8], + cluster_id: uuid::Uuid, + expected_sets: usize, + expected_drives_per_set: usize, +) -> (CandidateDiskFormatState, Option, Option) { + match serde_json::from_slice::(raw) { + Ok(fmt) => { + if fmt.id != cluster_id { + ( + CandidateDiskFormatState::ForeignCluster, + Some(fmt.id.to_string()), + Some(format!( + "disk belongs to foreign cluster deployment ID {} (expected {})", + fmt.id, cluster_id + )), + ) + } else if fmt.erasure.sets.len() != expected_sets + || fmt.erasure.sets.first().map_or(0, Vec::len) != expected_drives_per_set + { + ( + CandidateDiskFormatState::TopologyMismatch, + Some(fmt.id.to_string()), + Some(format!( + "disk format geometry ({}x{}) does not match target pool ({}x{})", + fmt.erasure.sets.len(), + fmt.erasure.sets.first().map_or(0, Vec::len), + expected_sets, + expected_drives_per_set + )), + ) + } else { + (CandidateDiskFormatState::MatchingCluster, Some(fmt.id.to_string()), None) + } + } + Err(err) => (CandidateDiskFormatState::Corrupt, None, Some(format!("corrupted format.json: {err}"))), + } +} + +fn collect_remote_hosts(endpoints: &EndpointServerPools) -> HashSet { + let mut hosts = HashSet::new(); + for pool in endpoints.as_ref() { + for ep in pool.endpoints.as_ref() { + if !ep.is_local { + let grid_host = ep.grid_host(); + if !grid_host.is_empty() { + hosts.insert(grid_host); + } + let host_port = ep.host_port(); + if !host_port.is_empty() { + hosts.insert(host_port); + } + } + } + } + hosts +} + +async fn evict_unretained_peer_connection(grid_host: &str, host_port: &str, retained_hosts: &HashSet) { + if retained_hosts.contains(grid_host) || retained_hosts.contains(host_port) { + return; + } + if !grid_host.is_empty() { + rustfs_protos::evict_failed_connection_with_log_level(grid_host, rustfs_common::ConnectionEvictionLogLevel::Debug).await; + } + if !host_port.is_empty() && host_port != grid_host { + rustfs_protos::evict_failed_connection_with_log_level(host_port, rustfs_common::ConnectionEvictionLogLevel::Debug).await; + } +} + +async fn propagate_buckets_to_added_pools( + new_pools: &[Arc], + added_cmds: &HashSet<&str>, + buckets: &[BucketInfo], + already_propagated: &mut HashSet, +) -> Result { + let mut count = 0usize; + for bucket in buckets { + if !already_propagated.insert(bucket.name.clone()) { + continue; + } + for (pool_idx, pool_sets) in new_pools.iter().enumerate() { + if !added_cmds.contains(pool_sets.endpoints.cmd_line.as_str()) { + continue; + } + let opts = MakeBucketOptions { + force_create: true, + ..Default::default() + }; + match pool_sets.make_bucket(&bucket.name, &opts).await { + Ok(()) => { + count = count.saturating_add(1); + } + Err(err) if crate::error::is_err_bucket_exists(&err) => {} + Err(err) => { + warn!( + event = EVENT_TOPOLOGY_RELOAD_STAGE, + component = LOG_COMPONENT_ECSTORE, + subsystem = LOG_SUBSYSTEM_TOPOLOGY_RELOAD, + stage = "propagate_bucket", + pool_index = pool_idx, + bucket = %bucket.name, + error = %err, + "Failed to create existing bucket on newly added pool during hot-reload" + ); + return Err(Error::other_with_context( + "failed to propagate bucket onto expanded pool", + format!("bucket `{}`, pool {pool_idx}: {err}", bucket.name), + )); + } + } + } + } + Ok(count) +} + +impl ECStore { + /// Returns the current topology hot-reload generation for this store instance. + pub fn topology_generation(&self) -> u64 { + self.ctx.topology_generation() + } + + /// Advance this instance's topology generation monotonically to at least + /// `min_generation` (used when a newly joined standby peer converges onto an + /// active cluster's reload generation). + pub fn sync_topology_generation_at_least(&self, min_generation: u64) -> u64 { + self.ctx.sync_topology_generation_at_least(min_generation) + } + + /// Returns true if `other` belongs to the exact same `InstanceContext` as `self`. + pub fn same_instance_ctx(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.ctx, &other.ctx) + } + + /// Return a generation-aware handle that resolves this instance's live [`ECStore`] + /// and eagerly rebinds to successor generations at hot-reload cutover. + pub fn dynamic_handle(self: &Arc) -> DynamicECStoreHandle { + let cell = Arc::new(std::sync::RwLock::new(self.clone())); + self.ctx.register_rebindable_store_cell(&cell); + DynamicECStoreHandle { + ctx: self.ctx.clone(), + cell, + } + } + + /// Return `(node_count, total_endpoint_drives)` for the currently active + /// topology on this store's `InstanceContext`, if endpoints are configured. + pub fn active_topology_node_and_drive_counts(&self) -> Option<(usize, usize)> { + let endpoints = self.ctx.endpoints()?; + let nodes = endpoints.get_nodes().len(); + let drives = endpoints.as_ref().iter().map(|pool| pool.endpoints.as_ref().len()).sum(); + Some((nodes, drives)) + } + + /// Retire an superseded `ECStore` generation after atomic cutover: stops every + /// `Sets` reconnect monitor, closes remote disk clients, evicts decommissioned + /// peer channels from the connection cache, and closes removed local disk handles. + pub(crate) async fn retire(&self, retained_remote_hosts: &HashSet, removed_local_disks: Vec) { + for pool in &self.pools { + pool.stop_endpoint_monitor(); + } + let mut evicted_keys = HashSet::new(); + for disks in self.disk_map.values() { + for disk in disks.iter().flatten() { + if !disk.is_local() { + let ep = disk.endpoint(); + let grid_host = ep.grid_host(); + let host_port = ep.host_port(); + let _ = disk.close().await; + let key = if !grid_host.is_empty() { + grid_host.clone() + } else { + host_port.clone() + }; + if evicted_keys.insert(key) { + evict_unretained_peer_connection(&grid_host, &host_port, retained_remote_hosts).await; + } + } + } + } + for disk in removed_local_disks { + if let crate::disk::Disk::Local(wrapper) = disk.as_ref() { + wrapper.retire_handle(); + } + let _ = disk.close().await; + } + } + + /// Probe candidate disks and erasure formats for an expansion or decommission + /// preflight check without mutating any disk, directory, or cluster state. + pub async fn probe_candidate_pool_disks( + self: &Arc, + target: &EndpointServerPools, + diff: &TopologyDiff, + ) -> CandidateDiskProbeReport { + let mut errors = Vec::new(); + let mut warnings = Vec::new(); + let mut disks = Vec::new(); + + let active_endpoints = self + .ctx + .endpoints() + .unwrap_or_else(runtime_sources::endpoint_pools_or_default); + let active_remote_hosts = collect_remote_hosts(&active_endpoints); + let resolved_parities = Self::validate_storage_class_with_kvs(target, None) + .ok() + .and_then(|cfg| cfg.parities_for_sc(crate::config::storageclass::STANDARD)); + + let existing_local_snapshot: Vec<(String, std::path::PathBuf, DiskStore)> = { + let map_arc = self.ctx.local_disk_map(); + let guard = map_arc.read().await; + guard + .iter() + .filter_map(|(ep_str, maybe_disk)| { + let disk = maybe_disk.as_ref()?.clone(); + let path = std::path::PathBuf::from(disk.endpoint().get_file_path()); + Some((ep_str.clone(), path, disk)) + }) + .collect() + }; + let existing_local_snapshot = Arc::new(existing_local_snapshot); + + // Determine which target pool indices need disk/format probing: + // - For expansion: probe all added pools thoroughly (plus quick quorum sanity on retained pools). + // - For decommission: probe all retained (surviving) pools to confirm read/write quorum. + let added_cmds: HashSet<&str> = diff.added_pools.iter().map(|p| p.cmd_line.as_str()).collect(); + let probe_opt = DiskOption { + cleanup: false, + health_check: false, + }; + + for (pool_idx, pool_eps) in target.as_ref().iter().enumerate() { + let is_added = added_cmds.contains(pool_eps.cmd_line.as_str()); + let mut futures = Vec::with_capacity(pool_eps.endpoints.as_ref().len()); + + for ep in pool_eps.endpoints.as_ref() { + let ep_clone = ep.clone(); + let instance_ctx = self.ctx.clone(); + let cluster_id = self.id; + let expected_sets = pool_eps.set_count; + let expected_drives_per_set = pool_eps.drives_per_set; + let opt = probe_opt.clone(); + let local_snapshot = existing_local_snapshot.clone(); + let active_hosts = active_remote_hosts.clone(); + + futures.push(async move { + let host = ep_clone.host_port(); + let grid_host = ep_clone.grid_host(); + let ep_str = ep_clone.to_string(); + + if ep_clone.is_local { + let file_path = ep_clone.get_file_path().to_string(); + let candidate_path = std::path::PathBuf::from(&file_path); + let matched_existing = local_snapshot + .iter() + .find(|(k, p, _)| k == &ep_str || p == &candidate_path) + .map(|(_, _, d)| d.clone()); + + let existing = match matched_existing { + Some(d) => Some(d), + None => { + let snap = local_snapshot.clone(); + let cp = candidate_path.clone(); + tokio::task::spawn_blocking(move || { + let canon_cand = std::fs::canonicalize(&cp).ok()?; + snap.iter() + .find(|(_, p, _)| std::fs::canonicalize(p).ok().as_ref() == Some(&canon_cand)) + .map(|(_, _, d)| d.clone()) + }) + .await + .ok() + .flatten() + } + }; + + if let Some(disk) = existing { + let info_res = disk.disk_info(&DiskInfoOptions::default()).await; + let (total_bytes, free_bytes, free_inodes, fs_type, info_err) = match info_res { + Ok(info) => (info.total, info.free, info.free_inodes, info.fs_type, None), + Err(err) => (0, 0, 0, String::new(), Some(err.to_string())), + }; + let (format_state, dep_id, fmt_err) = + match disk.read_all(RUSTFS_META_BUCKET, FORMAT_CONFIG_FILE).await { + Ok(raw) => { + classify_probed_format(raw.as_ref(), cluster_id, expected_sets, expected_drives_per_set) + } + Err(DiskError::VolumeNotFound | DiskError::FileNotFound | DiskError::UnformattedDisk) => { + (CandidateDiskFormatState::Unformatted, None, None) + } + Err(err) => ( + CandidateDiskFormatState::Offline, + None, + Some(format!("failed to read disk format: {err}")), + ), + }; + return CandidateDiskProbe { + pool_index: pool_idx, + endpoint: ep_str, + host, + is_local: true, + reachable: info_err.is_none() && format_state != CandidateDiskFormatState::Offline, + format_state, + deployment_id: dep_id, + total_bytes, + free_bytes, + free_inodes, + fs_type, + error: fmt_err.or(info_err), + }; + } + + // Pure read-only filesystem probe: NEVER call LocalDisk::new on unregistered paths! + return match tokio::task::spawn_blocking(move || { + probe_local_unregistered_disk_sync( + pool_idx, + ep_str.clone(), + host.clone(), + file_path, + cluster_id, + expected_sets, + expected_drives_per_set, + ) + }) + .await + { + Ok(probe) => probe, + Err(err) => CandidateDiskProbe { + pool_index: pool_idx, + endpoint: ep_clone.to_string(), + host: ep_clone.host_port(), + is_local: true, + reachable: false, + format_state: CandidateDiskFormatState::Offline, + deployment_id: None, + total_bytes: 0, + free_bytes: 0, + free_inodes: 0, + fs_type: String::new(), + error: Some(format!("local disk probe worker panicked: {err}")), + }, + }; + } + + crate::cluster::rpc::http_auth::with_v2_only_rpc_signing(async move { + let disk = match crate::disk::new_disk_for_instance(&instance_ctx, &ep_clone, &opt).await { + Ok(disk) => disk, + Err(err) => { + evict_unretained_peer_connection(&grid_host, &host, &active_hosts).await; + return CandidateDiskProbe { + pool_index: pool_idx, + endpoint: ep_str, + host, + is_local: false, + reachable: false, + format_state: CandidateDiskFormatState::Offline, + deployment_id: None, + total_bytes: 0, + free_bytes: 0, + free_inodes: 0, + fs_type: String::new(), + error: Some(err.to_string()), + }; + } + }; + + let info_res = disk.disk_info(&DiskInfoOptions::default()).await; + let (total_bytes, free_bytes, free_inodes, fs_type, info_err) = match info_res { + Ok(info) => (info.total, info.free, info.free_inodes, info.fs_type, None), + Err(err) => (0, 0, 0, String::new(), Some(err.to_string())), + }; + + let (format_state, dep_id, fmt_err) = match disk.read_all(RUSTFS_META_BUCKET, FORMAT_CONFIG_FILE).await { + Ok(raw) => classify_probed_format(raw.as_ref(), cluster_id, expected_sets, expected_drives_per_set), + Err(DiskError::VolumeNotFound | DiskError::FileNotFound | DiskError::UnformattedDisk) => { + (CandidateDiskFormatState::Unformatted, None, None) + } + Err(err) => ( + CandidateDiskFormatState::Offline, + None, + Some(format!("failed to read disk format: {err}")), + ), + }; + + let _ = disk.close().await; + evict_unretained_peer_connection(&grid_host, &host, &active_hosts).await; + + CandidateDiskProbe { + pool_index: pool_idx, + endpoint: ep_str, + host, + is_local: false, + reachable: info_err.is_none() && format_state != CandidateDiskFormatState::Offline, + format_state, + deployment_id: dep_id, + total_bytes, + free_bytes, + free_inodes, + fs_type, + error: fmt_err.or(info_err), + } + }) + .await + }); + } + + let mut indexed_probes: Vec<(usize, CandidateDiskProbe)> = stream::iter(futures.into_iter().enumerate()) + .map(|(idx, fut)| async move { (idx, fut.await) }) + .buffer_unordered(16) + .collect() + .await; + indexed_probes.sort_by_key(|(idx, _)| *idx); + let pool_probes: Vec = indexed_probes.into_iter().map(|(_, p)| p).collect(); + + let mut online_count = 0usize; + let mut unformatted_count = 0usize; + let mut matching_count = 0usize; + + for probe in &pool_probes { + if probe.reachable { + online_count = online_count.saturating_add(1); + } + match probe.format_state { + CandidateDiskFormatState::Unformatted => unformatted_count = unformatted_count.saturating_add(1), + CandidateDiskFormatState::MatchingCluster => matching_count = matching_count.saturating_add(1), + CandidateDiskFormatState::ForeignCluster => { + errors.push(format!( + "pool {} endpoint `{}` belongs to a foreign cluster ({})", + pool_idx, + probe.endpoint, + probe.deployment_id.as_deref().unwrap_or("unknown") + )); + } + CandidateDiskFormatState::TopologyMismatch => { + errors.push(format!( + "pool {} endpoint `{}` has incompatible erasure geometry: {}", + pool_idx, + probe.endpoint, + probe.error.as_deref().unwrap_or("mismatch") + )); + } + CandidateDiskFormatState::Corrupt => { + errors.push(format!( + "pool {} endpoint `{}` has corrupted format metadata: {}", + pool_idx, + probe.endpoint, + probe.error.as_deref().unwrap_or("corrupt") + )); + } + CandidateDiskFormatState::Offline => { + if is_added { + errors.push(format!( + "new pool {} endpoint `{}` is unreachable: {}", + pool_idx, + probe.endpoint, + probe.error.as_deref().unwrap_or("offline") + )); + } else { + warnings.push(format!( + "existing pool {} endpoint `{}` is currently offline: {}", + pool_idx, + probe.endpoint, + probe.error.as_deref().unwrap_or("offline") + )); + } + } + } + if probe.reachable && probe.free_inodes > 0 && probe.free_inodes < MIN_RECOMMENDED_FREE_INODES { + warnings.push(format!( + "pool {} endpoint `{}` has low free inodes ({})", + pool_idx, probe.endpoint, probe.free_inodes + )); + } + } + + let total_in_pool = pool_probes.len(); + if is_added { + // New pool requires ALL endpoints reachable and consistent (either all fresh unformatted + // or already formatted with THIS cluster's deployment ID in quorum). + if online_count < total_in_pool { + errors.push(format!( + "new pool {pool_idx} (`{}`) has only {online_count}/{total_in_pool} reachable drives; all drives must be online before expansion", + pool_eps.cmd_line + )); + } else if unformatted_count > 0 && matching_count > 0 { + errors.push(format!( + "new pool {pool_idx} (`{}`) mixes {unformatted_count} unformatted drives with {matching_count} formatted drives", + pool_eps.cmd_line + )); + } + } else if pool_eps.drives_per_set > 0 { + // Retained/surviving pool must maintain strict write quorum per erasure set: + // when data == parity, write quorum is `data + 1` (preventing 50/50 split-brain). + let parity = resolved_parities + .as_ref() + .and_then(|v| v.get(pool_idx).copied()) + .or_else(|| crate::store::init_format::ec_drives_no_config(pool_eps.drives_per_set).ok()) + .unwrap_or(0); + let data = pool_eps.drives_per_set.saturating_sub(parity); + let required_per_set = if data > 0 && data == parity { data + 1 } else { data.max(1) }; + for (set_idx, set_probes) in pool_probes.chunks(pool_eps.drives_per_set).enumerate() { + let set_online = set_probes + .iter() + .filter(|p| p.reachable && p.format_state == CandidateDiskFormatState::MatchingCluster) + .count(); + if set_online < required_per_set { + errors.push(format!( + "surviving pool {pool_idx} set {set_idx} has only {set_online}/{} healthy drives (need at least {required_per_set} for write quorum)", + pool_eps.drives_per_set + )); + } + } + } + + disks.extend(pool_probes); + } + + // For decommission removal, also verify pool metadata write gate is healthy. + if diff.kind == TopologyTransitionKind::Decommission { + let gate = self.pool_meta_write_gate_status().await; + if !gate.writes_ready || gate.write_blocked { + errors.push(format!( + "pool metadata write gate is blocked (reason: {}); recover pool.bin before removing a pool", + gate.reason.unwrap_or("unknown") + )); + } + } + + CandidateDiskProbeReport { + ok: errors.is_empty(), + disks, + errors, + warnings, + } + } + + /// Execute a zero-downtime live pool topology hot-reload, returning the newly + /// published generation `Arc` without closing listeners or restarting + /// the process. + pub async fn prepare_and_commit_topology_reload( + self: &Arc, + server_addr: SocketAddr, + target_endpoints: EndpointServerPools, + target_setup_type: SetupType, + mode: TopologyReloadMode, + shutdown_token: CancellationToken, + topology_fingerprint: Option, + ) -> Result { + self.prepare_and_commit_topology_reload_with_barrier( + server_addr, + target_endpoints, + target_setup_type, + mode, + shutdown_token, + topology_fingerprint, + || async { Ok(()) }, + ) + .await + } + + /// Execute a two-phase zero-downtime live pool topology hot-reload, invoking + /// `before_cutover` strictly AFTER `pool.bin` has been durably committed across + /// quorum and strictly BEFORE this node switches live S3 traffic to the new + /// `ECStore` generation. + #[allow(clippy::too_many_arguments)] + pub async fn prepare_and_commit_topology_reload_with_barrier( + self: &Arc, + server_addr: SocketAddr, + target_endpoints: EndpointServerPools, + target_setup_type: SetupType, + mode: TopologyReloadMode, + shutdown_token: CancellationToken, + topology_fingerprint: Option, + before_cutover: F, + ) -> Result + where + F: FnOnce() -> Fut, + Fut: std::future::Future>, + { + self.prepare_and_commit_topology_reload_with_cutover( + server_addr, + target_endpoints, + target_setup_type, + mode, + shutdown_token, + topology_fingerprint, + before_cutover, + |_new_ec| async { Ok(()) }, + ) + .await + } + + /// Execute a two-phase zero-downtime live pool topology hot-reload with a unified + /// atomic `on_cutover` hook so upper-layer `ServerContextSlot` / `AppContext` / `IAM` + /// handles switch in lockstep with `ECStore` and `BucketMetadataSys`. + #[allow(clippy::too_many_arguments)] + pub async fn prepare_and_commit_topology_reload_with_cutover( + self: &Arc, + server_addr: SocketAddr, + target_endpoints: EndpointServerPools, + target_setup_type: SetupType, + mode: TopologyReloadMode, + shutdown_token: CancellationToken, + topology_fingerprint: Option, + before_cutover: F, + on_cutover: C, + ) -> Result + where + F: FnOnce() -> Fut, + Fut: std::future::Future>, + C: FnOnce(Arc) -> CFut, + CFut: std::future::Future>, + { + let started = Instant::now(); + let movement_gate = self.ctx.movement_start_gate(); + let _movement_guard = movement_gate.lock().await; + let _start_guard = self.start_gate.lock().await; + + self.ensure_not_retired()?; + if self.is_rebalance_started().await { + return Err(Error::other("cannot hot-reload pool topology while a rebalance is in progress")); + } + if self.is_decommission_running().await { + return Err(Error::other("cannot hot-reload pool topology while a pool decommission is in progress")); + } + + let current_endpoints = self + .ctx + .endpoints() + .unwrap_or_else(runtime_sources::endpoint_pools_or_default); + let current_pool_meta = self.pool_meta.read().await.clone(); + + let diff = analyze_topology_transition(¤t_endpoints, &target_endpoints, ¤t_pool_meta, Some(mode)); + if !diff.errors.is_empty() { + return Err(Error::other_with_context("topology reload rejected", diff.errors.join("; "))); + } + + let default_pool_parities = resolve_startup_pool_defaults(&target_endpoints)?; + preflight_startup_rpc_secret(&target_endpoints)?; + + // Resolve the target storage class configuration up front so candidate + // pool metadata commits use the exact target pool layout without racing + // against in-flight requests on the active store generation. + let target_sc_kvs = runtime_sources::server_config() + .and_then(|cfg| cfg.get_value(crate::config::com::STORAGE_CLASS_SUB_SYS, rustfs_config::DEFAULT_DELIMITER)) + .unwrap_or_default(); + let target_drive_counts: Vec = target_endpoints.as_ref().iter().map(|p| p.drives_per_set).collect(); + let target_storage_class = crate::config::storageclass::lookup_config_for_pools(&target_sc_kvs, &target_drive_counts)?; + let target_storage_class_arc = Arc::new(target_storage_class.clone()); + + // Capture existing buckets BEFORE topology swap (propagating errors!) so every + // existing bucket directory exists on newly added pools before traffic cutover. + let existing_buckets = if mode == TopologyReloadMode::Expand { + self.list_buckets_for_metadata_startup().await? + } else { + Vec::new() + }; + + let previous_pool_count = self.pools.len(); + let mut old_to_new_pool = HashMap::new(); + for (new_idx, pool_eps) in target_endpoints.as_ref().iter().enumerate() { + if let Some((old_idx, _)) = current_endpoints + .as_ref() + .iter() + .enumerate() + .find(|(_, cur)| cur.cmd_line == pool_eps.cmd_line) + { + old_to_new_pool.insert(old_idx, new_idx); + } + } + + // Stage local disks, lock clients, and local peer identity WITHOUT mutating + // any live registry until atomic cutover. + let mut staged_locals = + runtime_sources::prepare_staged_local_disks_for_reload(&self.ctx, target_endpoints.clone()).await?; + let staged_lock_clients = build_staged_lock_clients_map(&target_endpoints); + let staged_lock_registry = runtime_sources::LockRegistry::new(staged_lock_clients.clone()); + let mut host = server_addr.ip().to_string(); + if host.is_empty() { + host = runtime_sources::rustfs_host().await; + } + let mut port = server_addr.port().to_string(); + if port.is_empty() { + port = runtime_sources::rustfs_port().to_string(); + } + let staged_local_node_name = resolve_local_peer_name(&target_endpoints, &host, &port); + let active_remote_hosts = collect_remote_hosts(¤t_endpoints); + let retained_remote_hosts = collect_remote_hosts(&target_endpoints); + + let mut opened_remote_disks: Vec = Vec::new(); + let mut created_sets: Vec> = Vec::new(); + let mut pool_meta_persisted_by_writer = false; + + let build_result: Result<(Arc, HashSet, usize)> = async { + let added_cmds: HashSet<&str> = diff.added_pools.iter().map(|p| p.cmd_line.as_str()).collect(); + let mut new_pools = Vec::with_capacity(target_endpoints.as_ref().len()); + let mut new_disk_map = HashMap::with_capacity(target_endpoints.as_ref().len()); + let mut pool_meta_bootstrap_authorities = Vec::with_capacity(target_endpoints.as_ref().len()); + + for (i, pool_eps) in target_endpoints.as_ref().iter().enumerate() { + let is_added_pool = added_cmds.contains(pool_eps.cmd_line.as_str()); + // Single-creator invariant: ONLY the node owning endpoint 0 of pool `i` + // may create `format.json` on unformatted drives in pool `i`. + let allow_format_creator = pool_first_endpoint_is_local(pool_eps); + + let parity_drives = default_pool_parities.get(i).copied().ok_or_else(|| { + Error::other_with_context("topology reload failed to resolve pool parity", format!("pool {i}")) + })?; + + let (mut disks, errs) = init_format::init_disks_with_staged_locals( + &self.ctx, + &pool_eps.endpoints, + &DiskOption { + cleanup: false, + health_check: true, + }, + &staged_locals.local_disk_map, + ) + .await; + for disk in disks.iter().flatten() { + if !disk.is_local() { + opened_remote_disks.push(disk.clone()); + } + } + check_disk_fatal_errs(&errs)?; + + let loaded_format = { + let mut times = 0_u32; + let mut interval = 1_u64; + loop { + match init_format::connect_load_init_formats_staged( + &self.ctx, + allow_format_creator, + &mut disks, + pool_eps.set_count, + pool_eps.drives_per_set, + Some(self.id), + ) + .await + { + Ok(fm) => break Ok(fm), + Err(e) if !should_retry_format_load(&e) => break Err(e), + Err(e) if format_load_retry_exhausted(&e, times) || times >= 6 => { + break Err(Error::other_with_context( + "topology reload failed to load pool format after retries", + format!("pool {i} after {times} retries: {e}"), + )); + } + Err(_) => {} + } + times = times.saturating_add(1); + interval = (interval * 2).min(4); + tokio::select! { + _ = shutdown_token.cancelled() => { + return Err(Error::other("topology reload cancelled while loading formats")); + } + _ = sleep(Duration::from_secs(interval)) => {} + } + for disk in disks.iter().flatten() { + disk.reset_health_for_store_init_retry(); + } + } + }?; + + let fm = loaded_format.format; + if fm.id != self.id { + return Err(Error::InconsistentDisk); + } + pool_meta_bootstrap_authorities.push(if is_added_pool { + loaded_format.pool_meta_bootstrap_authority + } else { + PoolMetaBootstrapAuthority::None + }); + + runtime_sources::sync_staged_local_disks_with_quorum(&mut staged_locals, i, pool_eps, &disks); + for disk in disks.iter().flatten() { + disk.enable_health_check(); + } + + let sets = Sets::new_with_staged_resources( + disks.clone(), + pool_eps, + &fm, + i, + parity_drives, + self.ctx.clone(), + Some(target_setup_type == SetupType::DistErasure), + staged_locals.set_drives.get(i).map(Vec::as_slice), + Some(&staged_lock_registry), + Some(staged_local_node_name.clone()), + ) + .await?; + created_sets.push(sets.clone()); + new_pools.push(sets); + new_disk_map.insert(i, disks); + } + + let mut propagated_names = HashSet::new(); + let mut buckets_propagated = 0usize; + if mode == TopologyReloadMode::Expand && !existing_buckets.is_empty() { + buckets_propagated = buckets_propagated.saturating_add( + propagate_buckets_to_added_pools(&new_pools, &added_cmds, &existing_buckets, &mut propagated_names).await?, + ); + } + + let remapped_rebalance_meta = { + let current_rebal = self.rebalance_meta.read().await.clone(); + current_rebal.map(|mut meta| { + if !meta.pool_stats.is_empty() { + let mut next_stats = + vec![crate::services::rebalance::RebalanceStats::default(); target_endpoints.as_ref().len()]; + for (&old_idx, &new_idx) in &old_to_new_pool { + if let Some(stat) = meta.pool_stats.get(old_idx) + && let Some(slot) = next_stats.get_mut(new_idx) + { + *slot = stat.clone(); + } + } + meta.pool_stats = next_stats; + } + meta + }) + }; + + let peer_sys = S3PeerSys::new_with_instance_ctx(&target_endpoints, self.ctx.clone()); + let mut candidate_pool_meta = PoolMeta::new(&new_pools, ¤t_pool_meta)?; + candidate_pool_meta.dont_save = true; + let elected_bootstrap_writer = new_pools + .first() + .is_some_and(|pool| pool_first_endpoint_is_local(&pool.endpoints)); + let pool_meta_write_state = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities( + self.id, + pool_meta_bootstrap_authorities, + elected_bootstrap_writer, + ); + + let new_ec = Arc::new(ECStore { + id: self.id, + disk_map: new_disk_map, + pools: new_pools, + peer_sys, + pool_meta: RwLock::new(candidate_pool_meta), + rebalance_meta: RwLock::new(remapped_rebalance_meta), + decommission_cancelers: RwLock::new(vec![None; target_endpoints.as_ref().len()]), + start_gate: Mutex::new(()), + pool_meta_save_gate: crate::core::pools::PoolMetaSaveGate::new(pool_meta_write_state), + ctx: self.ctx.clone(), + bucket_fence_registry: self.bucket_fence_registry.clone(), + }); + + // Pin the resolved target storage class on the staged generation before + // persisting `pool.bin.identity` / `pool.bin`, so writes target the new + // pool layout while the live generation keeps serving uninterrupted. + for pool in &new_ec.pools { + for set in &pool.disk_set { + set.set_storage_class_config_override(Some(target_storage_class_arc.clone())); + } + } + + // Persist or observe the updated durable `pool.bin` across quorum. + let mut attempt = 0usize; + loop { + match new_ec.init_pool_metadata_for_startup().await { + Ok(_) => { + if elected_bootstrap_writer { + pool_meta_persisted_by_writer = true; + } + break; + } + Err(err) if is_pool_meta_bootstrap_pending(&err) && attempt < NON_WRITER_POOL_META_WAIT_ATTEMPTS => { + attempt = attempt.saturating_add(1); + tokio::select! { + _ = shutdown_token.cancelled() => { + return Err(Error::other("topology reload cancelled while waiting for pool.bin commit")); + } + _ = sleep(NON_WRITER_POOL_META_WAIT_INTERVAL) => {} + } + } + Err(err) => return Err(err), + } + } + + // Two-phase cutover barrier: run caller coordination (e.g. waking and + // awaiting joining standby peers so they exit bootstrap mode) AFTER + // `pool.bin` is durable on quorum and BEFORE this node routes any live + // S3 traffic to the new generation. + before_cutover().await?; + + Ok((new_ec, propagated_names, buckets_propagated)) + } + .await; + + let (new_ec, mut propagated_names, mut buckets_propagated) = match build_result { + Ok(result) => result, + Err(err) => { + for sets in created_sets { + sets.stop_endpoint_monitor(); + } + for disk in opened_remote_disks { + let ep = disk.endpoint(); + let grid_host = ep.grid_host(); + let host_port = ep.host_port(); + let _ = disk.close().await; + evict_unretained_peer_connection(&grid_host, &host_port, &active_remote_hosts).await; + } + runtime_sources::abort_staged_local_disks_for_reload(staged_locals).await; + if pool_meta_persisted_by_writer + && let Err(rb_err) = self.rollback_pool_meta_after_failed_reload(¤t_pool_meta).await + { + warn!( + event = EVENT_TOPOLOGY_RELOAD_STAGE, + component = LOG_COMPONENT_ECSTORE, + subsystem = LOG_SUBSYSTEM_TOPOLOGY_RELOAD, + stage = "rollback_pool_meta", + error = %rb_err, + "Failed to roll back pool.bin after aborted staged hot-reload" + ); + } + return Err(err); + } + }; + + // Hold exclusive `bucket_topology_gate` across the final delta bucket sync + // and atomic RCU cutover so concurrent `CreateBucket` operations cannot + // straddle old/new generations or miss bucket propagation on expanded pools. + let bucket_gate = self.ctx.bucket_topology_gate(); + let _bucket_cutover_guard = bucket_gate.write().await; + + if mode == TopologyReloadMode::Expand { + let added_cmds: HashSet<&str> = diff.added_pools.iter().map(|p| p.cmd_line.as_str()).collect(); + let latest_buckets = self.list_buckets_for_metadata_startup().await?; + buckets_propagated = buckets_propagated.saturating_add( + propagate_buckets_to_added_pools(&new_ec.pools, &added_cmds, &latest_buckets, &mut propagated_names).await?, + ); + } + + // Pin the retiring store generation to the previous storage class snapshot + // so any in-flight requests still finishing on `self` never observe a + // mismatched pool count after the active storage class switches over. + let previous_storage_class = runtime_sources::storage_class_config_snapshot(); + for pool in &self.pools { + for set in &pool.disk_set { + set.set_storage_class_config_override(Some(previous_storage_class.clone())); + } + } + + // Atomic RCU cutover: commit staged local disk registries (including shifted + // `pool_idx` on surviving disks and pruned `local_disk_id_map`), lock clients, + // positional state, storage class, BucketMetadataSys, and upper-layer handles. + let removed_local_disks = runtime_sources::commit_staged_local_disks_for_reload(&self.ctx, staged_locals).await?; + self.ctx.reconcile_positional_pool_state(&old_to_new_pool); + self.ctx.delete_recovery_hints().reset_on_topology_reload(&old_to_new_pool); + runtime_sources::replace_lock_clients(staged_lock_clients); + runtime_sources::set_local_node_name(staged_local_node_name).await; + + crate::config::set_global_storage_class(target_storage_class); + for pool in &new_ec.pools { + for set in &pool.disk_set { + set.set_storage_class_config_override(None); + } + } + self.ctx.replace_endpoints(target_endpoints.clone()); + self.ctx.update_erasure_type(target_setup_type).await; + let node_count = u64::try_from(target_endpoints.get_nodes().len().max(1)).unwrap_or(1); + self.ctx.replace_bucket_monitor(node_count); + self.ctx.rebind_bucket_metadata_store_sync(&new_ec); + self.ctx.set_live_store(&new_ec); + runtime_sources::replace_object_store(new_ec.clone()); + on_cutover(new_ec.clone()).await?; + drop(_bucket_cutover_guard); + let _ = replace_global_notification_sys(target_endpoints.clone(), topology_fingerprint).await; + let generation = self.ctx.advance_topology_generation(); + + // Retire Gen-N-1 background monitors/connections and transfer per-generation + // background supervisors onto `new_ec`. + self.retire(&retained_remote_hosts, removed_local_disks).await; + let _ = new_ec.spawn_generation_background_workers(&target_endpoints, &shutdown_token); + + let duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + let added_pools: Vec = diff.added_pools.iter().map(|p| p.cmd_line.clone()).collect(); + let removed_pools: Vec = diff.removed_pools.iter().map(|p| p.cmd_line.clone()).collect(); + + info!( + event = EVENT_TOPOLOGY_RELOAD_STAGE, + component = LOG_COMPONENT_ECSTORE, + subsystem = LOG_SUBSYSTEM_TOPOLOGY_RELOAD, + state = "committed", + mode = mode.as_str(), + generation, + previous_pool_count, + new_pool_count = new_ec.pools.len(), + added_pool_count = added_pools.len(), + removed_pool_count = removed_pools.len(), + buckets_propagated, + duration_ms, + "Committed live zero-downtime pool topology hot-reload" + ); + debug!( + added_pools = ?added_pools, + removed_pools = ?removed_pools, + "Topology hot-reload pool delta" + ); + + Ok(TopologyReloadOutcome { + store: new_ec, + generation, + mode, + previous_pool_count, + new_pool_count: target_endpoints.as_ref().len(), + added_pools, + removed_pools, + buckets_propagated, + duration_ms, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::pools::{PoolDecommissionInfo, PoolStatus}; + use crate::layout::endpoint::Endpoint; + use crate::layout::endpoints::Endpoints; + use time::OffsetDateTime; + + fn make_pool(pool_idx: i32, host_prefix: &str, drives_per_set: usize) -> PoolEndpoints { + let mut endpoints = Vec::with_capacity(drives_per_set); + for d in 0..drives_per_set { + let mut ep = Endpoint::try_from(format!("http://{host_prefix}-{}:9000/data/d{}", d + 1, d + 1).as_str()) + .expect("test endpoint must parse"); + ep.pool_idx = pool_idx; + ep.set_idx = 0; + ep.disk_idx = i32::try_from(d).expect("disk index fits i32"); + ep.is_local = d == 0 && pool_idx == 0; + endpoints.push(ep); + } + PoolEndpoints { + legacy: false, + set_count: 1, + drives_per_set, + cmd_line: format!("http://{host_prefix}-{{1...{drives_per_set}}}:9000/data/d{{1...{drives_per_set}}}"), + endpoints: Endpoints::from(endpoints), + platform: String::new(), + } + } + + fn pool_meta_from(pools: &EndpointServerPools, completed_decommission: &[usize]) -> PoolMeta { + PoolMeta { + version: 1, + dont_save: true, + pools: pools + .as_ref() + .iter() + .enumerate() + .map(|(idx, pool)| PoolStatus { + id: idx, + cmd_line: pool.cmd_line.clone(), + last_update: OffsetDateTime::now_utc(), + decommission: completed_decommission.contains(&idx).then(|| PoolDecommissionInfo { + complete: true, + ..Default::default() + }), + }) + .collect(), + } + } + + #[test] + fn analyze_topology_transition_accepts_valid_expansion() { + let current = EndpointServerPools::from(vec![make_pool(0, "node-a", 4)]); + let target = EndpointServerPools::from(vec![make_pool(0, "node-a", 4), make_pool(1, "node-b", 4)]); + let meta = pool_meta_from(¤t, &[]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Expand)); + assert_eq!(diff.kind, TopologyTransitionKind::Expand); + assert!(diff.errors.is_empty(), "unexpected errors: {:?}", diff.errors); + assert_eq!(diff.added_pools.len(), 1); + assert_eq!(diff.retained_pools.len(), 1); + assert!(diff.removed_pools.is_empty()); + } + + #[test] + fn analyze_topology_transition_accepts_completed_decommission_removal() { + let current = EndpointServerPools::from(vec![make_pool(0, "node-a", 4), make_pool(1, "node-b", 4)]); + let target = EndpointServerPools::from(vec![make_pool(0, "node-b", 4)]); + let meta = pool_meta_from(¤t, &[0]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Decommission)); + assert_eq!(diff.kind, TopologyTransitionKind::Decommission); + assert!(diff.errors.is_empty(), "unexpected errors: {:?}", diff.errors); + assert_eq!(diff.removed_pools.len(), 1); + assert_eq!(diff.retained_pools.len(), 1); + assert!(diff.added_pools.is_empty()); + } + + #[test] + fn analyze_topology_transition_rejects_removing_active_non_decommissioned_pool() { + let current = EndpointServerPools::from(vec![make_pool(0, "node-a", 4), make_pool(1, "node-b", 4)]); + let target = EndpointServerPools::from(vec![make_pool(0, "node-b", 4)]); + let meta = pool_meta_from(¤t, &[]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Decommission)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors.iter().any(|e| e.contains("has not been decommissioned")), + "expected non-decommissioned error, got {:?}", + diff.errors + ); + } + + #[test] + fn analyze_topology_transition_rejects_mixed_expand_and_remove() { + let current = EndpointServerPools::from(vec![make_pool(0, "node-a", 4), make_pool(1, "node-b", 4)]); + let target = EndpointServerPools::from(vec![make_pool(0, "node-b", 4), make_pool(1, "node-c", 4)]); + let meta = pool_meta_from(¤t, &[0]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Expand)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors + .iter() + .any(|e| e.contains("simultaneously add new pools and remove")), + "expected mixed transition error, got {:?}", + diff.errors + ); + } + + #[test] + fn analyze_topology_transition_rejects_duplicate_endpoints_across_pools() { + let p0 = make_pool(0, "node-a", 4); + let mut p1 = make_pool(1, "node-a", 4); + p1.cmd_line = "http://node-a-{1...4}:9000/data/d{1...4}#dup".to_string(); + let current = EndpointServerPools::from(vec![p0.clone()]); + let target = EndpointServerPools::from(vec![p0, p1]); + let meta = pool_meta_from(¤t, &[]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Expand)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors.iter().any(|e| e.contains("duplicate endpoint")), + "expected duplicate endpoint error, got {:?}", + diff.errors + ); + } + + #[test] + fn analyze_topology_transition_rejects_mode_mismatch() { + let current = EndpointServerPools::from(vec![make_pool(0, "node-a", 4)]); + let target = EndpointServerPools::from(vec![make_pool(0, "node-a", 4), make_pool(1, "node-b", 4)]); + let meta = pool_meta_from(¤t, &[]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Decommission)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors.iter().any(|e| e.contains("maintenance mode is `decommission`")), + "expected mode mismatch error, got {:?}", + diff.errors + ); + } + + #[test] + fn analyze_topology_transition_rejects_surviving_pool_reordering_during_decommission() { + let current = EndpointServerPools::from(vec![ + make_pool(0, "node-a", 4), + make_pool(1, "node-b", 4), + make_pool(2, "node-c", 4), + ]); + // Remove Pool 0 (completed), but swap surviving Pool 1 and Pool 2! + let target = EndpointServerPools::from(vec![make_pool(0, "node-c", 4), make_pool(1, "node-b", 4)]); + let meta = pool_meta_from(¤t, &[0]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Decommission)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors.iter().any(|e| e.contains("reordering surviving pools")), + "expected surviving pool reordering error, got {:?}", + diff.errors + ); + } + + #[test] + fn analyze_topology_transition_rejects_local_to_distributed_mode_change() { + let mut local_pool = make_pool(0, "local-a", 4); + for ep in local_pool.endpoints.as_mut() { + ep.is_local = true; + } + let remote_pool = make_pool(1, "remote-b", 4); + let current = EndpointServerPools::from(vec![local_pool.clone()]); + let target = EndpointServerPools::from(vec![local_pool, remote_pool]); + let meta = pool_meta_from(¤t, &[]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Expand)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors + .iter() + .any(|e| e.contains("cannot transition between single-node local topology and distributed")), + "expected local <-> distributed transition error, got {:?}", + diff.errors + ); + } + + #[test] + fn analyze_topology_transition_rejects_expand_when_completed_decommission_pool_remains() { + let current = EndpointServerPools::from(vec![make_pool(0, "node-a", 4), make_pool(1, "node-b", 4)]); + let target = EndpointServerPools::from(vec![ + make_pool(0, "node-a", 4), + make_pool(1, "node-b", 4), + make_pool(2, "node-c", 4), + ]); + let meta = pool_meta_from(¤t, &[0]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Expand)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors.iter().any(|e| e.contains("has already completed decommission")), + "expected completed-decommission blocking error on expand, got {:?}", + diff.errors + ); + } + + #[test] + fn analyze_topology_transition_rejects_single_drive_erasure_pool() { + let current = EndpointServerPools::from(vec![make_pool(0, "node-a", 4)]); + let target = EndpointServerPools::from(vec![make_pool(0, "node-a", 4), make_pool(1, "node-single", 1)]); + let meta = pool_meta_from(¤t, &[]); + + let diff = analyze_topology_transition(¤t, &target, &meta, Some(TopologyReloadMode::Expand)); + assert_eq!(diff.kind, TopologyTransitionKind::Invalid); + assert!( + diff.errors.iter().any(|e| e.contains("minimum for erasure coding is 4")), + "expected drives_per_set < 4 error for 1-drive pool, got {:?}", + diff.errors + ); + } + + #[test] + fn probe_local_unregistered_disk_sync_is_purely_read_only_without_creating_rustfs_sys() { + let dir = tempfile::tempdir().expect("tempdir"); + let path_str = dir.path().display().to_string(); + let probe = probe_local_unregistered_disk_sync(1, path_str.clone(), String::new(), path_str, uuid::Uuid::new_v4(), 1, 4); + assert!(probe.reachable, "empty candidate directory should be reachable: {probe:?}"); + assert_eq!(probe.format_state, CandidateDiskFormatState::Unformatted); + assert!(probe.total_bytes > 0, "statvfs should report positive total_bytes"); + assert!( + !dir.path().join(RUSTFS_META_BUCKET).exists(), + "read-only candidate probe MUST NOT create .rustfs.sys directory" + ); + let entries: Vec<_> = std::fs::read_dir(dir.path()).expect("read_dir").collect(); + assert!( + entries.is_empty(), + "read-only candidate probe MUST NOT leave any probe or reserve files behind: {entries:?}" + ); + } +} diff --git a/crates/ecstore/tests/dst_production_ecstore.rs b/crates/ecstore/tests/dst_production_ecstore.rs new file mode 100644 index 0000000000..b0afc96119 --- /dev/null +++ b/crates/ecstore/tests/dst_production_ecstore.rs @@ -0,0 +1,744 @@ +// Copyright 2026 RustFS Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Production Deterministic Simulation Testing (DST) integration suite for `rustfs-ecstore`. +//! +//! Exercises REAL `SetDisks` erasure coding, SIMD Reed-Solomon, HighwayHash256S bitrot +//! framing, `FileMeta` (`xl.meta`), recoverable deletes, and `HealOperations::heal_object` +//! directly on top of `rustfs_dst_runtime::disk::SimDiskIo` (`Disk::Sim(Box)`). + +#![cfg(feature = "dst")] + +mod storage_api; + +use std::collections::{BTreeMap, BTreeSet}; + +use bytes::Bytes; +use http::HeaderMap; +use rustfs_filemeta::FileMeta; +use sha2::{Digest, Sha256}; +use storage_api::dst_production_ecstore::{ + BLOCK_SIZE_V2, BucketOperations, CHECK_PART_FILE_CORRUPT, CHECK_PART_SUCCESS, CrashPoint, CrashSemantics, DiskAPI, + DstSimSetFixture, EcstoreResult, Error as EcstoreError, HealOperations, HealOpts, HealScanMode, MakeBucketOptions, ObjectIO, + ObjectOperations, ObjectOptions, PutObjReader, ReadOptions, RngSource, STORAGE_FORMAT_FILE, SimDiskIoTrait, SimRng, + dst_object_options, is_err_object_not_found, load_format_erasure, make_dst_sim_set_disks, +}; +use tokio::io::AsyncReadExt; + +fn deterministic_payload(seed: u64, tag: &str, len: usize) -> Vec { + let rng = SimRng::from_seed(seed); + let mut header = format!("rustfs-dst:{tag}:seed={seed}:len={len}:").into_bytes(); + let mut out = Vec::with_capacity(len); + let copy_hdr = header.len().min(len); + out.extend_from_slice(&header[..copy_hdr]); + header.clear(); + while out.len() < len { + let word = rng.next_u64().to_le_bytes(); + let take = (len - out.len()).min(word.len()); + out.extend_from_slice(&word[..take]); + } + out +} + +fn tail_drained_opts() -> ObjectOptions { + dst_object_options() +} + +async fn put_bytes(fixture: &DstSimSetFixture, bucket: &str, key: &str, payload: &[u8]) -> EcstoreResult<()> { + let mut reader = PutObjReader::from_vec(payload.to_vec()); + let info = fixture + .set_disks + .put_object(bucket, key, &mut reader, &tail_drained_opts()) + .await?; + assert_eq!(info.size, payload.len() as i64); + Ok(()) +} + +async fn get_bytes(fixture: &DstSimSetFixture, bucket: &str, key: &str) -> EcstoreResult> { + let mut reader = fixture + .set_disks + .get_object_reader(bucket, key, None, HeaderMap::new(), &ObjectOptions::default()) + .await?; + let mut buf = Vec::new(); + reader.stream.read_to_end(&mut buf).await.map_err(EcstoreError::from)?; + Ok(buf) +} + +/// Locate `///part.1` on simulated drive `disk_idx`. +fn find_part1_rel_path(fixture: &DstSimSetFixture, disk_idx: usize, bucket: &str, key: &str) -> Option { + let prefix = format!("{bucket}/{key}/"); + fixture.sim_disks[disk_idx] + .sim() + .all_files() + .into_iter() + .find(|p| p.starts_with(&prefix) && p.ends_with("/part.1")) +} + +// ============================================================================ +// Test 1: Real production put_object / get_object / delete_object + degraded +// quorum read/write when drives go offline + ENOSPC handling +// ============================================================================ +#[tokio::test] +async fn dst_prod_test1_quorum_put_get_delete_offline_and_enospc() { + for &seed in &[0x000A_11CE_0001_u64, 0x000A_11CE_0002_u64, 0x000A_11CE_0003_u64] { + let fixture = make_dst_sim_set_disks(seed, 4, 2, None) + .await + .expect("dst sim 4-drive SetDisks should initialize"); + + // Verify real `format.json` (`FormatV3`) persisted and readable on every drive + for (slot, disk) in fixture.disks.iter().enumerate() { + let loaded = load_format_erasure(disk, true) + .await + .expect("format.json should load from DstSimDisk"); + assert_eq!(loaded.id, fixture.format.id); + assert_eq!(loaded.erasure.this, fixture.format.erasure.sets[0][slot]); + assert!(loaded.disk_info.expect("heal disk_info").fresh_capacity); + } + + let bucket = "dst-prod-quorum"; + fixture + .set_disks + .make_bucket(bucket, &MakeBucketOptions::default()) + .await + .expect("make_bucket should succeed across 4 Sim drives"); + + // Exercise BOTH inline small object AND multi-block (>1 MiB) erasure-coded object + let small_key = "inline/small.bin"; + let small_payload = deterministic_payload(seed, "small", 4096); + let large_key = "erasure/multi-block.bin"; + let large_payload = deterministic_payload(seed, "large", BLOCK_SIZE_V2 + 98_304); + + put_bytes(&fixture, bucket, small_key, &small_payload) + .await + .expect("put small inline object"); + put_bytes(&fixture, bucket, large_key, &large_payload) + .await + .expect("put large Reed-Solomon object"); + + // Verify real physical shards (`part.1`) exist on all 4 drives for the large object + for slot in 0..4 { + assert!( + find_part1_rel_path(&fixture, slot, bucket, large_key).is_some(), + "drive {slot} must store physical bitrot-framed part.1 shard" + ); + } + + assert_eq!(get_bytes(&fixture, bucket, small_key).await.expect("get small"), small_payload); + assert_eq!(get_bytes(&fixture, bucket, large_key).await.expect("get large"), large_payload); + + // Take 2 drives offline (equals parity = 2 on a 2+2 set): degraded read AND write must work! + fixture.sim_disks[0].set_online(false); + fixture.sim_disks[2].set_online(false); + fixture.invalidate_set_caches(); + + assert_eq!( + get_bytes(&fixture, bucket, small_key) + .await + .expect("degraded read small with 2 drives offline"), + small_payload + ); + assert_eq!( + get_bytes(&fixture, bucket, large_key) + .await + .expect("degraded Reed-Solomon reconstruct read with 2 drives offline"), + large_payload + ); + + // Degraded quorum write while 1 drive is offline (3 online >= write quorum) + fixture.sim_disks[2].set_online(true); + fixture.invalidate_set_caches(); + let degraded_key = "erasure/written-while-d0-offline.bin"; + let degraded_payload = deterministic_payload(seed ^ 0x55, "degraded-put", BLOCK_SIZE_V2 + 16_384); + put_bytes(&fixture, bucket, degraded_key, °raded_payload) + .await + .expect("degraded put_object with 1 drive offline should succeed at quorum"); + assert_eq!( + get_bytes(&fixture, bucket, degraded_key).await.expect("read degraded-put"), + degraded_payload + ); + + // Take 3 drives offline (only 1 online < read/write quorum): operations must fail closed! + fixture.sim_disks[1].set_online(false); + fixture.sim_disks[2].set_online(false); + fixture.invalidate_set_caches(); + + assert!( + get_bytes(&fixture, bucket, large_key).await.is_err(), + "read below quorum (3/4 drives offline) must fail closed" + ); + assert!( + put_bytes(&fixture, bucket, "below-quorum.bin", b"must-not-commit") + .await + .is_err(), + "write below quorum (3/4 drives offline) must fail closed" + ); + + // Bring all drives back online, heal the object written while drive 0 was offline, + // and verify real recoverable delete_object! + for sim in &fixture.sim_disks { + sim.set_online(true); + } + fixture.invalidate_set_caches(); + + let (heal_res, heal_err) = fixture + .set_disks + .heal_object( + bucket, + degraded_key, + "", + &HealOpts { + scan_mode: HealScanMode::Deep, + remove: true, + ..Default::default() + }, + ) + .await + .expect("heal_object on degraded_key should succeed"); + assert!(heal_err.is_none(), "heal_object error should be None: {heal_err:?}"); + assert!(find_part1_rel_path(&fixture, 0, bucket, degraded_key).is_some()); + let _ = heal_res; + + // Delete object through production recoverable-delete protocol + fixture + .set_disks + .delete_object(bucket, small_key, dst_object_options()) + .await + .expect("delete_object small_key"); + let after_del = get_bytes(&fixture, bucket, small_key).await; + assert!( + after_del.is_err() && is_err_object_not_found(after_del.as_ref().unwrap_err()), + "deleted object must return ObjectNotFound, got: {after_del:?}" + ); + + // ENOSPC quota enforcement on 3 drives -> write must fail without corrupting existing objects + for slot in [0, 1, 2] { + let current_used = fixture.sim_disks[slot].sim().used_bytes(); + fixture.sim_disks[slot].set_capacity_bytes(Some(current_used + 1024)); + } + let enospc_payload = vec![0xAB; BLOCK_SIZE_V2]; + assert!( + put_bytes(&fixture, bucket, "enospc-denied.bin", &enospc_payload) + .await + .is_err(), + "put_object exceeding drive capacity across quorum must fail with ENOSPC" + ); + // Existing large_key remains 100% intact! + fixture.invalidate_set_caches(); + assert_eq!(get_bytes(&fixture, bucket, large_key).await.expect("get after enospc"), large_payload); + } +} + +// ============================================================================ +// Test 2: Real physical shard silent bitrot + tail truncation detected by +// production HighwayHash256S and reconstructed + healed by ecstore +// ============================================================================ +#[tokio::test] +async fn dst_prod_test2_physical_bitrot_highwayhash_detect_reconstruct_and_heal() { + // Test across BOTH 4-drive (2+2) and 8-drive (4+4) production erasure topologies! + for &(seed, drives, parity, rot_slots) in &[ + (0xB172_0701_u64, 4usize, 2usize, &[0usize, 2usize][..]), + (0xB172_0702_u64, 4usize, 2usize, &[1usize, 3usize][..]), + (0xB172_0703_u64, 8usize, 4usize, &[0usize, 2usize, 5usize, 7usize][..]), + ] { + let fixture = make_dst_sim_set_disks(seed, drives, parity, None) + .await + .expect("dst sim SetDisks should initialize"); + let bucket = "dst-prod-bitrot"; + fixture + .set_disks + .make_bucket(bucket, &MakeBucketOptions::default()) + .await + .expect("make_bucket"); + + let key = "critical/ledger-stripe.bin"; + let payload = deterministic_payload(seed, "bitrot-target", BLOCK_SIZE_V2 * 2 + 77_777); + put_bytes(&fixture, bucket, key, &payload) + .await + .expect("put multi-stripe object"); + + // 1. Pre-fault verification: every drive passes production HighwayHash256S `verify_file` + for disk in fixture.disks.iter().take(drives) { + let fi = disk + .read_version("", bucket, key, "", &ReadOptions::default()) + .await + .expect("read_version on healthy drive"); + let check = disk + .verify_file(bucket, key, &fi) + .await + .expect("verify_file on healthy drive"); + assert_eq!(check.results, vec![CHECK_PART_SUCCESS]); + } + + // 2. Inject silent physical bitrot (and tail truncation on the last corrupted slot) + // directly into the underlying `SimDiskIo` `part.1` files! + for (idx, &slot) in rot_slots.iter().enumerate() { + let part_rel = find_part1_rel_path(&fixture, slot, bucket, key).expect("part.1 path"); + if idx + 1 == rot_slots.len() && rot_slots.len() > 1 { + assert!( + fixture.sim_disks[slot].inject_tail_truncate(&part_rel, 19), + "tail truncation must shrink part.1 on drive {slot}" + ); + } else { + assert!( + fixture.sim_disks[slot].inject_bitrot(&part_rel), + "bitrot injection must flip a byte in part.1 on drive {slot}" + ); + } + + // Confirm production `verify_file` immediately flags `CHECK_PART_FILE_CORRUPT` + let fi = fixture.disks[slot] + .read_version("", bucket, key, "", &ReadOptions::default()) + .await + .expect("xl.meta still readable"); + let check = fixture.disks[slot] + .verify_file(bucket, key, &fi) + .await + .expect("verify_file must classify corruption"); + assert_eq!( + check.results, + vec![CHECK_PART_FILE_CORRUPT], + "HighwayHash256S verify_file must detect silent corruption on drive {slot}" + ); + } + + // 3. Transparent Reed-Solomon reconstruction on GET: corrupt shards are rejected by + // `BitrotReader` and exact plaintext is reconstructed from surviving shards! + fixture.invalidate_set_caches(); + let reconstructed = get_bytes(&fixture, bucket, key) + .await + .expect("GET must transparently reconstruct despite silent bitrot on parity-many drives"); + assert_eq!(reconstructed, payload); + + // 4. Execute REAL production `HealOperations::heal_object` with `HealScanMode::Deep`! + let (_heal_item, heal_err) = fixture + .set_disks + .heal_object( + bucket, + key, + "", + &HealOpts { + scan_mode: HealScanMode::Deep, + remove: true, + ..Default::default() + }, + ) + .await + .expect("production deep heal_object must succeed"); + assert!(heal_err.is_none(), "deep heal_object returned unexpected err: {heal_err:?}"); + + // 5. Post-heal proof: ALL drives now pass HighwayHash256S `verify_file` (`CHECK_PART_SUCCESS`), + // AND taking the untouched drives offline proves the healed shards serve valid data! + for (slot, disk) in fixture.disks.iter().enumerate().take(drives) { + let fi = disk + .read_version("", bucket, key, "", &ReadOptions::default()) + .await + .expect("post-heal read_version"); + let check = disk.verify_file(bucket, key, &fi).await.expect("post-heal verify_file"); + assert_eq!( + check.results, + vec![CHECK_PART_SUCCESS], + "drive {slot} shard must be 100% healed and verified on disk" + ); + } + + // Take `parity` previously-healthy drives offline so GET is forced to read the healed drives! + let mut offlined = 0; + for (slot, sim_disk) in fixture.sim_disks.iter().enumerate().take(drives) { + if !rot_slots.contains(&slot) && offlined < parity { + sim_disk.set_online(false); + offlined += 1; + } + } + fixture.invalidate_set_caches(); + let post_heal_degraded = get_bytes(&fixture, bucket, key) + .await + .expect("GET reading directly from healed shards must succeed"); + assert_eq!(post_heal_degraded, payload); + } +} + +// ============================================================================ +// Test 3: ALICE power-loss crash (`CrashSemantics::DirtySubsetAndSectorTear` + +// `crash_and_reboot`) across multiple drives & CrashPoints — proving +// old-or-new-never-mixed atomicity and zero FileMeta corruption! +// ============================================================================ +#[tokio::test] +async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixed() { + let crash_points = [ + CrashPoint::RenameAfterDataRename, + CrashPoint::RenameAfterBackupBeforeMetaCommit, + CrashPoint::RenameAfterMetaCommit, + CrashPoint::MetaWriteAfterTmpBeforeRename, + ]; + + for (seed_idx, &seed) in [0xC2A5_4001_u64, 0xC2A5_4002_u64, 0xC2A5_4003_u64, 0xC2A5_4004_u64] + .iter() + .enumerate() + { + let fixture = make_dst_sim_set_disks(seed, 4, 2, None) + .await + .expect("dst sim SetDisks should initialize"); + + // Enable ALICE / CrashMonkey `DirtySubsetAndSectorTear` on every drive! + for sim in &fixture.sim_disks { + sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear); + } + + let bucket = "dst-alice-powerloss"; + fixture + .set_disks + .make_bucket(bucket, &MakeBucketOptions::default()) + .await + .expect("make_bucket"); + + // Commit baseline anchor objects (inline + multi-block Reed-Solomon) + let anchor_small_key = "anchor/small.bin"; + let anchor_small_v1 = deterministic_payload(seed, "anchor-small-v1", 6144); + let anchor_large_key = "anchor/large.bin"; + let anchor_large_v1 = deterministic_payload(seed, "anchor-large-v1", BLOCK_SIZE_V2 + 65_536); + + put_bytes(&fixture, bucket, anchor_small_key, &anchor_small_v1) + .await + .expect("put anchor small"); + put_bytes(&fixture, bucket, anchor_large_key, &anchor_large_v1) + .await + .expect("put anchor large"); + + // Stage dirty un-fsynced files directly in `.rustfs.sys/tmp` to trigger ALICE dirty-page + // subset & 512B sector-tear reconstruction during power loss, then crash all 4 drives! + for (slot, sim) in fixture.sim_disks.iter().enumerate() { + let dirty_tmp = format!(".rustfs.sys/tmp/inflight-unfsynced-{slot}/part.1"); + SimDiskIoTrait::write_file(sim.sim(), &dirty_tmp, Bytes::from(vec![0xEE; 16 * 1024 + 333])) + .await + .expect("stage dirty temp file"); + } + + fixture.crash_and_reboot_all(); + + // Anchor objects MUST survive abrupt ALICE power loss 100% bit-exact! + assert_eq!( + get_bytes(&fixture, bucket, anchor_small_key) + .await + .expect("anchor small after ALICE crash"), + anchor_small_v1 + ); + assert_eq!( + get_bytes(&fixture, bucket, anchor_large_key) + .await + .expect("anchor large after ALICE crash"), + anchor_large_v1 + ); + + // Now test overwriting an existing multi-block object `v1 -> v2` while arming each + // commit `CrashPoint` across 1, 2, or 3 drives, followed by full-cluster ALICE power loss! + for (cp_idx, &point) in crash_points.iter().enumerate() { + let key = format!("overwrite/cp-{cp_idx}.bin"); + let v1 = deterministic_payload(seed ^ (cp_idx as u64 + 10), "v1", BLOCK_SIZE_V2 + 24_576); + let v2 = deterministic_payload(seed ^ (cp_idx as u64 + 99), "v2", BLOCK_SIZE_V2 + 49_152); + + put_bytes(&fixture, bucket, &key, &v1).await.expect("commit v1 before crash"); + assert_eq!(get_bytes(&fixture, bucket, &key).await.expect("verify v1"), v1); + + // Arm crash point on `(seed_idx + cp_idx) % 3 + 1` drives (1, 2, or 3 drives) + let affected_drives = ((seed_idx + cp_idx) % 3) + 1; + for slot in 0..affected_drives { + fixture.crash_registry.arm_on_drive(point, &key, "dst-node0", slot); + } + + // Attempt overwrite `v2` (may succeed at quorum if only 1 drive crashed, or fail if >=2 crashed) + let _overwrite_outcome = put_bytes(&fixture, bucket, &key, &v2).await; + fixture.crash_registry.clear(); + + // Simulate simultaneous cluster-wide power outage & ALICE reboot! + fixture.crash_and_reboot_all(); + + // INVARIANT 1: Zero `xl.meta` (`FileMeta`) structural corruption on ANY drive! + for (slot, sim_disk) in fixture.sim_disks.iter().enumerate().take(4) { + let xl_rel = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}"); + if let Ok(raw) = SimDiskIoTrait::read_file(sim_disk.sim(), &xl_rel).await { + let parsed = FileMeta::load(&raw); + assert!( + parsed.is_ok(), + "ALICE power-loss left corrupt xl.meta on drive {slot} at {point:?} (seed={seed:#x}): {parsed:?}" + ); + } + } + + // INVARIANT 2: Old-or-New-Never-Mixed! Reading `key` must return 100% bit-exact `v1` + // OR 100% bit-exact `v2` — NEVER partial, zeroed, or mixed bytes! + let observed = get_bytes(&fixture, bucket, &key) + .await + .unwrap_or_else(|e| panic!("committed object {key} unreadable after ALICE crash at {point:?}: {e:?}")); + assert!( + observed == v1 || observed == v2, + "atomicity violation after ALICE crash at {point:?} (seed={seed:#x}): payloadlen={} matches neither v1 ({}) nor v2 ({})", + observed.len(), + v1.len(), + v2.len() + ); + + // INVARIANT 3: Production `heal_object` converges all 4 drives back to unanimous health, + // and previously untouched anchor objects remain 100% bit-exact! + let (_, heal_err) = fixture + .set_disks + .heal_object( + bucket, + &key, + "", + &HealOpts { + scan_mode: HealScanMode::Deep, + remove: true, + ..Default::default() + }, + ) + .await + .expect("post-crash heal_object should succeed"); + assert!(heal_err.is_none()); + + let post_heal = get_bytes(&fixture, bucket, &key) + .await + .expect("readable after post-crash heal"); + assert_eq!(post_heal, observed, "heal must preserve the winning committed generation"); + assert_eq!(get_bytes(&fixture, bucket, anchor_large_key).await.unwrap(), anchor_large_v1); + } + } +} + +// ============================================================================ +// Test 4: Deterministic multi-seed chaos loop driving concurrent `tokio::join!` +// operations against real production `SetDisks` + deterministic replay +// ============================================================================ +async fn execute_chaos_seed(seed: u64) -> [u8; 32] { + let fixture = make_dst_sim_set_disks(seed, 4, 2, None) + .await + .expect("dst sim SetDisks should initialize"); + for sim in &fixture.sim_disks { + sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear); + } + + let bucket = "dst-chaos-bucket"; + fixture + .set_disks + .make_bucket(bucket, &MakeBucketOptions::default()) + .await + .expect("make_bucket"); + + let rng = SimRng::from_seed(seed ^ 0xCAFE_BABE_1234_5678); + // Reference state per key: set of permissible payloads (None = deleted/absent, Some(bytes) = valid generation). + // When an operation runs under fault/crash and returns Err, either old or new state is legal; + // when an operation returns Ok with all drives healthy, it narrows to the exact committed state! + let mut model: BTreeMap>>> = BTreeMap::new(); + let keys: Vec = (0..6).map(|i| format!("chaos/obj-{i}.bin")).collect(); + for k in &keys { + model.insert(k.clone(), vec![None]); + } + + for step in 0..12u64 { + // Pick two distinct keys for concurrent `tokio::join!` operations so the two tasks + // contend on real `SetDisks` drives, bitrot verifiers, and namespace locks deterministically! + let idx_a = rng.gen_range_usize(keys.len()); + let idx_b = (idx_a + 1 + rng.gen_range_usize(keys.len() - 1)) % keys.len(); + let key_a = keys[idx_a].clone(); + let key_b = keys[idx_b].clone(); + + // Optionally offline 1 random drive during this wave (within parity = 2 budget) + let offline_slot = if rng.gen_bool(0.45) { + let s = rng.gen_range_usize(4); + fixture.sim_disks[s].set_online(false); + fixture.invalidate_set_caches(); + Some(s) + } else { + None + }; + + let size_a = if rng.gen_bool(0.5) { + 2048 + rng.gen_range_usize(4096) + } else { + BLOCK_SIZE_V2 + rng.gen_range_usize(32_768) + }; + let payload_a = deterministic_payload(seed.wrapping_add(step * 31 + 1), &key_a, size_a); + + let do_delete_b = rng.gen_bool(0.35); + let payload_b = deterministic_payload(seed.wrapping_add(step * 31 + 2), &key_b, 3072 + rng.gen_range_usize(8192)); + + let fut_a = put_bytes(&fixture, bucket, &key_a, &payload_a); + let fut_b = async { + if do_delete_b { + fixture + .set_disks + .delete_object(bucket, &key_b, dst_object_options()) + .await + .map(|_| None) + } else { + put_bytes(&fixture, bucket, &key_b, &payload_b) + .await + .map(|()| Some(payload_b.clone())) + } + }; + let read_key = keys[(idx_b + 1) % keys.len()].clone(); + let fut_read = get_bytes(&fixture, bucket, &read_key); + + let (res_a, res_b, res_read) = tokio::join!(fut_a, fut_b, fut_read); + + // Build linearizable candidate set for `fut_read`: any state permissible + // before the wave PLUS any concurrent mutation targeting `read_key` in this wave! + let mut linearizable_read_states: Vec>> = model.get(&read_key).expect("tracked key").clone(); + if read_key == key_a { + linearizable_read_states.push(Some(payload_a.clone())); + } + if read_key == key_b { + linearizable_read_states.push(if do_delete_b { None } else { Some(payload_b.clone()) }); + } + match res_read { + Ok(bytes) => { + assert!( + linearizable_read_states + .iter() + .any(|st| st.as_deref() == Some(bytes.as_slice())), + "seed={seed:#x} step={step}: concurrent GET on {read_key} returned unexpected bytes (len={})", + bytes.len() + ); + } + Err(e) => { + assert!( + is_err_object_not_found(&e) && linearizable_read_states.iter().any(Option::is_none), + "seed={seed:#x} step={step}: concurrent GET on {read_key} failed unexpectedly: {e:?}" + ); + } + } + + match res_a { + Ok(()) => { + model.insert(key_a.clone(), vec![Some(payload_a)]); + } + Err(_) => { + model.entry(key_a.clone()).or_default().push(Some(payload_a)); + } + } + + match res_b { + Ok(new_state) => { + model.insert(key_b.clone(), vec![new_state]); + } + Err(_) => { + let candidate = if do_delete_b { None } else { Some(payload_b) }; + model.entry(key_b.clone()).or_default().push(candidate); + } + } + + // Restore any offlined drive + if let Some(s) = offline_slot { + fixture.sim_disks[s].set_online(true); + fixture.invalidate_set_caches(); + } + + // Periodically inject physical bitrot on one random drive OR trigger ALICE power-loss crash, + // then heal affected keys! + if step % 3 == 1 { + let rot_drive = rng.gen_range_usize(4); + if let Some(part_rel) = find_part1_rel_path(&fixture, rot_drive, bucket, &key_a) { + fixture.sim_disks[rot_drive].inject_bitrot(&part_rel); + } + } + if step % 4 == 3 { + fixture.crash_and_reboot_all(); + } + + // Heal touched keys so degraded/bitrotted shards converge before next chaos wave + for k in [&key_a, &key_b] { + let _ = fixture + .set_disks + .heal_object( + bucket, + k, + "", + &HealOpts { + scan_mode: HealScanMode::Deep, + remove: true, + ..Default::default() + }, + ) + .await; + } + } + + // Final convergence & full-audit pass across all keys and all 4 drives! + fixture.invalidate_set_caches(); + let mut final_hasher = Sha256::new(); + let mut live_keys = BTreeSet::new(); + + for key in &keys { + let _ = fixture + .set_disks + .heal_object( + bucket, + key, + "", + &HealOpts { + scan_mode: HealScanMode::Deep, + remove: true, + ..Default::default() + }, + ) + .await; + + let allowed = model.get(key).expect("tracked key"); + match get_bytes(&fixture, bucket, key).await { + Ok(bytes) => { + assert!( + allowed.iter().any(|st| st.as_deref() == Some(bytes.as_slice())), + "seed={seed:#x}: final state of {key} violates linearizable/crash-safe model" + ); + live_keys.insert(key.clone()); + final_hasher.update(key.as_bytes()); + final_hasher.update((bytes.len() as u64).to_le_bytes()); + final_hasher.update(&bytes); + + // Every drive's xl.meta must parse cleanly, and non-inline parts must pass verify_file! + for disk in fixture.disks.iter().take(4) { + let fi = disk + .read_version("", bucket, key, "", &ReadOptions::default()) + .await + .expect("healthy xl.meta on every drive after final heal"); + if !fi.inline_data() && fi.size > 0 { + let check = disk + .verify_file(bucket, key, &fi) + .await + .expect("verify_file after final heal"); + assert_eq!(check.results, vec![CHECK_PART_SUCCESS]); + } + } + } + Err(e) => { + assert!( + is_err_object_not_found(&e) && allowed.iter().any(Option::is_none), + "seed={seed:#x}: unexpected final GET error on {key}: {e:?}" + ); + final_hasher.update(key.as_bytes()); + final_hasher.update(b""); + } + } + } + assert!(!live_keys.is_empty(), "chaos run should leave at least one live object"); + final_hasher.finalize().into() +} + +#[tokio::test(flavor = "current_thread")] +async fn dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equivalence() { + for &seed in &[0xD57_0001_u64, 0xD57_0002_u64, 0xD57_0003_u64, 0xD57_0004_u64] { + let digest_run1 = execute_chaos_seed(seed).await; + let digest_run2 = execute_chaos_seed(seed).await; + assert_eq!(digest_run1, digest_run2, "deterministic replay invariant violated for seed {seed:#x}"); + } +} diff --git a/crates/ecstore/tests/hotpath_cpu_attribution_contract_test.rs b/crates/ecstore/tests/hotpath_cpu_attribution_contract_test.rs index b990f38892..b03f78e6b6 100644 --- a/crates/ecstore/tests/hotpath_cpu_attribution_contract_test.rs +++ b/crates/ecstore/tests/hotpath_cpu_attribution_contract_test.rs @@ -49,6 +49,8 @@ fn inherent_hotpath_measurements_have_cpu_attribution_types() { "encode_data_bytes_mut", "decode_data", "decode_data_and_parity", + "decode_data_with_reconstruction_verification", + "decode_data_with_reconstruction_verification_for_lockstep", ] { assert_measured_as(ERASURE, "Erasure", function); } diff --git a/crates/ecstore/tests/storage_api.rs b/crates/ecstore/tests/storage_api.rs index 0b8b9b6281..8c693c9622 100644 --- a/crates/ecstore/tests/storage_api.rs +++ b/crates/ecstore/tests/storage_api.rs @@ -103,3 +103,18 @@ pub(crate) mod local_drive_retirement { pub(crate) use super::{DiskAPI, DiskOption, Endpoint, new_disk}; pub(crate) use rustfs_ecstore::api::disk::Disk; } + +#[cfg(feature = "dst")] +pub(crate) mod dst_production_ecstore { + pub(crate) use super::storage_contracts::{BucketOperations, HealOperations, MakeBucketOptions, ObjectIO, ObjectOperations}; + pub(crate) use super::{DiskAPI, Error, ObjectOptions, PutObjReader, STORAGE_FORMAT_FILE}; + pub(crate) use rustfs_ecstore::api::{ + disk::ReadOptions, + dst::{ + CHECK_PART_FILE_CORRUPT, CHECK_PART_SUCCESS, CrashPoint, CrashSemantics, DiskIo as SimDiskIoTrait, DstSimSetFixture, + HealOpts, HealScanMode, RngSource, SimRng, dst_object_options, load_format_erasure, make_dst_sim_set_disks, + }, + error::{Result as EcstoreResult, is_err_object_not_found}, + object::BLOCK_SIZE_V2, + }; +} diff --git a/crates/heal/src/heal/manager/root_recovery.rs b/crates/heal/src/heal/manager/root_recovery.rs index e080c7876f..2616c39503 100644 --- a/crates/heal/src/heal/manager/root_recovery.rs +++ b/crates/heal/src/heal/manager/root_recovery.rs @@ -427,7 +427,7 @@ impl RootHealTerminal { self.heal_type.validate()?; if !matches!( self.status, - HealTaskStatus::Completed | HealTaskStatus::Cancelled | HealTaskStatus::Failed { .. } + HealTaskStatus::Completed | HealTaskStatus::Cancelled | HealTaskStatus::Timeout | HealTaskStatus::Failed { .. } ) { return Err(Error::Other(format!("Non-terminal root heal receipt {task_id}"))); } @@ -1326,8 +1326,7 @@ impl RootHealRecovery { }; let mut intent = decode_intent(&task.id, &expected)?; intent.validate_task(task)?; - // A terminal timeout leaves no runtime owner for stop() to snapshot. - // Checkpoint its consumed budget before publishing terminal status; + // Checkpoint consumed execution budget before retrying or handing off; // never refund time if an earlier checkpoint is already stricter. intent.options.timeout = match (intent.options.timeout, remaining) { (Some(previous), Some(remaining)) => Some(previous.min(remaining)), diff --git a/crates/heal/src/heal/manager/root_recovery/report.rs b/crates/heal/src/heal/manager/root_recovery/report.rs index fc646882ea..df8cf0a088 100644 --- a/crates/heal/src/heal/manager/root_recovery/report.rs +++ b/crates/heal/src/heal/manager/root_recovery/report.rs @@ -86,7 +86,9 @@ fn decode_report(task_id: &str, bytes: &[u8]) -> Result { if let Some(outcome) = &report.outcome && (matches!(outcome.execution, HealExecutionOutcome::Pending | HealExecutionOutcome::Running) || (report.terminal.status == HealTaskStatus::Cancelled - && outcome.execution != HealExecutionOutcome::Aborted(HealAbortReason::Cancelled))) + && outcome.execution != HealExecutionOutcome::Aborted(HealAbortReason::Cancelled)) + || (report.terminal.status == HealTaskStatus::Timeout + && outcome.execution != HealExecutionOutcome::Aborted(HealAbortReason::Deadline))) { return Err(Error::Other(format!("Non-terminal or mismatched heal outcome for {task_id}"))); } @@ -201,4 +203,39 @@ mod tests { .contains("size limit") ); } + + #[test] + fn root_report_decoding_validates_timeout_outcome_alignment() { + let task_id = Uuid::new_v4().to_string(); + let mut completed = RootHealTerminal::cancelled(&task_id, &HealType::Cluster, HealOptions::default()) + .expect("cluster is an administrator recovery type") + .into_completed(); + completed.status = HealTaskStatus::Timeout; + let terminal = RootHealTerminal::from_completed(&task_id, &completed).expect("timeout terminal receipt"); + + let mut deadline_outcome = crate::heal::outcome::HealTaskOutcome::default(); + deadline_outcome.start(); + deadline_outcome.finish(Some(HealAbortReason::Deadline)); + completed.outcome = Some(Arc::new(deadline_outcome)); + let valid_bytes = RootHealReport::from_completed(terminal.clone(), &completed) + .encode() + .expect("encode valid timeout report"); + let decoded = decode_report(&task_id, &valid_bytes).expect("deadline outcome must decode"); + assert_eq!(decoded.terminal().status, HealTaskStatus::Timeout); + + for bad_abort in [None, Some(HealAbortReason::Cancelled)] { + let mut mismatched_outcome = crate::heal::outcome::HealTaskOutcome::default(); + mismatched_outcome.start(); + mismatched_outcome.finish(bad_abort); + completed.outcome = Some(Arc::new(mismatched_outcome)); + let invalid_bytes = RootHealReport::from_completed(terminal.clone(), &completed) + .encode() + .expect("encode mismatched timeout report"); + let err = match decode_report(&task_id, &invalid_bytes) { + Ok(_) => panic!("timeout report with non-deadline outcome must fail closed"), + Err(err) => err, + }; + assert!(err.to_string().contains("Non-terminal or mismatched"), "{err}"); + } + } } diff --git a/crates/heal/src/heal/manager/scheduler.rs b/crates/heal/src/heal/manager/scheduler.rs index cecd499495..c41ef4ec4a 100644 --- a/crates/heal/src/heal/manager/scheduler.rs +++ b/crates/heal/src/heal/manager/scheduler.rs @@ -397,7 +397,10 @@ impl HealManager { } let terminal_completion = matches!( completed_status, - HealTaskStatus::Completed | HealTaskStatus::Cancelled | HealTaskStatus::Failed { .. } + HealTaskStatus::Completed + | HealTaskStatus::Cancelled + | HealTaskStatus::Timeout + | HealTaskStatus::Failed { .. } ); if (owns_completion || cancelled_completion) && terminal_completion diff --git a/crates/heal/src/heal/manager/tests/root_recovery.rs b/crates/heal/src/heal/manager/tests/root_recovery.rs index d4e731d6ad..e62c8b9919 100644 --- a/crates/heal/src/heal/manager/tests/root_recovery.rs +++ b/crates/heal/src/heal/manager/tests/root_recovery.rs @@ -2671,7 +2671,9 @@ async fn root_recovery_exhausted_timeout_is_not_reset_by_restart() { process_manager_queue_once(&restarted).await; tokio::time::timeout(Duration::from_secs(5), async { loop { - if matches!(restarted.get_task_status(&request.id).await, Ok(HealTaskStatus::Timeout)) { + if matches!(restarted.get_task_status(&request.id).await, Ok(HealTaskStatus::Timeout)) + && !restarted.active_heals.lock().await.contains_key(&request.id) + { break; } tokio::task::yield_now().await; @@ -2679,11 +2681,20 @@ async fn root_recovery_exhausted_timeout_is_not_reset_by_restart() { }) .await .expect("exhausted request stays timed out"); - restarted - .cancel_task(&request.id) - .await - .expect("timeout responsibility remains cancellable"); - assert!(restarted.root_recovery.pending().await.expect("retired timeout").is_empty()); + assert!( + restarted.root_recovery.pending().await.expect("retired timeout").is_empty(), + "terminal timeout must retire durable pending intent" + ); + assert_eq!( + restarted + .root_recovery + .completed(&request.id) + .await + .expect("read terminal timeout receipt") + .expect("terminal timeout receipt retained") + .status, + HealTaskStatus::Timeout + ); } #[tokio::test] @@ -2735,7 +2746,7 @@ async fn root_recovery_force_start_after_shutdown_does_not_retire_original_owner } #[tokio::test] -async fn root_recovery_terminal_timeout_updates_only_existing_journal_before_second_restart() { +async fn root_recovery_terminal_timeout_retires_pending_and_admits_followup_admin_heal() { for durable in [false, true] { let (_temp, disk) = recovery_disk().await; let manager = recovery_manager(vec![disk.clone()]); @@ -2768,20 +2779,41 @@ async fn root_recovery_terminal_timeout_updates_only_existing_journal_before_sec .await .expect("real execution exhausts a nonzero budget"); assert!(!manager.active_heals.lock().await.contains_key(&request.id)); + assert!( + manager + .root_recovery + .pending() + .await + .expect("pending retired after timeout") + .is_empty(), + "durable={durable}" + ); + + // A subsequent non-forceStart admin heal must not be rejected with AlreadyRunning (409). + let followup = root_request(); + let admission = manager + .submit_heal_request_with_receipt(followup.clone()) + .await + .expect("follow-up admin heal after timeout"); + assert_eq!(admission.result, HealAdmissionResult::Accepted, "durable={durable}"); + manager + .cancel_task(&followup.id) + .await + .expect("cancel follow-up before restart"); + + // Restart preserves the timed-out terminal receipt without re-queuing a zero-budget zombie. let restarted = recovery_manager(vec![disk]); restarted .replay_root_heals() .await .expect("second restart after terminal timeout"); - let queue = restarted.heal_queue.lock().await; + assert_eq!(restarted.get_queue_length().await, 0, "durable={durable}"); assert_eq!( - queue - .requests() - .next() - .expect("remaining timeout responsibility") - .options - .timeout, - Some(Duration::ZERO), + restarted + .get_task_status(&request.id) + .await + .expect("terminal timeout survives restart"), + HealTaskStatus::Timeout, "durable={durable}" ); } diff --git a/crates/heal/src/heal/storage.rs b/crates/heal/src/heal/storage.rs index 46474ade64..750451ce4d 100644 --- a/crates/heal/src/heal/storage.rs +++ b/crates/heal/src/heal/storage.rs @@ -30,8 +30,8 @@ use super::outcome::{HealObjectDisposition, HealObjectIdentity, HealObjectKind, use super::progress::stable_generation; pub use super::replacement_execution::ReplacementExecution; use super::storage_api::owner::{ - EcstoreHealLifecycleExpiryContext, PhysicalResourcePlan, ecstore_load_admin_data_usage_from_backend_cached, - ecstore_with_background_resource_set, + EcstoreDynamicStoreHandle, EcstoreHealLifecycleExpiryContext, PhysicalResourcePlan, + ecstore_load_admin_data_usage_from_backend_cached, ecstore_with_background_resource_set, }; use super::storage_api::storage::{ BucketInfo, BucketOperations, DiskSetSelector, EcstoreHealObjectStorageResult, HealOperations as _, ListOperations as _, @@ -982,14 +982,14 @@ async fn await_admitted_object( /// ECStore Heal storage layer implementation pub struct ECStoreHealStorage { - ecstore: Arc, + store_handle: EcstoreDynamicStoreHandle, admission: Option>, } impl ECStoreHealStorage { pub fn new(ecstore: Arc) -> Self { Self { - ecstore, + store_handle: ecstore.dynamic_handle(), admission: None, } } @@ -1001,6 +1001,12 @@ impl ECStoreHealStorage { self } + /// Resolve the live hot-reloaded `ECStore` generation for this instance + /// context without pinning retired generations in memory. + fn live_ecstore(&self) -> Arc { + self.store_handle.current() + } + async fn heal_object_admitted( &self, bucket: &str, @@ -1011,7 +1017,7 @@ impl ECStoreHealStorage { ) -> Result<(HealResultItem, Option)> { run_background_object_inner( self.admission.as_ref(), - || self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage), + || self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage), opts, task_cancel, |result: &(HealResultItem, Option)| result.1.is_none(), @@ -1038,7 +1044,7 @@ impl ECStoreHealStorage { object, version_id, opts, - self.ecstore.heal_object(bucket, object, version_id_str, opts).await, + self.live_ecstore().heal_object(bucket, object, version_id_str, opts).await, ) }), ) @@ -1094,7 +1100,7 @@ impl ECStoreHealStorage { async fn resume_disk_inventory(&self, set_disk_id: &str) -> Result> { let (pool_idx, set_idx) = crate::heal::utils::parse_set_disk_id(set_disk_id)?; - let disks = StorageAdminApi::disk_set_inventory(self.ecstore.as_ref(), DiskSetSelector::new(pool_idx, set_idx)) + let disks = StorageAdminApi::disk_set_inventory(self.live_ecstore().as_ref(), DiskSetSelector::new(pool_idx, set_idx)) .await .map_err(|e| Error::TaskExecutionFailed { message: format!("Failed to get disks for pool {pool_idx} set {set_idx}: {e}"), @@ -1157,7 +1163,7 @@ impl ECStoreHealStorage { { let bucket_incarnation_id = match expected { Some(expected) => Some(expected), - None => self.ecstore.bucket_incarnation_id(bucket).await.ok(), + None => self.live_ecstore().bucket_incarnation_id(bucket).await.ok(), }; bucket_incarnation_id .and_then(|incarnation| verified_object_receipt(bucket, object, version_id, opts, &item, incarnation)) @@ -1183,7 +1189,7 @@ impl ECStoreHealStorage { "Heal storage request started" ); - let reader = match (*self.ecstore) + let reader = match (*self.live_ecstore()) .get_object_reader(bucket, object, None, Default::default(), &Default::default()) .await { @@ -1280,7 +1286,7 @@ impl HealStorageAPI for ECStoreHealStorage { opts: &HealOpts, ) -> Result { let removed = self - .ecstore + .live_ecstore() .purge_delete_marker_with_proof(bucket, object, version_id, purge, opts) .await .map_err(Error::Storage)?; @@ -1309,7 +1315,7 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn admit_bucket_incarnation(&self, bucket: &str) -> Result { - match self.ecstore.bucket_incarnation_id_from_disk(bucket).await { + match self.live_ecstore().bucket_incarnation_id_from_disk(bucket).await { Ok(id) if !id.is_nil() => Ok(id), Ok(_) | Err(StorageError::BucketNotFound(_)) => Err(Error::StaleBucketIncarnation { bucket: bucket.to_owned(), @@ -1320,7 +1326,7 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn heal_bucket_at_incarnation(&self, bucket: &str, expected: Uuid, opts: &HealOpts) -> Result { - self.ecstore + self.live_ecstore() .heal_bucket_at_incarnation(bucket, expected, opts) .await .map_err(|error| incarnation_storage_error(bucket, expected, error)) @@ -1336,12 +1342,12 @@ impl HealStorageAPI for ECStoreHealStorage { ) -> Result { run_background_object( self.admission.as_ref(), - || self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage), + || self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage), opts, |result: &HealStorageObjectResult| result.error.is_none(), boxed_object_operation(|| async { let result = self - .ecstore + .live_ecstore() .heal_object_at_incarnation(bucket, object, version_id.unwrap_or_default(), expected, opts) .await .map_err(|error| incarnation_storage_error(bucket, expected, error))?; @@ -1364,13 +1370,13 @@ impl HealStorageAPI for ECStoreHealStorage { ) -> Result { run_background_object_inner( self.admission.as_ref(), - || self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage), + || self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage), opts, Some(task_cancel), |result: &HealStorageObjectResult| result.error.is_none(), boxed_object_operation(|| async { let result = self - .ecstore + .live_ecstore() .heal_object_at_incarnation(bucket, object, version_id.unwrap_or_default(), expected, opts) .await .map_err(|error| incarnation_storage_error(bucket, expected, error))?; @@ -1392,12 +1398,12 @@ impl HealStorageAPI for ECStoreHealStorage { ) -> Result { run_background_object( self.admission.as_ref(), - || self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage), + || self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage), opts, |result: &HealStorageObjectResult| result.error.is_none(), boxed_object_operation(|| async { let result = self - .ecstore + .live_ecstore() .heal_mrf_object_at_incarnation(bucket, object, version_id.unwrap_or_default(), expected, opts) .await .map_err(|error| incarnation_storage_error(bucket, expected, error))?; @@ -1421,7 +1427,7 @@ impl HealStorageAPI for ECStoreHealStorage { "Heal storage request started" ); - match self.ecstore.get_object_info(bucket, object, &Default::default()).await { + match self.live_ecstore().get_object_info(bucket, object, &Default::default()).await { Ok(info) => Ok(Some(info)), Err(e) => { // Map ObjectNotFound to None to align with Option return type @@ -1557,7 +1563,7 @@ impl HealStorageAPI for ECStoreHealStorage { "Heal storage admin operation started" ); - match self.ecstore.get_bucket_info(bucket, &Default::default()).await { + match self.live_ecstore().get_bucket_info(bucket, &Default::default()).await { Ok(info) => Ok(Some(info)), Err(e) => { error!( @@ -1577,7 +1583,7 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn mrf_bucket_incarnation_id(&self, bucket: &str) -> Result> { - match self.ecstore.bucket_incarnation_id(bucket).await { + match self.live_ecstore().bucket_incarnation_id(bucket).await { Ok(incarnation) => Ok(Some(incarnation)), // A missing bucket leaves the current identity unresolved. It is // not a retirement receipt for an unknown source generation. @@ -1587,14 +1593,14 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn replacement_bucket_incarnation(&self, bucket: &str) -> Result> { - self.ecstore + self.live_ecstore() .replacement_bucket_incarnation_from_disk(bucket) .await .map_err(Error::Storage) } async fn mrf_bucket_incarnation_retired(&self, bucket: &str, expected: Uuid) -> Result { - self.ecstore + self.live_ecstore() .is_bucket_incarnation_retired(bucket, expected) .await .map_err(Error::Storage) @@ -1605,7 +1611,7 @@ impl HealStorageAPI for ECStoreHealStorage { return Ok(None); } - let info = match ecstore_load_admin_data_usage_from_backend_cached(self.ecstore.clone()).await { + let info = match ecstore_load_admin_data_usage_from_backend_cached(self.live_ecstore()).await { Ok(info) if info.is_complete_bucket_usage_snapshot() => info, Ok(_) | Err(_) => return Ok(None), }; @@ -1663,7 +1669,7 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn load_heal_lifecycle_expiry_context(&self, bucket: &str) -> Result> { - match self.ecstore.load_heal_lifecycle_expiry_context(bucket).await { + match self.live_ecstore().load_heal_lifecycle_expiry_context(bucket).await { Ok(Some(context)) => Ok(Some(HealLifecycleExpiryContext::ecstore(context))), Ok(None) => Ok(None), Err(err) => { @@ -1696,7 +1702,7 @@ impl HealStorageAPI for ECStoreHealStorage { HealLifecycleExpiryContextInner::Test => return Ok(false), }; match self - .ecstore + .live_ecstore() .enqueue_heal_lifecycle_expiry(context, bucket, object, version_id, object_info) .await { @@ -1721,7 +1727,7 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn list_buckets_for_admin_heal(&self, selector: Option) -> Result> { - let listing = self.ecstore.list_buckets_for_admin_heal(selector).await?; + let listing = self.live_ecstore().list_buckets_for_admin_heal(selector).await?; if !listing.topology_complete { return Err(Error::BucketDiscoveryIncomplete); } @@ -1739,7 +1745,7 @@ impl HealStorageAPI for ECStoreHealStorage { "Heal storage admin operation started" ); - match self.ecstore.list_bucket(&Default::default()).await { + match self.live_ecstore().list_bucket(&Default::default()).await { Ok(buckets) => Ok(buckets), Err(e) => { error!( @@ -1776,7 +1782,7 @@ impl HealStorageAPI for ECStoreHealStorage { ..Default::default() }; - match self.ecstore.get_object_info(bucket, object, &opts).await { + match self.live_ecstore().get_object_info(bucket, object, &opts).await { Ok(_) => Ok(true), // Object exists Err(e) => { if matches!(e, StorageError::ObjectNotFound(_, _)) { @@ -1828,7 +1834,7 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn bucket_incarnation_id(&self, bucket: &str) -> Result> { - self.ecstore + self.live_ecstore() .bucket_incarnation_id(bucket) .await .map(Some) @@ -1866,12 +1872,12 @@ impl HealStorageAPI for ECStoreHealStorage { ) -> Result { run_background_object( self.admission.as_ref(), - || self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage), + || self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage), opts, |result: &HealStorageObjectResult| result.error.is_none(), boxed_object_operation(|| async { let result = self - .ecstore + .live_ecstore() .heal_object_with_proof(bucket, object, version_id.unwrap_or(""), opts) .await .map_err(Error::Storage)?; @@ -1890,7 +1896,7 @@ impl HealStorageAPI for ECStoreHealStorage { expected: Option, opts: &HealOpts, ) -> Result> { - self.ecstore + self.live_ecstore() .recover_delete_transactions_at_incarnation(bucket, object, expected, opts) .await .map_err(Error::Storage) @@ -1903,7 +1909,7 @@ impl HealStorageAPI for ECStoreHealStorage { expected: Option, opts: &HealOpts, ) -> Result> { - self.ecstore + self.live_ecstore() .recover_delete_prefix_at_incarnation(bucket, prefix, expected, opts) .await .map_err(Error::Storage) @@ -1923,7 +1929,7 @@ impl HealStorageAPI for ECStoreHealStorage { "Heal storage repair started" ); - match self.ecstore.heal_bucket(bucket, opts).await { + match self.live_ecstore().heal_bucket(bucket, opts).await { Ok(result) => { debug!( target: "rustfs::heal::storage", @@ -1967,7 +1973,7 @@ impl HealStorageAPI for ECStoreHealStorage { "Heal storage repair started" ); - match self.ecstore.heal_format(dry_run).await { + match self.live_ecstore().heal_format(dry_run).await { Ok((result, ecstore_error)) => { let error = ecstore_error.map(Error::Storage); debug!( @@ -2006,7 +2012,7 @@ impl HealStorageAPI for ECStoreHealStorage { set_index: usize, targets: &[String], ) -> Result<(HealResultItem, Option)> { - self.ecstore + self.live_ecstore() .heal_replacement_format(dry_run, pool_index, set_index, targets) .await .map(|(result, error)| (result, error.map(Error::Storage))) @@ -2020,13 +2026,13 @@ impl HealStorageAPI for ECStoreHealStorage { let set_index = opts .set .ok_or_else(|| Error::other("replacement pool metadata placement is missing set scope"))?; - self.ecstore + self.live_ecstore() .replacement_pool_metadata_required(pool_index, set_index) .map_err(Error::Storage) } async fn heal_replacement_bucket_metadata(&self, bucket: &str, opts: &HealOpts, targets: &[String]) -> Result<()> { - self.ecstore + self.live_ecstore() .heal_replacement_bucket_metadata(bucket, opts, targets) .await .map_err(Error::Storage) @@ -2039,7 +2045,7 @@ impl HealStorageAPI for ECStoreHealStorage { opts: &HealOpts, targets: &[String], ) -> Result<()> { - self.ecstore + self.live_ecstore() .heal_replacement_bucket_metadata_at_incarnation(bucket, expected, opts, targets) .await .map_err(|error| incarnation_storage_error(bucket, expected, error)) @@ -2059,7 +2065,7 @@ impl HealStorageAPI for ECStoreHealStorage { let set_index = opts .set .ok_or_else(|| Error::other("replacement target readback is missing set scope"))?; - self.ecstore + self.live_ecstore() .replacement_targets_have_version(bucket, object, version_id.unwrap_or(""), pool_index, set_index, targets) .await .map_err(Error::Storage) @@ -2094,8 +2100,7 @@ impl HealStorageAPI for ECStoreHealStorage { // Enumerate EVERY version (not just the latest) so old versions and // delete-marker-latest objects are healed too. let list_info = match self - .ecstore - .clone() + .live_ecstore() .list_object_versions(bucket, prefix, marker, version_marker, None, MAX_KEYS) .await { @@ -2175,7 +2180,7 @@ impl HealStorageAPI for ECStoreHealStorage { } async fn heal_erasure_set_scopes(&self, opts: &HealOpts) -> Result>> { - self.ecstore + self.live_ecstore() .heal_erasure_set_scopes(opts) .await .map(Some) @@ -2216,7 +2221,7 @@ impl HealStorageAPI for ECStoreHealStorage { let forward_to = decode_disk_walk_token(continuation_token.unwrap_or("")); let (versions, next_forward, is_truncated) = self - .ecstore + .live_ecstore() .heal_walk_versions_page( pool_idx, set_idx, @@ -2499,7 +2504,7 @@ impl HealStorageAPI for ECStoreHealStorage { async fn replacement_preformat_retry_is_safe(&self, set_disk_id: &str, targets: &[String]) -> Result { let (pool_index, set_index) = crate::heal::utils::parse_set_disk_id(set_disk_id)?; - self.ecstore + self.live_ecstore() .replacement_preformat_retry_is_safe(pool_index, set_index, targets) .await .map_err(Error::Storage) diff --git a/crates/heal/src/heal/storage_api.rs b/crates/heal/src/heal/storage_api.rs index 653d9fe6f1..cc681a99f4 100644 --- a/crates/heal/src/heal/storage_api.rs +++ b/crates/heal/src/heal/storage_api.rs @@ -61,8 +61,9 @@ pub(crate) use rustfs_ecstore::api::runtime::local_disk_map_read as ecstore_loca #[cfg(test)] pub(crate) use rustfs_ecstore::api::storage::init_local_disks as ecstore_init_local_disks; pub(crate) use rustfs_ecstore::api::storage::{ - ECStore as EcstoreStore, HealLifecycleExpiryContext as EcstoreHealLifecycleExpiryContext, - HealObjectStorageResult as EcstoreHealObjectStorageResult, POOL_META_NAME as ECSTORE_POOL_META_NAME, + DynamicECStoreHandle as EcstoreDynamicStoreHandle, ECStore as EcstoreStore, + HealLifecycleExpiryContext as EcstoreHealLifecycleExpiryContext, HealObjectStorageResult as EcstoreHealObjectStorageResult, + POOL_META_NAME as ECSTORE_POOL_META_NAME, }; use rustfs_storage_api as storage_contracts; @@ -85,8 +86,9 @@ pub(crate) mod owner { ECSTORE_BUCKET_META_PREFIX, ECSTORE_DATA_USAGE_CACHE_NAME, ECSTORE_HEAL_REPLACEMENT_RECOVERY_DIR, ECSTORE_HEALING_MARKER_PATH, ECSTORE_POOL_META_NAME, ECSTORE_RUSTFS_META_BUCKET, EcstoreConditionalFileUpdate, EcstoreDeleteOptions, EcstoreDiskAPI, EcstoreDiskBytes, EcstoreDiskError, EcstoreDiskResult, EcstoreDiskStore, - EcstoreEndpoint, EcstoreErrorType, EcstoreHealLifecycleExpiryContext, EcstoreStorageError, EcstoreStore, - ecstore_is_reserved_or_invalid_bucket, ecstore_load_admin_data_usage_from_backend_cached, ecstore_local_disk_map_read, + EcstoreDynamicStoreHandle, EcstoreEndpoint, EcstoreErrorType, EcstoreHealLifecycleExpiryContext, EcstoreStorageError, + EcstoreStore, ecstore_is_reserved_or_invalid_bucket, ecstore_load_admin_data_usage_from_backend_cached, + ecstore_local_disk_map_read, }; pub(crate) use super::{EcstoreDiskOption, ecstore_new_disk}; diff --git a/crates/iam/src/store/object.rs b/crates/iam/src/store/object.rs index df002db243..df8834947b 100644 --- a/crates/iam/src/store/object.rs +++ b/crates/iam/src/store/object.rs @@ -26,6 +26,7 @@ use crate::{ manager::{extract_jwt_claims, extract_jwt_claims_allow_missing_exp, get_default_policies}, root_credentials, }; +use arc_swap::ArcSwap; use futures::future::join_all; use rustfs_io_metrics::record_system_path_failure; use rustfs_policy::{auth::UserIdentity, policy::PolicyDoc}; @@ -255,7 +256,7 @@ pub(crate) fn decrypt_iam_blob(data: &[u8]) -> Result> { #[derive(Clone)] pub struct ObjectStore { - object_api: Arc, + object_api: Arc>, } struct ObjectGroupEdit { @@ -309,7 +310,20 @@ impl ObjectStore { const BUCKET_NAME: &'static str = ".rustfs.sys"; pub fn new(object_api: Arc) -> Self { - Self { object_api } + Self { + object_api: Arc::new(ArcSwap::from(object_api)), + } + } + + #[inline] + fn api(&self) -> Arc { + self.object_api.load_full() + } + + /// Atomically rebind this IAM store to a successor `ECStore` generation + /// during a live pool topology hot-reload. + pub fn rebind_store(&self, object_api: Arc) { + self.object_api.store(object_api); } fn decrypt_data_with_source(data: &[u8]) -> Result { @@ -484,7 +498,7 @@ impl ObjectStore { ..Default::default() }); - save_iam_config_with_opts(self.object_api.clone(), path, encrypted, &opts).await + save_iam_config_with_opts(self.api(), path, encrypted, &opts).await } fn is_plaintext_json(data: &[u8]) -> bool { @@ -502,7 +516,7 @@ impl ObjectStore { mode: LoadMode, ) -> Result<(Vec, IamObjectInfo)> { let path_ref = path.as_ref(); - let (data, obj) = read_iam_config_with_metadata(self.object_api.clone(), path_ref, &mode.read_opts()).await?; + let (data, obj) = read_iam_config_with_metadata(self.api(), path_ref, &mode.read_opts()).await?; let outcome = Self::decrypt_data_with_source(&data)?; self.maybe_schedule_lazy_rewrite(path_ref, &outcome, &obj); @@ -512,7 +526,7 @@ impl ObjectStore { async fn list_iam_config_items(&self, prefix: &str, ctx: CancellationToken, sender: Sender) { // debug!("list iam config items, prefix: {}", &prefix); - let store = self.object_api.clone(); + let store = self.api(); let (tx, mut rx) = mpsc::channel::(100); @@ -686,7 +700,7 @@ impl ObjectStore { /// keeps the bootstrap snapshot load free of namespace locks (rustfs#4304). async fn load_iam_config_with(&self, path: impl AsRef + Send, mode: LoadMode) -> Result { let path_ref = path.as_ref(); - let (data, obj) = read_iam_config_with_metadata(self.object_api.clone(), path_ref, &mode.read_opts()).await?; + let (data, obj) = read_iam_config_with_metadata(self.api(), path_ref, &mode.read_opts()).await?; let outcome = match Self::decrypt_data_with_source(&data) { Ok(v) => v, @@ -708,8 +722,7 @@ impl ObjectStore { } async fn read_iam_record_with_revision(&self, path: &str) -> Result> { - let existing = - read_config_preserve_empty_with_metadata_opts(self.object_api.clone(), path, &LoadMode::Locked.read_opts()).await; + let existing = read_config_preserve_empty_with_metadata_opts(self.api(), path, &LoadMode::Locked.read_opts()).await; match existing.map_err(Error::from) { Ok((data, metadata)) => { let record = Self::decode_iam_config_strict(&data)?; @@ -769,7 +782,7 @@ impl ObjectStore { ..Default::default() }; let data = Self::prepare_data_for_storage(&serde_json::to_vec(record)?)?; - save_iam_config_with_opts(self.object_api.clone(), &path, data, &opts).await?; + save_iam_config_with_opts(self.api(), &path, data, &opts).await?; Ok(()) } @@ -963,7 +976,7 @@ impl ObjectStore { // If it doesn't exist, the system bucket or metadata is not ready. let probe_path = format!("{}/format.json", *IAM_CONFIG_PREFIX); - match read_iam_config_no_lock(self.object_api.clone(), &probe_path).await { + match read_iam_config_no_lock(self.api(), &probe_path).await { Ok(_) => Ok(()), Err(IamStorageError::ConfigNotFound) => Err(Error::other(format!( "Storage metadata not ready: probe object '{}' not found (expected IAM config to be initialized)", @@ -977,7 +990,7 @@ impl ObjectStore { #[async_trait::async_trait] impl Store for ObjectStore { async fn load_bucket_tags(&self, bucket: &str) -> Result> { - Ok(self.object_api.get_bucket_tags_for_policy(bucket).await?) + Ok(self.api().get_bucket_tags_for_policy(bucket).await?) } fn has_watcher(&self) -> bool { @@ -988,8 +1001,7 @@ impl Store for ObjectStore { } async fn load_iam_config_strict(&self, path: impl AsRef + Send) -> Result { let (data, _) = - read_config_preserve_empty_with_metadata_opts(self.object_api.clone(), path.as_ref(), &LoadMode::Locked.read_opts()) - .await?; + read_config_preserve_empty_with_metadata_opts(self.api(), path.as_ref(), &LoadMode::Locked.read_opts()).await?; Self::decode_iam_config_strict(&data) } /// Saves IAM configuration with a retry mechanism on failure. @@ -1015,7 +1027,7 @@ impl Store for ObjectStore { let path_ref = path.as_ref(); loop { - match save_iam_config(self.object_api.clone(), path_ref, data.clone()).await { + match save_iam_config(self.api(), path_ref, data.clone()).await { Ok(_) => { debug!("Successfully saved IAM config to {}", path_ref); return Ok(()); @@ -1038,7 +1050,7 @@ impl Store for ObjectStore { } } async fn delete_iam_config(&self, path: impl AsRef + Send) -> Result<()> { - delete_iam_config(self.object_api.clone(), path.as_ref()).await?; + delete_iam_config(self.api(), path.as_ref()).await?; Ok(()) } @@ -1165,18 +1177,15 @@ impl Store for ObjectStore { } let policy_path = get_mapped_policy_path(name, UserType::Svc, false); - let policy_revision = match read_config_preserve_empty_with_metadata_opts( - self.object_api.clone(), - &policy_path, - &LoadMode::Locked.read_opts(), - ) - .await - .map_err(Error::from) - { - Ok((_, metadata)) => metadata.etag.filter(|tag| !tag.is_empty() && tag != "*"), - Err(err) if is_err_config_not_found(&err) => None, - Err(err) => return Err(err), - }; + let policy_revision = + match read_config_preserve_empty_with_metadata_opts(self.api(), &policy_path, &LoadMode::Locked.read_opts()) + .await + .map_err(Error::from) + { + Ok((_, metadata)) => metadata.etag.filter(|tag| !tag.is_empty() && tag != "*"), + Err(err) if is_err_config_not_found(&err) => None, + Err(err) => return Err(err), + }; // Conditionally delete the identity before touching any mapped policy. Keep `delete_prefix` // false so ECStore evaluates `If-Match` against the current identity object revision. @@ -1189,7 +1198,7 @@ impl Store for ObjectStore { ..Default::default() }; match self - .object_api + .api() .delete_object(Self::BUCKET_NAME, &identity_path, identity_opts) .await { @@ -1209,11 +1218,7 @@ impl Store for ObjectStore { }), ..Default::default() }; - match self - .object_api - .delete_object(Self::BUCKET_NAME, &policy_path, policy_opts) - .await - { + match self.api().delete_object(Self::BUCKET_NAME, &policy_path, policy_opts).await { Ok(_) | Err( IamStorageError::PreconditionFailed | IamStorageError::FileNotFound | IamStorageError::ObjectNotFound(_, _), @@ -1284,7 +1289,7 @@ impl Store for ObjectStore { let path = get_group_info_path(name); // Take the transaction lock before any object locks. A distinct key lets ordinary // config reads, writes and deletes keep taking their own namespace locks. - let lock = self.object_api.new_ns_lock(Self::BUCKET_NAME, &format!("{path}.txn")).await?; + let lock = self.api().new_ns_lock(Self::BUCKET_NAME, &format!("{path}.txn")).await?; let guard = WriteCommitGuard::acquire(&lock, get_lock_acquire_timeout()) .await .map_err(Error::other)?; @@ -1294,7 +1299,7 @@ impl Store for ObjectStore { Err(err) => return Err(err), }; let edit = ObjectGroupEdit { - api: self.object_api.clone(), + api: self.api(), path, policy_path: get_mapped_policy_path(name, UserType::Reg, true), guard, diff --git a/crates/iam/src/sys.rs b/crates/iam/src/sys.rs index c17839f786..83a2a54065 100644 --- a/crates/iam/src/sys.rs +++ b/crates/iam/src/sys.rs @@ -585,7 +585,20 @@ impl IamSys { pub fn sync_metrics_snapshot(&self) -> IamSyncMetricsSnapshot { self.store.sync_metrics_snapshot() } +} +impl IamSys { + /// Atomically rebind the IAM storage backend to a successor `ECStore` + /// generation after a live pool topology hot-reload. + pub fn rebind_store(&self, store: Arc) { + self.store.api.rebind_store(store); + } +} + +impl IamSys +where + T: Store, +{ pub async fn set_policy_plugin_client(client: rustfs_policy::policy::opa::AuthZPlugin) { get_policy_plugin_state().store(Arc::new(PolicyPluginState::Ready(client))); } @@ -3518,8 +3531,8 @@ mod tests { ("no_proxy", Some("127.0.0.1,localhost")), ], async { - let previous = IamSys::::policy_plugin_state().await; - *get_policy_plugin_state().write().await = PolicyPluginState::Disabled; + let plugin_state = get_policy_plugin_state(); + let previous = plugin_state.swap(Arc::new(PolicyPluginState::Disabled)); let result = std::panic::AssertUnwindSafe(async { let store = StsTestMockStore::new(true); let iam = IamSys::new(IamCache::new(store).await.expect("initialize Vector IAM fixture")); @@ -3527,7 +3540,7 @@ mod tests { }) .catch_unwind() .await; - *get_policy_plugin_state().write().await = previous; + plugin_state.store(previous); if let Err(payload) = result { std::panic::resume_unwind(payload); } @@ -4106,9 +4119,9 @@ mod tests { .await, Ok(false) )); - *get_policy_plugin_state().write().await = PolicyPluginState::Failed; + get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed)); assert!(matches!(iam.is_allowed_with_resource_policy(&request, None).await, Ok(true))); - *get_policy_plugin_state().write().await = PolicyPluginState::Disabled; + get_policy_plugin_state().store(Arc::new(PolicyPluginState::Disabled)); request.is_owner = false; assert!(iam.is_allowed_with_resource_policy(&request, None).await.is_err()); @@ -4254,12 +4267,12 @@ mod tests { assert_eq!(input["input"]["identity"]["account"], credential.access_key); assert_eq!(input["input"]["identity"]["is_owner"], false); } - *get_policy_plugin_state().write().await = PolicyPluginState::Failed; + get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed)); assert!(matches!( iam.is_allowed_with_resource_policy(&request, None).await, Err(Error::IamSysNotInitialized) )); - *get_policy_plugin_state().write().await = PolicyPluginState::Disabled; + get_policy_plugin_state().store(Arc::new(PolicyPluginState::Disabled)); } }) .await; @@ -4285,7 +4298,7 @@ mod tests { )); attach(&iam, ACCOUNT, Some(policy("Allow", "s3vectors:GetVectors"))); assert!(matches!(iam.is_allowed_with_resource_policy(&request, Some(&resource)).await, Ok(true))); - *get_policy_plugin_state().write().await = PolicyPluginState::Failed; + get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed)); assert!(matches!( iam.is_allowed_with_resource_policy(&request, Some(&resource)).await, Err(Error::IAMActionNotAllowed) @@ -4410,7 +4423,7 @@ mod tests { assert_eq!(input["input"]["context"]["conditions"]["ResourceTag/project"], json!(["search"])); } for state in [PolicyPluginState::Initializing, PolicyPluginState::Failed] { - *get_policy_plugin_state().write().await = state; + get_policy_plugin_state().store(Arc::new(state)); assert!(matches!( iam.is_allowed_with_resource_policy(&request, Some(&resource)).await, Err(Error::IamSysNotInitialized) diff --git a/crates/kms/Cargo.toml b/crates/kms/Cargo.toml index 22bb4e5e16..14bb977ac2 100644 --- a/crates/kms/Cargo.toml +++ b/crates/kms/Cargo.toml @@ -75,11 +75,11 @@ rustfs-s3-types = { workspace = true } # `rustls` named explicitly: `reqwest::Identity::from_pem` (Vault mTLS) is only # available on the rustls TLS backend, and relying on another crate's feature # unification to enable it would break silently if that crate changed. -reqwest = { workspace = true, features = ["rustls"] } -vaultrs = { workspace = true } +reqwest = { workspace = true, features = ["rustls"], optional = true } +vaultrs = { workspace = true, optional = true } # vaultrs surfaces transport-level failures as wrapped rustify errors; the # operation policy needs the concrete type to classify them for retry decisions. -rustify = { workspace = true } +rustify = { workspace = true, optional = true } tokio-util = { workspace = true } # AWS KMS backend. Credentials come from the standard aws-config provider chain @@ -110,7 +110,9 @@ http = { workspace = true } tracing-subscriber = { workspace = true, features = ["fmt"] } [features] -default = [] +default = ["vault"] +vault = ["dep:reqwest", "dep:rustify", "dep:vaultrs"] +fuzzing = [] hotpath = [ "hotpath/hotpath", "hotpath/tokio", diff --git a/crates/kms/src/backends/mod.rs b/crates/kms/src/backends/mod.rs index 7100a0d735..8b811c11d4 100644 --- a/crates/kms/src/backends/mod.rs +++ b/crates/kms/src/backends/mod.rs @@ -13,6 +13,7 @@ // limitations under the License. //! KMS backend implementations +#![cfg_attr(not(feature = "vault"), allow(dead_code))] use crate::error::{KmsError, Result}; use crate::types::*; @@ -25,11 +26,14 @@ pub mod aws; #[cfg(test)] mod contract_tests; pub mod local; -#[cfg(test)] +#[cfg(all(test, feature = "vault"))] pub(crate) mod scripted_vault; pub mod static_kms; +#[cfg(feature = "vault")] pub mod vault; +#[cfg(feature = "vault")] pub(crate) mod vault_credentials; +#[cfg(feature = "vault")] pub mod vault_transit; /// Refuse a key identifier that cannot be used as a single path segment. @@ -1000,6 +1004,7 @@ mod tests { insta::assert_json_snapshot!("local_backend_capabilities", capabilities_snapshot(backend.capabilities())); } + #[cfg(feature = "vault")] #[tokio::test] async fn vault_kv2_backend_capabilities_golden() { let config = KmsConfig::vault( @@ -1015,6 +1020,7 @@ mod tests { insta::assert_json_snapshot!("vault_kv2_backend_capabilities", capabilities_snapshot(backend.capabilities())); } + #[cfg(feature = "vault")] #[tokio::test] async fn vault_transit_backend_capabilities_golden() { let config = KmsConfig::vault_transit( diff --git a/crates/kms/src/backup/mod.rs b/crates/kms/src/backup/mod.rs index 4263686e00..4a477cf5f3 100644 --- a/crates/kms/src/backup/mod.rs +++ b/crates/kms/src/backup/mod.rs @@ -58,6 +58,7 @@ mod error; pub mod local_export; pub mod local_restore; mod manifest; +#[cfg(feature = "vault")] pub mod vault_restore; pub use capability::{AtRestProtection, BackupBackendKind, BackupResponsibility}; @@ -82,6 +83,7 @@ pub use manifest::{ DigestAlgorithm, LocalKdfDescriptor, LocalKeyDerivation, ReservedSlot, VaultExternalReferences, VaultKvRecordReference, VaultTransitReference, }; +#[cfg(feature = "vault")] pub use vault_restore::{ VaultRestoreAbortReport, VaultRestoreAbortSkip, VaultRestoreAbortSkipReason, VaultRestoreClient, VaultRestoreMismatch, VaultRestoreReport, VaultRestoreRequest, VaultRestoreSequence, VaultRestoreStage, VaultRestoreTarget, abort_vault_restore, diff --git a/crates/kms/src/encryption/mod.rs b/crates/kms/src/encryption/mod.rs index 67d14ead9b..9e5c659185 100644 --- a/crates/kms/src/encryption/mod.rs +++ b/crates/kms/src/encryption/mod.rs @@ -17,7 +17,9 @@ pub mod ciphers; pub mod dek; +#[cfg(feature = "vault")] +pub use dek::desired_context_binding; pub use dek::{ - AesDekCrypto, CONTEXT_BINDING_AAD_V1, DataKeyEnvelope, DekCrypto, context_aad, desired_context_binding, - envelope_aad_write_enabled, envelope_wrap_aad, generate_key_material, is_data_key_envelope, + AesDekCrypto, CONTEXT_BINDING_AAD_V1, DataKeyEnvelope, DekCrypto, context_aad, envelope_aad_write_enabled, envelope_wrap_aad, + generate_key_material, is_data_key_envelope, }; diff --git a/crates/kms/src/error.rs b/crates/kms/src/error.rs index d3bf346dc1..07f749c6e9 100644 --- a/crates/kms/src/error.rs +++ b/crates/kms/src/error.rs @@ -407,6 +407,7 @@ impl From for KmsError { } } +#[cfg(feature = "vault")] impl From for KmsError { fn from(error: reqwest::Error) -> Self { Self::BackendError { diff --git a/crates/kms/src/lib.rs b/crates/kms/src/lib.rs index f34b219b0b..8d929a67bf 100644 --- a/crates/kms/src/lib.rs +++ b/crates/kms/src/lib.rs @@ -84,6 +84,17 @@ pub mod service_manager; mod time_serde; pub mod types; +#[cfg(feature = "fuzzing")] +pub mod fuzz_exports { + pub use crate::encryption::{ + ciphers::{AesCipher, ChaCha20Cipher, ObjectCipher}, + dek::{ + AesDekCrypto, CONTEXT_BINDING_AAD_V1, DataKeyEnvelope, DekCrypto, context_aad, desired_context_binding, + envelope_wrap_aad, is_data_key_envelope, + }, + }; +} + #[cfg(test)] pub(crate) mod test_support { use crate::persisted_observability::UNKNOWN_FIELDS_METRIC; diff --git a/crates/kms/src/policy.rs b/crates/kms/src/policy.rs index 26ee8f6152..28f3814232 100644 --- a/crates/kms/src/policy.rs +++ b/crates/kms/src/policy.rs @@ -13,6 +13,7 @@ // limitations under the License. //! Operation execution policy for external KMS backend calls. +#![cfg_attr(not(feature = "vault"), allow(dead_code))] //! //! Vault-backed operations leave the process boundary, so every call needs a //! per-attempt timeout, a total operation deadline, and classification-driven @@ -100,6 +101,7 @@ pub(crate) enum ErrorClass { /// page from an intermediate load balancer). Everything that is not throttling, /// a recoverable 5xx, or a connection-level failure is fatal; in particular /// 400/401/403/404 must never be retried. +#[cfg(feature = "vault")] pub(crate) fn classify_vaultrs(error: &vaultrs::error::ClientError) -> ErrorClass { use rustify::errors::ClientError as RestError; use vaultrs::error::ClientError; @@ -145,6 +147,7 @@ impl AttemptError { /// Classification reads the raw error before `map` consumes it, so call /// sites keep their site-specific error mapping (404 to key-not-found and /// so on) without losing the status code the retry decision needs. + #[cfg(feature = "vault")] pub(crate) fn from_vaultrs( error: vaultrs::error::ClientError, map: impl FnOnce(vaultrs::error::ClientError) -> KmsError, @@ -1811,6 +1814,7 @@ mod tests { assert_eq!(policy.max_attempts, in_range.retry_attempts); } + #[cfg(feature = "vault")] #[test] fn classify_vaultrs_matrix() { use rustify::errors::ClientError as RestError; diff --git a/crates/kms/src/service_manager.rs b/crates/kms/src/service_manager.rs index 67ab5b17c5..f315912bbf 100644 --- a/crates/kms/src/service_manager.rs +++ b/crates/kms/src/service_manager.rs @@ -15,6 +15,7 @@ //! KMS service manager for dynamic configuration and runtime management use crate::audit::KmsAuditSink; +#[cfg(feature = "vault")] use crate::backends::vault_credentials::CredentialTaskHandle; use crate::backends::{KmsBackend, local::LocalKmsBackend}; use crate::config::{BackendConfig, KmsConfig}; @@ -118,6 +119,7 @@ struct ServiceVersion { /// Owner of the backend's credential renewal task, if the backend needs /// one. Stop shuts it down explicitly; reconfigure recycles it through /// the handle's cancel-on-drop behavior when the old version is discarded. + #[cfg(feature = "vault")] credential_task: Option>, /// Background deletion worker owned by this service version, if the /// backend supports deletion scheduling @@ -444,6 +446,7 @@ impl KmsServiceManager { // Shut down the stopped version's credential renewal task before // reporting stopped, so stop deterministically recycles the background // task even while in-flight operations still hold the old service Arc. + #[cfg(feature = "vault")] if let Some(task) = state.current_service.as_ref().and_then(|sv| sv.credential_task.clone()) { task.shutdown().await; } @@ -622,6 +625,7 @@ impl KmsServiceManager { // Create backend. Vault backends may also spawn a background // credential renewal task whose owner handle lives on the service // version, so replacing the version recycles the task. + #[cfg(feature = "vault")] let mut credential_task = None; let backend = match &config.backend_config { BackendConfig::Local(_) => { @@ -630,16 +634,30 @@ impl KmsServiceManager { Arc::new(backend) as Arc } BackendConfig::VaultKv2(_) => { - info!("Creating Vault KV2 KMS backend for version {}", version); - let backend = crate::backends::vault::VaultKmsBackend::new(config.clone()).await?; - credential_task = backend.spawn_credential_renewal().map(Arc::new); - Arc::new(backend) as Arc + #[cfg(feature = "vault")] + { + info!("Creating Vault KV2 KMS backend for version {}", version); + let backend = crate::backends::vault::VaultKmsBackend::new(config.clone()).await?; + credential_task = backend.spawn_credential_renewal().map(Arc::new); + Arc::new(backend) as Arc + } + #[cfg(not(feature = "vault"))] + { + return Err(KmsError::configuration_error("Vault KV2 KMS backend disabled at compile time")); + } } BackendConfig::VaultTransit(_) => { - info!("Creating Vault Transit KMS backend for version {}", version); - let backend = crate::backends::vault_transit::VaultTransitKmsBackend::new(config.clone()).await?; - credential_task = backend.spawn_credential_renewal().map(Arc::new); - Arc::new(backend) as Arc + #[cfg(feature = "vault")] + { + info!("Creating Vault Transit KMS backend for version {}", version); + let backend = crate::backends::vault_transit::VaultTransitKmsBackend::new(config.clone()).await?; + credential_task = backend.spawn_credential_renewal().map(Arc::new); + Arc::new(backend) as Arc + } + #[cfg(not(feature = "vault"))] + { + return Err(KmsError::configuration_error("Vault Transit KMS backend disabled at compile time")); + } } BackendConfig::Static(_) => { info!("Creating Static KMS backend for version {}", version); @@ -687,6 +705,7 @@ impl KmsServiceManager { version, service: encryption_service, manager: kms_manager, + #[cfg(feature = "vault")] credential_task, deletion_worker: None, probe_worker: None, diff --git a/crates/nixl/Cargo.toml b/crates/nixl/Cargo.toml index 9edaf04ece..b1807a11b8 100644 --- a/crates/nixl/Cargo.toml +++ b/crates/nixl/Cargo.toml @@ -20,7 +20,7 @@ workspace = true # workspace build touches vendor C/C++ tooling. [target.'cfg(target_os = "linux")'.dependencies] aws-credential-types = { workspace = true, optional = true } -aws-sigv4 = { version = "1.2", optional = true } +aws-sigv4 = { version = "1.6", optional = true } base64-simd = { workspace = true, optional = true } bytes = { workspace = true, optional = true } libc = { workspace = true, optional = true } @@ -29,7 +29,7 @@ nixl-sys = { workspace = true, optional = true } parking_lot = { workspace = true, optional = true } quick-xml = { workspace = true, features = ["serialize"], optional = true } # Match the native rc transport so it can retain its alias TLS and proxy policy. -reqwest = { version = "0.12", default-features = false, optional = true } +reqwest = { version = ">=0.12, <0.13", default-features = false, optional = true } rustix = { workspace = true, features = ["fs"], optional = true } serde = { workspace = true, features = ["derive"], optional = true } thiserror = { workspace = true, optional = true } diff --git a/crates/object-capacity/src/capacity_manager.rs b/crates/object-capacity/src/capacity_manager.rs index 7881b02546..c29a1e6e50 100644 --- a/crates/object-capacity/src/capacity_manager.rs +++ b/crates/object-capacity/src/capacity_manager.rs @@ -1471,6 +1471,20 @@ pub async fn start_background_task(disks: Vec) { /// Start capacity refresh and metrics schedulers with lifecycle ownership. pub async fn start_background_tasks(disks: Vec) -> CapacityBackgroundTasks { + start_background_tasks_dynamic(move || { + let disks = disks.clone(); + async move { disks } + }) + .await +} + +/// Start capacity refresh and metrics schedulers using a dynamic local-disk +/// discovery closure so topology hot-reload additions and removals are tracked. +pub async fn start_background_tasks_dynamic(disk_provider: F) -> CapacityBackgroundTasks +where + F: Fn() -> Fut + Send + Sync + 'static, + Fut: std::future::Future> + Send + 'static, +{ let manager = get_capacity_manager(); let manager_for_refresh = manager.clone(); let manager_for_metrics = manager.clone(); @@ -1487,7 +1501,12 @@ pub async fn start_background_tasks(disks: Vec) -> CapacityBack tasks.spawn(async move { run_scheduled_refresh_loop(refresh_interval, refresh_shutdown, move || { - run_scheduled_capacity_refresh(manager_for_refresh.clone(), disks.clone()) + let manager = manager_for_refresh.clone(); + let fut = disk_provider(); + async move { + let disks = fut.await; + run_scheduled_capacity_refresh(manager, disks).await + } }) .await; }); diff --git a/crates/s3select-api/Cargo.toml b/crates/s3select-api/Cargo.toml index 4294ce374e..2662421ce6 100644 --- a/crates/s3select-api/Cargo.toml +++ b/crates/s3select-api/Cargo.toml @@ -29,7 +29,8 @@ documentation = "https://docs.rs/rustfs-s3select-api/latest/rustfs_s3select_api/ workspace = true [features] -default = [] +default = ["parquet"] +parquet = ["datafusion/parquet"] hotpath = [ "hotpath/hotpath", "hotpath/tokio", @@ -70,7 +71,7 @@ chrono = { workspace = true, features = ["serde"] } jiff = { workspace = true, features = ["serde"] } crc-fast.workspace = true rustfs-common.workspace = true -datafusion = { workspace = true, default-features = false, features = ["parquet", "recursive_protection", "sql"] } +datafusion = { workspace = true, default-features = false, features = ["recursive_protection", "sql"] } rustfs-ecstore.workspace = true rustfs-gateway-types.workspace = true rustfs-s3-types = { workspace = true } diff --git a/crates/s3select-api/src/lib.rs b/crates/s3select-api/src/lib.rs index 2a49197f74..e3f34b4336 100644 --- a/crates/s3select-api/src/lib.rs +++ b/crates/s3select-api/src/lib.rs @@ -14,10 +14,11 @@ #![recursion_limit = "256"] +#[cfg(feature = "parquet")] +use datafusion::parquet::errors::ParquetError; use datafusion::{ arrow::error::ArrowError, common::{DataFusionError, SchemaError}, - parquet::errors::ParquetError, sql::sqlparser::parser::ParserError, }; use std::{error::Error as StdError, fmt::Display}; @@ -27,6 +28,7 @@ mod csv_input; mod input_stream; mod metrics; pub mod object_store; +#[cfg(feature = "parquet")] pub mod parquet_budget; pub mod query; pub mod request; @@ -220,6 +222,7 @@ fn classify_select_error_source(err: &(dyn StdError + 'static)) -> Option Some(SelectError::InternalError), }; } + #[cfg(feature = "parquet")] if let Some(error) = err.downcast_ref::() { return match error { ParquetError::External(_) => None, @@ -281,8 +285,9 @@ fn classify_select_error_source(err: &(dyn StdError + 'static)) -> Option