mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-02 22:26:21 +00:00
Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a9e18477b1 | |||
| 5d5f96d60a | |||
| b9eed0f462 | |||
| b3d26e5e36 | |||
| 86c3f1eace | |||
| 2843fddcf8 | |||
| a6bf9b42a3 | |||
| 204a657a28 | |||
| 4160c9f44a | |||
| 6b18a8c50b | |||
| 9e11105370 | |||
| 7271e4be23 | |||
| b1b27d3dfb | |||
| ef28002b95 | |||
| 7a3fd82aa0 | |||
| bef517a1ee | |||
| c5d47e0462 | |||
| f5d6ea1623 | |||
| 5619b880b1 | |||
| 17a4feb685 | |||
| dfc05048cf | |||
| b388fae57a | |||
| 39bfa6ccf6 | |||
| 744ec5fb1d | |||
| e043b00d74 | |||
| a14bc4029b | |||
| af3b0c5bfc | |||
| 4014e284da | |||
| 8dc8b52dcc | |||
| e237b6dd54 | |||
| b8602068e7 | |||
| 13236a2cfc | |||
| 3a06e82e33 | |||
| 20c9263169 | |||
| c62ed4edfe | |||
| 3882240e11 | |||
| a3040b9252 | |||
| 009cd1bb0f | |||
| 1584b0e767 | |||
| 8f63f76af2 | |||
| b8c32fb9d1 | |||
| 4effd4b63a | |||
| f65b9be7a4 | |||
| 8c1d9ee7f1 | |||
| f1042c2413 | |||
| a2753868f5 | |||
| c0977b4862 | |||
| 321790b42d | |||
| 7bbf1e14b1 | |||
| 3a18bacc48 | |||
| 30d25b7ca3 | |||
| 6ca2376ad6 |
@@ -1,2 +1,2 @@
|
||||
sha256-linux=91e916670df110001286fe08c61564f8aff32d1a86ec579a5e9ac923322adc17
|
||||
sha256-darwin=91e916670df110001286fe08c61564f8aff32d1a86ec579a5e9ac923322adc17
|
||||
sha256-linux=8fcd4fd42b17ee0f39c8dd5ebde43fcf524620feeb33ad5f45137044f06d7390
|
||||
sha256-darwin=8fcd4fd42b17ee0f39c8dd5ebde43fcf524620feeb33ad5f45137044f06d7390
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
sha256-darwin=2760507f6c38d1b4bb19aad9c333a9630bdd007fc0622427b069e81dae71c5e9
|
||||
sha256-darwin=f828705c47195159293b4f50031f325e0f760718137b4736e7df5bed97e486c3
|
||||
sha256-linux=88dfb5119dd16fa0095f3dc3801dbd6c438526fa122f9871f87c8387bcdf7779
|
||||
|
||||
+10
-2
@@ -80,12 +80,16 @@ filter = """
|
||||
test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
|
||||
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
|
||||
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
|
||||
| test(=server::gateway_stack::object_lock_tests::object_lock_round_trips_the_default_retention)
|
||||
| test(=server::gateway_stack::snowball_tests::snowball_extract_preserves_sha256_failure_after_sniffing)
|
||||
| test(=server::gateway_stack::tests::control_plane::typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda)
|
||||
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
|
||||
| test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
|
||||
)) | (package(rustfs-iam) & (
|
||||
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
|
||||
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
|
||||
))
|
||||
)) | (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test)
|
||||
& test(=serial_tests::test_heal_delete_marker_latest_enumerated_and_healed))
|
||||
"""
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
@@ -443,12 +447,16 @@ filter = """
|
||||
test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
|
||||
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
|
||||
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
|
||||
| test(=server::gateway_stack::object_lock_tests::object_lock_round_trips_the_default_retention)
|
||||
| test(=server::gateway_stack::snowball_tests::snowball_extract_preserves_sha256_failure_after_sniffing)
|
||||
| test(=server::gateway_stack::tests::control_plane::typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda)
|
||||
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
|
||||
| test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
|
||||
)) | (package(rustfs-iam) & (
|
||||
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
|
||||
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
|
||||
))
|
||||
)) | (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test)
|
||||
& test(=serial_tests::test_heal_delete_marker_latest_enumerated_and_healed))
|
||||
"""
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
|
||||
@@ -106,7 +106,6 @@ jobs:
|
||||
targets_csv: ${{ steps.select.outputs.targets_csv }}
|
||||
has_targets: ${{ steps.select.outputs.has_targets }}
|
||||
run_mutants: ${{ steps.select.outputs.run_mutants }}
|
||||
build_matrix: ${{ steps.group-builds.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -165,19 +164,6 @@ jobs:
|
||||
--ci-mode "$CALLER_CI_MODE" \
|
||||
--output artifacts/security-input-gate/selection-manifest.json
|
||||
|
||||
- name: Group selected harness builds
|
||||
id: group-builds
|
||||
env:
|
||||
SELECTED_TARGETS: ${{ steps.select.outputs.targets_json }}
|
||||
run: |
|
||||
matrix=$(jq -cn --argjson selected "$SELECTED_TARGETS" '
|
||||
{include: [
|
||||
{profile: "core", targets_csv: ($selected | map(select(. != "fuzz_s3_select_sql")) | join(","))},
|
||||
{profile: "s3-select", targets_csv: ($selected | map(select(. == "fuzz_s3_select_sql")) | join(","))}
|
||||
] | map(select(.targets_csv != ""))}
|
||||
')
|
||||
printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload selection manifest
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
@@ -198,10 +184,7 @@ jobs:
|
||||
needs.select-targets.outputs.has_targets == 'true'
|
||||
# Self-hosted runner required: nightly libFuzzer builds exceed hosted disk budget.
|
||||
runs-on: sm-standard-4
|
||||
# Full validation builds one instrumented dependency graph per runner.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.select-targets.outputs.build_matrix) }}
|
||||
# The full target set shares one instrumented dependency build.
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
@@ -219,7 +202,7 @@ jobs:
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: nightly
|
||||
cache-shared-key: fuzz-nightly-${{ matrix.profile }}-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'schedule' }}
|
||||
|
||||
- name: Install cargo-fuzz
|
||||
@@ -236,12 +219,12 @@ jobs:
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
# Split monolithic ASan+SanCov LLVM modules across 16 codegen units so huge crates stay within 28 GB RAM.
|
||||
FUZZ_CODEGEN_UNITS: "16"
|
||||
FUZZ_TARGET: ${{ matrix.targets_csv }}
|
||||
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
|
||||
|
||||
- name: Stage prebuilt fuzz binaries
|
||||
env:
|
||||
SELECTED_TARGETS_CSV: ${{ matrix.targets_csv }}
|
||||
SELECTED_TARGETS_CSV: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
run: |
|
||||
binary_root="fuzz/prebuilt/${CARGO_BUILD_TARGET}/release"
|
||||
mkdir -p "${binary_root}"
|
||||
@@ -259,10 +242,8 @@ jobs:
|
||||
- name: Upload prebuilt fuzz binaries
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.profile }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/
|
||||
# Reuse successful group artifacts when another group is rerun.
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
compression-level: 0
|
||||
@@ -301,7 +282,7 @@ jobs:
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
|
||||
|
||||
- name: Restore executable bit
|
||||
@@ -410,7 +391,7 @@ jobs:
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
|
||||
|
||||
- name: Restore executable bit
|
||||
|
||||
Generated
+13
-14
@@ -9924,9 +9924,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.19"
|
||||
version = "0.2.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe"
|
||||
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||
|
||||
[[package]]
|
||||
name = "piper"
|
||||
@@ -12109,7 +12109,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway"
|
||||
version = "0.70.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -12156,7 +12156,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-core"
|
||||
version = "0.67.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -12177,7 +12177,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-corpus"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -12187,7 +12187,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-corpus-recorder"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http 1.6.0",
|
||||
@@ -12202,7 +12202,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-dialect-rustfs-admin"
|
||||
version = "0.15.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
@@ -12216,7 +12216,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-http"
|
||||
version = "0.1.4"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
"http 1.6.0",
|
||||
@@ -12235,7 +12235,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-macros"
|
||||
version = "0.1.4"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -12245,7 +12245,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-sig"
|
||||
version = "0.18.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
"http 1.6.0",
|
||||
@@ -12261,7 +12261,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-stream"
|
||||
version = "0.2.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytes",
|
||||
@@ -12272,7 +12272,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-types"
|
||||
version = "0.44.0+aws.2026-10-02"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"crc-fast",
|
||||
@@ -12294,7 +12294,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "rustfs-gateway-xml"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f047bff1d446b0919#ac50e9af28fd1cbb2a643e3f047bff1d446b0919"
|
||||
source = "git+https://github.com/rustfs/gateway.git?rev=7bf6c08b50a5bb04a2db5d3524be1091020308e7#7bf6c08b50a5bb04a2db5d3524be1091020308e7"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
]
|
||||
@@ -12784,7 +12784,6 @@ dependencies = [
|
||||
"rustfs-audit",
|
||||
"rustfs-common",
|
||||
"rustfs-config",
|
||||
"rustfs-data-usage",
|
||||
"rustfs-ecstore",
|
||||
"rustfs-heal-contracts",
|
||||
"rustfs-iam",
|
||||
|
||||
+7
-7
@@ -162,17 +162,17 @@ rustfs-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = fa
|
||||
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 = "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 }
|
||||
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.44.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", 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 = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.70.0", default-features = false }
|
||||
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", 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 = "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 }
|
||||
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", default-features = false }
|
||||
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.67.0", default-features = false }
|
||||
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.1.0", default-features = false }
|
||||
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "7bf6c08b50a5bb04a2db5d3524be1091020308e7", version = "0.15.0", default-features = false }
|
||||
|
||||
# Async Runtime and Networking
|
||||
async-channel = "2.5.0"
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
//! channel and await a checkpoint receipt; ordinary complete writes do not use
|
||||
//! it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::{BuildHasher, Hash};
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
@@ -225,36 +225,21 @@ impl MrfDurableRepairAnchor {
|
||||
})
|
||||
}
|
||||
|
||||
fn proof_identity(&self) -> MrfProofIdentity<'_> {
|
||||
MrfProofIdentity {
|
||||
kind: self.kind,
|
||||
bucket: &self.bucket,
|
||||
object: &self.object,
|
||||
version_id: self.version_id,
|
||||
scope: self.scope,
|
||||
delete_marker_purge: self.delete_marker_purge,
|
||||
lease: self.lease,
|
||||
bucket_incarnation_id: self.bucket_incarnation_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
|
||||
event.proof_identity() == Some(self.proof_identity())
|
||||
let Some(lease) = event.lease else {
|
||||
return false;
|
||||
};
|
||||
self.kind == event.kind
|
||||
&& self.bucket == event.bucket
|
||||
&& self.object == event.object
|
||||
&& self.version_id == event.version_id
|
||||
&& self.scope == event.scope
|
||||
&& self.delete_marker_purge == event.delete_marker_purge
|
||||
&& self.lease == lease
|
||||
&& self.bucket_incarnation_id == event.bucket_incarnation_id
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash)]
|
||||
struct MrfProofIdentity<'a> {
|
||||
kind: MrfKind,
|
||||
bucket: &'a str,
|
||||
object: &'a str,
|
||||
version_id: Option<[u8; 16]>,
|
||||
scope: Option<MrfScope>,
|
||||
delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
|
||||
lease: MrfIngressLease,
|
||||
bucket_incarnation_id: Uuid,
|
||||
}
|
||||
|
||||
/// Consume only anchors proven by a complete verified-repair identity. The
|
||||
/// caller remains responsible for persisting the resulting anchor set before
|
||||
/// deleting older replay files.
|
||||
@@ -267,81 +252,44 @@ pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnch
|
||||
before.saturating_sub(anchors.len())
|
||||
}
|
||||
|
||||
/// Consume recorded verified repairs for one bucket, retaining unmatched events.
|
||||
/// Consume recorded verified repairs for one bucket without draining
|
||||
/// unrelated or still-unmatched proofs. If the caller crashes before
|
||||
/// persisting the retained anchor set, the proof may be replayed by repair
|
||||
/// instead of silently deleting the old responsibility.
|
||||
pub fn consume_recorded_verified_mrf_repair_events_for(bucket: &str, anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
|
||||
consume_recorded_verified_mrf_repairs(anchors, Some(bucket))
|
||||
}
|
||||
|
||||
/// Match recorded receipts across all supplied anchors in one pass.
|
||||
/// Only the first exact receipt for each identity is consumed. The caller
|
||||
/// persists the successor checkpoint before cleaning up older replay files.
|
||||
pub fn consume_recorded_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
|
||||
consume_recorded_verified_mrf_repairs(anchors, None)
|
||||
}
|
||||
|
||||
fn consume_recorded_verified_mrf_repairs(anchors: &mut Vec<MrfDurableRepairAnchor>, bucket: Option<&str>) -> usize {
|
||||
let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
|
||||
return 0;
|
||||
};
|
||||
let leases: HashSet<_> = {
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
};
|
||||
if events.is_empty() {
|
||||
events.shrink_to_fit();
|
||||
return 0;
|
||||
}
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| bucket.is_none_or(|bucket| event.bucket.as_ref() == bucket))
|
||||
.filter_map(|event| event.lease)
|
||||
.collect()
|
||||
};
|
||||
let proved = {
|
||||
// The queue bounds the relevant leases. Scan the journal outside the
|
||||
// lock and hash full identities only for those leases.
|
||||
let pending = anchors
|
||||
.iter()
|
||||
.filter(|anchor| leases.contains(&anchor.lease) && bucket.is_none_or(|bucket| anchor.bucket.as_ref() == bucket))
|
||||
.map(|anchor| (anchor.proof_identity(), anchor))
|
||||
.collect();
|
||||
let matched = {
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
};
|
||||
match_recorded_verified_mrf_repairs(&mut events, &pending)
|
||||
};
|
||||
matched.into_iter().cloned().collect()
|
||||
};
|
||||
remove_proved_anchors(anchors, &proved)
|
||||
}
|
||||
|
||||
fn match_recorded_verified_mrf_repairs<'a>(
|
||||
events: &mut VecDeque<MrfVerifiedRepairEvent>,
|
||||
pending: &HashMap<MrfProofIdentity<'_>, &'a MrfDurableRepairAnchor>,
|
||||
) -> HashSet<&'a MrfDurableRepairAnchor> {
|
||||
let previous_event_count = events.len();
|
||||
let mut proved = HashSet::new();
|
||||
events.retain(|event| {
|
||||
let Some(anchor) = event.proof_identity().and_then(|identity| pending.get(&identity)) else {
|
||||
return true;
|
||||
};
|
||||
!proved.insert(*anchor)
|
||||
});
|
||||
// Release the backing buffer on an empty pass and keep all unmatched
|
||||
// notices in FIFO order.
|
||||
events.shrink_to(previous_event_count);
|
||||
proved
|
||||
}
|
||||
|
||||
fn remove_proved_anchors(anchors: &mut Vec<MrfDurableRepairAnchor>, proved: &HashSet<MrfDurableRepairAnchor>) -> usize {
|
||||
if proved.is_empty() {
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
consume_verified_mrf_repair_events_from_queue(bucket, anchors, &mut events)
|
||||
}
|
||||
|
||||
fn consume_verified_mrf_repair_events_from_queue(
|
||||
bucket: &str,
|
||||
anchors: &mut Vec<MrfDurableRepairAnchor>,
|
||||
events: &mut std::collections::VecDeque<MrfVerifiedRepairEvent>,
|
||||
) -> usize {
|
||||
let before = anchors.len();
|
||||
let leases: HashSet<_> = proved.iter().map(|anchor| anchor.lease).collect();
|
||||
anchors.retain(|anchor| !leases.contains(&anchor.lease) || !proved.contains(anchor));
|
||||
before - anchors.len()
|
||||
let previous_event_count = events.len();
|
||||
events.retain(|event| {
|
||||
if event.bucket.as_ref() != bucket {
|
||||
return true;
|
||||
}
|
||||
let mut matched = false;
|
||||
anchors.retain(|anchor| {
|
||||
let proven = anchor.is_proven_by(event);
|
||||
matched |= proven;
|
||||
!proven
|
||||
});
|
||||
!matched
|
||||
});
|
||||
// The old queue rebuild reserved the pre-consumption event count. Reuse
|
||||
// that buffer when possible without extending its capacity lifetime:
|
||||
// an emptied queue releases its backing storage on the next consumption.
|
||||
events.shrink_to(previous_event_count);
|
||||
before.saturating_sub(anchors.len())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -922,21 +870,6 @@ pub struct MrfVerifiedRepairEvent {
|
||||
pub disposition: MrfVerifiedRepairDisposition,
|
||||
}
|
||||
|
||||
impl MrfVerifiedRepairEvent {
|
||||
fn proof_identity(&self) -> Option<MrfProofIdentity<'_>> {
|
||||
Some(MrfProofIdentity {
|
||||
kind: self.kind,
|
||||
bucket: &self.bucket,
|
||||
object: &self.object,
|
||||
version_id: self.version_id,
|
||||
scope: self.scope,
|
||||
delete_marker_purge: self.delete_marker_purge,
|
||||
lease: self.lease?,
|
||||
bucket_incarnation_id: self.bucket_incarnation_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound on the repaired-event backlog. Notices are best-effort hints; when
|
||||
/// the ring is full the oldest are dropped and the affected ledger entries
|
||||
/// simply expire through their own attempts/age limits.
|
||||
@@ -1059,15 +992,6 @@ pub fn note_mrf_unverified_legacy(event: MrfUnverifiedLegacyEvent) {
|
||||
/// Take held-legacy notices for one bucket. The durable ledger still verifies
|
||||
/// the full anchor before changing the journal entry to its held state.
|
||||
pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
take_mrf_unverified_legacy_events_matching(|candidate| candidate == bucket)
|
||||
}
|
||||
|
||||
/// Take held-legacy notices for the supplied buckets in queue order.
|
||||
pub fn take_mrf_unverified_legacy_events_for_buckets(buckets: &HashSet<&str>) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
take_mrf_unverified_legacy_events_matching(|bucket| buckets.contains(bucket))
|
||||
}
|
||||
|
||||
fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> bool) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
let Some(registry) = MRF_UNVERIFIED_LEGACY_EVENTS.get() else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -1076,7 +1000,7 @@ fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> b
|
||||
};
|
||||
let mut taken = Vec::new();
|
||||
events.retain(|event| {
|
||||
if matches(&event.anchor.bucket) {
|
||||
if event.anchor.bucket.as_ref() == bucket {
|
||||
taken.push(event.clone());
|
||||
false
|
||||
} else {
|
||||
|
||||
@@ -138,70 +138,3 @@ fn event_presence_keeps_poisoned_legacy_unknown() {
|
||||
assert!(mrf_durable_repair_events_may_be_pending());
|
||||
assert!(registry.is_poisoned(), "the hint must not clear or recover poisoned state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_consumption_matches_exact_receipts_and_keeps_other_notices() {
|
||||
if isolated("batch_consumption_matches_exact_receipts_and_keeps_other_notices") {
|
||||
return;
|
||||
}
|
||||
let first = MrfDurableRepairAnchor {
|
||||
kind: MrfKind::PartialWrite,
|
||||
bucket: Arc::from("batch-first"),
|
||||
object: Arc::from("same-object"),
|
||||
version_id: None,
|
||||
scope: Some(MrfScope {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
}),
|
||||
delete_marker_purge: None,
|
||||
lease: MrfIngressLease::new(41),
|
||||
bucket_incarnation_id: Uuid::new_v4(),
|
||||
};
|
||||
let second = MrfDurableRepairAnchor {
|
||||
bucket: Arc::from("batch-second"),
|
||||
..first.clone()
|
||||
};
|
||||
let waiting = MrfDurableRepairAnchor {
|
||||
lease: MrfIngressLease::new(42),
|
||||
..first.clone()
|
||||
};
|
||||
let other = MrfDurableRepairAnchor {
|
||||
bucket: Arc::from("batch-other"),
|
||||
..first.clone()
|
||||
};
|
||||
let proof = |anchor: &MrfDurableRepairAnchor| MrfVerifiedRepairEvent {
|
||||
kind: anchor.kind,
|
||||
bucket: anchor.bucket.clone(),
|
||||
object: anchor.object.clone(),
|
||||
version_id: anchor.version_id,
|
||||
scope: anchor.scope,
|
||||
delete_marker_purge: anchor.delete_marker_purge,
|
||||
lease: Some(anchor.lease),
|
||||
bucket_incarnation_id: anchor.bucket_incarnation_id,
|
||||
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
|
||||
};
|
||||
let stale = MrfVerifiedRepairEvent {
|
||||
bucket_incarnation_id: Uuid::new_v4(),
|
||||
..proof(&waiting)
|
||||
};
|
||||
for event in [proof(&other), proof(&second), proof(&first), stale.clone(), proof(&first)] {
|
||||
note_mrf_verified_repair(event);
|
||||
}
|
||||
let legacy = |anchor: &MrfDurableRepairAnchor| MrfUnverifiedLegacyEvent { anchor: anchor.clone() };
|
||||
for anchor in [&other, &second, &first] {
|
||||
note_mrf_unverified_legacy(legacy(anchor));
|
||||
}
|
||||
|
||||
let mut anchors = vec![first.clone(), waiting.clone(), second.clone(), first.clone()];
|
||||
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
|
||||
assert_eq!(
|
||||
take_mrf_unverified_legacy_events_for_buckets(&buckets),
|
||||
vec![legacy(&second), legacy(&first)]
|
||||
);
|
||||
assert_eq!(consume_recorded_verified_mrf_repair_events(&mut anchors), 3);
|
||||
assert_eq!(anchors, vec![waiting]);
|
||||
assert_eq!(take_mrf_verified_repair_events_for(&first.bucket), vec![stale, proof(&first)]);
|
||||
assert!(take_mrf_verified_repair_events_for(&second.bucket).is_empty());
|
||||
assert_eq!(take_mrf_verified_repair_events_for(&other.bucket), vec![proof(&other)]);
|
||||
assert_eq!(take_mrf_unverified_legacy_events_for(&other.bucket), vec![legacy(&other)]);
|
||||
}
|
||||
|
||||
@@ -15,25 +15,6 @@
|
||||
use super::*;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
fn consume_verified_mrf_repair_events_from_queue(
|
||||
bucket: &str,
|
||||
anchors: &mut Vec<MrfDurableRepairAnchor>,
|
||||
events: &mut VecDeque<MrfVerifiedRepairEvent>,
|
||||
) -> usize {
|
||||
let proved = {
|
||||
let pending = anchors
|
||||
.iter()
|
||||
.filter(|anchor| anchor.bucket.as_ref() == bucket)
|
||||
.map(|anchor| (anchor.proof_identity(), anchor))
|
||||
.collect();
|
||||
match_recorded_verified_mrf_repairs(events, &pending)
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
remove_proved_anchors(anchors, &proved)
|
||||
}
|
||||
|
||||
fn proof_fixture() -> (MrfDurableRepairAnchor, MrfVerifiedRepairEvent) {
|
||||
let anchor = MrfDurableRepairAnchor {
|
||||
kind: MrfKind::PartialWrite,
|
||||
|
||||
@@ -25,14 +25,6 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
pub const S3VECTORS_MAINTENANCE_SUB_SYS: &str = "s3vectors_maintenance";
|
||||
/// Existing ordinary IAM account selected to execute Vector maintenance.
|
||||
pub const S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT: &str = "execution_account";
|
||||
/// Environment variable enabling or disabling the external S3 Vectors HTTP service.
|
||||
///
|
||||
/// Defaults to `true`. Setting `0`, `false`, `off`, or `no` makes S3 Vectors
|
||||
/// requests fail closed with `503 ServiceUnavailableException` while keeping
|
||||
/// ordinary S3 traffic unaffected.
|
||||
pub const ENV_S3VECTORS_ENABLE: &str = "RUSTFS_S3VECTORS_ENABLE";
|
||||
/// Default enablement for the external S3 Vectors HTTP service.
|
||||
pub const DEFAULT_S3VECTORS_ENABLE: bool = true;
|
||||
|
||||
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
|
||||
/// Defaults to false. Enable only after all possible writers support receipt
|
||||
|
||||
@@ -54,9 +54,6 @@ pub const DATA_USAGE_OBJECT_NAME: &str = ".usage.v2.json";
|
||||
/// [`DATA_USAGE_OBJECT_NAME`], this object is never authoritative for quota
|
||||
/// admission because namespace activity may have raced the scan.
|
||||
pub const DATA_USAGE_OBSERVED_OBJECT_NAME: &str = ".usage.observed.json";
|
||||
/// Completed bucket measurements between full namespace snapshots. Older
|
||||
/// leaders keep reading the unchanged authoritative object during rollout.
|
||||
pub const DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME: &str = ".usage.buckets.json";
|
||||
|
||||
/// Usage snapshot written by scanner implementations predating distributed
|
||||
/// leadership fencing. It is read only when neither authoritative snapshot
|
||||
@@ -637,21 +634,6 @@ pub struct DataUsageInfo {
|
||||
/// authoritative usage snapshot yet.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub usage_snapshot_bootstrap_pending: bool,
|
||||
/// Only an initial bootstrap can authorize display of first-scan progress.
|
||||
/// Recovery, reset and older markers leave this false across restarts.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub usage_snapshot_initial_bootstrap: bool,
|
||||
/// Present only on the independent completed-bucket snapshot object.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_certified_buckets: Option<CertifiedBucketsScope>,
|
||||
/// An older writer drops this opt-in, disabling initial fallback.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_initial_view_version: Option<u16>,
|
||||
/// Non-first barriers are durable before bucket-sidecar publication.
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub usage_snapshot_noninitial_buckets: HashMap<String, String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_rebuild_generation: Option<String>,
|
||||
/// Deprecated kept here for backward compatibility reasons
|
||||
pub bucket_sizes: HashMap<String, u64>,
|
||||
/// Per-disk snapshot information when available
|
||||
@@ -672,25 +654,6 @@ pub struct DataUsageSnapshotIdentity {
|
||||
pub scanner_epoch: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CertifiedBucketsScope {
|
||||
pub version: u16,
|
||||
pub baseline_initial_bootstrap: bool,
|
||||
pub baseline_bootstrap_pending: bool,
|
||||
pub movement_generation: u64,
|
||||
pub sources: Vec<CertifiedBucketsSource>,
|
||||
pub bucket_incarnations: HashMap<String, String>,
|
||||
pub baseline: DataUsageSnapshotIdentity,
|
||||
pub baseline_rebuild_generation: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CertifiedBucketsSource {
|
||||
pub pool_index: u64,
|
||||
pub set_index: u64,
|
||||
pub layout: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct DataUsageSegmentInvalidationProof {
|
||||
#[serde(default)]
|
||||
@@ -724,149 +687,6 @@ pub struct DataUsageSnapshotSetState {
|
||||
}
|
||||
|
||||
impl DataUsageInfo {
|
||||
/// Whether the canonical root can supply completed values to a persisted usage view.
|
||||
pub fn is_completed_usage_baseline(&self) -> bool {
|
||||
self.is_complete_bucket_usage_snapshot()
|
||||
&& !self.usage_snapshot_observational
|
||||
&& !self.usage_snapshot_partial
|
||||
&& self.usage_snapshot_certified_buckets.is_none()
|
||||
}
|
||||
|
||||
/// A bootstrap marker records ownership and history before a namespace baseline exists.
|
||||
/// It cannot contain measurements, observations or partial coverage.
|
||||
pub fn has_usage_bootstrap_marker_shape(&self) -> bool {
|
||||
self.usage_snapshot_bootstrap_pending
|
||||
&& self.last_update.is_some()
|
||||
&& self
|
||||
== &Self {
|
||||
last_update: self.last_update,
|
||||
scanner_epoch: self.scanner_epoch,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_rebuild_generation: self.usage_snapshot_rebuild_generation.clone(),
|
||||
usage_snapshot_initial_bootstrap: self.usage_snapshot_initial_bootstrap,
|
||||
usage_snapshot_initial_view_version: self.usage_snapshot_initial_view_version,
|
||||
usage_snapshot_noninitial_buckets: self.usage_snapshot_noninitial_buckets.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Ownership fencing alone does not refresh a completed measurement.
|
||||
pub fn certified_buckets_match_baseline(&self, baseline: &Self) -> bool {
|
||||
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
|
||||
(baseline.is_completed_usage_baseline() || baseline.has_usage_bootstrap_marker_shape())
|
||||
&& self.is_certified_buckets_snapshot()
|
||||
&& scope.baseline.last_update == baseline.last_update
|
||||
&& scope.baseline.scanner_cycle == baseline.scanner_cycle
|
||||
&& baseline.scanner_epoch >= scope.baseline.scanner_epoch
|
||||
&& scope.baseline_initial_bootstrap == baseline.usage_snapshot_initial_bootstrap
|
||||
&& scope.baseline_bootstrap_pending == baseline.usage_snapshot_bootstrap_pending
|
||||
&& scope.baseline_rebuild_generation == baseline.usage_snapshot_rebuild_generation
|
||||
}
|
||||
/// Keep earlier complete bucket values under the same persisted scope.
|
||||
pub fn retain_prior_certified_buckets(&mut self, previous: &Self) -> bool {
|
||||
let (Some(current), Some(old)) = (&self.usage_snapshot_certified_buckets, &previous.usage_snapshot_certified_buckets)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
if !previous.is_certified_buckets_snapshot()
|
||||
|| current.baseline.last_update != old.baseline.last_update
|
||||
|| current.baseline.scanner_cycle != old.baseline.scanner_cycle
|
||||
|| current.baseline.scanner_epoch < old.baseline.scanner_epoch
|
||||
|| current.baseline_rebuild_generation != old.baseline_rebuild_generation
|
||||
|| current.baseline_initial_bootstrap != old.baseline_initial_bootstrap
|
||||
|| current.baseline_bootstrap_pending != old.baseline_bootstrap_pending
|
||||
|| current.movement_generation != old.movement_generation
|
||||
|| current.sources != old.sources
|
||||
{
|
||||
return true;
|
||||
}
|
||||
for (bucket, usage) in &previous.buckets_usage {
|
||||
if usage.bucket_incarnation.as_ref() == current.bucket_incarnations.get(bucket) {
|
||||
let replace = self.buckets_usage.get(bucket).is_none_or(|current| {
|
||||
match (usage.usage_certification, current.usage_certification) {
|
||||
(Some(old), Some(next)) => {
|
||||
(old.epoch, old.cycle, old.certified_at) > (next.epoch, next.cycle, next.certified_at)
|
||||
}
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
if replace {
|
||||
self.buckets_usage.insert(bucket.clone(), usage.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
|
||||
self.checked_calculate_totals() && self.is_certified_buckets_snapshot()
|
||||
}
|
||||
|
||||
/// Validate the independent bucket snapshot without granting whole-cycle
|
||||
/// convergence, namespace completeness or dirty-usage acknowledgement.
|
||||
pub fn is_certified_buckets_snapshot(&self) -> bool {
|
||||
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
|
||||
let (Some(epoch), Some(cycle), Some(updated_at)) = (self.scanner_epoch, self.scanner_cycle, self.last_update) else {
|
||||
return false;
|
||||
};
|
||||
if scope.version != 1
|
||||
|| scope.sources.is_empty()
|
||||
|| !scope
|
||||
.sources
|
||||
.windows(2)
|
||||
.all(|pair| (pair[0].pool_index, pair[0].set_index) < (pair[1].pool_index, pair[1].set_index))
|
||||
|| scope.sources.iter().any(|source| source.layout == [0; 32])
|
||||
|| self.usage_snapshot_authoritative_baseline != Some(scope.baseline)
|
||||
|| scope.baseline.last_update.is_none()
|
||||
|| self.usage_snapshot_complete
|
||||
|| self.usage_snapshot_converged == Some(true)
|
||||
|| !self.usage_snapshot_partial
|
||||
|| self.usage_snapshot_observational
|
||||
|| self.usage_snapshot_admin_projection
|
||||
|| self.usage_snapshot_bootstrap_pending
|
||||
|| self.buckets_usage.is_empty()
|
||||
|| u64::try_from(self.buckets_usage.len()).ok() != Some(self.buckets_count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut objects = 0_u64;
|
||||
let mut bytes = 0_u64;
|
||||
let mut versions = 0_u64;
|
||||
let mut markers = 0_u64;
|
||||
for (bucket, usage) in &self.buckets_usage {
|
||||
let Some(certificate) = usage.usage_certification else { return false };
|
||||
if usage.bucket_incarnation.as_ref() != scope.bucket_incarnations.get(bucket)
|
||||
|| usage.bucket_incarnation.is_none()
|
||||
|| !matches!(
|
||||
usage.usage_value_state,
|
||||
Some(crate::BucketUsageValueState::Certified | crate::BucketUsageValueState::Carried)
|
||||
)
|
||||
|| (certificate.epoch, certificate.cycle) > (epoch, cycle)
|
||||
|| certificate.certified_at > updated_at
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let (Some(next_objects), Some(next_bytes)) =
|
||||
(objects.checked_add(usage.objects_count), bytes.checked_add(usage.size))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
objects = next_objects;
|
||||
bytes = next_bytes;
|
||||
let (Some(next_versions), Some(next_markers)) = (
|
||||
versions.checked_add(usage.versions_count),
|
||||
markers.checked_add(usage.delete_markers_count),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
versions = next_versions;
|
||||
markers = next_markers;
|
||||
}
|
||||
objects == self.objects_total_count
|
||||
&& bytes == self.objects_total_size
|
||||
&& versions == self.versions_total_count
|
||||
&& markers == self.delete_markers_total_count
|
||||
}
|
||||
|
||||
pub fn snapshot_identity(&self) -> DataUsageSnapshotIdentity {
|
||||
DataUsageSnapshotIdentity {
|
||||
last_update: self.last_update,
|
||||
@@ -2637,24 +2457,6 @@ impl DataUsageInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update all scalar totals atomically, rejecting overflow without wrapping.
|
||||
pub fn checked_calculate_totals(&mut self) -> bool {
|
||||
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
|
||||
Some([
|
||||
total[0].checked_add(usage.objects_count)?,
|
||||
total[1].checked_add(usage.size)?,
|
||||
total[2].checked_add(usage.versions_count)?,
|
||||
total[3].checked_add(usage.delete_markers_count)?,
|
||||
])
|
||||
});
|
||||
let Some([objects, size, versions, markers]) = totals else { return false };
|
||||
self.objects_total_count = objects;
|
||||
self.objects_total_size = size;
|
||||
self.versions_total_count = versions;
|
||||
self.delete_markers_total_count = markers;
|
||||
true
|
||||
}
|
||||
|
||||
/// Merge another DataUsageInfo into this one
|
||||
pub fn merge(&mut self, other: &DataUsageInfo) {
|
||||
// Merge bucket usage
|
||||
@@ -2851,117 +2653,6 @@ pub struct CompressionTotalInfo {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn complete_bucket_sidecar() -> (DataUsageInfo, DataUsageInfo) {
|
||||
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
|
||||
let baseline = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
scanner_epoch: Some(1),
|
||||
scanner_cycle: Some(2),
|
||||
usage_snapshot_complete: true,
|
||||
..Default::default()
|
||||
};
|
||||
let id = "00000000-0000-0000-0000-000000000001".to_owned();
|
||||
let mut usage = BucketUsageInfo {
|
||||
size: 71,
|
||||
objects_count: 7,
|
||||
versions_count: 8,
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
usage.certify(crate::BucketUsageCertification {
|
||||
epoch: 3,
|
||||
cycle: 4,
|
||||
certified_at: time,
|
||||
});
|
||||
let mut data = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
scanner_epoch: Some(3),
|
||||
scanner_cycle: Some(4),
|
||||
usage_snapshot_partial: true,
|
||||
buckets_count: 1,
|
||||
buckets_usage: HashMap::from([("bucket".into(), usage)]),
|
||||
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
|
||||
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
|
||||
version: 1,
|
||||
baseline: baseline.snapshot_identity(),
|
||||
baseline_initial_bootstrap: false,
|
||||
baseline_bootstrap_pending: false,
|
||||
baseline_rebuild_generation: None,
|
||||
movement_generation: 0,
|
||||
sources: vec![CertifiedBucketsSource {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
layout: [1; 32],
|
||||
}],
|
||||
bucket_incarnations: HashMap::from([("bucket".into(), id)]),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
data.calculate_totals();
|
||||
(baseline, data)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_is_not_whole_namespace_or_observational_usage() {
|
||||
let (mut baseline, data) = complete_bucket_sidecar();
|
||||
assert!(data.is_certified_buckets_snapshot());
|
||||
assert!(!data.is_complete_bucket_usage_snapshot());
|
||||
assert!(data.certified_buckets_match_baseline(&baseline));
|
||||
baseline.scanner_epoch = Some(5);
|
||||
assert!(
|
||||
data.certified_buckets_match_baseline(&baseline),
|
||||
"owner fencing must retain the original complete bucket value"
|
||||
);
|
||||
baseline.usage_snapshot_rebuild_generation = Some("reset".into());
|
||||
assert!(!data.certified_buckets_match_baseline(&baseline));
|
||||
let mut bad = data.clone();
|
||||
bad.versions_total_count += 1;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
let mut bad = data.clone();
|
||||
bad.buckets_usage.get_mut("bucket").expect("bucket").usage_certification = None;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
let mut bad = data;
|
||||
bad.usage_snapshot_observational = true;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_retains_newer_sidecar_value_over_carried_primary_value() {
|
||||
let (_, previous) = complete_bucket_sidecar();
|
||||
let mut candidate = previous.clone();
|
||||
candidate.scanner_cycle = Some(5);
|
||||
let carried = candidate.buckets_usage.get_mut("bucket").expect("carried bucket");
|
||||
carried.objects_count = 1;
|
||||
carried.usage_certification.as_mut().expect("certificate").cycle = 3;
|
||||
let id = "00000000-0000-0000-0000-000000000002".to_owned();
|
||||
let mut next = BucketUsageInfo {
|
||||
size: 20,
|
||||
objects_count: 2,
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
next.certify(crate::BucketUsageCertification {
|
||||
epoch: 3,
|
||||
cycle: 5,
|
||||
certified_at: candidate.last_update.expect("timestamp"),
|
||||
});
|
||||
candidate
|
||||
.usage_snapshot_certified_buckets
|
||||
.as_mut()
|
||||
.expect("scope")
|
||||
.bucket_incarnations
|
||||
.insert("new".into(), id);
|
||||
candidate.buckets_usage.insert("new".into(), next);
|
||||
assert!(candidate.retain_prior_certified_buckets(&previous));
|
||||
assert_eq!(candidate.buckets_usage["bucket"].objects_count, 7);
|
||||
assert_eq!(
|
||||
candidate.buckets_usage["bucket"].usage_certification,
|
||||
previous.buckets_usage["bucket"].usage_certification
|
||||
);
|
||||
assert_eq!((candidate.objects_total_count, candidate.objects_total_size), (9, 91));
|
||||
assert_eq!(candidate.buckets_usage["new"].objects_count, 2);
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct LegacyUsageReader {
|
||||
buckets_count: u64,
|
||||
|
||||
@@ -47,10 +47,6 @@ pub struct BucketScanProgressSource {
|
||||
/// Accepted logical object usage; enumeration alone leaves both absent.
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
/// Why this sample has not completed its sweep, when the writer knows.
|
||||
/// Display-only; it never authorizes reuse or quota admission.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
/// Response-only progress, deliberately separate from a bucket's total usage.
|
||||
@@ -62,15 +58,6 @@ pub struct BucketScanProgress {
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
/// True while this sample is not an authoritative complete sweep.
|
||||
#[serde(default)]
|
||||
pub partial: bool,
|
||||
/// True only when every expected source completed and agrees.
|
||||
#[serde(default)]
|
||||
pub converged: bool,
|
||||
/// The dominant incomplete stage, or `unknown` when no writer reported one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
impl BucketScanProgressSource {
|
||||
@@ -133,21 +120,6 @@ pub fn aggregate_bucket_scan_progress(
|
||||
}
|
||||
}
|
||||
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
|
||||
let blockers = selected
|
||||
.values()
|
||||
.filter_map(|sample| sample.blocker.as_deref())
|
||||
.filter(|blocker| !blocker.is_empty())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let blocker = if complete {
|
||||
None
|
||||
} else {
|
||||
match blockers.len() {
|
||||
// Samples written before the blocker field existed remain readable.
|
||||
0 => Some("unknown".to_owned()),
|
||||
1 => blockers.first().map(|blocker| (*blocker).to_owned()),
|
||||
_ => Some("multiple".to_owned()),
|
||||
}
|
||||
};
|
||||
Some(BucketScanProgress {
|
||||
stage: if complete {
|
||||
BucketScanStage::Completed
|
||||
@@ -163,9 +135,6 @@ pub fn aggregate_bucket_scan_progress(
|
||||
size,
|
||||
sources_observed: u64::try_from(selected.len()).ok()?,
|
||||
sources_total: u64::try_from(expected.len()).ok()?,
|
||||
partial: !complete,
|
||||
converged: complete,
|
||||
blocker,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -189,7 +158,6 @@ mod tests {
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(77),
|
||||
blocker: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,43 +208,6 @@ mod tests {
|
||||
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_progress_reports_blocker_and_completion_converges() {
|
||||
let mut scanning = sample(0);
|
||||
scanning.blocker = Some("object_budget".into());
|
||||
let partial = aggregate_bucket_scan_progress([scanning], &[(0, 0)]).expect("partial progress");
|
||||
assert!(partial.partial);
|
||||
assert!(!partial.converged);
|
||||
assert_eq!(partial.blocker.as_deref(), Some("object_budget"));
|
||||
|
||||
let mut one = sample(0);
|
||||
one.stage = BucketScanStage::Completed;
|
||||
one.blocker = None;
|
||||
let mut two = sample(1);
|
||||
two.stage = BucketScanStage::Completed;
|
||||
two.blocker = None;
|
||||
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed progress");
|
||||
assert!(!done.partial);
|
||||
assert!(done.converged);
|
||||
assert_eq!(done.blocker, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_progress_defaults_new_state_for_old_readers() {
|
||||
let decoded: BucketScanProgress = serde_json::from_value(serde_json::json!({
|
||||
"stage": "scanning",
|
||||
"updated_at": 1000,
|
||||
"objects": 7,
|
||||
"size": 77,
|
||||
"sources_observed": 1,
|
||||
"sources_total": 2
|
||||
}))
|
||||
.expect("legacy aggregate progress");
|
||||
assert!(!decoded.partial);
|
||||
assert!(!decoded.converged);
|
||||
assert_eq!(decoded.blocker, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
|
||||
let one = sample(0);
|
||||
|
||||
@@ -148,6 +148,14 @@ mod tests {
|
||||
.await
|
||||
.expect("HEAD should succeed after tag replacement");
|
||||
assert_eq!(replace_head.tag_count(), Some(2));
|
||||
let replaced = client
|
||||
.get_object()
|
||||
.bucket(bucket)
|
||||
.key("replace.txt")
|
||||
.send()
|
||||
.await
|
||||
.expect("GET should return the replacement tags' count");
|
||||
assert_eq!(replaced.tag_count(), Some(2));
|
||||
|
||||
client
|
||||
.copy_object()
|
||||
@@ -167,6 +175,14 @@ mod tests {
|
||||
.await
|
||||
.expect("HEAD should succeed after empty tag replacement");
|
||||
assert_eq!(empty_head.tag_count(), None);
|
||||
let empty = client
|
||||
.get_object()
|
||||
.bucket(bucket)
|
||||
.key("empty-replace.txt")
|
||||
.send()
|
||||
.await
|
||||
.expect("GET should succeed after clearing the tags");
|
||||
assert_eq!(empty.tag_count(), None);
|
||||
|
||||
client
|
||||
.copy_object()
|
||||
@@ -360,6 +376,14 @@ mod tests {
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let read = local_http_client()
|
||||
.get(format!("{}/{source_bucket}/source.txt", env.url))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(read.status(), reqwest::StatusCode::OK);
|
||||
assert!(!read.headers().contains_key("x-amz-tagging-count"));
|
||||
assert_eq!(read.bytes().await?.as_ref(), b"source");
|
||||
|
||||
let destination_policy = serde_json::json!({
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
|
||||
@@ -46,6 +46,7 @@ mod scanner_heal_topology_test;
|
||||
mod scanner_heal_topology_tier_test;
|
||||
mod scanner_peer_bucket_fixture;
|
||||
mod scanner_peer_bucket_test;
|
||||
mod scanner_remote_progress_test;
|
||||
mod site_replication_test;
|
||||
mod table_catalog_test;
|
||||
mod upgrade_test;
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
//! Follow one persisted scanner source across cycles while a different node
|
||||
//! acknowledges unrelated writes. The fixture owns all four server processes.
|
||||
|
||||
use super::harness::{DistCluster, DistLayout, TestResult};
|
||||
use crate::common::admin_request;
|
||||
use crate::storage_api::scanner_peer_bucket::{RUSTFS_META_BUCKET, calc_shard_size};
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use futures::{StreamExt, TryStreamExt, stream};
|
||||
use rustfs_data_usage::{BUCKET_SCAN_PROGRESS_MAX_BYTES, BucketScanProgressSource, BucketScanStage, bucket_scan_progress_path};
|
||||
use rustfs_filemeta::FileMeta;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use tokio::time::{Instant, sleep, timeout};
|
||||
|
||||
const LONG: &str = "long-scanner-progress";
|
||||
const OTHER: &str = "unrelated-writer";
|
||||
const OBJECTS: u64 = 96;
|
||||
const WIDTH: u64 = 32;
|
||||
|
||||
// The small source object occupies one erasure stripe in our single set.
|
||||
// Ignore an in-flight publication until all sixteen disks name the same ETag.
|
||||
// A malformed frame or a bad checksum is a fixture failure.
|
||||
fn disk_sample(cluster: &DistCluster) -> TestResult<Option<BucketScanProgressSource>> {
|
||||
let key = bucket_scan_progress_path(LONG);
|
||||
let mut revision = None;
|
||||
let mut shards = BTreeMap::new();
|
||||
for drive in cluster.cluster.nodes.iter().flat_map(|node| &node.data_dirs) {
|
||||
let object = Path::new(drive).join(RUSTFS_META_BUCKET).join(&key);
|
||||
let raw = match std::fs::read(object.join("xl.meta")) {
|
||||
Ok(raw) => raw,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
let info = FileMeta::load(&raw)?.into_fileinfo(RUSTFS_META_BUCKET, &key, "", true, false, true)?;
|
||||
info.validate_for_metadata_read()?;
|
||||
let size = usize::try_from(info.size)?;
|
||||
let ec = &info.erasure;
|
||||
if !(1..=BUCKET_SCAN_PROGRESS_MAX_BYTES).contains(&size)
|
||||
|| size > ec.block_size
|
||||
|| info.parts.len() != 1
|
||||
|| ec.data_blocks == 0
|
||||
|| ec.data_blocks.checked_add(ec.parity_blocks) != Some(16)
|
||||
|| !(1..=16).contains(&ec.index)
|
||||
{
|
||||
return Err("unexpected scanner progress stripe".into());
|
||||
}
|
||||
let identity = (
|
||||
info.get_etag()
|
||||
.filter(|etag| !etag.is_empty())
|
||||
.ok_or("missing scanner ETag")?,
|
||||
size,
|
||||
ec.data_blocks,
|
||||
);
|
||||
if revision.as_ref().is_some_and(|old| *old != identity) {
|
||||
return Ok(None);
|
||||
}
|
||||
revision = Some(identity);
|
||||
let part = &info.parts[0];
|
||||
let framed = if info.inline_data() {
|
||||
info.data.as_ref().ok_or("missing inline scanner shard")?.to_vec()
|
||||
} else {
|
||||
let path = object
|
||||
.join(info.data_dir.ok_or("missing scanner data directory")?.to_string())
|
||||
.join(format!("part.{}", part.number));
|
||||
match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
};
|
||||
let checksum = ec.get_checksum_info(part.number).algorithm;
|
||||
let header = checksum.size();
|
||||
if header == 0
|
||||
|| framed.len() != header + calc_shard_size(size, ec.data_blocks)
|
||||
|| checksum.hash_encode(&framed[header..]).as_ref() != &framed[..header]
|
||||
{
|
||||
return Err("scanner progress shard checksum or length mismatch".into());
|
||||
}
|
||||
if shards.insert(ec.index, framed[header..].to_vec()).is_some() {
|
||||
return Err("two disks reported the same scanner shard index".into());
|
||||
}
|
||||
}
|
||||
if shards.len() != 16 {
|
||||
return Err("expected sixteen distinct scanner progress shards".into());
|
||||
}
|
||||
let (_, size, data) = revision.ok_or("missing scanner progress drives")?;
|
||||
let mut bytes = Vec::with_capacity(size);
|
||||
for index in 1..=data {
|
||||
bytes.extend_from_slice(shards.get(&index).ok_or("missing scanner data shard")?);
|
||||
}
|
||||
bytes.truncate(size);
|
||||
let sample: BucketScanProgressSource = serde_json::from_slice(&bytes)?;
|
||||
if sample.version != rustfs_data_usage::BUCKET_SCAN_PROGRESS_VERSION
|
||||
|| sample.updated_at == 0
|
||||
|| sample.movement_generation.is_none()
|
||||
|| sample.bucket != LONG
|
||||
|| sample.bucket_incarnation.is_empty()
|
||||
|| sample.pool_index != 0
|
||||
|| sample.set_index != 0
|
||||
{
|
||||
return Err("unexpected persisted scanner source identity".into());
|
||||
}
|
||||
Ok(Some(sample))
|
||||
}
|
||||
|
||||
async fn coordinator(cluster: &DistCluster) -> TestResult<Option<usize>> {
|
||||
let mut nodes = Vec::new();
|
||||
for (index, node) in cluster.cluster.nodes.iter().enumerate() {
|
||||
let (status, body) = admin_request(
|
||||
&node.url,
|
||||
http::Method::GET,
|
||||
"/rustfs/admin/v3/scanner/status",
|
||||
None,
|
||||
&cluster.cluster.access_key,
|
||||
&cluster.cluster.secret_key,
|
||||
)
|
||||
.await?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("scanner status returned {status}").into());
|
||||
}
|
||||
let observed: Value = serde_json::from_str(&body)?;
|
||||
if observed["metrics"]["leader_lock_held_by_this_process"].as_bool() == Some(true) {
|
||||
nodes.push(index);
|
||||
}
|
||||
}
|
||||
Ok((nodes.len() == 1).then(|| nodes[0]))
|
||||
}
|
||||
|
||||
fn same_source(a: &BucketScanProgressSource, b: &BucketScanProgressSource) -> bool {
|
||||
a.bucket_incarnation == b.bucket_incarnation
|
||||
&& a.set_layout == b.set_layout
|
||||
&& a.pool_index == b.pool_index
|
||||
&& a.set_index == b.set_index
|
||||
&& a.scanner_epoch == b.scanner_epoch
|
||||
&& a.publication_epoch == b.publication_epoch
|
||||
&& a.movement_generation == b.movement_generation
|
||||
}
|
||||
|
||||
fn scanning_count(sample: &BucketScanProgressSource) -> Option<u64> {
|
||||
let count = sample.objects?;
|
||||
(sample.stage == BucketScanStage::Scanning && (1..OBJECTS).contains(&count) && sample.size == Some(WIDTH * count))
|
||||
.then_some(count)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn long_bucket_persists_three_cycles_during_unrelated_remote_puts() -> TestResult {
|
||||
let mut cluster = DistCluster::new_stopped_with_env(
|
||||
DistLayout::FourByFour,
|
||||
&[
|
||||
("RUSTFS_UNSAFE_BYPASS_DISK_CHECK", "true"),
|
||||
("RUSTFS_ERASURE_SET_DRIVE_COUNT", "16"),
|
||||
("RUSTFS_SCANNER_ENABLED", "false"),
|
||||
("RUST_LOG", "rustfs=info,rustfs_notify=debug,rustfs::server::http=warn"),
|
||||
("RUSTFS_SCANNER_CYCLE", "2"),
|
||||
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
|
||||
("RUSTFS_SCANNER_CYCLE_MAX_OBJECTS", "32"),
|
||||
("RUSTFS_SCANNER_BUCKET_QUANTUM_OBJECTS", "8"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
let root = PathBuf::from(&cluster.cluster.temp_dir);
|
||||
for node in 0..cluster.cluster.nodes.len() {
|
||||
let log = format!("{}/node{node}.log", cluster.cluster.temp_dir);
|
||||
cluster.cluster.set_node_capture_log_path(node, log)?;
|
||||
}
|
||||
cluster.cluster.start().await?;
|
||||
let seed = cluster.client(0)?;
|
||||
for bucket in [LONG, OTHER] {
|
||||
seed.create_bucket().bucket(bucket).send().await?;
|
||||
}
|
||||
stream::iter(0..OBJECTS)
|
||||
.map(Ok)
|
||||
.try_for_each_concurrent(6, |index| {
|
||||
let client = seed.clone();
|
||||
async move {
|
||||
client
|
||||
.put_object()
|
||||
.bucket(LONG)
|
||||
.key(format!("prefix-{index:04}/entry"))
|
||||
.body(ByteStream::from(vec![u8::try_from(index)?; usize::try_from(WIDTH)?]))
|
||||
.send()
|
||||
.await?;
|
||||
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
cluster.cluster.stop();
|
||||
cluster.cluster.set_env("RUSTFS_SCANNER_ENABLED", "true");
|
||||
cluster.cluster.start().await?;
|
||||
let leader = timeout(Duration::from_secs(120), async {
|
||||
loop {
|
||||
if let Some(leader) = coordinator(&cluster).await? {
|
||||
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(leader);
|
||||
}
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
let nodes = &cluster.cluster.nodes;
|
||||
let pids: BTreeSet<_> = nodes
|
||||
.iter()
|
||||
.filter_map(|node| node.process.as_ref().map(std::process::Child::id))
|
||||
.collect();
|
||||
if nodes.len() != 4 || pids.len() != 4 || nodes.iter().any(|node| node.data_dirs.len() != 4) {
|
||||
return Err("the native scanner fixture requires four live processes and four drives per node".into());
|
||||
}
|
||||
let ingress = (leader + 1) % cluster.cluster.nodes.len();
|
||||
let writer = cluster.client(ingress)?;
|
||||
let reader = cluster.client(leader)?;
|
||||
let mut history: Vec<(BucketScanProgressSource, u64)> = Vec::new();
|
||||
let end = Instant::now() + Duration::from_secs(420);
|
||||
let mut writes = 0_u64;
|
||||
while history.len() < 3 {
|
||||
if Instant::now() >= end {
|
||||
return Err(
|
||||
format!("fewer than three consecutive persisted cycles after {writes} unrelated PUTs: {history:?}").into(),
|
||||
);
|
||||
}
|
||||
let before = disk_sample(&cluster)?;
|
||||
writes += 1;
|
||||
writer
|
||||
.put_object()
|
||||
.bucket(OTHER)
|
||||
.key("changing")
|
||||
.body(ByteStream::from(writes.to_be_bytes().to_vec()))
|
||||
.send()
|
||||
.await?;
|
||||
let after = disk_sample(&cluster)?;
|
||||
if let (Some(a), Some(b)) = (before, after)
|
||||
&& same_source(&a, &b)
|
||||
&& a.scanner_cycle == b.scanner_cycle
|
||||
&& let (Some(first), Some(last)) = (scanning_count(&a), scanning_count(&b))
|
||||
&& first <= last
|
||||
&& history.last().is_none_or(|(prev, _)| prev.scanner_cycle != b.scanner_cycle)
|
||||
{
|
||||
if history.last().is_some_and(|(prev, _)| {
|
||||
!same_source(prev, &b)
|
||||
|| prev.scanner_cycle.checked_add(1) != Some(b.scanner_cycle)
|
||||
|| prev.objects >= Some(first)
|
||||
}) {
|
||||
history.clear();
|
||||
}
|
||||
history.push((b, writes));
|
||||
}
|
||||
sleep(Duration::from_millis(400)).await;
|
||||
}
|
||||
assert_eq!(coordinator(&cluster).await?, Some(leader));
|
||||
let body = reader
|
||||
.get_object()
|
||||
.bucket(OTHER)
|
||||
.key("changing")
|
||||
.send()
|
||||
.await?
|
||||
.body
|
||||
.collect()
|
||||
.await?
|
||||
.into_bytes();
|
||||
assert_eq!(&body[..], &writes.to_be_bytes());
|
||||
assert_eq!(
|
||||
reader.list_objects_v2().bucket(LONG).send().await?.contents().len(),
|
||||
usize::try_from(OBJECTS)?
|
||||
);
|
||||
let endpoints: Vec<_> = cluster.cluster.nodes.iter().map(|node| node.address.clone()).collect();
|
||||
let points: Vec<_> = history
|
||||
.iter()
|
||||
.map(|(s, ack)| json!({"cycle":s.scanner_cycle,"objects":s.objects,"bytes":s.size,"ack":ack}))
|
||||
.collect();
|
||||
let epoch = history[0].0.scanner_epoch;
|
||||
drop(cluster);
|
||||
assert!(!root.try_exists()?);
|
||||
for endpoint in endpoints {
|
||||
assert!(tokio::net::TcpStream::connect(endpoint).await.is_err());
|
||||
}
|
||||
println!(
|
||||
"usage_assertion: {}",
|
||||
json!({"case_id":"USAGE-02","assertion_id":"USAGE-02-A01","status":"PASS","evidence":{"coordinator_node":leader,"writer_node":ingress,"epoch":epoch,"remote_puts":writes,"persisted_progress":points,"verified_drives":16}})
|
||||
);
|
||||
println!("usage_cleanup: {}", json!({"case_id":"USAGE-02","status":"PASS","fixture_removed":true}));
|
||||
Ok(())
|
||||
}
|
||||
@@ -4444,8 +4444,7 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
|
||||
|
||||
let bucket = "extract-sse-c";
|
||||
let archive_key = "bundle.tar";
|
||||
let extracted_key = "nested/file.txt";
|
||||
let expected_body = b"extract-sse-c-body".to_vec();
|
||||
let members: [(&str, &[u8]); 2] = [("nested/file.txt", b"extract-sse-c-body"), ("second.txt", b"another member")];
|
||||
let customer_key = "01234567890123456789012345678901";
|
||||
let customer_key_b64 = base64_simd::STANDARD.encode_to_string(customer_key);
|
||||
let customer_key_md5 = sse_customer_key_md5_base64(customer_key);
|
||||
@@ -4453,7 +4452,7 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
|
||||
let client = env.create_s3_client();
|
||||
client.create_bucket().bucket(bucket).send().await?;
|
||||
|
||||
let archive = make_tar(&[(extracted_key, expected_body.as_slice())], &[]).await;
|
||||
let archive = make_tar(&members, &[]).await;
|
||||
|
||||
client
|
||||
.put_object()
|
||||
@@ -4473,28 +4472,30 @@ async fn test_signed_put_object_extract_preserves_sse_c() -> Result<(), Box<dyn
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let extracted = client
|
||||
.head_object()
|
||||
.bucket(bucket)
|
||||
.key("extract-root/nested/file.txt")
|
||||
.sse_customer_algorithm("AES256")
|
||||
.sse_customer_key(customer_key_b64.clone())
|
||||
.sse_customer_key_md5(customer_key_md5.clone())
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(extracted.sse_customer_algorithm(), Some("AES256"));
|
||||
for (key, expected) in members {
|
||||
let object = format!("extract-root/{key}");
|
||||
let extracted = client
|
||||
.head_object()
|
||||
.bucket(bucket)
|
||||
.key(&object)
|
||||
.sse_customer_algorithm("AES256")
|
||||
.sse_customer_key(customer_key_b64.clone())
|
||||
.sse_customer_key_md5(customer_key_md5.clone())
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(extracted.sse_customer_algorithm(), Some("AES256"));
|
||||
|
||||
let fetched = client
|
||||
.get_object()
|
||||
.bucket(bucket)
|
||||
.key("extract-root/nested/file.txt")
|
||||
.sse_customer_algorithm("AES256")
|
||||
.sse_customer_key(customer_key_b64)
|
||||
.sse_customer_key_md5(customer_key_md5)
|
||||
.send()
|
||||
.await?;
|
||||
let actual_body = fetched.body.collect().await?.into_bytes().to_vec();
|
||||
assert_eq!(actual_body, expected_body);
|
||||
let fetched = client
|
||||
.get_object()
|
||||
.bucket(bucket)
|
||||
.key(&object)
|
||||
.sse_customer_algorithm("AES256")
|
||||
.sse_customer_key(customer_key_b64.clone())
|
||||
.sse_customer_key_md5(customer_key_md5.clone())
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(fetched.body.collect().await?.into_bytes().as_ref(), expected);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -135,14 +135,14 @@ enum ObjectShape {
|
||||
/// Single-part object uploaded with `x-amz-checksum-sha256`; the replica
|
||||
/// must carry the same header (rustfs/backlog#2340).
|
||||
Checksummed,
|
||||
/// Single-part SSE-S3 object. Its ETag is a keyed fingerprint, not the
|
||||
/// plaintext MD5 (docs/operations/encrypted-etags.md), while the replica
|
||||
/// travels as plaintext under `x-amz-server-side-encryption: AES256`.
|
||||
/// Single-part SSE-S3 with a content MD5.
|
||||
SseS3,
|
||||
/// Single-part SSE-KMS with an opaque ETag on the source.
|
||||
SseKms,
|
||||
}
|
||||
|
||||
impl ObjectShape {
|
||||
const ALL: [ObjectShape; 9] = [
|
||||
const ALL: [ObjectShape; 10] = [
|
||||
ObjectShape::Empty,
|
||||
ObjectShape::Plain,
|
||||
ObjectShape::Retention,
|
||||
@@ -152,6 +152,7 @@ impl ObjectShape {
|
||||
ObjectShape::OdmPreservedMd5Multipart,
|
||||
ObjectShape::Checksummed,
|
||||
ObjectShape::SseS3,
|
||||
ObjectShape::SseKms,
|
||||
];
|
||||
|
||||
fn key(self) -> &'static str {
|
||||
@@ -165,6 +166,7 @@ impl ObjectShape {
|
||||
ObjectShape::OdmPreservedMd5Multipart => "matrix/odm-preserved-md5.bin",
|
||||
ObjectShape::Checksummed => "matrix/checksummed.bin",
|
||||
ObjectShape::SseS3 => "matrix/sse-s3.bin",
|
||||
ObjectShape::SseKms => "matrix/sse-kms.bin",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,22 +250,24 @@ impl ObjectShape {
|
||||
.await?;
|
||||
Ok(body)
|
||||
}
|
||||
ObjectShape::SseS3 => {
|
||||
ObjectShape::SseS3 | ObjectShape::SseKms => {
|
||||
let body = payload(56 * 1024, 0x77);
|
||||
let algorithm = if self == ObjectShape::SseS3 {
|
||||
ServerSideEncryption::Aes256
|
||||
} else {
|
||||
ServerSideEncryption::AwsKms
|
||||
};
|
||||
let put = client
|
||||
.put_object()
|
||||
.bucket(bucket)
|
||||
.key(key)
|
||||
.body(ByteStream::from(body.clone()))
|
||||
.server_side_encryption(ServerSideEncryption::Aes256)
|
||||
.server_side_encryption(algorithm)
|
||||
.send()
|
||||
.await?;
|
||||
// The cell only proves something while the source ETag is
|
||||
// not the content MD5 a generic target reports back.
|
||||
let plaintext_md5 = hex_simd::encode_to_string(Md5::digest(&body), hex_simd::AsciiCase::Lower);
|
||||
if put.e_tag().map(|etag| etag.trim_matches('"')) == Some(plaintext_md5.as_str()) {
|
||||
return Err("SSE-S3 source ETag is the plaintext MD5; the cell no longer exercises encrypted ETags".into());
|
||||
}
|
||||
let source_etag = put.e_tag().ok_or("managed-SSE write returned no ETag")?.trim_matches('"');
|
||||
assert_eq!(source_etag == plaintext_md5, self == ObjectShape::SseS3, "{self:?}");
|
||||
Ok(body)
|
||||
}
|
||||
}
|
||||
@@ -311,7 +315,7 @@ async fn matrix_mint_own_version_ids_redrive_does_not_duplicate() -> TestResult
|
||||
run_redrive_does_not_duplicate(RedriveObjects::Plaintext).await
|
||||
}
|
||||
|
||||
/// The same re-drives for SSE-S3 objects against a target that also computes
|
||||
/// The same re-drives for SSE-KMS objects against a target that also computes
|
||||
/// its own ETags (AWS S3). The source ETag is a keyed fingerprint
|
||||
/// (docs/operations/encrypted-etags.md) while the replica reports the MD5 of
|
||||
/// the plaintext it received, so no exact-ETag lookup can ever find the
|
||||
@@ -319,18 +323,18 @@ async fn matrix_mint_own_version_ids_redrive_does_not_duplicate() -> TestResult
|
||||
/// without comparing ETags.
|
||||
#[tokio::test]
|
||||
async fn matrix_mint_own_version_ids_encrypted_redrive_does_not_duplicate() -> TestResult {
|
||||
run_redrive_does_not_duplicate(RedriveObjects::SseS3OnEtagComputingTarget).await
|
||||
run_redrive_does_not_duplicate(RedriveObjects::SseKmsOnEtagComputingTarget).await
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum RedriveObjects {
|
||||
Plaintext,
|
||||
SseS3OnEtagComputingTarget,
|
||||
SseKmsOnEtagComputingTarget,
|
||||
}
|
||||
|
||||
async fn run_redrive_does_not_duplicate(objects: RedriveObjects) -> TestResult {
|
||||
init_logging();
|
||||
let encrypted = objects == RedriveObjects::SseS3OnEtagComputingTarget;
|
||||
let encrypted = objects == RedriveObjects::SseKmsOnEtagComputingTarget;
|
||||
|
||||
let target = FakeS3Target::start().await?;
|
||||
let target_bucket = "matrix-mint-own-redrive-dst".to_string();
|
||||
@@ -388,7 +392,7 @@ async fn run_redrive_does_not_duplicate(objects: RedriveObjects) -> TestResult {
|
||||
.key(key)
|
||||
.body(ByteStream::from(payload(len, fill)));
|
||||
let request = if encrypted {
|
||||
request.server_side_encryption(ServerSideEncryption::Aes256)
|
||||
request.server_side_encryption(ServerSideEncryption::AwsKms)
|
||||
} else {
|
||||
request
|
||||
};
|
||||
@@ -1004,7 +1008,7 @@ async fn run_row(mode: TargetMode) -> TestResult {
|
||||
env_vars.extend_from_slice(&[("NO_PROXY", "127.0.0.1,localhost"), ("HTTP_PROXY", ""), ("HTTPS_PROXY", "")]);
|
||||
let env = OdmTestEnv::start_with(OdmEnvOptions {
|
||||
env: env_vars,
|
||||
// The SseS3 shape needs a KMS for SSE-S3.
|
||||
// Both managed-SSE shapes use the local KMS.
|
||||
local_kms: true,
|
||||
..OdmEnvOptions::default()
|
||||
})
|
||||
|
||||
@@ -56,15 +56,6 @@ async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str)
|
||||
Ok(response.error_for_status()?.json().await?)
|
||||
}
|
||||
|
||||
async fn account_bucket(env: &RustFSTestEnvironment, resource: &str) -> TestResult<serde_json::Value> {
|
||||
let account: serde_json::Value = admin(env, resource).await?;
|
||||
account["buckets"]
|
||||
.as_array()
|
||||
.and_then(|buckets| buckets.iter().find(|bucket| bucket["name"] == BUCKET))
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("accountinfo omitted visible bucket {BUCKET}").into())
|
||||
}
|
||||
|
||||
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
|
||||
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
|
||||
let mut sizes = BTreeMap::new();
|
||||
@@ -144,20 +135,6 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
// The checkpoint and its display companion commit independently. Wait for
|
||||
// both before terminating the process to exercise the actual first-scan API.
|
||||
let row = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
if row["initial_scan"] != true {
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
assert!(row.get("objects").is_none() && row.get("size").is_none(), "{row}");
|
||||
let progress = &row["scan_progress"];
|
||||
assert_eq!(progress["sources_observed"], 1);
|
||||
assert_eq!(progress["sources_total"], 1);
|
||||
assert!(progress["updated_at"].as_u64().is_some_and(|ts| ts > 0));
|
||||
assert_eq!(progress["partial"], true);
|
||||
assert_eq!(progress["converged"], false);
|
||||
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
|
||||
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
|
||||
}
|
||||
@@ -166,8 +143,6 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
|
||||
let ordinary = account_bucket(&env, "accountinfo").await?;
|
||||
assert!(ordinary.get("initial_scan").is_none(), "default account view opted into initial progress");
|
||||
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
|
||||
assert!(
|
||||
partial
|
||||
@@ -217,16 +192,6 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
let bytes = expected.values().sum::<u64>();
|
||||
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
|
||||
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
|
||||
let completed = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
assert_eq!(completed["initial_scan"], false);
|
||||
assert!(completed.get("scan_progress").is_none());
|
||||
assert_eq!(completed["objects"], count);
|
||||
assert_eq!(completed["size"], bytes);
|
||||
let snapshot: serde_json::Value = admin(&env, "datausageinfo?view=snapshot").await?;
|
||||
assert_eq!(snapshot["snapshot_view"], true);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["objects_count"], count);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["size"], bytes);
|
||||
assert!(snapshot["initial_scan_progress"].get(BUCKET).is_none());
|
||||
eprintln!(
|
||||
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
|
||||
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
|
||||
|
||||
@@ -839,8 +839,10 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
|
||||
.version_id(version)
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(read.tag_count(), Some(1));
|
||||
assert_eq!(read.body.collect().await?.into_bytes().as_ref(), b"report");
|
||||
opa.expect_bucket_tags("s3:GetObjectVersion", source, Some("finance")).await?;
|
||||
opa.expect_versioned_tag_permission(source, "report", version).await?;
|
||||
let head = client
|
||||
.head_object()
|
||||
.bucket(source)
|
||||
@@ -1070,6 +1072,7 @@ async fn test_bucket_tags_opa_contract() -> TestResult {
|
||||
.await?;
|
||||
assert_eq!(read.body.collect().await?.into_bytes().as_ref(), b"report");
|
||||
opa.expect_bucket_tags("s3:GetObjectVersion", source, Some("finance")).await?;
|
||||
opa.expect_versioned_tag_permission(source, "report", version).await?;
|
||||
|
||||
let error = client
|
||||
.get_object()
|
||||
|
||||
@@ -192,8 +192,8 @@ pub mod bucket {
|
||||
BUCKET_REPLICATION_CONFIG, BUCKET_REQUEST_PAYMENT_CONFIG, BUCKET_SSECONFIG, BUCKET_TABLE_CATALOG_META_PREFIX,
|
||||
BUCKET_TABLE_CATALOG_TABLE_BUCKETS_PREFIX, BUCKET_TABLE_CONFIG, BUCKET_TABLE_RESERVED_PREFIX, BUCKET_TAGGING_CONFIG,
|
||||
BUCKET_TARGETS_FILE, BUCKET_VECTOR_STORAGE_PREFIX, BUCKET_VERSIONING_CONFIG, BUCKET_WEBSITE_CONFIG, BucketMetadata,
|
||||
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, is_vector_pagination_session,
|
||||
load_bucket_metadata, table_catalog_path_hash, unreadable_config_refusal,
|
||||
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, load_bucket_metadata,
|
||||
table_catalog_path_hash, unreadable_config_refusal,
|
||||
};
|
||||
pub use crate::bucket::metadata::{
|
||||
BUCKET_DURABILITY_CONFIG, BUCKET_ETAG_CONFIG, BUCKET_ON_DEMAND_MIGRATION_CONFIG, MAX_SWIFT_METADATA_COUNT,
|
||||
@@ -453,9 +453,8 @@ pub mod data_usage {
|
||||
};
|
||||
#[cfg(feature = "test-util")]
|
||||
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
|
||||
pub use crate::data_usage::{AdminUsageSnapshot, load_admin_usage_snapshot};
|
||||
pub use crate::data_usage::{
|
||||
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME, PutUsageReceipt,
|
||||
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
|
||||
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
|
||||
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
|
||||
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
|
||||
|
||||
@@ -925,29 +925,24 @@ impl BucketTargetSys {
|
||||
target: &BucketTarget,
|
||||
update: bool,
|
||||
) -> Result<(), BucketTargetError> {
|
||||
let mut found = false;
|
||||
|
||||
for (idx, existing_target) in bucket_targets.iter().enumerate() {
|
||||
if existing_target.target_type.to_string() == target.target_type.to_string() {
|
||||
if existing_target.arn == target.arn {
|
||||
if !update {
|
||||
return Err(BucketTargetError::BucketRemoteAlreadyExists {
|
||||
bucket: existing_target.target_bucket.clone(),
|
||||
});
|
||||
}
|
||||
bucket_targets[idx] = target.clone();
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
if existing_target.endpoint == target.endpoint {
|
||||
return Err(BucketTargetError::BucketRemoteAlreadyExists {
|
||||
bucket: existing_target.target_bucket.clone(),
|
||||
});
|
||||
}
|
||||
let mut replace_index = None;
|
||||
for (index, existing) in bucket_targets.iter().enumerate() {
|
||||
if existing.target_type != target.target_type {
|
||||
continue;
|
||||
}
|
||||
if update && existing.arn == target.arn {
|
||||
replace_index.get_or_insert(index);
|
||||
} else if existing.arn == target.arn
|
||||
|| (existing.endpoint == target.endpoint && existing.target_bucket == target.target_bucket)
|
||||
{
|
||||
return Err(BucketTargetError::BucketRemoteAlreadyExists {
|
||||
bucket: existing.target_bucket.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if !found && !update {
|
||||
if let Some(index) = replace_index {
|
||||
bucket_targets[index] = target.clone();
|
||||
} else if !update {
|
||||
bucket_targets.push(target.clone());
|
||||
}
|
||||
|
||||
@@ -5567,6 +5562,59 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn site_and_bucket_replication_can_register_distinct_destinations_on_one_peer() {
|
||||
let site = BucketTarget {
|
||||
target_bucket: "source".into(),
|
||||
..repair_target("source", "site")
|
||||
};
|
||||
let operator = repair_target("source", "archive");
|
||||
for (first, second) in [(&site, &operator), (&operator, &site)] {
|
||||
let mut targets = vec![first.clone()];
|
||||
BucketTargetSys::upsert_target_entry(&mut targets, second, false).expect("register the other destination");
|
||||
let mut edited = second.clone();
|
||||
edited.bandwidth_limit = 4096;
|
||||
BucketTargetSys::upsert_target_entry(&mut targets, &edited, true).expect("update only the selected ARN");
|
||||
assert_eq!(targets.len(), 2);
|
||||
assert_eq!(targets[0].arn, first.arn);
|
||||
assert_eq!(targets[0].bandwidth_limit, first.bandwidth_limit);
|
||||
assert_eq!(targets[1].arn, second.arn);
|
||||
assert_eq!(targets[1].target_bucket, second.target_bucket);
|
||||
assert_eq!(targets[1].bandwidth_limit, 4096);
|
||||
let duplicate = BucketTarget {
|
||||
arn: "another-arn".into(),
|
||||
..second.clone()
|
||||
};
|
||||
assert!(matches!(
|
||||
BucketTargetSys::upsert_target_entry(&mut targets, &duplicate, false),
|
||||
Err(BucketTargetError::BucketRemoteAlreadyExists { .. })
|
||||
));
|
||||
assert!(BucketTargetSys::upsert_target_entry(&mut targets, first, false).is_err());
|
||||
assert_eq!(targets.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retargeting_to_an_existing_destination_preserves_both_entries_in_either_order() {
|
||||
let first = repair_target("source", "first");
|
||||
let old = BucketTarget {
|
||||
endpoint: "second.example.com".into(),
|
||||
..repair_target("source", "second")
|
||||
};
|
||||
let edit = BucketTarget {
|
||||
endpoint: first.endpoint.clone(),
|
||||
..old.clone()
|
||||
};
|
||||
for mut targets in [vec![first.clone(), old.clone()], vec![old, first]] {
|
||||
let before = serde_json::to_vec(&targets).unwrap();
|
||||
assert!(matches!(
|
||||
BucketTargetSys::upsert_target_entry(&mut targets, &edit, true),
|
||||
Err(BucketTargetError::BucketRemoteAlreadyExists { .. })
|
||||
));
|
||||
assert_eq!(serde_json::to_vec(&targets).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unreadable_target_set_refuses_cached_writes() {
|
||||
let sys = BucketTargetSys::default();
|
||||
|
||||
@@ -5692,25 +5692,26 @@ const _MAX_RESTORE_OBJECT_REQUEST_SIZE: i64 = 2 << 20;
|
||||
|
||||
/// Builds an exact-version lifecycle delete target with the concrete
|
||||
/// generation observed by the evaluator. The null S3 version ID is reusable,
|
||||
/// so a null data version needs a body revision that survives pool movement.
|
||||
/// so null data versions additionally require a write-unique data directory.
|
||||
pub fn lifecycle_version_delete_target(oi: &ObjectInfo) -> Option<ObjectToDelete> {
|
||||
let version_id = oi.version_id?;
|
||||
if version_id.is_nil()
|
||||
&& ((!oi.delete_marker && oi.data_dir.is_none_or(|data_dir| data_dir.is_nil()))
|
||||
|| (oi.delete_marker && oi.mod_time.is_none_or(|mod_time| mod_time == OffsetDateTime::UNIX_EPOCH)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let target = ObjectToDelete {
|
||||
object_name: oi.name.clone(),
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
};
|
||||
if !version_id.is_nil() {
|
||||
return Some(target);
|
||||
}
|
||||
let revision = if oi.delete_marker {
|
||||
oi.mod_time.filter(|time| *time != OffsetDateTime::UNIX_EPOCH)?;
|
||||
oi.data_dir
|
||||
Some(if version_id.is_nil() {
|
||||
target.with_expected_identity(oi.data_dir, oi.mod_time, oi.delete_marker)
|
||||
} else {
|
||||
oi.data_dir.filter(|id| !id.is_nil())?;
|
||||
oi.logical_body_revision()
|
||||
};
|
||||
Some(target.with_expected_identity(revision, oi.mod_time, oi.delete_marker))
|
||||
target
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn eval_action_from_lifecycle(
|
||||
|
||||
@@ -557,23 +557,6 @@ pub fn table_bucket_catalog_metadata_prefix(bucket: &str) -> String {
|
||||
/// Internal physical names are reserved even if their identity record is missing.
|
||||
pub const BUCKET_VECTOR_STORAGE_PREFIX: &str = "rustfs-v-";
|
||||
|
||||
/// Server-owned pagination sessions in physical Vector buckets carry no dataset quota charge.
|
||||
pub fn is_vector_pagination_session(bucket: &str, object: &str) -> bool {
|
||||
if !bucket.starts_with(BUCKET_VECTOR_STORAGE_PREFIX) {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = object.strip_prefix(".rustfs-table/") else {
|
||||
return false;
|
||||
};
|
||||
let Some((table, file)) = path.split_once("/query-results/") else {
|
||||
return false;
|
||||
};
|
||||
Uuid::parse_str(table).is_ok_and(|id| !id.is_nil())
|
||||
&& file
|
||||
.strip_suffix(".session")
|
||||
.is_some_and(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct BucketIdentityConfigError(&'static str);
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ use crate::storage_api_contracts::heal::HealOperations as _;
|
||||
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
|
||||
use crate::store::{ECStore, await_bucket_namespace_operation};
|
||||
use futures::future::join_all;
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
use rustfs_gateway_types::cors_tagging::{PersistedCorsConfiguration as CORSConfiguration, PersistedTagging as Tagging};
|
||||
use rustfs_gateway_types::persistence::{
|
||||
PersistedAccelerateConfiguration as AccelerateConfiguration,
|
||||
@@ -52,7 +51,7 @@ use std::{
|
||||
};
|
||||
use time::OffsetDateTime;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use tokio::time::{Instant, sleep};
|
||||
use tokio::time::sleep;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::{error, warn};
|
||||
use uuid::Uuid;
|
||||
@@ -4233,70 +4232,6 @@ impl BucketMetadataSys {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read configured quota limits for observability, in input order.
|
||||
///
|
||||
/// An unavailable or unset limit is reported as zero. Cache misses use the
|
||||
/// regular metadata lookup, including its namespace and publication fences.
|
||||
/// Returns `None` after the observation's deadline. Already admitted reads
|
||||
/// finish their metadata publication before the result is discarded.
|
||||
pub async fn quota_limits_for_metrics<'a>(
|
||||
&self,
|
||||
mut buckets: impl ExactSizeIterator<Item = &'a str> + Send,
|
||||
deadline: Option<Instant>,
|
||||
) -> Option<Vec<u64>> {
|
||||
const CACHE_BATCH_SIZE: usize = 256;
|
||||
const MAX_COLD_READS: usize = 4;
|
||||
|
||||
let expired = || deadline.is_some_and(|deadline| Instant::now() >= deadline);
|
||||
if expired() {
|
||||
return None;
|
||||
}
|
||||
let mut limits = Vec::with_capacity(buckets.len());
|
||||
let mut missing = Vec::new();
|
||||
while buckets.len() != 0 {
|
||||
// Read only the quota field under the map lock. Release it between
|
||||
// batches and before acquiring any lazy-load or namespace locks.
|
||||
let cached = self.metadata_map.read().await;
|
||||
if expired() {
|
||||
return None;
|
||||
}
|
||||
for bucket in buckets.by_ref().take(CACHE_BATCH_SIZE) {
|
||||
let limit = match cached.get(bucket) {
|
||||
Some(metadata) => metadata
|
||||
.quota_config
|
||||
.as_ref()
|
||||
.and_then(BucketQuota::get_quota_limit)
|
||||
.unwrap_or(0),
|
||||
None => {
|
||||
missing.push((limits.len(), bucket));
|
||||
0
|
||||
}
|
||||
};
|
||||
limits.push(limit);
|
||||
}
|
||||
}
|
||||
|
||||
let mut missing = missing.into_iter();
|
||||
let mut reads = FuturesUnordered::new();
|
||||
loop {
|
||||
for (index, bucket) in missing.by_ref().take_while(|_| !expired()).take(MAX_COLD_READS - reads.len()) {
|
||||
reads.push(async move {
|
||||
let limit = self
|
||||
.get_quota_config(bucket)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|(quota, _)| quota.get_quota_limit());
|
||||
(index, limit.unwrap_or(0))
|
||||
});
|
||||
}
|
||||
let Some((index, limit)) = reads.next().await else {
|
||||
break;
|
||||
};
|
||||
limits[index] = limit;
|
||||
}
|
||||
(!expired()).then_some(limits)
|
||||
}
|
||||
|
||||
async fn cached_quota_config_and_incarnation(&self, bucket: &str) -> Result<Option<CachedQuotaMetadataSnapshot>> {
|
||||
let metadata = {
|
||||
let metadata_map = self.metadata_map.read().await;
|
||||
@@ -6680,92 +6615,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn metrics_quota_batch_reads_cache_and_falls_back_to_persisted_limits() {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let cold = "metrics-quota-cold";
|
||||
store
|
||||
.make_bucket(cold, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create cold quota fixture");
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(cold)
|
||||
.await
|
||||
.expect("read cold bucket incarnation");
|
||||
store
|
||||
.update_bucket_metadata_config_for_incarnation_validated(
|
||||
cold,
|
||||
"quota.json",
|
||||
br#"{"quota":4096}"#.to_vec(),
|
||||
incarnation,
|
||||
|| Ok(()),
|
||||
)
|
||||
.await
|
||||
.expect("persist cold quota fixture");
|
||||
|
||||
let sys = BucketMetadataSys::new(store.clone());
|
||||
let warm = "metrics-quota-warm";
|
||||
let mut cached = BucketMetadata::new(warm);
|
||||
cached.quota_config = Some(BucketQuota::new(Some(2048)));
|
||||
let invalid = "metrics-quota-invalid";
|
||||
let mut malformed = BucketMetadata::new(invalid);
|
||||
malformed.quota_config_json = b"{not-json".to_vec();
|
||||
sys.metadata_map.write().await.extend([
|
||||
(warm.to_string(), Arc::new(cached)),
|
||||
(invalid.to_string(), Arc::new(malformed)),
|
||||
]);
|
||||
|
||||
let buckets = [cold, warm, invalid, warm];
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
|
||||
Some(vec![4096, 2048, 0, 2048])
|
||||
);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
|
||||
Some(vec![4096, 2048, 0, 2048])
|
||||
);
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(std::iter::repeat_n(warm, 257), None).await,
|
||||
Some(vec![2048; 257]),
|
||||
);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn expired_metrics_quota_batch_drains_admitted_reads_without_starting_more() {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
let sys = BucketMetadataSys::new(store.clone());
|
||||
let names = ["expired-q1", "expired-q2", "expired-q3", "expired-q4", "expired-q5"];
|
||||
let mut guards = Vec::new();
|
||||
for name in &names[..4] {
|
||||
guards.push(sys.lazy_load_lock(name).lock_owned().await);
|
||||
}
|
||||
|
||||
tokio::time::pause();
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
let mut batch = std::pin::pin!(sys.quota_limits_for_metrics(names.into_iter(), Some(deadline)));
|
||||
assert!(futures::poll!(&mut batch).is_pending());
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
// The deadline alone cannot cancel a read holding or awaiting a metadata lock.
|
||||
assert!(futures::poll!(&mut batch).is_pending());
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 0);
|
||||
drop(guards);
|
||||
tokio::time::resume();
|
||||
|
||||
assert_eq!(batch.await, None);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
|
||||
assert_eq!(sys.quota_limits_for_metrics([names[4]].into_iter(), Some(deadline)).await, None,);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn validated_config_update_rejects_a_different_bucket_incarnation() {
|
||||
|
||||
@@ -782,36 +782,12 @@ impl QuotaReservation {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Complete the reservation after object publication. V1 growth is
|
||||
/// already charged, so its terminal record can drain in the background.
|
||||
/// Shrinking writes settle inline so they can signal the recount promptly.
|
||||
pub(crate) async fn commit(mut self) {
|
||||
self.state = ReservationState::Committed;
|
||||
let Some(ledger) = self.ledger.as_ref() else {
|
||||
return;
|
||||
};
|
||||
crate::store::list_objects::observe_scanner_namespace_mutations(ledger.bucket(), 1);
|
||||
if let ReservationLedgerData::Single(data) = ledger
|
||||
&& data.reservation.new_size >= data.reservation.old_size
|
||||
&& let Ok(slot) = Arc::clone(&data.store.ctx.v1_quota_settlement_slots).try_acquire_owned()
|
||||
{
|
||||
let ctx = Arc::clone(&data.store.ctx);
|
||||
drop(ctx.spawn_detached_mutation(async move {
|
||||
let _slot = slot;
|
||||
self.finish_commit().await;
|
||||
if let Some(ledger) = self.ledger.take() {
|
||||
retry_settlement(&ledger, true, self.metadata_guard.as_ref()).await;
|
||||
}
|
||||
}));
|
||||
return;
|
||||
}
|
||||
self.finish_commit().await;
|
||||
}
|
||||
|
||||
async fn finish_commit(&mut self) {
|
||||
let Some(ledger) = self.ledger.as_ref() else {
|
||||
return;
|
||||
};
|
||||
match settle(ledger, true, self.metadata_guard.as_ref()).await {
|
||||
Ok(()) => self.ledger = None,
|
||||
Err(err) => log_deferred_settlement(ledger, "commit_deferred", &err),
|
||||
@@ -853,17 +829,13 @@ impl Drop for QuotaReservation {
|
||||
};
|
||||
runtime.spawn(async move {
|
||||
let _shard_operation_guard = shard_operation_guard;
|
||||
retry_settlement(&ledger, committed, metadata_guard.as_ref()).await;
|
||||
if let Err(err) = settle(&ledger, committed, metadata_guard.as_ref()).await {
|
||||
log_deferred_settlement(&ledger, "background_retry_failed", &err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn retry_settlement(ledger: &ReservationLedgerData, committed: bool, metadata_guard: Option<&Arc<NamespaceLockGuard>>) {
|
||||
if let Err(err) = settle(ledger, committed, metadata_guard).await {
|
||||
log_deferred_settlement(ledger, "background_retry_failed", &err);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn begin(
|
||||
ctx: &crate::runtime::instance::InstanceContext,
|
||||
bucket: &str,
|
||||
@@ -877,9 +849,8 @@ pub(crate) async fn begin(
|
||||
// A lockless cache PUT is only taken when the bucket has no quota, so it
|
||||
// reserves nothing and needs no metadata-transaction lock.
|
||||
let lockless_cache = opts.is_lockless_cache_write() && snapshot_admission.is_none();
|
||||
let meta_bucket = crate::bucket::utils::is_meta_bucketname(bucket);
|
||||
if lockless_cache || meta_bucket || crate::bucket::metadata::is_vector_pagination_session(bucket, object) {
|
||||
if meta_bucket && !lockless_cache {
|
||||
if lockless_cache || crate::bucket::utils::is_meta_bucketname(bucket) {
|
||||
if !lockless_cache {
|
||||
let meta_bucket_fast_path_started = rustfs_io_metrics::put_stage_timer();
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_QUOTA_BEGIN_META_BUCKET_FAST_PATH,
|
||||
@@ -1109,11 +1080,15 @@ fn quota_cache_reason(quota: Option<&crate::bucket::quota::BucketQuota>) -> &'st
|
||||
}
|
||||
|
||||
pub(crate) async fn replaced_logical_size(set_disks: &SetDisks, bucket: &str, object: &str, opts: &ObjectOptions) -> Result<u64> {
|
||||
let Some(version_id) = opts.replaced_version_id()? else {
|
||||
if opts.versioned && !opts.version_suspended && opts.version_id.is_none() {
|
||||
return Ok(0);
|
||||
};
|
||||
}
|
||||
let version_id = opts
|
||||
.version_id
|
||||
.clone()
|
||||
.or_else(|| opts.version_suspended.then(|| Uuid::nil().to_string()));
|
||||
let lookup_opts = ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
version_id,
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
@@ -3020,79 +2995,6 @@ mod tests {
|
||||
.expect("owner guard");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn v1_published_growth_settles_in_a_bounded_tracked_task() {
|
||||
let (_directories, job) = reconciliation_fixture(100).await;
|
||||
job.run().await.expect("bootstrap");
|
||||
let object = ledger_object(&job.bucket);
|
||||
let slots = &job.store.ctx.v1_quota_settlement_slots;
|
||||
let capacity = slots.available_permits();
|
||||
let mut reservation = quota_reservation(&job, 0, 1).await.expect("durable reservation");
|
||||
reservation.mark_commit_started().await.expect("durable marker");
|
||||
let Some(ReservationLedgerData::Single(data)) = reservation.ledger.as_ref() else {
|
||||
panic!("expected a v1 reservation");
|
||||
};
|
||||
let operation_id = data.operation_id;
|
||||
let operation = job
|
||||
.store
|
||||
.new_ns_lock(RUSTFS_META_BUCKET, &operation_lock_object(&object, operation_id))
|
||||
.await
|
||||
.expect("operation lock");
|
||||
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
|
||||
.await
|
||||
.expect("block settlement after the marker");
|
||||
tokio::time::timeout(Duration::from_secs(1), reservation.commit())
|
||||
.await
|
||||
.expect("publication must not wait for the blocked v1 settlement");
|
||||
assert_eq!(slots.available_permits(), capacity - 1);
|
||||
assert_eq!(job.store.ctx.detached_mutation_count(), 1);
|
||||
assert!(operation.get_write_lock_quiet(Duration::from_millis(10)).await.is_err());
|
||||
let pending = read_test_ledger(&job).await;
|
||||
assert_eq!(pending.accounted_usage, 11);
|
||||
assert!(pending.reservations[&operation_id].commit_started);
|
||||
|
||||
fail_next_quota_ledger_save_for_test();
|
||||
drop(guard);
|
||||
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
|
||||
let settled = read_test_ledger(&job).await;
|
||||
assert_eq!(settled.accounted_usage, 11);
|
||||
assert!(settled.reservations.is_empty(), "the tracked task owns the retry");
|
||||
assert_eq!(slots.available_permits(), capacity);
|
||||
|
||||
let _full = Arc::clone(slots)
|
||||
.try_acquire_many_owned(capacity.try_into().expect("slot count fits"))
|
||||
.expect("fill the background budget");
|
||||
let mut reservation = quota_reservation(&job, 0, 0).await.expect("second reservation");
|
||||
reservation.mark_commit_started().await.expect("second marker");
|
||||
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
|
||||
.await
|
||||
.expect("block the inline fallback");
|
||||
let mut fallback = Box::pin(reservation.commit());
|
||||
assert!(futures::poll!(fallback.as_mut()).is_pending());
|
||||
assert_eq!(job.store.ctx.detached_mutation_count(), 0);
|
||||
drop(guard);
|
||||
tokio::time::timeout(Duration::from_secs(10), fallback)
|
||||
.await
|
||||
.expect("inline settlement completes");
|
||||
assert!(read_test_ledger(&job).await.reservations.is_empty());
|
||||
drop(_full);
|
||||
|
||||
let mut reservation = quota_reservation(&job, 1, 0).await.expect("shrinking reservation");
|
||||
reservation.mark_commit_started().await.expect("shrinking marker");
|
||||
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
|
||||
.await
|
||||
.expect("block the shrinking settlement");
|
||||
let mut shrink = Box::pin(reservation.commit());
|
||||
assert!(futures::poll!(shrink.as_mut()).is_pending());
|
||||
assert_eq!(slots.available_permits(), capacity);
|
||||
drop(guard);
|
||||
tokio::time::timeout(Duration::from_secs(10), shrink)
|
||||
.await
|
||||
.expect("shrinking settlement completes inline");
|
||||
assert!(read_test_ledger(&job).await.reconcile_required);
|
||||
}
|
||||
|
||||
async fn queue_v1_test_admissions(
|
||||
job: &ReconcileJob,
|
||||
names: &[&str],
|
||||
@@ -3624,7 +3526,6 @@ mod tests {
|
||||
"shrink" | "grow" => {
|
||||
reservation.mark_commit_started().await.expect("commit marker");
|
||||
reservation.commit().await;
|
||||
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
|
||||
None
|
||||
}
|
||||
"reap" => {
|
||||
|
||||
@@ -32,16 +32,14 @@ use super::replication_storage_boundary::{
|
||||
pub struct ReplicationObjectBridge;
|
||||
|
||||
impl ReplicationObjectBridge {
|
||||
/// Builds a decision snapshot using the replication-request flag from the
|
||||
/// caller's authorized storage options.
|
||||
pub fn must_replicate_options(
|
||||
user_defined: &HashMap<String, String>,
|
||||
user_tags: String,
|
||||
status: ReplicationStatusType,
|
||||
op_type: ReplicationType,
|
||||
replication_request: bool,
|
||||
opts: ObjectOptions,
|
||||
) -> MustReplicateOptions {
|
||||
get_must_replicate_options(user_defined, user_tags, status, op_type, replication_request)
|
||||
get_must_replicate_options(user_defined, user_tags, status, op_type, opts)
|
||||
}
|
||||
|
||||
pub async fn must_replicate(bucket: &str, object: &str, options: MustReplicateOptions) -> ReplicateDecision {
|
||||
@@ -206,7 +204,7 @@ mod tests {
|
||||
String::new(),
|
||||
ReplicationStatusType::Empty,
|
||||
ReplicationType::Metadata,
|
||||
false,
|
||||
ObjectOptions::default(),
|
||||
);
|
||||
assert!(metadata.is_metadata_replication());
|
||||
assert!(!metadata.is_existing_object_replication());
|
||||
@@ -216,7 +214,7 @@ mod tests {
|
||||
String::new(),
|
||||
ReplicationStatusType::Empty,
|
||||
ReplicationType::ExistingObject,
|
||||
false,
|
||||
ObjectOptions::default(),
|
||||
);
|
||||
assert!(existing.is_existing_object_replication());
|
||||
assert!(!existing.is_metadata_replication());
|
||||
|
||||
@@ -25,6 +25,7 @@ use tracing::error;
|
||||
|
||||
use super::replication_config_boundary::{
|
||||
ObjectOpts, ReplicationConfigurationExt as _, ReplicationRuleExt as _, invalid_replication_config_status_field,
|
||||
site_replication_rule_deployment_id,
|
||||
};
|
||||
use super::replication_error_boundary::Result;
|
||||
use super::replication_filemeta_boundary::{
|
||||
@@ -153,7 +154,9 @@ fn validate_delete_replication_config(
|
||||
"enabled replication rule has no destination ARN",
|
||||
));
|
||||
}
|
||||
if !role.is_empty() && !destination.is_empty() {
|
||||
// The reconciler appends a rule per site while preserving the operator's role.
|
||||
// Its peer ID and destination ARN identify it independently of the operator rules.
|
||||
if !role.is_empty() && !destination.is_empty() && site_replication_rule_deployment_id(rule).is_none() {
|
||||
match role_destination {
|
||||
Some(existing) if existing != destination => {
|
||||
return Err(super::replication_error_boundary::Error::other(
|
||||
@@ -396,9 +399,9 @@ pub(crate) fn get_must_replicate_options(
|
||||
user_tags: String,
|
||||
status: ReplicationStatusType,
|
||||
op_type: ReplicationType,
|
||||
replication_request: bool,
|
||||
opts: ObjectOptions,
|
||||
) -> MustReplicateOptions {
|
||||
MustReplicateOptions::new(user_defined, user_tags, op_type, replication_request).with_replication_status(status)
|
||||
MustReplicateOptions::new(user_defined, user_tags, op_type, opts.replication_request).with_replication_status(status)
|
||||
}
|
||||
|
||||
pub(crate) async fn check_replicate_delete(
|
||||
@@ -716,7 +719,10 @@ mod tests {
|
||||
"env=prod".to_string(),
|
||||
ReplicationStatusType::Empty,
|
||||
ReplicationType::Metadata,
|
||||
true,
|
||||
ObjectOptions {
|
||||
replication_request: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert!(options.is_metadata_replication());
|
||||
@@ -752,6 +758,31 @@ mod tests {
|
||||
assert!(validate_delete_replication_config(&VersioningConfiguration::default(), Some(&config)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_snapshot_accepts_an_operator_role_alongside_a_reconciled_site_rule() {
|
||||
let mut operator = replication_rule();
|
||||
operator.destination.bucket = "arn:rustfs:replication::operator:archive".to_owned();
|
||||
let mut site = replication_rule();
|
||||
site.id = Some("site-repl-peer".to_owned());
|
||||
site.destination.bucket = "arn:rustfs:replication::peer:photos".to_owned();
|
||||
let mut metadata = BucketMetadata::new("photos");
|
||||
metadata.versioning_config = Some(VersioningConfiguration {
|
||||
status: Some("Enabled".to_owned()),
|
||||
..Default::default()
|
||||
});
|
||||
metadata.replication_config = Some(PersistedReplicationConfiguration {
|
||||
role: operator.destination.bucket.clone(),
|
||||
rules: vec![operator, site],
|
||||
});
|
||||
let snapshot = delete_request_snapshot_from_metadata(Arc::new(metadata.clone()))
|
||||
.expect("a site rule coexists with bucket replication");
|
||||
assert_eq!(snapshot.replication_config().expect("active rules").rules.len(), 2);
|
||||
|
||||
// An operator can choose any rule ID. Its prefix alone cannot establish site ownership.
|
||||
metadata.replication_config.as_mut().unwrap().rules[1].id = Some("site-repl-other".to_owned());
|
||||
assert!(delete_request_snapshot_from_metadata(Arc::new(metadata)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_snapshot_rejects_unknown_status_values() {
|
||||
let invalid_versioning = VersioningConfiguration {
|
||||
|
||||
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
|
||||
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
|
||||
};
|
||||
use super::replication_resyncer::{
|
||||
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
|
||||
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
|
||||
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
|
||||
replicate_object_with_outcome, update_resync_status_cas,
|
||||
};
|
||||
use super::replication_state::ReplicationStats;
|
||||
use super::replication_storage_boundary::{
|
||||
@@ -1329,14 +1329,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let storage = self.storage.clone();
|
||||
let stats = self.stats.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut rx = rx;
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1391,14 +1389,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let stats = self.stats.clone();
|
||||
let storage = self.storage.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut rx = rx;
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1438,7 +1434,6 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let stats = self.stats.clone();
|
||||
let storage = self.storage.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
@@ -1458,8 +1453,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let Some(operation) = operation else { break };
|
||||
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
}
|
||||
});
|
||||
self.task_handles.lock().await.push(handle);
|
||||
@@ -1941,14 +1935,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(
|
||||
operation,
|
||||
stats.clone(),
|
||||
self.storage.clone(),
|
||||
self.in_flight.clone(),
|
||||
&self.mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1966,8 +1953,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
|
||||
.await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1984,14 +1970,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(
|
||||
operation,
|
||||
stats.clone(),
|
||||
self.storage.clone(),
|
||||
self.in_flight.clone(),
|
||||
&self.mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2560,7 +2539,6 @@ async fn process_replication_operation<S: ReplicationStorage>(
|
||||
stats: Arc<ReplicationStats>,
|
||||
storage: Arc<S>,
|
||||
in_flight: Arc<ReplicationInFlight>,
|
||||
mrf_save_tx: &Sender<MrfReplicateEntry>,
|
||||
) {
|
||||
match operation {
|
||||
ReplicationOperation::Object(obj_info) => {
|
||||
@@ -2570,14 +2548,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
|
||||
}
|
||||
ReplicationOperation::Delete(del_info) => {
|
||||
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
|
||||
// The delete request already succeeded, so a source lock that is
|
||||
// still held (a bulk delete keeps its key locks until the whole
|
||||
// batch commits) must not cost the replication: journal it for
|
||||
// the next MRF replay.
|
||||
let retry_entry = del_info.to_mrf_entry();
|
||||
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
|
||||
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
|
||||
}
|
||||
replicate_delete(*del_info, storage).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4535,102 +4506,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
|
||||
async fn delete_worker_journal(
|
||||
delete: DeletedObjectReplicationInfo,
|
||||
writeback_error: EcstoreError,
|
||||
) -> Vec<MrfReplicateEntry> {
|
||||
let shared = empty_resync_shared_state();
|
||||
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
|
||||
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
|
||||
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
|
||||
|
||||
process_replication_operation(
|
||||
ReplicationOperation::Delete(Box::new(delete)),
|
||||
Arc::new(ReplicationStats::new()),
|
||||
storage,
|
||||
Arc::new(ReplicationInFlight::default()),
|
||||
&mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
|
||||
drop(mrf_save_tx);
|
||||
let mut journaled = Vec::new();
|
||||
while let Some(entry) = mrf_save_rx.recv().await {
|
||||
journaled.push(entry);
|
||||
}
|
||||
journaled
|
||||
}
|
||||
|
||||
fn purged_on_target_delete(
|
||||
arn: &str,
|
||||
version_id: Uuid,
|
||||
target_status: VersionPurgeStatusType,
|
||||
) -> DeletedObjectReplicationInfo {
|
||||
DeletedObjectReplicationInfo {
|
||||
bucket: "source".to_string(),
|
||||
delete_object: ReplicationDeletedObject {
|
||||
object_name: "purged".to_string(),
|
||||
version_id: Some(version_id),
|
||||
replication_state: Some(ReplicationState {
|
||||
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
|
||||
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
op_type: ReplicationType::Delete,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
|
||||
let arn = "arn:test";
|
||||
let version_id = Uuid::new_v4();
|
||||
// A bulk delete of the same key still holds the object lock.
|
||||
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
|
||||
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
|
||||
));
|
||||
|
||||
let journaled =
|
||||
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
|
||||
|
||||
assert_eq!(
|
||||
journaled.len(),
|
||||
1,
|
||||
"a delete whose result never reached the source must be kept for replay"
|
||||
);
|
||||
let entry = &journaled[0];
|
||||
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
|
||||
assert_eq!(entry.version_id, Some(version_id));
|
||||
assert_eq!(entry.op, MrfOpKind::Delete);
|
||||
assert_eq!(entry.target_arns, vec![arn.to_string()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
|
||||
let arn = "arn:test";
|
||||
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
|
||||
|
||||
let completed = delete_worker_journal(
|
||||
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
|
||||
source_gone(),
|
||||
)
|
||||
.await;
|
||||
assert!(completed.is_empty(), "a completed delete must not be replayed");
|
||||
|
||||
let target_pending = delete_worker_journal(
|
||||
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
|
||||
source_gone(),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
target_pending.is_empty(),
|
||||
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_preserves_persisted_admission_without_live_config() {
|
||||
let arn = "arn:test";
|
||||
|
||||
@@ -354,9 +354,8 @@ fn replica_etag_verification_enabled() -> bool {
|
||||
/// mismatch fails the replication instead. Encrypted sources are exempt: an
|
||||
/// SSE-C ciphertext passthrough sends ciphertext while the source ETag is the
|
||||
/// plaintext MD5 (that path has its own HEAD-back audit), and a managed-SSE
|
||||
/// (SSE-S3 / SSE-KMS) source stores a keyed fingerprint, or a legacy plaintext
|
||||
/// MD5, that the ETag of the target's re-encrypted replica can neither confirm
|
||||
/// nor refute. A managed-SSE source forwards no checksum either
|
||||
/// source can carry either a content MD5 or an opaque fingerprint depending
|
||||
/// on its scheme and writer version. A target can assign its own ETag. A managed-SSE source forwards no checksum either
|
||||
/// (`replication_put_object_options`), so its replica has no post-PUT
|
||||
/// content audit.
|
||||
fn verify_single_part_replica(
|
||||
@@ -2422,40 +2421,12 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
|
||||
let _ = replicate_delete_with_outcome(dobj, storage).await;
|
||||
}
|
||||
|
||||
/// How one delete replication attempt ended.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum DeleteReplicationAttempt {
|
||||
/// Every admitted target finished and the source state was persisted.
|
||||
Completed,
|
||||
/// The attempt did not finish for a reason another path already owns: a
|
||||
/// target failure is recorded in the persisted state for the scanner, and
|
||||
/// a force delete or delete-marker purge journals its own intent.
|
||||
Unfinished,
|
||||
/// A source-side lock or read kept the attempt from running, or from
|
||||
/// persisting its result. Nothing durable records that, so the caller must
|
||||
/// keep the delete for a later attempt.
|
||||
SourceDeferred,
|
||||
}
|
||||
|
||||
impl DeleteReplicationAttempt {
|
||||
fn from_finished(finished: bool) -> Self {
|
||||
if finished { Self::Completed } else { Self::Unfinished }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
dobj: DeletedObjectReplicationInfo,
|
||||
storage: Arc<S>,
|
||||
) -> bool {
|
||||
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
|
||||
}
|
||||
|
||||
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
dobj: DeletedObjectReplicationInfo,
|
||||
storage: Arc<S>,
|
||||
) -> DeleteReplicationAttempt {
|
||||
if dobj.delete_object.force_delete {
|
||||
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
|
||||
return replicate_force_delete_to_targets(&dobj, storage).await;
|
||||
}
|
||||
|
||||
let bucket = dobj.bucket.clone();
|
||||
@@ -2500,7 +2471,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return DeleteReplicationAttempt::Unfinished;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let target_arns = dobj.admitted_target_arns();
|
||||
@@ -2508,7 +2479,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
// Batch expiry can return an empty state after removing the source.
|
||||
// It owes no remote work or local writeback. Persisted target admission
|
||||
// must still be honored even when the live configuration is gone.
|
||||
return DeleteReplicationAttempt::Completed;
|
||||
return true;
|
||||
}
|
||||
|
||||
if dobj.delete_object.delete_marker
|
||||
@@ -2530,7 +2501,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
reason = "source_not_delete_marker",
|
||||
"Skipping stale delete-marker replication"
|
||||
);
|
||||
return DeleteReplicationAttempt::Completed;
|
||||
return true;
|
||||
}
|
||||
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
|
||||
debug!(
|
||||
@@ -2548,7 +2519,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
// purge-intent replay landing here on purpose). Purge instead
|
||||
// of just skipping; the result decides whether an MRF replay
|
||||
// may acknowledge the entry.
|
||||
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
|
||||
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
|
||||
}
|
||||
Err(err) => {
|
||||
// A transient source error (lock timeout, IO error) must not
|
||||
@@ -2557,7 +2528,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
// target mint one more delete marker (rustfs#6823). Fail the
|
||||
// entry without touching the target; the MRF replay / heal
|
||||
// scanner retries once the source is readable again.
|
||||
warn!(
|
||||
debug!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2582,7 +2553,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2593,7 +2564,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
{
|
||||
Ok(ns_lock) => ns_lock,
|
||||
Err(e) => {
|
||||
warn!(
|
||||
debug!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2617,14 +2588,14 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
|
||||
Ok(lock_guard) => lock_guard,
|
||||
Err(e) => {
|
||||
warn!(
|
||||
debug!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2648,7 +2619,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2886,12 +2857,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
}
|
||||
};
|
||||
|
||||
if !state_persisted {
|
||||
// The targets were driven, but the result never reached the source
|
||||
// metadata, so a scanner pass would still see the pre-attempt state.
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
|
||||
replicate_delete_outcome(
|
||||
expected_targets,
|
||||
rinfos.targets.len(),
|
||||
state_persisted,
|
||||
@@ -2899,7 +2865,7 @@ pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
// error returns early above instead of replicating unverified.
|
||||
true,
|
||||
&replication_status,
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
/// Reads the source version addressed by `delete_marker_version_id` so a
|
||||
|
||||
@@ -2008,12 +2008,10 @@ fn sync_rendered_target_section(
|
||||
|
||||
fn encode_server_config_blob(cfg: &Config, seed: Option<&[u8]>) -> Result<Vec<u8>> {
|
||||
let mut root = seed.and_then(parse_object_seed).unwrap_or_default();
|
||||
if !super::vector_maintenance::is_default(cfg) || root.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS) {
|
||||
root.insert(
|
||||
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
|
||||
super::vector_maintenance::encode(cfg)?,
|
||||
);
|
||||
}
|
||||
root.insert(
|
||||
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
|
||||
super::vector_maintenance::encode(cfg)?,
|
||||
);
|
||||
|
||||
if !matches!(root.get("version"), Some(Value::String(v)) if !v.trim().is_empty()) {
|
||||
root.insert("version".to_string(), Value::String("33".to_string()));
|
||||
@@ -3597,7 +3595,6 @@ mod tests {
|
||||
replication_decision: String::new(),
|
||||
checksum: None,
|
||||
multipart_completion_replayed: false,
|
||||
put_usage: None,
|
||||
backfilled_old_current_size: None,
|
||||
ec_block_size: None,
|
||||
}
|
||||
@@ -6169,43 +6166,4 @@ mod tests {
|
||||
assert!(err.is_quorum_error(), "expected quorum error, got {err:?}");
|
||||
assert_eq!(store.heal_calls.load(Ordering::SeqCst), 1, "heal should still be attempted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encode_server_config_blob_omits_default_s3vectors_maintenance_and_preserves_explicit() {
|
||||
super::super::init();
|
||||
let default_cfg = Config::new();
|
||||
assert!(
|
||||
default_cfg.0.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
|
||||
"Config::new() after config::init() populates default KVS"
|
||||
);
|
||||
|
||||
let blob = encode_server_config_blob(&default_cfg, None).expect("encode default server config");
|
||||
let parsed: serde_json::Map<String, Value> = serde_json::from_slice(&blob).expect("parse encoded config");
|
||||
assert!(
|
||||
!parsed.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
|
||||
"unrelated config saves must not inject default s3vectors_maintenance"
|
||||
);
|
||||
|
||||
let mut enabled_cfg = Config::new();
|
||||
let mut kvs = super::super::vector_maintenance::DEFAULT_KVS.clone();
|
||||
kvs.insert(rustfs_config::ENABLE_KEY.into(), "on".into());
|
||||
kvs.insert(rustfs_config::S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT.into(), "vec-maint-user".into());
|
||||
super::super::vector_maintenance::install(&mut enabled_cfg, kvs);
|
||||
|
||||
let enabled_blob = encode_server_config_blob(&enabled_cfg, None).expect("encode enabled vector maintenance");
|
||||
let enabled_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&enabled_blob).expect("parse enabled config");
|
||||
assert_eq!(
|
||||
enabled_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
|
||||
Value::String("on".into())
|
||||
);
|
||||
|
||||
// Resetting back to defaults on an existing seed that already contains s3vectors_maintenance
|
||||
// must overwrite the existing entry back to "off".
|
||||
let reset_blob = encode_server_config_blob(&default_cfg, Some(&enabled_blob)).expect("encode reset config");
|
||||
let reset_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&reset_blob).expect("parse reset config");
|
||||
assert_eq!(
|
||||
reset_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
|
||||
Value::String("off".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,20 +174,6 @@ pub(super) fn encode(config: &Config) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn is_default(config: &Config) -> bool {
|
||||
let Some(targets) = config.0.get(S3VECTORS_MAINTENANCE_SUB_SYS) else {
|
||||
return true;
|
||||
};
|
||||
if targets.len() != 1 || !targets.contains_key(DEFAULT_DELIMITER) {
|
||||
return false;
|
||||
}
|
||||
let Ok(normalized) = normalize(&targets[DEFAULT_DELIMITER]) else {
|
||||
return false;
|
||||
};
|
||||
normalized.get(ENABLE_KEY) == DEFAULT_KVS.get(ENABLE_KEY)
|
||||
&& normalized.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT) == DEFAULT_KVS.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT)
|
||||
}
|
||||
|
||||
pub(super) fn equivalent(lhs: &Config, rhs: &Config) -> bool {
|
||||
matches!((encode(lhs), encode(rhs)), (Ok(lhs), Ok(rhs)) if lhs == rhs)
|
||||
}
|
||||
|
||||
@@ -164,8 +164,7 @@ async fn verified_shard(info: &FileInfo) -> Result<Vec<u8>> {
|
||||
}
|
||||
let mut reader = BitrotReader::new(Cursor::new(data.clone()), shard_size, HashAlgorithm::HighwayHash256S, false);
|
||||
if let Some(integrity) = &info.parts[0].integrity {
|
||||
let proof =
|
||||
PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT, None)?;
|
||||
let proof = PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT)?;
|
||||
reader.set_integrity(ShardVerifier::new(proof, info.erasure.index - 1, 0, None)?)?;
|
||||
}
|
||||
let mut shard = vec![0; shard_size];
|
||||
|
||||
@@ -142,7 +142,7 @@ const DECOMMISSION_ENTRY_CONCURRENCY_DEFAULT_CAP: usize = 8;
|
||||
const DECOMMISSION_ENTRY_CONCURRENCY_HARD_CAP: usize = 64;
|
||||
const DECOMMISSION_ENTRY_WORKERS_PER_SET: usize = 2;
|
||||
const DECOMMISSION_CAPACITY_SNAPSHOT_CONCURRENCY: usize = 4;
|
||||
const DECOMMISSION_META_PREFIXES: [&str; 5] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX, "s3tables", "s3vectors"];
|
||||
const DECOMMISSION_META_PREFIXES: [&str; 3] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX];
|
||||
const DECOMMISSION_CAPACITY_LEGACY_MODEL_VERSION: u16 = 1;
|
||||
const DECOMMISSION_CAPACITY_TARGET_FENCE_MODEL_VERSION: u16 = 2;
|
||||
#[cfg(test)]
|
||||
@@ -13684,6 +13684,17 @@ impl ECStore {
|
||||
target_pool_indices: &[usize],
|
||||
admission: DecommissionCapacityAdmission,
|
||||
) -> Result<rustfs_lock::NamespaceLockGuard> {
|
||||
Ok(self
|
||||
.acquire_external_decommission_capacity_fence_with_active_source(target_pool_indices, admission)
|
||||
.await?
|
||||
.0)
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_external_decommission_capacity_fence_with_active_source(
|
||||
&self,
|
||||
target_pool_indices: &[usize],
|
||||
admission: DecommissionCapacityAdmission,
|
||||
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
|
||||
let save_guard = self.pool_meta_save_gate.read().await;
|
||||
let (pool_meta_guard, snapshot) = self
|
||||
.acquire_pool_meta_read_guard(&save_guard, "target capacity admission failed")
|
||||
@@ -13704,7 +13715,9 @@ impl ECStore {
|
||||
for target_pool_index in target_pool_indices.iter().copied() {
|
||||
ensure_external_decommission_target_admission(&snapshot, target_pool_index, admission)?;
|
||||
}
|
||||
Ok(pool_meta_guard)
|
||||
let has_active_source = pool_meta_has_active_decommission(&snapshot);
|
||||
drop(save_guard);
|
||||
Ok((pool_meta_guard, has_active_source))
|
||||
}
|
||||
|
||||
/// Fence healing of the pool metadata object itself without recursively
|
||||
@@ -13732,12 +13745,16 @@ impl ECStore {
|
||||
Ok((pool_meta_guard, admissions, save_guard))
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_decommission_capacity_release_fence(&self) -> Result<rustfs_lock::NamespaceLockGuard> {
|
||||
pub(crate) async fn acquire_decommission_capacity_release_fence_with_active_source(
|
||||
&self,
|
||||
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
|
||||
let save_guard = self.pool_meta_save_gate.read().await;
|
||||
let (pool_meta_guard, _) = self
|
||||
let (pool_meta_guard, snapshot) = self
|
||||
.acquire_pool_meta_read_guard(&save_guard, "capacity release fence failed")
|
||||
.await?;
|
||||
Ok(pool_meta_guard)
|
||||
let has_active_source = pool_meta_has_active_decommission(&snapshot);
|
||||
drop(save_guard);
|
||||
Ok((pool_meta_guard, has_active_source))
|
||||
}
|
||||
|
||||
pub(crate) async fn run_decommission_capacity_admitted_mutation<T, F, Fut>(
|
||||
@@ -22560,7 +22577,6 @@ mod tests {
|
||||
"buckets/.usage.v2.json",
|
||||
"buckets/.usage.v2.json.bkp",
|
||||
"buckets/.usage.observed.json",
|
||||
"buckets/.usage.buckets.json",
|
||||
"buckets/.usage-progress.json",
|
||||
"buckets/photos/.usage-progress.json.bkp",
|
||||
"buckets/photos/.usage-progress.json.extra",
|
||||
@@ -22641,7 +22657,6 @@ mod tests {
|
||||
let controls = [
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.v2.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.observed.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.buckets.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/photos/.usage-progress.json.bkp"),
|
||||
(RUSTFS_META_BUCKET, "buckets/photos/.usage-cache.bin.extra"),
|
||||
(user_bucket, "ordinary-object"),
|
||||
@@ -22891,7 +22906,6 @@ mod tests {
|
||||
"buckets/photos/.usage-cache.bin.bkp.extra",
|
||||
"buckets/.usage.v2.json",
|
||||
"buckets/.usage.observed.json",
|
||||
"buckets/.usage.buckets.json",
|
||||
"buckets/photos/.usage-progress.json.bkp",
|
||||
] {
|
||||
let source_set = store.pools[0].get_disks_by_key(object);
|
||||
@@ -28002,7 +28016,7 @@ mod tests {
|
||||
.expect("hold the namespace writer while the read-only admission waits");
|
||||
let admission = tokio::spawn({
|
||||
let store = store.clone();
|
||||
async move { store.acquire_decommission_capacity_release_fence().await }
|
||||
async move { store.acquire_decommission_capacity_release_fence_with_active_source().await }
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
@@ -28051,7 +28065,7 @@ mod tests {
|
||||
);
|
||||
|
||||
drop(writer);
|
||||
let read_fence = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
|
||||
let (read_fence, _) = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
|
||||
.await
|
||||
.expect("the read-only admission must finish after releasing the namespace writer")
|
||||
.expect("the admission task must not panic")
|
||||
@@ -43353,12 +43367,6 @@ mod pools_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decommission_meta_prefixes_include_s3tables_and_s3vectors() {
|
||||
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3tables"));
|
||||
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3vectors"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn test_path2_bucket_object_with_base_path_supports_windows_separators() {
|
||||
|
||||
@@ -4150,97 +4150,6 @@ mod decommission_lock_order_tests {
|
||||
.expect("decommission activation should commit after the probe release");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn waiting_put_does_not_hold_capacity_needed_by_conditional_commit_and_activation() {
|
||||
use crate::set_disk::{PutObjectCommitBarrier, PutObjectCommitPause};
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
run_large_stack_current_thread_async_test("staged-put-activation", || async {
|
||||
let (_dirs, store, _peer) = test_three_pool_stores_with_isolated_node_contexts(None).await;
|
||||
let bucket = test_bucket("staged-put-activation");
|
||||
let object = "entry";
|
||||
store.make_bucket(&bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
let seeded = store.pools[2]
|
||||
.put_object(
|
||||
&bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"before".to_vec()),
|
||||
&ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
|
||||
set_decommission_capacity_info_overrides_for_test(
|
||||
store.id,
|
||||
vec![vec![
|
||||
DecommissionPoolCapacityInfo::for_test(0, layout, 0, 1024, 1024),
|
||||
DecommissionPoolCapacityInfo::for_test(1, layout, 1024, 1024, 0),
|
||||
DecommissionPoolCapacityInfo::for_test(2, layout, 1024, 1024, 0),
|
||||
]],
|
||||
);
|
||||
|
||||
let after = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::AfterNamespace);
|
||||
let conditional_store = Arc::clone(&store);
|
||||
let conditional_bucket = bucket.clone();
|
||||
let conditional = tokio::spawn(async move {
|
||||
conditional_store
|
||||
.put_object(
|
||||
&conditional_bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"conditional".to_vec()),
|
||||
&ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: seeded.etag,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
after.wait_until_paused().await;
|
||||
let before = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::BeforeNamespace);
|
||||
let ordinary_store = Arc::clone(&store);
|
||||
let ordinary_bucket = bucket.clone();
|
||||
let ordinary = tokio::spawn(async move {
|
||||
ordinary_store.pools[2]
|
||||
.put_object(
|
||||
&ordinary_bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"ordinary".to_vec()),
|
||||
&ObjectOptions {
|
||||
decommission_capacity_admission: Some(Arc::clone(&ordinary_store)),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
before.wait_until_paused().await;
|
||||
before.release_and_wait_until_namespace_pending().await;
|
||||
assert!(!before.namespace_acquired());
|
||||
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
store.save_current_pool_meta_for_decommission_start(&[0], Vec::new()),
|
||||
)
|
||||
.await
|
||||
.expect("an object-lock waiter must leave capacity available to activation")
|
||||
.expect("activate decommission of a separate source");
|
||||
drop(after);
|
||||
drop(before);
|
||||
conditional
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("publish under the active capacity reservation");
|
||||
let written = ordinary.await.unwrap().expect("publish the queued PUT");
|
||||
let visible = store
|
||||
.get_object_info(&bucket, object, &ObjectOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(visible.etag, written.etag);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn staged_external_put_rechecks_retiring_source_on_another_node() {
|
||||
|
||||
@@ -1584,12 +1584,11 @@ impl Sets {
|
||||
version_id: &str,
|
||||
opts: &HealOpts,
|
||||
proof: crate::set_disk::AbsenceProofRequest<'_>,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<(HealResultItem, Option<Error>, Option<crate::set_disk::HealedObjectAbsence>)> {
|
||||
let mut absence = None;
|
||||
let (item, error) = self
|
||||
.get_disks_for_heal_object(object, opts)?
|
||||
.heal_object_for_store(bucket, object, version_id, opts, &mut absence, proof, capacity_store)
|
||||
.heal_object_with_retirement(bucket, object, version_id, opts, &mut absence, proof)
|
||||
.await?;
|
||||
// A caller-owned lock does not expose its lease to this boundary.
|
||||
// Keep cleanup unverified when that lease cannot be checked here.
|
||||
|
||||
@@ -369,14 +369,6 @@ fn data_movement_user_defined(object_info: &ObjectInfo) -> HashMap<String, Strin
|
||||
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
|
||||
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
|
||||
insert_data_movement_checksum(&mut user_defined, object_info);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
if let Some(logical_rev) = object_info.logical_body_revision() {
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut user_defined,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
logical_rev.to_string(),
|
||||
);
|
||||
}
|
||||
if !object_info.user_tags.is_empty() {
|
||||
user_defined.insert(AMZ_OBJECT_TAGGING.to_string(), (*object_info.user_tags).clone());
|
||||
}
|
||||
@@ -1003,24 +995,6 @@ fn data_movement_publication_marker_valid(object_info: &ObjectInfo) -> bool {
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn data_movement_logical_body_revision_marker_presence(object_info: &ObjectInfo) -> Option<bool> {
|
||||
let mut found: Option<uuid::Uuid> = None;
|
||||
for (key, value) in object_info.user_defined.iter() {
|
||||
if !is_data_movement_internal_metadata(key, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX) {
|
||||
continue;
|
||||
}
|
||||
let parsed = uuid::Uuid::parse_str(value.trim()).ok().filter(|id| !id.is_nil())?;
|
||||
if found.is_some_and(|existing| existing != parsed) {
|
||||
return None;
|
||||
}
|
||||
found = Some(parsed);
|
||||
}
|
||||
if found.is_some() && object_info.data_dir.is_none_or(|dir| dir.is_nil()) {
|
||||
return None;
|
||||
}
|
||||
Some(found.is_some())
|
||||
}
|
||||
|
||||
fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, normalize_compression_size: bool) -> bool {
|
||||
[
|
||||
SUFFIX_DATA_MOVED,
|
||||
@@ -1032,7 +1006,6 @@ fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, norm
|
||||
// Inline placement is local to each physical copy, like its data directory.
|
||||
rustfs_utils::http::SUFFIX_INLINE_DATA,
|
||||
crate::object_api::ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
]
|
||||
.iter()
|
||||
.any(|suffix| is_data_movement_internal_metadata(key, suffix))
|
||||
@@ -1088,16 +1061,6 @@ pub(crate) fn is_equivalent_data_movement_metadata(
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let source_logical_rev_marker = data_movement_logical_body_revision_marker_presence(source);
|
||||
let target_logical_rev_marker = data_movement_logical_body_revision_marker_presence(target);
|
||||
if !is_compatible_data_movement_marker_presence(source_logical_rev_marker, target_logical_rev_marker) {
|
||||
return false;
|
||||
}
|
||||
if (source_logical_rev_marker == Some(true) || target_logical_rev_marker == Some(true))
|
||||
&& source.logical_body_revision() != target.logical_body_revision()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
source
|
||||
.user_defined
|
||||
@@ -1111,13 +1074,6 @@ pub(crate) fn is_equivalent_data_movement_metadata(
|
||||
.all(|(key, value)| source.user_defined.get(key) == Some(value))
|
||||
}
|
||||
|
||||
/// A listing can encounter either physical copy first. Migration verification
|
||||
/// itself remains directional so it still detects metadata lost on the target.
|
||||
pub(crate) fn equivalent_listed_object_versions(left: &ObjectInfo, right: &ObjectInfo) -> bool {
|
||||
is_equivalent_data_movement_object_identity(left, right, true, true)
|
||||
|| is_equivalent_data_movement_object_identity(right, left, true, true)
|
||||
}
|
||||
|
||||
pub(crate) fn is_equivalent_data_movement_object_identity(
|
||||
source: &ObjectInfo,
|
||||
target: &ObjectInfo,
|
||||
@@ -5267,75 +5223,4 @@ mod tests {
|
||||
|
||||
assert!(!result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_movement_preserves_logical_body_revision_across_hops_and_passes_equivalence() {
|
||||
let d1 = Uuid::from_u128(0x1111);
|
||||
let d2 = Uuid::from_u128(0x2222);
|
||||
let d3 = Uuid::from_u128(0x3333);
|
||||
let source = ObjectInfo {
|
||||
bucket: "vec-bucket".to_string(),
|
||||
name: "manifest.json".to_string(),
|
||||
size: 64,
|
||||
actual_size: 64,
|
||||
etag: Some("etag-1".to_string()),
|
||||
mod_time: Some(OffsetDateTime::UNIX_EPOCH),
|
||||
data_dir: Some(d1),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(source.logical_body_revision(), Some(d1));
|
||||
|
||||
let hop1 = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(data_movement_user_defined(&source)),
|
||||
..source.clone()
|
||||
};
|
||||
assert_eq!(hop1.logical_body_revision(), Some(d1));
|
||||
assert!(is_equivalent_data_movement_object(&source, &hop1));
|
||||
|
||||
let hop2 = ObjectInfo {
|
||||
data_dir: Some(d3),
|
||||
user_defined: Arc::new(data_movement_user_defined(&hop1)),
|
||||
..hop1.clone()
|
||||
};
|
||||
assert_eq!(hop2.logical_body_revision(), Some(d1));
|
||||
assert!(is_equivalent_data_movement_object(&hop1, &hop2));
|
||||
assert!(is_equivalent_data_movement_object(&source, &hop2));
|
||||
|
||||
// Dropping the marker after the object has already been migrated must fail equivalence.
|
||||
let dropped_marker = ObjectInfo {
|
||||
data_dir: Some(d3),
|
||||
user_defined: Arc::new(HashMap::new()),
|
||||
..hop1.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&hop1, &dropped_marker));
|
||||
|
||||
// Mismatched or malformed logical body revision markers must fail equivalence.
|
||||
let mut wrong_meta = data_movement_user_defined(&source);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut wrong_meta, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut wrong_meta,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
Uuid::from_u128(0x9999).to_string(),
|
||||
);
|
||||
let wrong_rev = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(wrong_meta),
|
||||
..source.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&source, &wrong_rev));
|
||||
|
||||
let mut malformed_meta = HashMap::new();
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut malformed_meta,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
"not-a-valid-uuid".to_string(),
|
||||
);
|
||||
let malformed = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(malformed_meta),
|
||||
..source.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&source, &malformed));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,9 +19,7 @@ pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
|
||||
pub use admin_bucket_identity::verified_account_bucket_usage;
|
||||
pub mod local_snapshot;
|
||||
mod scan_progress;
|
||||
mod snapshot_view;
|
||||
pub use scan_progress::load_bucket_scan_progress_for_admin;
|
||||
pub use snapshot_view::{AdminUsageSnapshot, load_admin_usage_snapshot};
|
||||
|
||||
use crate::storage_api_contracts::{
|
||||
bucket::{BucketOperations as _, BucketOptions},
|
||||
@@ -639,7 +637,7 @@ fn stale_data_usage_persist_reason_for_source(
|
||||
/// Store data usage info to backend storage
|
||||
#[instrument(skip(store))]
|
||||
pub async fn store_data_usage_in_backend(data_usage_info: DataUsageInfo, store: Arc<ECStore>) -> Result<(), Error> {
|
||||
reject_display_only_usage(&data_usage_info)?;
|
||||
reject_admin_usage_projection(&data_usage_info)?;
|
||||
if data_usage_info.usage_snapshot_converged == Some(false) {
|
||||
return Err(Error::other(
|
||||
"nonconverged data usage observations cannot replace the quota-authoritative snapshot",
|
||||
@@ -669,7 +667,7 @@ async fn save_data_usage_in_backend(
|
||||
store: Arc<ECStore>,
|
||||
expected_publication_epoch: u64,
|
||||
) -> Result<(), Error> {
|
||||
reject_display_only_usage(&data_usage_info)?;
|
||||
reject_admin_usage_projection(&data_usage_info)?;
|
||||
let data =
|
||||
serde_json::to_vec(&data_usage_info).map_err(|e| Error::other(format!("Failed to serialize data usage info: {e}")))?;
|
||||
|
||||
@@ -1284,17 +1282,14 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
|
||||
e.column()
|
||||
))
|
||||
})?;
|
||||
reject_display_only_usage(&info)?;
|
||||
reject_admin_usage_projection(&info)?;
|
||||
for usage in info.buckets_usage.values_mut() {
|
||||
usage.normalize_usage_provenance();
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn reject_display_only_usage(info: &DataUsageInfo) -> Result<(), Error> {
|
||||
if info.usage_snapshot_certified_buckets.is_some() {
|
||||
return Err(Error::other("completed-bucket sidecar is not a namespace baseline"));
|
||||
}
|
||||
fn reject_admin_usage_projection(info: &DataUsageInfo) -> Result<(), Error> {
|
||||
if info.usage_snapshot_admin_projection {
|
||||
return Err(Error::other("admin usage projections cannot be persisted or used as a storage baseline"));
|
||||
}
|
||||
@@ -2126,9 +2121,6 @@ impl BucketUsageAccumulator {
|
||||
}
|
||||
|
||||
pub fn quota_object_size(object: &ObjectInfo) -> Result<u64, Error> {
|
||||
if crate::bucket::metadata::is_vector_pagination_session(&object.bucket, &object.name) {
|
||||
return Ok(0);
|
||||
}
|
||||
// A compressed object may carry -1 while the transformed size is unknown
|
||||
// (legacy streaming sentinel). In that case the persisted physical size
|
||||
// is still a valid accounting floor; every other negative value is corrupt.
|
||||
@@ -2468,84 +2460,54 @@ pub async fn seed_bucket_usage_memory_for_test(bucket: &str, size: u64) {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A successful PUT's change to logical bucket usage.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PutUsageReceipt {
|
||||
had_live_version: bool,
|
||||
replaced: ReplacedVersion,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ReplacedVersion {
|
||||
Absent,
|
||||
DeleteMarker,
|
||||
Data(u64),
|
||||
}
|
||||
|
||||
impl PutUsageReceipt {
|
||||
pub(crate) fn from_predecessors(had_live_version: bool, replaced: Option<&ObjectInfo>) -> Result<Self, Error> {
|
||||
let replaced = match replaced {
|
||||
None => ReplacedVersion::Absent,
|
||||
Some(info) if info.delete_marker => ReplacedVersion::DeleteMarker,
|
||||
Some(info) => ReplacedVersion::Data(quota_object_size(info)?),
|
||||
};
|
||||
Ok(Self {
|
||||
had_live_version,
|
||||
replaced,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replaced_size(&self) -> u64 {
|
||||
match self.replaced {
|
||||
ReplacedVersion::Data(size) => size,
|
||||
ReplacedVersion::Absent | ReplacedVersion::DeleteMarker => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply this committed version change to the bucket's immediate usage counters.
|
||||
pub async fn record(self, bucket: &str, new_size: u64) {
|
||||
ensure_bucket_usage_cached(bucket).await;
|
||||
let mut cache = memory_cache().write().await;
|
||||
let entry = cache
|
||||
.entry(bucket.to_owned())
|
||||
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
|
||||
entry.usage.size = entry.usage.size.saturating_sub(self.replaced_size()).saturating_add(new_size);
|
||||
if !self.had_live_version {
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
}
|
||||
if !matches!(self.replaced, ReplacedVersion::Data(_)) {
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
}
|
||||
if self.replaced == ReplacedVersion::DeleteMarker {
|
||||
entry.usage.delete_markers_count = entry.usage.delete_markers_count.saturating_sub(1);
|
||||
}
|
||||
let now = SystemTime::now();
|
||||
entry.refreshed_at = now;
|
||||
entry.usage_updated_at = now;
|
||||
entry.dirty = true;
|
||||
entry.stale_snapshot_pending = false;
|
||||
entry.pending_scanner_position = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fast in-memory update for immediate quota and admin usage consistency.
|
||||
pub async fn record_bucket_object_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
|
||||
PutUsageReceipt {
|
||||
had_live_version: previous_current_size.is_some(),
|
||||
replaced: previous_current_size.map_or(ReplacedVersion::Absent, ReplacedVersion::Data),
|
||||
}
|
||||
.record(bucket, new_size)
|
||||
.await;
|
||||
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, false).await;
|
||||
}
|
||||
|
||||
/// Fast in-memory update for versioned object writes.
|
||||
pub async fn record_bucket_object_version_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
|
||||
PutUsageReceipt {
|
||||
had_live_version: previous_current_size.is_some(),
|
||||
replaced: ReplacedVersion::Absent,
|
||||
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, true).await;
|
||||
}
|
||||
|
||||
async fn record_bucket_object_write_memory_inner(
|
||||
bucket: &str,
|
||||
previous_current_size: Option<u64>,
|
||||
new_size: u64,
|
||||
creates_new_version: bool,
|
||||
) {
|
||||
ensure_bucket_usage_cached(bucket).await;
|
||||
|
||||
let mut cache = memory_cache().write().await;
|
||||
let entry = cache
|
||||
.entry(bucket.to_string())
|
||||
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
|
||||
|
||||
if creates_new_version {
|
||||
entry.usage.size = entry.usage.size.saturating_add(new_size);
|
||||
if previous_current_size.is_none() {
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
}
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
} else {
|
||||
match previous_current_size {
|
||||
Some(previous_size) => {
|
||||
entry.usage.size = entry.usage.size.saturating_sub(previous_size).saturating_add(new_size);
|
||||
}
|
||||
None => {
|
||||
entry.usage.size = entry.usage.size.saturating_add(new_size);
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
.record(bucket, new_size)
|
||||
.await;
|
||||
|
||||
let now = SystemTime::now();
|
||||
entry.refreshed_at = now;
|
||||
entry.usage_updated_at = now;
|
||||
entry.dirty = true;
|
||||
entry.stale_snapshot_pending = false;
|
||||
entry.pending_scanner_position = None;
|
||||
}
|
||||
|
||||
/// Degraded in-memory update for an object write whose previous current size
|
||||
@@ -5828,26 +5790,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_exempt_sessions_require_the_vector_storage_bucket_and_session_key() {
|
||||
let table = uuid::Uuid::new_v4();
|
||||
let session = "b".repeat(64);
|
||||
let key = format!(".rustfs-table/{table}/query-results/{session}.session");
|
||||
let size = |bucket: &str, name: &str| {
|
||||
quota_object_size(&ObjectInfo {
|
||||
bucket: bucket.to_owned(),
|
||||
name: name.to_owned(),
|
||||
size: 17,
|
||||
..Default::default()
|
||||
})
|
||||
.expect("quota size")
|
||||
};
|
||||
assert_eq!(size("rustfs-v-abc", &key), 0);
|
||||
assert_eq!(size("general-bucket", &key), 17);
|
||||
assert_eq!(size("rustfs-v-abc", &key.replace("/query-results/", "/dataset/")), 17);
|
||||
assert_eq!(size("rustfs-v-abc", &key.replace(&session, "other")), 17);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_object_size_accepts_compressed_unknown_actual_size_sentinel() {
|
||||
let mut metadata = HashMap::new();
|
||||
@@ -7496,46 +7438,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn put_usage_charges_the_replaced_version_and_counts_markers_separately() {
|
||||
let bucket = "put-usage-versions";
|
||||
let baseline = BucketUsageInfo {
|
||||
objects_count: 1,
|
||||
versions_count: 2,
|
||||
size: 90,
|
||||
..Default::default()
|
||||
};
|
||||
let null = ObjectInfo {
|
||||
size: 20,
|
||||
actual_size: 20,
|
||||
..Default::default()
|
||||
};
|
||||
let marker = ObjectInfo {
|
||||
delete_marker: true,
|
||||
..Default::default()
|
||||
};
|
||||
for (mut initial, had_live, replaced, expected) in [
|
||||
(baseline.clone(), true, Some(&null), (100, 1, 2, 0)),
|
||||
(baseline.clone(), true, None, (120, 1, 3, 0)),
|
||||
(baseline, true, Some(&marker), (120, 1, 3, 0)),
|
||||
(BucketUsageInfo::default(), false, Some(&marker), (30, 1, 1, 0)),
|
||||
] {
|
||||
initial.delete_markers_count = u64::from(replaced.is_some_and(|version| version.delete_marker));
|
||||
clear_usage_memory_cache_for_test().await;
|
||||
replace_bucket_usage_memory_from_authoritative(bucket, initial, SystemTime::now()).await;
|
||||
let receipt = PutUsageReceipt::from_predecessors(had_live, replaced).expect("valid version sizes");
|
||||
receipt.record(bucket, 30).await;
|
||||
let cache = memory_cache().read().await;
|
||||
let usage = &cache[bucket].usage;
|
||||
assert_eq!(
|
||||
(usage.size, usage.objects_count, usage.versions_count, usage.delete_markers_count),
|
||||
expected
|
||||
);
|
||||
}
|
||||
clear_usage_memory_cache_for_test().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn authoritative_versioned_refresh_replaces_stale_dirty_memory() {
|
||||
|
||||
@@ -40,19 +40,7 @@ pub async fn load_bucket_scan_progress_for_admin(
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
|
||||
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, false))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) async fn load_initial_bucket_scan_progress(
|
||||
store: Arc<ECStore>,
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
|
||||
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, true))
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -62,7 +50,6 @@ async fn bucket_progress_sources(
|
||||
bucket: String,
|
||||
sets: Arc<Vec<Arc<SetDisks>>>,
|
||||
movement_generation: u64,
|
||||
initial_baseline: Option<&DataUsageInfo>,
|
||||
) -> BoxStream<'static, ProgressEvent> {
|
||||
let Some(incarnation) = store
|
||||
.bucket_incarnation_id_from_disk(&bucket)
|
||||
@@ -72,19 +59,6 @@ async fn bucket_progress_sources(
|
||||
else {
|
||||
return futures::stream::empty().boxed();
|
||||
};
|
||||
if initial_baseline.as_ref().is_some_and(|baseline| {
|
||||
baseline
|
||||
.usage_snapshot_noninitial_buckets
|
||||
.get(&bucket)
|
||||
.is_some_and(|previous| {
|
||||
uuid::Uuid::parse_str(previous)
|
||||
.ok()
|
||||
.is_none_or(|previous| previous.is_nil() || previous == incarnation)
|
||||
})
|
||||
|| !super::snapshot_view::initial_progress_allowed(baseline.buckets_usage.get(&bucket), incarnation)
|
||||
}) {
|
||||
return futures::stream::empty().boxed();
|
||||
}
|
||||
let incarnation = incarnation.to_string();
|
||||
let path = bucket_scan_progress_path(&bucket);
|
||||
futures::stream::iter(0..sets.len())
|
||||
@@ -150,7 +124,6 @@ async fn load_progress(
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
read_deadline: tokio::time::Instant,
|
||||
initial_only: bool,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
|
||||
return HashMap::new();
|
||||
@@ -172,9 +145,8 @@ async fn load_progress(
|
||||
}
|
||||
// Emit each validated source immediately. A bucket waiting for another
|
||||
// source must not hide its healthy sample behind a whole-bucket future.
|
||||
let initial_baseline = initial_only.then_some(baseline);
|
||||
let work = futures::stream::iter(buckets.iter().cloned())
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation, initial_baseline))
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
|
||||
.buffer_unordered(4)
|
||||
.flatten_unordered(4);
|
||||
let samples = collect_progress_until(read_deadline, work).await;
|
||||
@@ -234,7 +206,6 @@ mod tests {
|
||||
},
|
||||
objects: Some(objects),
|
||||
size: Some(objects * 11),
|
||||
blocker: None,
|
||||
};
|
||||
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
|
||||
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
|
||||
@@ -300,7 +271,6 @@ mod tests {
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(71),
|
||||
blocker: None,
|
||||
};
|
||||
(dirs, store, sample)
|
||||
}
|
||||
@@ -315,171 +285,6 @@ mod tests {
|
||||
.expect("persist display sample on its source set");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_snapshot_allows_initial_progress_but_preserves_complete_values() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let mut baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10)),
|
||||
scanner_epoch: Some(9),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
let primary = "buckets/.usage.v2.json";
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("initial marker"))
|
||||
.await
|
||||
.expect("persist initial marker");
|
||||
let initial = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("initial view");
|
||||
assert!(initial.usage.buckets_usage.is_empty());
|
||||
assert_eq!(initial.initial_scan_progress["progress"].objects, Some(7));
|
||||
baseline.usage_snapshot_bootstrap_pending = false;
|
||||
baseline.usage_snapshot_complete = true;
|
||||
baseline.scanner_cycle = Some(10);
|
||||
let mut complete = BucketUsageInfo {
|
||||
size: 900,
|
||||
objects_count: 90,
|
||||
bucket_incarnation: Some(sample.bucket_incarnation.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
complete.certify(rustfs_data_usage::BucketUsageCertification {
|
||||
epoch: 9,
|
||||
cycle: 10,
|
||||
certified_at: baseline.last_update.expect("measurement time"),
|
||||
});
|
||||
baseline.buckets_usage.insert("progress".into(), complete);
|
||||
baseline.buckets_count = 1;
|
||||
baseline.calculate_totals();
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("complete snapshot"))
|
||||
.await
|
||||
.expect("persist complete snapshot");
|
||||
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("complete view");
|
||||
assert_eq!(view.usage.buckets_usage["progress"].objects_count, 90);
|
||||
assert!(view.initial_scan_progress.is_empty());
|
||||
baseline.usage_snapshot_bootstrap_pending = true;
|
||||
baseline.usage_snapshot_initial_bootstrap = false;
|
||||
baseline.usage_snapshot_complete = false;
|
||||
baseline.buckets_usage.clear();
|
||||
baseline.buckets_count = 0;
|
||||
baseline.calculate_totals();
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("recovery marker"))
|
||||
.await
|
||||
.expect("persist recovery marker");
|
||||
let recovered = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("recovery view");
|
||||
assert!(
|
||||
recovered.initial_scan_progress.is_empty(),
|
||||
"same incarnation does not become a first scan after recovery"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn noninitial_barrier_survives_a_missing_completed_bucket_sidecar() {
|
||||
let (_dirs, store, mut sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
scanner_epoch: Some(9),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_noninitial_buckets: HashMap::from([("progress".into(), sample.bucket_incarnation.clone())]),
|
||||
..Default::default()
|
||||
};
|
||||
save_config(
|
||||
store.clone(),
|
||||
"buckets/.usage.v2.json",
|
||||
serde_json::to_vec(&baseline).expect("history marker"),
|
||||
)
|
||||
.await
|
||||
.expect("persist history marker");
|
||||
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("bounded missing view");
|
||||
assert!(
|
||||
view.initial_scan_progress.is_empty(),
|
||||
"a lost sidecar cannot reopen initial-statistics fallback"
|
||||
);
|
||||
assert_eq!(view.unmeasured_buckets, ["progress"]);
|
||||
|
||||
// A freshly created incarnation with the same name has its own first scan.
|
||||
store
|
||||
.delete_bucket("progress", &Default::default())
|
||||
.await
|
||||
.expect("delete old bucket");
|
||||
store
|
||||
.make_bucket("progress", &Default::default())
|
||||
.await
|
||||
.expect("recreate bucket");
|
||||
let current = store
|
||||
.bucket_incarnation_id_from_disk("progress")
|
||||
.await
|
||||
.expect("new incarnation");
|
||||
assert_ne!(sample.bucket_incarnation, current.to_string());
|
||||
// Restore the historical marker to model a stale read after recreate.
|
||||
save_config(store.clone(), "buckets/.usage.v2.json", serde_json::to_vec(&baseline).unwrap())
|
||||
.await
|
||||
.expect("history of the previous incarnation");
|
||||
sample.bucket_incarnation = current.to_string();
|
||||
save(&store, &sample).await;
|
||||
let recreated = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("recreated view");
|
||||
assert!(recreated.usage.buckets_usage.is_empty());
|
||||
assert_eq!(recreated.initial_scan_progress["progress"].objects, Some(7));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_snapshot_never_returns_a_persisted_observed_row_as_completed_usage() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let mut observed = BucketUsageInfo {
|
||||
objects_count: 90,
|
||||
size: 900,
|
||||
bucket_incarnation: Some(sample.bucket_incarnation),
|
||||
..Default::default()
|
||||
};
|
||||
observed.mark_observed();
|
||||
let mut baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
scanner_epoch: Some(9),
|
||||
scanner_cycle: Some(10),
|
||||
usage_snapshot_complete: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_pending_bucket_count: 1,
|
||||
usage_snapshot_pending_buckets: vec!["progress".into()],
|
||||
buckets_count: 1,
|
||||
buckets_usage: HashMap::from([("progress".into(), observed)]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(baseline.checked_calculate_totals());
|
||||
save_config(
|
||||
store.clone(),
|
||||
"buckets/.usage.v2.json",
|
||||
serde_json::to_vec(&baseline).expect("observed root"),
|
||||
)
|
||||
.await
|
||||
.expect("persist old pending root");
|
||||
let view = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("strict view");
|
||||
assert!(view.usage.buckets_usage.is_empty());
|
||||
assert_eq!(view.unmeasured_buckets, ["progress"]);
|
||||
assert!(
|
||||
view.initial_scan_progress.is_empty(),
|
||||
"filtering an old row must not reopen initial fallback"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn display_progress_reloads_from_shared_storage_without_promoting_usage() {
|
||||
fn assert_send<T: Send>(value: T) -> T {
|
||||
|
||||
@@ -1,429 +0,0 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use super::*;
|
||||
use rustfs_data_usage::BucketScanProgress;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// Response-only view of persisted usage. Initial progress is never inserted
|
||||
/// into the authoritative map or used by quota admission.
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct AdminUsageSnapshot {
|
||||
#[serde(flatten)]
|
||||
pub usage: DataUsageInfo,
|
||||
pub snapshot_view: bool,
|
||||
pub initial_scan_progress: HashMap<String, BucketScanProgress>,
|
||||
pub unmeasured_buckets: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn initial_progress_allowed(previous: Option<&BucketUsageInfo>, incarnation: uuid::Uuid) -> bool {
|
||||
if incarnation.is_nil() {
|
||||
return false;
|
||||
}
|
||||
match previous {
|
||||
None => true,
|
||||
Some(previous) => previous
|
||||
.bucket_incarnation
|
||||
.as_deref()
|
||||
.and_then(|value| uuid::Uuid::parse_str(value).ok())
|
||||
.filter(|previous| !previous.is_nil())
|
||||
.is_some_and(|previous| previous != incarnation),
|
||||
}
|
||||
}
|
||||
|
||||
fn initial_snapshot_available(raw: &DataUsageInfo, source: UsageSnapshotSource) -> bool {
|
||||
source == UsageSnapshotSource::Primary
|
||||
&& raw.usage_snapshot_initial_view_version == Some(1)
|
||||
&& if raw.usage_snapshot_bootstrap_pending {
|
||||
raw.usage_snapshot_initial_bootstrap && raw.has_usage_bootstrap_marker_shape()
|
||||
} else {
|
||||
raw.is_completed_usage_baseline()
|
||||
}
|
||||
}
|
||||
|
||||
/// Read complete persisted values before considering initial progress.
|
||||
///
|
||||
/// The caller supplies only authorized bucket names. Primary/backup failures
|
||||
/// propagate; a filtered or unreadable historical value is not a first scan.
|
||||
/// Progress reads are bounded and optional, and never trigger object listing.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the persisted snapshot's read or decode error when neither copy
|
||||
/// supplies a usable baseline.
|
||||
pub async fn load_admin_usage_snapshot(store: Arc<ECStore>, buckets: &[String]) -> Result<AdminUsageSnapshot, Error> {
|
||||
let (raw, source) = load_data_usage_snapshot(store.clone()).await?;
|
||||
let certified = if source.is_authoritative() && (raw.is_completed_usage_baseline() || raw.has_usage_bootstrap_marker_shape())
|
||||
{
|
||||
load_certified_buckets(store.clone(), &raw).await
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
let history_available = certified.is_ok();
|
||||
let certified = certified.ok().flatten();
|
||||
let measured_names = buckets
|
||||
.iter()
|
||||
.filter(|bucket| {
|
||||
raw.buckets_usage.contains_key(*bucket)
|
||||
|| certified
|
||||
.as_ref()
|
||||
.is_some_and(|info| info.buckets_usage.contains_key(*bucket))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
let incarnations = current_admin_bucket_incarnations(
|
||||
store.clone(),
|
||||
measured_names,
|
||||
tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
// Check initial eligibility on unfiltered durable history. A timed-out or
|
||||
// unauthorized identity must never turn an existing row into a first scan.
|
||||
let mut initial_scan_progress = if history_available && initial_snapshot_available(&raw, source) {
|
||||
scan_progress::load_initial_bucket_scan_progress(store, buckets, &raw).await
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
let usage = project_completed_bucket_usage(raw, source, certified, &incarnations, buckets)?;
|
||||
initial_scan_progress.retain(|bucket, _| !usage.buckets_usage.contains_key(bucket));
|
||||
let mut unmeasured_buckets = buckets
|
||||
.iter()
|
||||
.filter(|bucket| !usage.buckets_usage.contains_key(*bucket))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
unmeasured_buckets.sort();
|
||||
unmeasured_buckets.dedup();
|
||||
Ok(AdminUsageSnapshot {
|
||||
usage,
|
||||
snapshot_view: true,
|
||||
initial_scan_progress,
|
||||
unmeasured_buckets,
|
||||
})
|
||||
}
|
||||
|
||||
/// Only a canonical complete root can vouch for a legacy row without an
|
||||
/// explicit certificate. A sidecar can vouch for a bucket independently of
|
||||
/// namespace completeness. Neither path admits observations or a memory overlay.
|
||||
fn project_completed_bucket_usage(
|
||||
mut usage: DataUsageInfo,
|
||||
source: UsageSnapshotSource,
|
||||
certified: Option<DataUsageInfo>,
|
||||
incarnations: &HashMap<String, String>,
|
||||
buckets: &[String],
|
||||
) -> Result<DataUsageInfo, Error> {
|
||||
use rustfs_data_usage::BucketUsageValueState::{Carried, Certified};
|
||||
let complete_root = source.is_authoritative() && usage.is_completed_usage_baseline();
|
||||
if !complete_root && !(source.is_authoritative() && usage.has_usage_bootstrap_marker_shape()) {
|
||||
return Ok(DataUsageInfo::default());
|
||||
}
|
||||
let allowed: HashSet<_> = buckets.iter().map(String::as_str).collect();
|
||||
let original_count = usage.buckets_usage.len();
|
||||
usage.buckets_usage.retain(|bucket, value| {
|
||||
incarnations
|
||||
.get(bucket)
|
||||
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
|
||||
&& complete_root
|
||||
&& match value.usage_value_state {
|
||||
Some(Certified | Carried) => value.usage_certification.is_some(),
|
||||
None => true,
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
let mut changed = usage.buckets_usage.len() != original_count;
|
||||
if let Some(certified) = certified {
|
||||
for (bucket, value) in certified.buckets_usage {
|
||||
if !incarnations
|
||||
.get(&bucket)
|
||||
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(next) = value.usage_certification else { continue };
|
||||
let previous = usage.buckets_usage.get(&bucket).and_then(|value| value.usage_certification);
|
||||
if previous.is_none_or(|old| (next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)) {
|
||||
usage.buckets_usage.insert(bucket, value);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Observations and legacy size-only maps cannot prove complete values for
|
||||
// the current incarnation. Never pass this derived view to quota admission.
|
||||
let pending_count = usage.usage_snapshot_pending_buckets.len();
|
||||
usage
|
||||
.usage_snapshot_pending_buckets
|
||||
.retain(|bucket| allowed.contains(bucket.as_str()));
|
||||
usage.usage_snapshot_pending_bucket_count =
|
||||
u64::try_from(usage.usage_snapshot_pending_buckets.len()).map_err(Error::other)?;
|
||||
changed |= pending_count != usage.usage_snapshot_pending_buckets.len()
|
||||
|| usage
|
||||
.bucket_sizes
|
||||
.keys()
|
||||
.any(|bucket| !usage.buckets_usage.contains_key(bucket))
|
||||
|| usage
|
||||
.usage_snapshot_bucket_observations
|
||||
.keys()
|
||||
.any(|bucket| !allowed.contains(bucket.as_str()));
|
||||
usage
|
||||
.usage_snapshot_noninitial_buckets
|
||||
.retain(|bucket, _| allowed.contains(bucket.as_str()));
|
||||
usage.usage_snapshot_bucket_observations.clear();
|
||||
refresh_completed_snapshot_totals(&mut usage, changed)?;
|
||||
Ok(usage)
|
||||
}
|
||||
|
||||
fn refresh_completed_snapshot_totals(usage: &mut DataUsageInfo, changed: bool) -> Result<(), Error> {
|
||||
if !usage.checked_calculate_totals() {
|
||||
return Err(Error::other("completed snapshot totals overflow"));
|
||||
}
|
||||
usage.buckets_count = u64::try_from(usage.buckets_usage.len()).map_err(Error::other)?;
|
||||
usage.bucket_sizes = usage
|
||||
.buckets_usage
|
||||
.iter()
|
||||
.map(|(name, bucket)| (name.clone(), bucket.size))
|
||||
.collect();
|
||||
if !changed {
|
||||
return Ok(());
|
||||
}
|
||||
usage.usage_snapshot_complete = false;
|
||||
usage.usage_snapshot_partial = true;
|
||||
usage.usage_snapshot_admin_projection = true;
|
||||
usage.usage_snapshot_converged = Some(false);
|
||||
usage.replication_info.clear();
|
||||
usage.tier_stats = None;
|
||||
usage.unknown_tier_stats = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_certified_buckets(store: Arc<ECStore>, baseline: &DataUsageInfo) -> Result<Option<DataUsageInfo>, Error> {
|
||||
let path = format!("buckets/{}", rustfs_data_usage::DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME);
|
||||
let bytes = match read_config_preserve_empty(store.clone(), &path).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(Error::ConfigNotFound) => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let info: DataUsageInfo = serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed-bucket snapshot"))?;
|
||||
if !info.is_certified_buckets_snapshot() {
|
||||
return Err(Error::other("unsupported completed-bucket snapshot"));
|
||||
}
|
||||
if !info.certified_buckets_match_baseline(baseline) {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = info
|
||||
.usage_snapshot_certified_buckets
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::other("missing completed-bucket scope"))?;
|
||||
let movement = store.scanner_durable_data_movement_generation().await;
|
||||
if movement != Some(scope.movement_generation) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut sources = Vec::new();
|
||||
for set in store.all_set_disks() {
|
||||
let Some(disks) = set.format.erasure.sets.get(set.set_index) else { return Ok(None) };
|
||||
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(set.format.id.as_bytes());
|
||||
for disk in disks {
|
||||
digest.update(disk.as_bytes());
|
||||
}
|
||||
sources.push(rustfs_data_usage::CertifiedBucketsSource {
|
||||
pool_index: u64::try_from(set.pool_index).map_err(Error::other)?,
|
||||
set_index: u64::try_from(set.set_index).map_err(Error::other)?,
|
||||
layout: digest.finalize().into(),
|
||||
});
|
||||
}
|
||||
sources.sort_by_key(|source| (source.pool_index, source.set_index));
|
||||
if sources != scope.sources || store.scanner_durable_data_movement_generation().await != movement {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(info))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_projection_recalculates_all_totals_without_refreshing_time() {
|
||||
let measured_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
|
||||
let mut usage = DataUsageInfo {
|
||||
last_update: Some(measured_at),
|
||||
usage_snapshot_complete: true,
|
||||
buckets_usage: HashMap::from([
|
||||
(
|
||||
"old".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 2,
|
||||
size: 20,
|
||||
versions_count: 4,
|
||||
delete_markers_count: 1,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"small".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 3,
|
||||
size: 30,
|
||||
versions_count: 5,
|
||||
delete_markers_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
refresh_completed_snapshot_totals(&mut usage, true).expect("valid complete buckets");
|
||||
assert_eq!(
|
||||
(
|
||||
usage.buckets_count,
|
||||
usage.objects_total_count,
|
||||
usage.objects_total_size,
|
||||
usage.versions_total_count,
|
||||
usage.delete_markers_total_count
|
||||
),
|
||||
(2, 5, 50, 9, 3)
|
||||
);
|
||||
assert_eq!(usage.bucket_sizes, HashMap::from([("old".into(), 20), ("small".into(), 30)]));
|
||||
assert_eq!(usage.last_update, Some(measured_at));
|
||||
assert!(!usage.usage_snapshot_complete);
|
||||
assert!(usage.usage_snapshot_admin_projection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_row_requires_a_healthy_persisted_namespace_baseline() {
|
||||
let time = SystemTime::UNIX_EPOCH;
|
||||
let id = uuid::Uuid::from_u128(1).to_string();
|
||||
let mut row = BucketUsageInfo {
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
size: 100,
|
||||
..Default::default()
|
||||
};
|
||||
row.certify(rustfs_data_usage::BucketUsageCertification {
|
||||
epoch: 0,
|
||||
cycle: 0,
|
||||
certified_at: time,
|
||||
});
|
||||
let raw = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_complete: true,
|
||||
buckets_usage: HashMap::from([("measured".into(), row)]),
|
||||
buckets_count: 1,
|
||||
objects_total_size: 100,
|
||||
..Default::default()
|
||||
};
|
||||
let current = HashMap::from([("measured".into(), id)]);
|
||||
for source in [UsageSnapshotSource::Primary, UsageSnapshotSource::Backup] {
|
||||
assert_eq!(
|
||||
project_completed_bucket_usage(raw.clone(), source, None, ¤t, &["measured".into()])
|
||||
.unwrap()
|
||||
.objects_total_size,
|
||||
100
|
||||
);
|
||||
}
|
||||
for invalid in [
|
||||
DataUsageInfo {
|
||||
usage_snapshot_complete: false,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_partial: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_observational: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_admin_projection: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
..raw.clone()
|
||||
},
|
||||
] {
|
||||
assert!(!initial_snapshot_available(&invalid, UsageSnapshotSource::Primary));
|
||||
let view =
|
||||
project_completed_bucket_usage(invalid, UsageSnapshotSource::Primary, None, ¤t, &["measured".into()])
|
||||
.unwrap();
|
||||
assert!(view.buckets_usage.is_empty());
|
||||
assert_eq!(view.objects_total_size, 0);
|
||||
}
|
||||
let legacy =
|
||||
project_completed_bucket_usage(raw, UsageSnapshotSource::LegacyPrimary, None, ¤t, &["measured".into()])
|
||||
.unwrap();
|
||||
assert!(legacy.buckets_usage.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_projection_rejects_counter_overflow() {
|
||||
let mut usage = DataUsageInfo {
|
||||
buckets_usage: HashMap::from([
|
||||
(
|
||||
"old".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: u64::MAX,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"small".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 1,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(refresh_completed_snapshot_totals(&mut usage, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_and_recovery_cannot_turn_missing_history_into_first_statistics() {
|
||||
let mut raw = DataUsageInfo {
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
|
||||
raw.usage_snapshot_initial_bootstrap = true;
|
||||
raw.usage_snapshot_initial_view_version = Some(1);
|
||||
assert!(initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
|
||||
for source in [
|
||||
UsageSnapshotSource::Backup,
|
||||
UsageSnapshotSource::LegacyPrimary,
|
||||
UsageSnapshotSource::LegacyBackup,
|
||||
UsageSnapshotSource::Missing,
|
||||
] {
|
||||
assert!(!initial_snapshot_available(&raw, source));
|
||||
}
|
||||
assert!(!initial_snapshot_available(&DataUsageInfo::default(), UsageSnapshotSource::Primary));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_progress_requires_absence_in_the_unfiltered_current_incarnation() {
|
||||
let incarnation = uuid::Uuid::from_u128(1);
|
||||
assert!(initial_progress_allowed(None, incarnation));
|
||||
let mut previous = BucketUsageInfo {
|
||||
bucket_incarnation: Some(incarnation.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
// Filtering this value, a new reader, or a leader handoff cannot make
|
||||
// the same persisted bucket a first scan again.
|
||||
previous.bucket_incarnation = None;
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some("invalid".into());
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some(uuid::Uuid::nil().to_string());
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some(uuid::Uuid::from_u128(2).to_string());
|
||||
assert!(initial_progress_allowed(Some(&previous), incarnation));
|
||||
assert!(!initial_progress_allowed(None, uuid::Uuid::nil()));
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
|
||||
let mut accidental_quota = HashMap::new();
|
||||
backfill_degraded_baseline_from_observed(&mut accidental_quota, &snapshot);
|
||||
assert!(accidental_quota.is_empty());
|
||||
assert!(reject_display_only_usage(&snapshot).is_err());
|
||||
assert!(reject_admin_usage_projection(&snapshot).is_err());
|
||||
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
|
||||
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
|
||||
assert_eq!(
|
||||
@@ -236,7 +236,7 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
|
||||
future
|
||||
}
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
let (dirs, store) = isolated_store_over_temp_disks().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let blocked = "usage-blocked-identity";
|
||||
let healthy = "usage-healthy-identity";
|
||||
@@ -260,6 +260,10 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
|
||||
canonical.usage_snapshot_pending_bucket_count = 2;
|
||||
canonical.buckets_count = 2;
|
||||
canonical.calculate_totals();
|
||||
let completed_at = canonical.usage_snapshot_bucket_observations[healthy].completed_at;
|
||||
let certificate = canonical.buckets_usage[healthy]
|
||||
.usage_certification
|
||||
.expect("persisted certificate");
|
||||
save_config(
|
||||
store.clone(),
|
||||
DATA_USAGE_OBJ_NAME_PATH.as_str(),
|
||||
@@ -276,6 +280,8 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
|
||||
)
|
||||
.await
|
||||
.expect("hold the real bucket metadata writer lock");
|
||||
let collected_at = SystemTime::now();
|
||||
assert!(collected_at > completed_at && completed_at > certificate.certified_at);
|
||||
let response = tokio::time::timeout(
|
||||
ADMIN_USAGE_INCARNATION_TIMEOUT + Duration::from_secs(3),
|
||||
assert_send(load_admin_data_usage_from_backend_cached(store.clone())),
|
||||
@@ -288,6 +294,9 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
|
||||
"an unavailable current identity cannot bind the canonical value"
|
||||
);
|
||||
assert!(!response.bucket_sizes.contains_key(blocked));
|
||||
assert!(!response.usage_snapshot_bucket_observations.contains_key(blocked));
|
||||
assert_eq!(response.usage_snapshot_bucket_observations[healthy].completed_at, completed_at);
|
||||
assert!(response.buckets_usage[healthy].usage_certification.is_none());
|
||||
assert_eq!(response.buckets_usage[healthy].size, 250);
|
||||
assert_eq!(response.buckets_usage[healthy].usage_value_state, Some(BucketUsageValueState::Observed));
|
||||
assert!(response.usage_snapshot_admin_projection);
|
||||
@@ -307,11 +316,32 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
|
||||
"unavailable identity can recover on a cache hit"
|
||||
);
|
||||
assert_eq!(recovered.buckets_usage[healthy].size, 250);
|
||||
for bucket in [blocked, healthy] {
|
||||
assert_eq!(recovered.usage_snapshot_bucket_observations[bucket].completed_at, completed_at);
|
||||
assert!(recovered.buckets_usage[bucket].usage_certification.is_none());
|
||||
}
|
||||
let quota = load_data_usage_from_backend_cached(store)
|
||||
.await
|
||||
.expect("separate canonical quota read");
|
||||
assert_eq!(quota.buckets_usage[blocked].size, 100);
|
||||
assert_eq!(quota.buckets_usage[healthy].size, 100);
|
||||
for bucket in [blocked, healthy] {
|
||||
assert_eq!(quota.buckets_usage[bucket].usage_certification, Some(certificate));
|
||||
}
|
||||
let evidence = serde_json::json!({
|
||||
"collection_started_at": collected_at, "persisted_observation_at": completed_at,
|
||||
"retained_certificate_at": certificate.certified_at, "blocked_bucket_unknown": true,
|
||||
});
|
||||
let paths: Vec<_> = dirs.iter().map(|dir| dir.path().to_path_buf()).collect();
|
||||
for dir in dirs {
|
||||
dir.close().expect("remove collector timeout fixture");
|
||||
}
|
||||
assert!(paths.iter().all(|path| !path.exists()));
|
||||
println!(
|
||||
"usage_assertion: {}",
|
||||
serde_json::json!({"case_id":"USAGE-18","assertion_id":"USAGE-18-A02","status":"PASS","evidence":evidence})
|
||||
);
|
||||
println!("usage_cleanup: {}", serde_json::json!({"case_id":"USAGE-18","status":"PASS"}));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
@@ -378,7 +408,7 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
|
||||
assert!(!second.bucket_sizes.contains_key(bucket));
|
||||
assert_eq!(second.usage_snapshot_converged, Some(false));
|
||||
assert!(second.usage_snapshot_admin_projection);
|
||||
assert!(reject_display_only_usage(&second).is_err());
|
||||
assert!(reject_admin_usage_projection(&second).is_err());
|
||||
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
|
||||
assert_eq!(
|
||||
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
|
||||
|
||||
@@ -1926,38 +1926,6 @@ impl LocalDiskWrapper {
|
||||
.map_err(DiskError::Io)
|
||||
}
|
||||
|
||||
pub(crate) async fn advance_background_delete_discovery(
|
||||
&self,
|
||||
volume: String,
|
||||
session: Option<super::local::DiscoverySession>,
|
||||
limit: u32,
|
||||
cancel: CancellationToken,
|
||||
) -> Result<(Vec<super::DeleteTransactionId>, Option<super::local::DiscoverySession>)> {
|
||||
self.check_scanner_handle()?;
|
||||
let retired = self.retirement_token();
|
||||
// A queued bucket lease must not occupy the only background disk slot.
|
||||
let lease = self.disk.lock_delete_discovery_bucket(&volume).await?;
|
||||
let disk = Arc::clone(&self.disk);
|
||||
super::with_background_disk_io(
|
||||
cancel.clone(),
|
||||
self.track_disk_health_with_op_timeout_action_and_mutation_with_io_permit(
|
||||
"discover_delete_transactions",
|
||||
|permit| async move {
|
||||
super::io_admission::spawn_blocking_with_disk_io_permit(permit, move || {
|
||||
let _lease = lease;
|
||||
disk.advance_background_delete_discovery(&volume, session, limit, &cancel, &retired)
|
||||
})
|
||||
.await
|
||||
.map_err(DiskError::other)?
|
||||
},
|
||||
Duration::ZERO,
|
||||
TimeoutHealthAction::IgnoreFailure,
|
||||
DiskMetricMutation::None,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
|
||||
self.disk.get_object_path(volume, path)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ use self::commit::lock_rename_commit_directories;
|
||||
|
||||
mod commit;
|
||||
pub(super) mod delete_recovery;
|
||||
pub(crate) use delete_recovery::DiscoverySession;
|
||||
mod delete_reserve;
|
||||
#[cfg(all(unix, test))]
|
||||
#[path = "fd_cache_tests.rs"]
|
||||
@@ -132,12 +131,26 @@ const PART_METADATA_READ_CONCURRENCY: usize = 8;
|
||||
const DELETE_VERSION_PREPARE_CONCURRENCY: usize = 8;
|
||||
|
||||
fn delete_version_batch_concurrency(versions: &[FileInfoVersions], opts: &DeleteOptions) -> usize {
|
||||
if !cfg!(target_os = "linux") || !opts.recoverable_delete || opts.undo_write || opts.undo_delete || versions.len() < 2 {
|
||||
if !cfg!(any(target_os = "linux", target_os = "macos"))
|
||||
|| !opts.recoverable_delete
|
||||
|| opts.undo_write
|
||||
|| opts.undo_delete
|
||||
|| versions.len() < 2
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
let mut names = HashSet::with_capacity(versions.len());
|
||||
for version in versions {
|
||||
let name = version.name.as_str();
|
||||
// A macOS volume may fold case and normalize Unicode. Only schedule
|
||||
// names from an unambiguous on-disk alphabet concurrently there.
|
||||
#[cfg(target_os = "macos")]
|
||||
if !name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'/' | b'.' | b'-' | b'_'))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if name.split('/').any(|segment| matches!(segment, "" | "." | "..")) || !names.insert(name) {
|
||||
return 1;
|
||||
}
|
||||
@@ -10305,7 +10318,14 @@ impl LocalDisk {
|
||||
|
||||
if fi.deleted && force_del_marker {
|
||||
return self
|
||||
.write_missing_delete_marker(volume, path, fi, file_path.as_path(), &opts, namespace_owner.clone())
|
||||
.write_missing_delete_markers(
|
||||
volume,
|
||||
path,
|
||||
std::slice::from_ref(&fi),
|
||||
file_path.as_path(),
|
||||
&opts,
|
||||
namespace_owner.clone(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
@@ -11954,11 +11974,11 @@ impl LocalDisk {
|
||||
Ok((bytes, modtime))
|
||||
}
|
||||
|
||||
async fn write_missing_delete_marker(
|
||||
async fn write_missing_delete_markers(
|
||||
&self,
|
||||
volume: &str,
|
||||
path: &str,
|
||||
fi: FileInfo,
|
||||
markers: &[FileInfo],
|
||||
object_dir: &Path,
|
||||
opts: &DeleteOptions,
|
||||
namespace_owner: Option<Arc<dyn Send + Sync>>,
|
||||
@@ -11974,6 +11994,9 @@ impl LocalDisk {
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(to_file_error(err).into()),
|
||||
}
|
||||
for marker in markers {
|
||||
marker.validate_for_metadata_read()?;
|
||||
}
|
||||
let mut recovery_target = None;
|
||||
if let Some(rollback_dir) = rollback_dir {
|
||||
if opts.recoverable_delete {
|
||||
@@ -11982,7 +12005,7 @@ impl LocalDisk {
|
||||
volume,
|
||||
path,
|
||||
None,
|
||||
std::slice::from_ref(&fi),
|
||||
markers,
|
||||
None,
|
||||
delete_recovery::DeletePreparationContext {
|
||||
transaction: rollback_dir,
|
||||
@@ -12004,23 +12027,32 @@ impl LocalDisk {
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let committed = if let Some(target) = recovery_target {
|
||||
async {
|
||||
fi.validate_for_metadata_read()?;
|
||||
self.write_all_meta_with_namespace_owner(
|
||||
volume,
|
||||
&format!("{path}/{STORAGE_FORMAT_FILE}"),
|
||||
target.into(),
|
||||
true,
|
||||
namespace_owner.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
let committed = async {
|
||||
let target = match (recovery_target, markers) {
|
||||
(Some(target), _) => target,
|
||||
(None, [marker]) => {
|
||||
return self
|
||||
.write_metadata_with_namespace_owner(volume, path, marker.clone(), namespace_owner.clone())
|
||||
.await;
|
||||
}
|
||||
(None, _) => {
|
||||
let mut meta = FileMeta::new();
|
||||
for marker in markers {
|
||||
meta.add_version(marker.clone())?;
|
||||
}
|
||||
meta.marshal_msg()?
|
||||
}
|
||||
};
|
||||
self.write_all_meta_with_namespace_owner(
|
||||
volume,
|
||||
&format!("{path}/{STORAGE_FORMAT_FILE}"),
|
||||
target.into(),
|
||||
true,
|
||||
namespace_owner.clone(),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
self.write_metadata_with_namespace_owner(volume, path, fi, namespace_owner.clone())
|
||||
.await
|
||||
};
|
||||
}
|
||||
.await;
|
||||
if let Err(err) = committed {
|
||||
if let Some(rollback_dir) = rollback_dir
|
||||
&& let Err(restore_err) = restore_delete_rollback_with_namespace_owner(
|
||||
@@ -12139,11 +12171,12 @@ impl LocalDisk {
|
||||
.await;
|
||||
// `deleted` alone can be an explicit marker purge; only
|
||||
// `mark_deleted` may create metadata that was not present.
|
||||
let Some(delete_marker) = fis.iter().find(|fi| fi.deleted && fi.mark_deleted).cloned() else {
|
||||
let markers: Vec<_> = fis.iter().filter(|fi| fi.deleted && fi.mark_deleted).cloned().collect();
|
||||
if markers.is_empty() {
|
||||
return Err(DiskError::FileNotFound);
|
||||
};
|
||||
}
|
||||
return self
|
||||
.write_missing_delete_marker(volume, path, delete_marker, object_dir, opts, namespace_owner.clone())
|
||||
.write_missing_delete_markers(volume, path, &markers, object_dir, opts, namespace_owner.clone())
|
||||
.await;
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
@@ -15254,11 +15287,12 @@ async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -
|
||||
metrics.as_deref(),
|
||||
LocalBatchReadStage::Read,
|
||||
|| {
|
||||
// Preload the requested window before reading it. Kernel
|
||||
// readahead is advisory and may still extend past the
|
||||
// window, so the tail is reclaimed after the read below.
|
||||
// Preload just this window. Disable automatic readahead
|
||||
// on this descriptor so pread does not start a second
|
||||
// read past the window while the explicit hint is in flight.
|
||||
#[cfg(target_os = "linux")]
|
||||
if let (Ok(start), Ok(len)) = (u64::try_from(offset), u64::try_from(length)) {
|
||||
let _ = rustix::fs::fadvise(&file, 0, None, rustix::fs::Advice::Random);
|
||||
let _ = rustix::fs::fadvise(
|
||||
&file,
|
||||
start,
|
||||
@@ -18065,7 +18099,7 @@ impl DiskAPI for LocalDisk {
|
||||
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
async fn update_metadata(&self, volume: &str, path: &str, fi: FileInfo, opts: &UpdateMetadataOpts) -> Result<()> {
|
||||
let status_only_candidate = super::usage_watch::status_only_metadata_candidate(&fi, opts);
|
||||
let status_only = super::usage_watch::status_only_metadata_update(&fi, opts);
|
||||
multipart_staging::reject_native_control_write(&self.root, self.io_root(), volume, path)?;
|
||||
pool_meta_native::reject_raw_path(&self.root, volume, path)?;
|
||||
let object_path = self.get_object_path(volume, path)?;
|
||||
@@ -18085,9 +18119,7 @@ impl DiskAPI for LocalDisk {
|
||||
.await;
|
||||
}
|
||||
let source_owner = self.multipart_source_owner(volume, path, false, true, None).await?;
|
||||
// A status-only candidate takes usage ownership below, once the stored
|
||||
// version shows whether the update changes anything usage observes.
|
||||
let source_owner = if status_only_candidate {
|
||||
let source_owner = if status_only {
|
||||
source_owner
|
||||
} else {
|
||||
self.usage_watch_binding.owner(volume, source_owner)
|
||||
@@ -18120,8 +18152,6 @@ impl DiskAPI for LocalDisk {
|
||||
let replace_user_metadata = opts.replace_user_metadata;
|
||||
let has_version_id = fi.version_id.is_some();
|
||||
let publication_root = self.publication_root.clone();
|
||||
let usage_watch_binding = Arc::clone(&self.usage_watch_binding);
|
||||
let usage_bucket = volume.to_string();
|
||||
let lease = os::acquire_namespace_mutation_lease_with_owner(&xl_file_path, namespace_owner).await;
|
||||
return os::run_blocking_namespace_operation_with_sync(
|
||||
lease,
|
||||
@@ -18137,20 +18167,13 @@ impl DiskAPI for LocalDisk {
|
||||
if !FileMeta::is_xl2_v1_format(&buf) {
|
||||
return Ok(Err(DiskError::FileVersionNotFound));
|
||||
}
|
||||
let (wbuf, status_only) = match FileMeta::load(&buf).and_then(|mut xl_meta| {
|
||||
let stored = status_only_candidate.then(|| xl_meta.clone());
|
||||
let wbuf = match FileMeta::load(&buf).and_then(|mut xl_meta| {
|
||||
xl_meta.update_object_version_with_opts(fi, replace_user_metadata)?;
|
||||
let status_only =
|
||||
stored.is_some_and(|stored| super::usage_watch::status_only_metadata_change(&stored, &xl_meta));
|
||||
Ok((xl_meta.marshal_msg()?, status_only))
|
||||
xl_meta.marshal_msg()
|
||||
}) {
|
||||
Ok(update) => update,
|
||||
Ok(wbuf) => wbuf,
|
||||
Err(err) => return Ok(Err(err.into())),
|
||||
};
|
||||
// Held until the rename below has finished.
|
||||
let _usage_owner = (status_only_candidate && !status_only)
|
||||
.then(|| usage_watch_binding.owner(&usage_bucket, None))
|
||||
.flatten();
|
||||
if let Some(parent) = tmp_file_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -18188,16 +18211,9 @@ impl DiskAPI for LocalDisk {
|
||||
}
|
||||
|
||||
let mut xl_meta = FileMeta::load(buf.as_ref())?;
|
||||
let stored = status_only_candidate.then(|| xl_meta.clone());
|
||||
|
||||
xl_meta.update_object_version_with_opts(fi, opts.replace_user_metadata)?;
|
||||
|
||||
let namespace_owner = match stored {
|
||||
Some(stored) if !super::usage_watch::status_only_metadata_change(&stored, &xl_meta) => {
|
||||
self.usage_watch_binding.owner(volume, namespace_owner)
|
||||
}
|
||||
_ => namespace_owner,
|
||||
};
|
||||
let wbuf = xl_meta.marshal_msg()?;
|
||||
|
||||
return self
|
||||
|
||||
@@ -31,26 +31,13 @@ pub(super) const PREPARED: &str = "delete-prepared";
|
||||
pub(super) const TARGET: &str = "delete-target";
|
||||
pub(super) const FINISHED: &str = "delete-commit-finished";
|
||||
const MAX_METADATA: u64 = 64 * 1024 * 1024;
|
||||
#[cfg(target_os = "linux")]
|
||||
type DiscoveryEntries = rustix::fs::Dir;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
type DiscoveryEntries = std::fs::ReadDir;
|
||||
|
||||
#[cfg(any(test, not(target_os = "linux")))]
|
||||
fn open_discovery_entries(path: &Path) -> std::io::Result<DiscoveryEntries> {
|
||||
#[cfg(target_os = "linux")]
|
||||
return rustix::fs::Dir::new(open_dir_fd(path)?).map_err(std::io::Error::from);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
std::fs::read_dir(path)
|
||||
}
|
||||
|
||||
pub(crate) struct DiscoverySession {
|
||||
struct DiscoverySession {
|
||||
disk_root: PathBuf,
|
||||
volume: String,
|
||||
object: Option<String>,
|
||||
root: PathBuf,
|
||||
_mount: std::fs::File,
|
||||
frames: Vec<(String, DiscoveryEntries)>,
|
||||
frames: Vec<(String, std::fs::ReadDir)>,
|
||||
touched: Instant,
|
||||
#[cfg(test)]
|
||||
metadata_stats: Arc<std::sync::atomic::AtomicUsize>,
|
||||
@@ -65,7 +52,6 @@ const PLAIN_CHILDREN_PER_BUDGET_ENTRY: u32 = 64;
|
||||
/// Entries one step of the resumable (background) discovery may visit. The
|
||||
/// foreground bounded protocol has its own, larger per-call allowance.
|
||||
const DISCOVERY_STEP_ENTRIES: u32 = 4096;
|
||||
const BACKGROUND_DISCOVERY_SLICE: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Wall-clock allowance of one bounded discovery call: a third of the drive
|
||||
/// timeout that wraps the call (including its wait for a lane worker), capped at
|
||||
@@ -104,23 +90,8 @@ impl DiscoverySession {
|
||||
max_entries: u32,
|
||||
should_stop: &dyn Fn() -> bool,
|
||||
) -> std::io::Result<(Vec<DeleteTransactionId>, Option<Self>, u32)> {
|
||||
if should_stop() {
|
||||
return Ok((Vec::new(), Some(self), 0));
|
||||
}
|
||||
if self.frames.is_empty() {
|
||||
#[cfg(target_os = "linux")]
|
||||
let entries = {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
let mut relative = PathBuf::from(&self.volume);
|
||||
if let Some(object) = &self.object {
|
||||
relative.push(object);
|
||||
}
|
||||
os::open_linux_relative(&self._mount, &relative, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty())
|
||||
.and_then(|fd| rustix::fs::Dir::new(fd).map_err(std::io::Error::from))
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let entries = open_discovery_entries(&self.root);
|
||||
match entries {
|
||||
match std::fs::read_dir(&self.root) {
|
||||
Ok(entries) => self.frames.push((String::new(), entries)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {
|
||||
return Ok((Vec::new(), None, 0));
|
||||
@@ -128,14 +99,15 @@ impl DiscoverySession {
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let limit = usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?;
|
||||
let mut transactions = BTreeSet::new();
|
||||
let mut seen_candidates = HashSet::new();
|
||||
let mut visited = 0u32;
|
||||
let mut skipped_by_name = 0u32;
|
||||
while !self.frames.is_empty() && transactions.len() < limit && visited < max_entries && !should_stop() {
|
||||
// A valid 1024-byte key can exceed 256 one-byte components.
|
||||
let can_descend = self.frames.len() < 1024;
|
||||
while !self.frames.is_empty()
|
||||
&& transactions.len() < usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?
|
||||
&& visited < max_entries
|
||||
&& !should_stop()
|
||||
{
|
||||
let (parent, entries) = self
|
||||
.frames
|
||||
.last_mut()
|
||||
@@ -147,17 +119,11 @@ impl DiscoverySession {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let name = entry.file_name();
|
||||
#[cfg(target_os = "linux")]
|
||||
if matches!(name.to_bytes(), b"." | b"..") {
|
||||
continue;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
let name = name.to_str().ok();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let name = name.to_str();
|
||||
let name = name.ok_or_else(|| std::io::Error::from(ErrorKind::InvalidData))?;
|
||||
if !safe_path(name, false) || name.contains('/') {
|
||||
let name = entry
|
||||
.file_name()
|
||||
.into_string()
|
||||
.map_err(|_| std::io::Error::from(ErrorKind::InvalidData))?;
|
||||
if !safe_path(&name, false) || name.contains('/') {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
// An object-scoped scan only ever descends into transaction (UUID)
|
||||
@@ -170,9 +136,9 @@ impl DiscoverySession {
|
||||
// folder prefix with many children, UUID-named or not, can complete.
|
||||
if self.object.is_some()
|
||||
&& if parent.is_empty() {
|
||||
!canonical_uuid(name).is_some_and(|id| !id.is_nil())
|
||||
!canonical_uuid(&name).is_some_and(|id| !id.is_nil())
|
||||
} else {
|
||||
!may_be_delete_evidence(name)
|
||||
!may_be_delete_evidence(&name)
|
||||
}
|
||||
{
|
||||
skipped_by_name += 1;
|
||||
@@ -182,186 +148,115 @@ impl DiscoverySession {
|
||||
continue;
|
||||
}
|
||||
visited += 1;
|
||||
#[cfg(target_os = "linux")]
|
||||
let is_dir = {
|
||||
use rustix::fs::{AtFlags, FileType, statat};
|
||||
|
||||
let kind = entry.file_type();
|
||||
#[cfg(test)]
|
||||
let kind = if FORCE_RAW_DIR_DT_UNKNOWN.with(std::cell::Cell::get) {
|
||||
FileType::Unknown
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
let kind = if kind == FileType::Unknown {
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
match statat(entries.fd()?, entry.file_name(), AtFlags::SYMLINK_NOFOLLOW) {
|
||||
Ok(stat) => FileType::from_raw_mode(stat.st_mode),
|
||||
Err(rustix::io::Errno::NOENT) => continue,
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
match kind {
|
||||
FileType::Directory => true,
|
||||
FileType::RegularFile => false,
|
||||
FileType::Symlink => return Err(std::io::Error::from(DiskError::InvalidPath)),
|
||||
_ => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let is_dir = {
|
||||
if self.object.is_none() && !may_be_delete_evidence(name) {
|
||||
let kind = match entry.file_type() {
|
||||
Ok(kind) => kind,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if kind.is_file() {
|
||||
continue;
|
||||
}
|
||||
if kind.is_symlink() {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
if !kind.is_dir() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
}
|
||||
|
||||
let path = self.root.join(parent.as_str()).join(name);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.is_dir() => true,
|
||||
Ok(metadata) if metadata.is_file() => false,
|
||||
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
if self.object.is_none() && !may_be_delete_evidence(&name) {
|
||||
let ft = match entry.file_type() {
|
||||
Ok(ft) => ft,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if ft.is_symlink() {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
};
|
||||
|
||||
if is_dir {
|
||||
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(name).is_some_and(|id| !id.is_nil())) {
|
||||
continue;
|
||||
}
|
||||
if !can_descend {
|
||||
if !ft.is_dir() && !ft.is_file() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
let relative = if parent.is_empty() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{parent}/{name}")
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let child = {
|
||||
use rustix::fs::{Mode, OFlags, openat};
|
||||
match openat(
|
||||
entries.fd()?,
|
||||
entry.file_name(),
|
||||
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
) {
|
||||
Ok(fd) => rustix::fs::Dir::new(fd).map_err(std::io::Error::from),
|
||||
Err(rustix::io::Errno::NOTDIR | rustix::io::Errno::LOOP) => {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let child = open_discovery_entries(&self.root.join(&relative));
|
||||
match child {
|
||||
Ok(entries) => self.frames.push((relative, entries)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if !may_be_delete_evidence(name) {
|
||||
// Ordinary data and metadata files cannot contribute a recovery hint.
|
||||
continue;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// Keep canonical, live-path validation for the sparse proof candidates.
|
||||
let path = self.root.join(parent.as_str()).join(name);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.is_file() => {}
|
||||
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
if ft.is_file() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let bound = match self.object.as_deref() {
|
||||
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
|
||||
Some(_) => None,
|
||||
None => parent.rsplit_once('/'),
|
||||
let relative = if parent.is_empty() {
|
||||
name.clone()
|
||||
} else {
|
||||
format!("{parent}/{name}")
|
||||
};
|
||||
if let Some((object, id)) = bound {
|
||||
let transaction = if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name) {
|
||||
canonical_uuid(id).filter(|id| !id.is_nil())
|
||||
} else {
|
||||
[
|
||||
DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
]
|
||||
.iter()
|
||||
.find_map(|prefix| delete_transaction_marker_id(name, prefix))
|
||||
let path = self.root.join(&relative);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
let kind = match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if !kind.is_dir() && !kind.is_file() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
if kind.is_file() {
|
||||
let bound = match self.object.as_deref() {
|
||||
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
|
||||
Some(_) => None,
|
||||
None => parent.rsplit_once('/'),
|
||||
};
|
||||
if let Some(transaction) = transaction {
|
||||
if !seen_candidates.insert((object.to_owned(), transaction)) {
|
||||
continue;
|
||||
if let Some((object, id)) = bound {
|
||||
let transaction =
|
||||
if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name.as_str()) {
|
||||
canonical_uuid(id).filter(|id| !id.is_nil())
|
||||
} else {
|
||||
[
|
||||
DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
]
|
||||
.iter()
|
||||
.find_map(|prefix| delete_transaction_marker_id(&name, prefix))
|
||||
};
|
||||
if let Some(transaction) = transaction {
|
||||
if !seen_candidates.insert((object.to_owned(), transaction)) {
|
||||
continue;
|
||||
}
|
||||
let physical = match self.object.as_ref() {
|
||||
Some(_) => self.root.clone(),
|
||||
None => self.root.join(object),
|
||||
};
|
||||
if name == STORAGE_FORMAT_FILE_BACKUP
|
||||
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let proof_root = physical.join(transaction.to_string());
|
||||
if self.object.is_some() {
|
||||
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
|
||||
transactions.insert((object.to_owned(), transaction));
|
||||
continue;
|
||||
}
|
||||
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
// Only a fully bound journal can name a logical
|
||||
// key. Other records remain discoverable by their
|
||||
// physical key for canonical inspection to reject.
|
||||
let record = match prepared {
|
||||
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
|
||||
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
|
||||
.map_err(std::io::Error::from)?
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
|
||||
.map(|receipt| receipt.journal),
|
||||
};
|
||||
let logical = record
|
||||
.filter(|journal| {
|
||||
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
|
||||
&& journal.volume == self.volume
|
||||
&& journal.transaction == transaction
|
||||
&& safe_path(&journal.object, false)
|
||||
&& match self.object.as_ref() {
|
||||
Some(scope) => scope == &journal.object,
|
||||
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
|
||||
}
|
||||
})
|
||||
.map_or_else(|| object.to_owned(), |journal| journal.object);
|
||||
transactions.insert((logical, transaction));
|
||||
}
|
||||
let physical = match self.object.as_ref() {
|
||||
Some(_) => self.root.clone(),
|
||||
None => self.root.join(object),
|
||||
};
|
||||
if name == STORAGE_FORMAT_FILE_BACKUP
|
||||
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let proof_root = physical.join(transaction.to_string());
|
||||
if self.object.is_some() {
|
||||
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
|
||||
transactions.insert((object.to_owned(), transaction));
|
||||
continue;
|
||||
}
|
||||
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
// Only a fully bound journal can name a logical
|
||||
// key. Other records remain discoverable by their
|
||||
// physical key for canonical inspection to reject.
|
||||
let record = match prepared {
|
||||
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
|
||||
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
|
||||
.map_err(std::io::Error::from)?
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
|
||||
.map(|receipt| receipt.journal),
|
||||
};
|
||||
let logical = record
|
||||
.filter(|journal| {
|
||||
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
|
||||
&& journal.volume == self.volume
|
||||
&& journal.transaction == transaction
|
||||
&& safe_path(&journal.object, false)
|
||||
&& match self.object.as_ref() {
|
||||
Some(scope) => scope == &journal.object,
|
||||
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
|
||||
}
|
||||
})
|
||||
.map_or_else(|| object.to_owned(), |journal| journal.object);
|
||||
transactions.insert((logical, transaction));
|
||||
}
|
||||
} else {
|
||||
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(&name).is_some_and(|id| !id.is_nil())) {
|
||||
continue;
|
||||
}
|
||||
// A valid 1024-byte key can exceed 256 one-byte path
|
||||
// components; allow its transaction/data directories too.
|
||||
if self.frames.len() >= 1024 {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
self.frames.push((relative, std::fs::read_dir(path)?));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,9 +274,10 @@ impl DiscoverySession {
|
||||
if !transactions.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(next) = next else {
|
||||
let Some(mut next) = next else {
|
||||
return Ok(false);
|
||||
};
|
||||
next.touched = Instant::now();
|
||||
self = next;
|
||||
}
|
||||
}
|
||||
@@ -2030,40 +1926,23 @@ impl LocalDisk {
|
||||
.await
|
||||
.map_err(to_file_error)?
|
||||
}
|
||||
pub(crate) async fn lock_delete_discovery_bucket(&self, volume: &str) -> Result<Arc<os::NamespaceMutationLease>> {
|
||||
if !safe_path(volume, false) || volume.contains('/') {
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
let path = build_local_disk_bucket_path(self.io_root(), volume);
|
||||
Ok(os::acquire_namespace_mutation_lease_with_owner(&path, None).await)
|
||||
}
|
||||
|
||||
pub(in crate::disk) fn advance_background_delete_discovery(
|
||||
&self,
|
||||
volume: &str,
|
||||
session: Option<DiscoverySession>,
|
||||
limit: u32,
|
||||
cancel: &tokio_util::sync::CancellationToken,
|
||||
retired: &tokio_util::sync::CancellationToken,
|
||||
) -> Result<(Vec<DeleteTransactionId>, Option<DiscoverySession>)> {
|
||||
if retired.is_cancelled() {
|
||||
return Err(DiskError::DiskNotFound);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Ok((Vec::new(), session));
|
||||
}
|
||||
let path = self.delete_discovery_path(volume, None)?;
|
||||
let session = match session {
|
||||
Some(session) => session,
|
||||
None => self.new_delete_discovery_session(volume, None, &path)?,
|
||||
/// Local maintenance may pause a page behind recovery backpressure. It
|
||||
/// retains only its own bounded set of cursors; remote callers still have
|
||||
/// the ordinary idle deadline and every resumed page rechecks mount identity.
|
||||
pub(crate) fn renew_delete_recovery_cursor(&self, volume: &str, cursor: &DeleteRecoveryCursor) -> bool {
|
||||
let mut sessions = DISCOVERY_SESSIONS.lock();
|
||||
let Some(session) = sessions.get_mut(&cursor.token) else {
|
||||
return false;
|
||||
};
|
||||
self.validate_delete_discovery_owner(&session)?;
|
||||
let deadline = Instant::now() + BACKGROUND_DISCOVERY_SLICE;
|
||||
let should_stop = || cancel.is_cancelled() || retired.is_cancelled() || Instant::now() >= deadline;
|
||||
let (transactions, next, _) = session
|
||||
.advance_bounded(limit, DISCOVERY_STEP_ENTRIES, &should_stop)
|
||||
.map_err(to_file_error)?;
|
||||
Ok((transactions, next))
|
||||
if session.disk_root != self.io_root()
|
||||
|| session.volume != volume
|
||||
|| session.object.is_some()
|
||||
|| session.touched.elapsed() > Duration::from_secs(300)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
session.touched = Instant::now();
|
||||
true
|
||||
}
|
||||
|
||||
fn delete_discovery_path(&self, volume: &str, object: Option<&str>) -> Result<PathBuf> {
|
||||
@@ -2119,7 +1998,7 @@ impl LocalDisk {
|
||||
}
|
||||
|
||||
fn validate_delete_discovery_owner(&self, session: &DiscoverySession) -> Result<()> {
|
||||
if session.disk_root != self.io_root() {
|
||||
if session.disk_root != self.io_root() || session.touched.elapsed() > Duration::from_secs(300) {
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
@@ -2213,10 +2092,7 @@ impl LocalDisk {
|
||||
.lock()
|
||||
.remove(&cursor.token)
|
||||
.ok_or(DiskError::FileNotFound)?;
|
||||
if session.volume != volume
|
||||
|| session.object.as_deref() != object
|
||||
|| session.touched.elapsed() > Duration::from_secs(300)
|
||||
{
|
||||
if session.volume != volume || session.object.as_deref() != object {
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
(cursor.token, session)
|
||||
@@ -4757,6 +4633,12 @@ mod tests {
|
||||
vec!["a//b", "a/b"],
|
||||
vec!["a/./b", "a/b"],
|
||||
vec!["a/../b", "b"],
|
||||
#[cfg(target_os = "macos")]
|
||||
vec!["object", "OBJECT"],
|
||||
#[cfg(target_os = "macos")]
|
||||
vec!["prefix", "Prefix/child"],
|
||||
#[cfg(target_os = "macos")]
|
||||
vec!["café", "cafe\u{301}"],
|
||||
] {
|
||||
let groups: Vec<_> = names
|
||||
.into_iter()
|
||||
@@ -4778,7 +4660,7 @@ mod tests {
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let expected = if cfg!(target_os = "linux") {
|
||||
let expected = if cfg!(any(target_os = "linux", target_os = "macos")) {
|
||||
super::super::DELETE_VERSION_PREPARE_CONCURRENCY
|
||||
} else {
|
||||
1
|
||||
@@ -4803,7 +4685,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_batch_prepares_independent_keys_while_one_metadata_lease_is_held() {
|
||||
let (temp, disk, info, _) = fixture().await;
|
||||
@@ -4820,7 +4702,8 @@ mod tests {
|
||||
fs::write(corrupt_root.join(STORAGE_FORMAT_FILE), b"invalid xl.meta")
|
||||
.await
|
||||
.expect("corrupt source");
|
||||
let held = os::acquire_metadata_mutation_lease(&temp.path().join("recovery/object"), None).await;
|
||||
let object_path = disk.get_object_path("recovery", "object").expect("object mutation path");
|
||||
let held = os::acquire_metadata_mutation_lease(&object_path, None).await;
|
||||
let groups = ["object", "corrupt", "healthy"]
|
||||
.into_iter()
|
||||
.map(|name| super::super::FileInfoVersions {
|
||||
@@ -7864,6 +7747,10 @@ mod tests {
|
||||
.expect("bounded discovery continues");
|
||||
found.extend(page.transactions.into_iter().map(|id| (id.object, id.transaction)));
|
||||
cursor = page.next;
|
||||
if let Some(cursor) = cursor.as_ref() {
|
||||
assert!(!disk.renew_delete_recovery_cursor("different-bucket", cursor));
|
||||
assert!(disk.renew_delete_recovery_cursor("recovery", cursor));
|
||||
}
|
||||
if cursor.is_none() {
|
||||
break;
|
||||
}
|
||||
@@ -8444,8 +8331,8 @@ mod tests {
|
||||
// Seed a valid DFS continuation so this assertion is independent of
|
||||
// filesystem directory ordering: the large empty frame runs first.
|
||||
session.frames = vec![
|
||||
(transaction.to_string(), open_discovery_entries(&proof).expect("later evidence frame")),
|
||||
(filler_id, open_discovery_entries(&filler).expect("empty intermediate frame")),
|
||||
(transaction.to_string(), std::fs::read_dir(&proof).expect("later evidence frame")),
|
||||
(filler_id, std::fs::read_dir(&filler).expect("empty intermediate frame")),
|
||||
];
|
||||
assert!(
|
||||
session
|
||||
@@ -9052,23 +8939,6 @@ mod tests {
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let prefix = temp.path().join("recovery/prefix");
|
||||
fs::create_dir_all(prefix.join("key")).await.expect("object directory");
|
||||
fs::create_dir(outside.path().join("key"))
|
||||
.await
|
||||
.expect("outside object directory");
|
||||
let path = disk
|
||||
.delete_discovery_path("recovery", Some("prefix/key"))
|
||||
.expect("validated key path");
|
||||
let session = disk
|
||||
.new_delete_discovery_session("recovery", Some("prefix/key"), &path)
|
||||
.expect("unopened key session");
|
||||
fs::remove_dir_all(&prefix).await.expect("remove original prefix");
|
||||
symlink(outside.path(), &prefix).expect("replace a parent after validation");
|
||||
assert!(session.advance(16).is_err(), "the real root open must reject a replaced ancestor");
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(outside.path().join("sentinel"))
|
||||
.await
|
||||
@@ -9102,36 +8972,13 @@ mod tests {
|
||||
assert!(transactions.is_empty());
|
||||
assert!(next.is_none());
|
||||
let stats = stats_counter.load(Ordering::Relaxed);
|
||||
// The fixture has 65 directories and 65 regular files. An ordinary
|
||||
// Linux walk uses d_type and opens directories relative to the parent FD.
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let expected = match open_discovery_entries(&bucket_root).expect("read dirents").find_map(|entry| {
|
||||
let entry = entry.expect("dirent");
|
||||
(!matches!(entry.file_name().to_bytes(), b"." | b"..")).then(|| entry.file_type())
|
||||
}) {
|
||||
Some(rustix::fs::FileType::Unknown) => 130,
|
||||
Some(_) => 0,
|
||||
None => panic!("the fixture contains directories"),
|
||||
};
|
||||
assert_eq!(stats, expected, "known directory types must skip path-based metadata checks");
|
||||
|
||||
let session = disk
|
||||
.new_delete_discovery_session("recovery", None, &disc_path)
|
||||
.expect("discovery session with unknown dirent types");
|
||||
let fallback_stats = Arc::clone(&session.metadata_stats);
|
||||
let result = FORCE_RAW_DIR_DT_UNKNOWN.with(|flag| {
|
||||
let previous = flag.replace(true);
|
||||
let result = session.advance(16);
|
||||
flag.set(previous);
|
||||
result
|
||||
});
|
||||
let (transactions, next) = result.expect("unknown directory types use no-follow statat");
|
||||
assert!(transactions.is_empty() && next.is_none());
|
||||
assert_eq!(fallback_stats.load(Ordering::Relaxed), 130, "one parent-relative stat per unknown entry");
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
assert_eq!(stats, 65, "the portable walk skips metadata checks for ordinary files");
|
||||
// fixture() pre-creates recovery/object (1 directory + 1 xl.meta); with 32 obj-XX + 32 data_dir directories,
|
||||
// only the 65 directories reach symlink_metadata, while all 65 regular files (xl.meta and part.1) are skipped
|
||||
// via DirEntry::file_type() with 0 stats.
|
||||
assert_eq!(
|
||||
stats, 65,
|
||||
"bucket-wide discovery must skip inert regular files without symlink_metadata stats"
|
||||
);
|
||||
|
||||
// A symlink with an inert file name ("part.1") inside a bucket-wide walk must still fail closed with InvalidPath.
|
||||
let outside = tempfile::tempdir().expect("outside dir");
|
||||
|
||||
@@ -98,81 +98,30 @@ async fn usage_watch_stays_inflight_after_metadata_is_visible_and_waiter_is_canc
|
||||
);
|
||||
}
|
||||
|
||||
const REPLICATION_TARGET_ARN: &str = "arn:rustfs:replication::target:bucket";
|
||||
|
||||
/// Stores one version and returns it the way a status write-back starts: the
|
||||
/// whole version metadata read back from the disk.
|
||||
async fn stored_version(disk: &LocalDisk) -> FileInfo {
|
||||
let mut info =
|
||||
super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
|
||||
info.metadata.insert("etag".into(), "5d41402abc4b2a76b9719d911017c592".into());
|
||||
info.metadata.insert("content-type".into(), "application/octet-stream".into());
|
||||
let version_id = info.version_id.expect("fixture version id").to_string();
|
||||
disk.write_metadata("", "bucket", "object", info)
|
||||
.await
|
||||
.expect("initial counted version");
|
||||
disk.read_version("", "bucket", "object", &version_id, &ReadOptions::default())
|
||||
.await
|
||||
.expect("stored version")
|
||||
}
|
||||
|
||||
/// Mirrors what `put_object_metadata` hands the disk for a status write-back.
|
||||
fn apply_replication_writeback(fi: &mut FileInfo, status: &str) {
|
||||
insert_replication_writeback(&mut fi.metadata, status);
|
||||
fi.acknowledge_data_movement();
|
||||
}
|
||||
|
||||
fn insert_replication_writeback(metadata: &mut HashMap<String, String>, status: &str) {
|
||||
use rustfs_utils::http::metadata_compat::insert_str;
|
||||
use rustfs_utils::http::{
|
||||
SUFFIX_REPLICATION_RESET_ARN_PREFIX, SUFFIX_REPLICATION_STATUS, SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX,
|
||||
};
|
||||
insert_str(metadata, SUFFIX_REPLICATION_STATUS, format!("{REPLICATION_TARGET_ARN}={status};"));
|
||||
insert_str(
|
||||
metadata,
|
||||
&format!("{SUFFIX_REPLICATION_RESET_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
|
||||
"2026-01-01T00:00:00Z;reset".into(),
|
||||
);
|
||||
insert_str(
|
||||
metadata,
|
||||
&format!("{SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
|
||||
"target-version".into(),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
let info = stored_version(&disk).await;
|
||||
let info = super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
|
||||
disk.write_metadata("", "bucket", "object", info.clone())
|
||||
.await
|
||||
.expect("initial counted version");
|
||||
let before = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("idle watch");
|
||||
// A write-back carries the whole version metadata, not only the status keys.
|
||||
for status in ["PENDING", "COMPLETED"] {
|
||||
let mut writeback = info.clone();
|
||||
apply_replication_writeback(&mut writeback, status);
|
||||
disk.update_metadata("bucket", "object", writeback, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("status-class metadata update");
|
||||
}
|
||||
let mut status = info.clone();
|
||||
status.metadata.clear();
|
||||
rustfs_utils::http::metadata_compat::insert_str(
|
||||
&mut status.metadata,
|
||||
rustfs_utils::http::SUFFIX_REPLICATION_STATUS,
|
||||
"arn=COMPLETED;".into(),
|
||||
);
|
||||
disk.update_metadata("bucket", "object", status, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("status-class metadata update");
|
||||
let after = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("status result watch");
|
||||
assert!(after.unchanged_since(&before), "replication counters retain maintenance cadence");
|
||||
let stored = disk
|
||||
.read_version(
|
||||
"",
|
||||
"bucket",
|
||||
"object",
|
||||
&info.version_id.expect("version id").to_string(),
|
||||
&ReadOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("written status");
|
||||
assert_eq!(
|
||||
rustfs_utils::http::get_consistent_str(&stored.metadata, rustfs_utils::http::SUFFIX_REPLICATION_STATUS),
|
||||
Some(format!("{REPLICATION_TARGET_ARN}=COMPLETED;").as_str()),
|
||||
);
|
||||
let mut next = info;
|
||||
next.version_id = Some(Uuid::new_v4());
|
||||
disk.write_metadata("", "bucket", "object", next).await.expect("new version");
|
||||
@@ -183,33 +132,6 @@ async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
|
||||
assert_eq!(changed.inflight, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_status_write_with_other_metadata_change_revokes_proof() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
let info = stored_version(&disk).await;
|
||||
let mut seeded = info.clone();
|
||||
apply_replication_writeback(&mut seeded, "PENDING");
|
||||
disk.update_metadata("bucket", "object", seeded.clone(), &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("seed status keys");
|
||||
let before = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("idle watch");
|
||||
// Status keys ride along, but the same update also rewrites user metadata.
|
||||
let mut tagged = seeded;
|
||||
apply_replication_writeback(&mut tagged, "COMPLETED");
|
||||
tagged.metadata.insert("x-amz-meta-owner".into(), "changed".into());
|
||||
disk.update_metadata("bucket", "object", tagged, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("mixed metadata update");
|
||||
let after = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("mixed update watch");
|
||||
assert!(after.revision > before.revision);
|
||||
assert!(!after.unchanged_since(&before), "a non-status change must revoke the proof");
|
||||
assert_eq!(after.inflight, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_raw_live_stream_revokes_coverage_and_internal_staging_does_not() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
|
||||
@@ -6583,7 +6583,7 @@ fn linux_relative_path_has_invalid_component(relative: &Path) -> bool {
|
||||
/// Open the actual IO handle with the same containment policy as path validation.
|
||||
/// Older kernels retain fd-relative traversal; only ENOSYS enables the fallback.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(in crate::disk) fn open_linux_relative(
|
||||
fn open_linux_relative(
|
||||
directory: &std::fs::File,
|
||||
relative: &Path,
|
||||
flags: rustix::fs::OFlags,
|
||||
|
||||
@@ -7,61 +7,27 @@
|
||||
use crate::runtime::usage_watch::{UsageWatchMutationGuard, UsageWatchRegistry};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
fn replication_status_class_key(key: &str) -> bool {
|
||||
use rustfs_utils::http::*;
|
||||
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
|
||||
let suffix = suffix.to_ascii_lowercase();
|
||||
[
|
||||
SUFFIX_REPLICA_STATUS,
|
||||
SUFFIX_REPLICA_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_STATUS,
|
||||
SUFFIX_REPLICATION_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_GENERATION,
|
||||
SUFFIX_REPLICATION_RESET,
|
||||
SUFFIX_PURGESTATUS,
|
||||
]
|
||||
.contains(&suffix.as_str())
|
||||
// Per-target resync stamps and target-assigned version ids.
|
||||
|| suffix.starts_with(SUFFIX_REPLICATION_RESET_ARN_PREFIX)
|
||||
|| suffix.starts_with(SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a metadata update may turn out to be status-only. Callers hand the
|
||||
/// disk the whole version metadata, so the keys alone cannot settle it; the
|
||||
/// decision is made by [`status_only_metadata_change`] against the stored
|
||||
/// version once it has been read under the mutation lease.
|
||||
pub(crate) fn status_only_metadata_candidate(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
|
||||
!opts.replace_user_metadata
|
||||
&& opts.transition_reconcile.is_none()
|
||||
&& fi.metadata.keys().any(|key| replication_status_class_key(key))
|
||||
}
|
||||
|
||||
/// Existing-version replication status writes change neither size nor version
|
||||
/// membership. Replication aggregates keep their existing maintenance cadence.
|
||||
///
|
||||
/// True only when every stored version is unchanged apart from replication
|
||||
/// status-class internal keys. Anything that cannot be compared counts as a
|
||||
/// usage-relevant change.
|
||||
pub(crate) fn status_only_metadata_change(before: &rustfs_filemeta::FileMeta, after: &rustfs_filemeta::FileMeta) -> bool {
|
||||
fn without_status_keys(version: &rustfs_filemeta::FileMetaShallowVersion) -> Option<rustfs_filemeta::FileMetaVersion> {
|
||||
let mut parsed = version.parse_version_meta().ok()?;
|
||||
if let Some(object) = parsed.object.as_mut() {
|
||||
// Metadata updates also stamp an empty data-movement
|
||||
// acknowledgement; only a non-empty marker carries state.
|
||||
object.meta_sys.retain(|key, value| {
|
||||
!replication_status_class_key(key)
|
||||
&& !(value.is_empty() && rustfs_utils::http::has_internal_suffix(key, rustfs_utils::http::SUFFIX_DATA_MOVED))
|
||||
});
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
before.versions.len() == after.versions.len()
|
||||
&& before.versions.iter().zip(&after.versions).all(|(old, new)| {
|
||||
old.meta == new.meta
|
||||
|| without_status_keys(old)
|
||||
.zip(without_status_keys(new))
|
||||
.is_some_and(|(old, new)| old == new)
|
||||
pub(crate) fn status_only_metadata_update(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
|
||||
use rustfs_utils::http::*;
|
||||
!opts.replace_user_metadata
|
||||
&& opts.transition_reconcile.is_none()
|
||||
&& !fi.metadata.is_empty()
|
||||
&& fi.metadata.keys().all(|key| {
|
||||
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
|
||||
[
|
||||
SUFFIX_REPLICA_STATUS,
|
||||
SUFFIX_REPLICA_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_STATUS,
|
||||
SUFFIX_REPLICATION_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_GENERATION,
|
||||
SUFFIX_REPLICATION_RESET,
|
||||
SUFFIX_PURGESTATUS,
|
||||
]
|
||||
.iter()
|
||||
.any(|known| suffix.eq_ignore_ascii_case(known))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -110,18 +110,6 @@ fn small_ingest_capacity(erasure: &Erasure, size_hint: usize) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
fn inline_ingest_capacity(erasure: &Erasure, size_hint: usize) -> std::io::Result<usize> {
|
||||
let capacity = small_ingest_capacity(erasure, size_hint);
|
||||
if capacity == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
erasure
|
||||
.total_shard_count()
|
||||
.checked_mul(HashAlgorithm::HighwayHash256S.size())
|
||||
.and_then(|hash_bytes| capacity.checked_add(hash_bytes))
|
||||
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "inline ingest capacity exceeds usize"))
|
||||
}
|
||||
|
||||
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
|
||||
/// task when its `JoinHandle` is dropped, so the producer must be aborted when
|
||||
/// an upload is cancelled before the encode pipeline finishes.
|
||||
@@ -942,27 +930,25 @@ impl Erasure {
|
||||
{
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
// Match read_to_end's minimum allocation; a zero-capacity BytesMut
|
||||
// otherwise grows to 64 bytes even when its first read reaches EOF.
|
||||
let mut buf = BytesMut::with_capacity(inline_ingest_capacity(&self, size_hint)?.max(32));
|
||||
loop {
|
||||
match reader.read_buf(&mut buf).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => {}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let total = buf.len();
|
||||
let mut buf = Vec::with_capacity(small_ingest_capacity(&self, size_hint));
|
||||
let total = reader.read_to_end(&mut buf).await?;
|
||||
if total == 0 {
|
||||
return Ok((reader, 0, Vec::new()));
|
||||
}
|
||||
|
||||
let block = self.encode_buffer_mut(buf, total)?;
|
||||
let block = self.encode_data_owned_block(buf)?;
|
||||
if let Some(integrity) = integrity {
|
||||
integrity.push(block.shards()).await?;
|
||||
}
|
||||
let inline_shards = block.into_inline_shards()?;
|
||||
let shard_count = block.shards().len();
|
||||
let mut encoded = BytesMut::with_capacity(shard_count * 32 + block.queued_bytes());
|
||||
let mut inline_shards = Vec::with_capacity(shard_count);
|
||||
for shard in block.shards() {
|
||||
let hash = HashAlgorithm::HighwayHash256S.hash_encode(shard);
|
||||
encoded.extend_from_slice(hash.as_ref());
|
||||
encoded.extend_from_slice(shard);
|
||||
inline_shards.push(encoded.split().freeze());
|
||||
}
|
||||
|
||||
Ok((reader, total, inline_shards))
|
||||
}
|
||||
@@ -3394,151 +3380,34 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn encode_inline_shards_matches_writer_bitrot_layout() {
|
||||
const DATA_SHARDS: usize = 2;
|
||||
const PARITY_SHARDS: usize = 2;
|
||||
const BLOCK_SIZE: usize = 64;
|
||||
let checksum_algo = HashAlgorithm::HighwayHash256S;
|
||||
for uses_legacy in [false, true] {
|
||||
for (data_shards, parity_shards) in [(1, 0), (2, 2), (4, 2), (12, 4)] {
|
||||
let erasure = Arc::new(Erasure::new_with_options(data_shards, parity_shards, BLOCK_SIZE, uses_legacy));
|
||||
for payload in [
|
||||
Vec::new(),
|
||||
vec![0xA5],
|
||||
(0_u8..63).collect(),
|
||||
(0_u8..64).collect(),
|
||||
vec![0x5A; BLOCK_SIZE - 1],
|
||||
vec![0xC3; BLOCK_SIZE],
|
||||
] {
|
||||
for hint in [0, payload.len(), BLOCK_SIZE * 2] {
|
||||
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
|
||||
let (_reader, total, inline_shards) = erasure
|
||||
.clone()
|
||||
.encode_inline_shards_with_size_hint(reader, hint)
|
||||
.await
|
||||
.expect("inline shards should encode");
|
||||
let erasure = Arc::new(Erasure::new_with_options(DATA_SHARDS, PARITY_SHARDS, BLOCK_SIZE, uses_legacy));
|
||||
for payload in [Vec::new(), vec![0xA5], vec![0x5A; BLOCK_SIZE - 1], vec![0xC3; BLOCK_SIZE]] {
|
||||
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
|
||||
let (_reader, total, inline_shards) = erasure
|
||||
.clone()
|
||||
.encode_inline_shards_with_size_hint(reader, payload.len())
|
||||
.await
|
||||
.expect("inline shards should encode");
|
||||
|
||||
assert_eq!(total, payload.len());
|
||||
if payload.is_empty() {
|
||||
assert!(inline_shards.is_empty());
|
||||
continue;
|
||||
}
|
||||
|
||||
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
|
||||
assert_eq!(inline_shards.len(), data_shards + parity_shards);
|
||||
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
|
||||
let mut writer =
|
||||
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
|
||||
writer.write(&raw).await.expect("reference writer should accept shard");
|
||||
writer.shutdown().await.expect("reference writer should shutdown");
|
||||
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
|
||||
}
|
||||
}
|
||||
assert_eq!(total, payload.len());
|
||||
if payload.is_empty() {
|
||||
assert!(inline_shards.is_empty());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inline_framing_keeps_integrity_over_raw_shards() {
|
||||
use rustfs_filemeta::shard_integrity::IntegrityLayout;
|
||||
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Arc::new(Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy));
|
||||
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
|
||||
let raw_shards = erasure.encode_data(&payload).expect("reference data must encode");
|
||||
let layout = IntegrityLayout::new(2, 2, erasure.block_size, uses_legacy).expect("valid layout");
|
||||
|
||||
let (_, total, inline, proof) = Arc::clone(&erasure)
|
||||
.encode_with_shard_integrity(
|
||||
Cursor::new(payload.clone()),
|
||||
&mut [],
|
||||
ShardWritePolicy::object(3),
|
||||
1,
|
||||
IntegrityEncodeMode::Inline(payload.len()),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.expect("protected inline data must encode");
|
||||
let proof = proof.expect("protected encode must retain its proof");
|
||||
|
||||
assert_eq!(total, payload.len());
|
||||
assert_eq!(inline.expect("inline payload").len(), 4);
|
||||
proof.part.validate().expect("the prepared part must be valid");
|
||||
assert_eq!(proof.part.layout, layout);
|
||||
assert_eq!(proof.part.size, u64::try_from(payload.len()).expect("payload length fits u64"));
|
||||
assert_eq!(proof.part.stripes, 1);
|
||||
let index = proof.inline_bytes().expect("inline proof");
|
||||
assert_eq!(index.len(), proof.part.index_size().expect("valid proof length"));
|
||||
assert!(index.starts_with(&proof.part.index_header()));
|
||||
let offset = proof.part.record_offset(0).expect("first stripe exists");
|
||||
let record = &index[offset..offset + proof.part.record_size()];
|
||||
for (coding_index, raw_shard) in raw_shards.iter().enumerate() {
|
||||
proof
|
||||
.part
|
||||
.verify_shard(0, coding_index, raw_shard, record)
|
||||
.expect("the authenticated proof must cover the raw shard without its bitrot prefix");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inline_framing_preserves_eof_digest_validation() {
|
||||
use crate::io_support::rio::HashReader;
|
||||
|
||||
let erasure = Arc::new(Erasure::new(2, 2, 64));
|
||||
let payload = vec![0xA5; 64];
|
||||
for (md5, sha256) in [(Some("0".repeat(32)), None), (None, Some("0".repeat(64)))] {
|
||||
let reader = HashReader::from_stream(Cursor::new(payload.clone()), 64, 64, md5, sha256, false)
|
||||
.expect("valid digest input shape");
|
||||
let err = Arc::clone(&erasure)
|
||||
.encode_inline_shards_with_size_hint(reader, payload.len())
|
||||
.await
|
||||
.err()
|
||||
.expect("a failed EOF digest must prevent inline publication");
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inline_ingest_retries_interrupted_and_preserves_other_errors() {
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::io::ReadBuf;
|
||||
|
||||
struct ErrorAfterPrefix {
|
||||
prefix: Cursor<Vec<u8>>,
|
||||
error: Option<std::io::ErrorKind>,
|
||||
}
|
||||
|
||||
impl AsyncRead for ErrorAfterPrefix {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
if self.prefix.position() < u64::try_from(self.prefix.get_ref().len()).expect("small test reader length") {
|
||||
return Pin::new(&mut self.prefix).poll_read(cx, buf);
|
||||
}
|
||||
if let Some(kind) = self.error.take() {
|
||||
return Poll::Ready(Err(std::io::Error::new(kind, "inline reader failed")));
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
let erasure = Arc::new(Erasure::new(2, 2, 64));
|
||||
for payload in [Vec::new(), (0_u8..7).collect()] {
|
||||
for kind in [
|
||||
std::io::ErrorKind::Interrupted,
|
||||
std::io::ErrorKind::InvalidData,
|
||||
std::io::ErrorKind::BrokenPipe,
|
||||
] {
|
||||
let reader = ErrorAfterPrefix {
|
||||
prefix: Cursor::new(payload.clone()),
|
||||
error: Some(kind),
|
||||
};
|
||||
let result = Arc::clone(&erasure).encode_inline_shards_with_size_hint(reader, 0).await;
|
||||
if kind == std::io::ErrorKind::Interrupted {
|
||||
let (_, total, shards) = result.expect("Interrupted must be retried through the final EOF");
|
||||
assert_eq!(total, payload.len());
|
||||
assert_eq!(shards.len(), if payload.is_empty() { 0 } else { 4 });
|
||||
} else {
|
||||
let err = result.err().expect("the original read error must prevent inline publication");
|
||||
assert_eq!(err.kind(), kind, "partial reads must preserve the error kind");
|
||||
assert_eq!(err.to_string(), "inline reader failed");
|
||||
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
|
||||
assert_eq!(inline_shards.len(), DATA_SHARDS + PARITY_SHARDS);
|
||||
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
|
||||
let mut writer =
|
||||
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
|
||||
writer.write(&raw).await.expect("reference writer should accept shard");
|
||||
writer.shutdown().await.expect("reference writer should shutdown");
|
||||
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ use crate::erasure::codec::shard_buf::ShardBytes;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use reed_solomon_simd;
|
||||
use rustfs_erasure_codec::galois_8::ReedSolomon;
|
||||
use rustfs_utils::HashAlgorithm;
|
||||
use smallvec::SmallVec;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
@@ -38,12 +37,14 @@ pub(crate) struct EncodedBlock {
|
||||
shard_size: usize,
|
||||
}
|
||||
|
||||
pub(crate) struct MutableEncodedBlock {
|
||||
data: BytesMut,
|
||||
shard_size: usize,
|
||||
}
|
||||
|
||||
impl EncodedBlock {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
data: Bytes::new(),
|
||||
shard_size: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
@@ -78,58 +79,6 @@ impl EncodedBlock {
|
||||
}
|
||||
}
|
||||
|
||||
impl MutableEncodedBlock {
|
||||
fn freeze(self) -> EncodedBlock {
|
||||
EncodedBlock {
|
||||
data: self.data.freeze(),
|
||||
shard_size: self.shard_size,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn shards(&self) -> impl ExactSizeIterator<Item = &[u8]> {
|
||||
debug_assert!(self.shard_size > 0, "only non-empty encoded blocks reach shard writers");
|
||||
debug_assert_eq!(self.data.len() % self.shard_size, 0);
|
||||
self.data.chunks_exact(self.shard_size)
|
||||
}
|
||||
|
||||
pub(crate) fn into_inline_shards(self) -> io::Result<Vec<Bytes>> {
|
||||
if self.data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
debug_assert!(self.shard_size > 0, "non-empty encoded blocks have a shard size");
|
||||
debug_assert_eq!(self.data.len() % self.shard_size, 0);
|
||||
let shard_count = self.data.len() / self.shard_size;
|
||||
let hash_algorithm = HashAlgorithm::HighwayHash256S;
|
||||
let hash_size = hash_algorithm.size();
|
||||
let frame_size = self
|
||||
.shard_size
|
||||
.checked_add(hash_size)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frame size overflows usize"))?;
|
||||
let framed_size = shard_count
|
||||
.checked_mul(frame_size)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frames exceed usize"))?;
|
||||
let mut data = self.data;
|
||||
data.resize(framed_size, 0);
|
||||
|
||||
// Expand from the last shard so each move only overwrites raw shards
|
||||
// whose payload has already reached its final, hash-prefixed location.
|
||||
for index in (0..shard_count).rev() {
|
||||
let source = index * self.shard_size;
|
||||
let frame = index * frame_size;
|
||||
data.copy_within(source..source + self.shard_size, frame + hash_size);
|
||||
let (hash, payload) = data[frame..frame + frame_size].split_at_mut(hash_size);
|
||||
hash.copy_from_slice(hash_algorithm.hash_encode(payload).as_ref());
|
||||
}
|
||||
|
||||
let mut shards = Vec::with_capacity(shard_count);
|
||||
for _ in 0..shard_count {
|
||||
shards.push(data.split_to(frame_size).freeze());
|
||||
}
|
||||
Ok(shards)
|
||||
}
|
||||
}
|
||||
|
||||
const MODERN_MAX_TOTAL_SHARDS: usize = <rustfs_erasure_codec::galois_8::Field as rustfs_erasure_codec::Field>::ORDER;
|
||||
const MODERN_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 64;
|
||||
const LEGACY_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 16;
|
||||
@@ -1128,12 +1077,7 @@ impl Erasure {
|
||||
self.encode_buffer(data_buffer, data_len)
|
||||
}
|
||||
|
||||
fn encode_buffer(&self, data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
|
||||
self.encode_buffer_mut(data_buffer, data_len).map(MutableEncodedBlock::freeze)
|
||||
}
|
||||
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub(crate) fn encode_buffer_mut(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<MutableEncodedBlock> {
|
||||
fn encode_buffer(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
} else {
|
||||
@@ -1141,10 +1085,7 @@ impl Erasure {
|
||||
};
|
||||
let per_shard_size = shard_size_fn(data_len, self.data_shards);
|
||||
if per_shard_size == 0 {
|
||||
return Ok(MutableEncodedBlock {
|
||||
data: BytesMut::new(),
|
||||
shard_size: 0,
|
||||
});
|
||||
return Ok(EncodedBlock::empty());
|
||||
}
|
||||
let need_total_size = per_shard_size * self.total_shard_count();
|
||||
|
||||
@@ -1171,8 +1112,8 @@ impl Erasure {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(MutableEncodedBlock {
|
||||
data: data_buffer,
|
||||
Ok(EncodedBlock {
|
||||
data: data_buffer.freeze(),
|
||||
shard_size: per_shard_size,
|
||||
})
|
||||
}
|
||||
@@ -1374,16 +1315,17 @@ impl Erasure {
|
||||
calc_shard_size(self.block_size, self.data_shards)
|
||||
}
|
||||
}
|
||||
/// Calculate the logical shard file size before bitrot framing.
|
||||
/// Calculate the total erasure file size for a given original size.
|
||||
// Returns the final erasure size from the original size
|
||||
pub fn shard_file_size(&self, total_length: i64) -> i64 {
|
||||
if total_length <= 0 {
|
||||
if total_length == 0 {
|
||||
return 0;
|
||||
}
|
||||
if total_length < 0 {
|
||||
return total_length;
|
||||
}
|
||||
let total_length = usize::try_from(total_length).unwrap_or(usize::MAX);
|
||||
i64::try_from(self.shard_file_size_bytes(total_length)).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
fn shard_file_size_bytes(&self, total_length: usize) -> usize {
|
||||
let total_length = total_length as usize;
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
} else {
|
||||
@@ -1393,24 +1335,21 @@ impl Erasure {
|
||||
let num_shards = total_length / self.block_size;
|
||||
let last_block_size = total_length % self.block_size;
|
||||
let last_shard_size = shard_size_fn(last_block_size, self.data_shards);
|
||||
num_shards.saturating_mul(self.shard_size()).saturating_add(last_shard_size)
|
||||
(num_shards * self.shard_size() + last_shard_size) as i64
|
||||
}
|
||||
|
||||
/// Return the exclusive logical shard offset for the requested object bytes.
|
||||
/// Only stripes touched by the range are included, clipped to the final partial stripe.
|
||||
/// An empty range ends at the start of its stripe.
|
||||
/// Calculate the offset in the erasure file where reading begins.
|
||||
// Returns the offset in the erasure file where reading begins
|
||||
pub fn shard_file_offset(&self, start_offset: usize, length: usize, total_length: usize) -> usize {
|
||||
let end = start_offset.saturating_add(length).min(total_length);
|
||||
let end_stripe = if length == 0 {
|
||||
end / self.block_size
|
||||
} else {
|
||||
end.div_ceil(self.block_size)
|
||||
};
|
||||
if end_stripe <= total_length / self.block_size {
|
||||
end_stripe.saturating_mul(self.shard_size())
|
||||
} else {
|
||||
self.shard_file_size_bytes(total_length)
|
||||
let shard_size = self.shard_size();
|
||||
let shard_file_size = self.shard_file_size(total_length as i64) as usize;
|
||||
let end_shard = (start_offset + length) / self.block_size;
|
||||
let mut till_offset = end_shard * shard_size + shard_size;
|
||||
if till_offset > shard_file_size {
|
||||
till_offset = shard_file_size;
|
||||
}
|
||||
|
||||
till_offset
|
||||
}
|
||||
|
||||
/// Encode all data from a reader in blocks, calling an async callback for each encoded block.
|
||||
@@ -2102,27 +2041,6 @@ mod tests {
|
||||
assert!(err.to_string().contains("invalid shard count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_shards_reuse_the_bytesmut_ingest_allocation() {
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy);
|
||||
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
|
||||
let frame_size = erasure.encoded_capacity_for_data_len(payload.len())
|
||||
+ erasure.total_shard_count() * HashAlgorithm::HighwayHash256S.size();
|
||||
let mut buffer = BytesMut::with_capacity(frame_size);
|
||||
buffer.extend_from_slice(&payload);
|
||||
let allocation = buffer.as_ptr();
|
||||
let block = erasure
|
||||
.encode_buffer_mut(buffer, payload.len())
|
||||
.expect("preallocated data must encode");
|
||||
let shards = block.into_inline_shards().expect("inline framing must succeed");
|
||||
|
||||
assert_eq!(shards.len(), erasure.total_shard_count());
|
||||
assert_eq!(shards[0].as_ptr(), allocation, "inline framing must retain the encoded allocation");
|
||||
assert_eq!(shards.iter().map(Bytes::len).sum::<usize>(), frame_size);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_data_owned_matches_borrowed_path() {
|
||||
for uses_legacy in [false, true] {
|
||||
@@ -2912,19 +2830,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_shard_file_offset() {
|
||||
const BLOCK: usize = 256 * 1024;
|
||||
const TOTAL: usize = 3 * BLOCK + 19;
|
||||
for legacy in [false, true] {
|
||||
let erasure = Erasure::try_new_with_options(3, 3, BLOCK, legacy).expect("supported erasure layout");
|
||||
let shard_size = erasure.shard_size();
|
||||
let tail = if legacy { 8 } else { 7 };
|
||||
assert_eq!(erasure.shard_file_offset(0, 0, TOTAL), 0);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 1, 0, TOTAL), shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 7, TOTAL), 2 * shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 6, TOTAL), 3 * shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(3 * BLOCK, 1, TOTAL), 3 * shard_size + tail);
|
||||
assert_eq!(erasure.shard_file_offset(0, TOTAL, TOTAL), 3 * shard_size + tail);
|
||||
}
|
||||
let erasure = Erasure::new(8, 8, 1024 * 1024);
|
||||
let offset = erasure.shard_file_offset(0, 86, 86);
|
||||
println!("offset={offset}");
|
||||
assert!(offset > 0);
|
||||
|
||||
let total_length = erasure.shard_file_size(86);
|
||||
println!("total_length={total_length}");
|
||||
assert!(total_length > 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -213,9 +213,11 @@ fn buffer_local_shard_stream(reader: ShardReader, length: usize) -> disk::error:
|
||||
// enlarge that reservation and allocate a second, unaccounted buffer.
|
||||
return Ok(ShardReader::Stream(Box::new(reader.take(limit))));
|
||||
}
|
||||
// Buffer long reads of small frames to avoid a blocking dispatch per frame.
|
||||
// Prefetch stays within the requested span, and each frame authenticates
|
||||
// when consumed by the bitrot reader.
|
||||
// Small layout stripes otherwise dispatch a blocking file read per frame.
|
||||
// Short ranges keep direct reads: the caller's conservative stream span
|
||||
// can include an extra stripe beyond the final requested block. Long
|
||||
// streams stay bounded to that span; prefetched frames still authenticate
|
||||
// individually when consumed by the bitrot reader.
|
||||
Ok(ShardReader::Stream(Box::new(tokio::io::BufReader::with_capacity(
|
||||
256 * 1024,
|
||||
reader.take(limit),
|
||||
@@ -1133,12 +1135,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_local_shard_stream_keeps_short_range_reads_direct() {
|
||||
async fn buffered_local_shard_stream_does_not_prefetch_conservative_short_range_tail() {
|
||||
const BLOCK: usize = 256 * 1024;
|
||||
const SHARD: usize = BLOCK / 2;
|
||||
let algo = HashAlgorithm::HighwayHash256S;
|
||||
// A short stream may be consumed only in part before cancellation.
|
||||
let logical_window = 5 * SHARD;
|
||||
let erasure = crate::erasure::coding::Erasure::new(2, 2, BLOCK);
|
||||
// An aligned 1 MiB Range consumes four data-shard frames, while the
|
||||
// existing reader planner conservatively opens five logical shards.
|
||||
let logical_window = erasure.shard_file_offset(0, 4 * BLOCK, 6 * BLOCK);
|
||||
assert_eq!(logical_window, 5 * SHARD);
|
||||
let (_, wire_window) = adjust_shard_read_params(0, logical_window, SHARD, &algo);
|
||||
let payload = vec![73; SHARD];
|
||||
let mut encoded = Vec::new();
|
||||
@@ -1147,7 +1152,10 @@ mod tests {
|
||||
for _ in 0..4 {
|
||||
writer.write(&payload).await.expect("encode requested range frames");
|
||||
}
|
||||
writer.write(&vec![99; SHARD]).await.expect("encode unread tail frame");
|
||||
writer
|
||||
.write(&vec![99; SHARD])
|
||||
.await
|
||||
.expect("encode unrequested conservative tail frame");
|
||||
}
|
||||
assert_eq!(encoded.len(), wire_window);
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
@@ -1160,7 +1168,7 @@ mod tests {
|
||||
})),
|
||||
wire_window,
|
||||
)
|
||||
.expect("open short range stream");
|
||||
.expect("open conservative short range stream");
|
||||
let mut reader = BitrotReader::new(source, SHARD, algo.clone(), false);
|
||||
let mut output = Vec::new();
|
||||
for _ in 0..4 {
|
||||
|
||||
@@ -31,6 +31,7 @@ use native as variant;
|
||||
pub use variant::*;
|
||||
|
||||
use rustfs_utils::CompressionAlgorithm;
|
||||
use rustfs_utils::http::object_encryption_keys::SSEType;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ReadCompressionBackend {
|
||||
@@ -61,6 +62,7 @@ pub enum ReadEncryptionBackend {
|
||||
pub struct WriteEncryption {
|
||||
key_bytes: [u8; 32],
|
||||
mode: WriteEncryptionMode,
|
||||
s3_content_etag: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -83,6 +85,7 @@ impl WriteEncryption {
|
||||
Self {
|
||||
key_bytes: object_key,
|
||||
mode: WriteEncryptionMode::SinglepartObjectKey,
|
||||
s3_content_etag: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +93,7 @@ impl WriteEncryption {
|
||||
Self {
|
||||
key_bytes,
|
||||
mode: WriteEncryptionMode::Singlepart { base_nonce },
|
||||
s3_content_etag: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,6 +104,7 @@ impl WriteEncryption {
|
||||
base_nonce,
|
||||
multipart_part_number,
|
||||
},
|
||||
s3_content_etag: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,8 +112,31 @@ impl WriteEncryption {
|
||||
Self {
|
||||
key_bytes: object_key,
|
||||
mode: WriteEncryptionMode::MultipartObjectKey { multipart_part_number },
|
||||
s3_content_etag: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// SSE-S3 clients verify a single PUT or upload part against the MD5 of the original bytes.
|
||||
pub const fn for_sse_type(mut self, scheme: SSEType) -> Self {
|
||||
self.s3_content_etag = matches!(scheme, SSEType::SseS3);
|
||||
self
|
||||
}
|
||||
|
||||
fn encrypt(self, reader: impl rustfs_rio::Reader + 'static, actual_size: i64) -> std::io::Result<HashReader> {
|
||||
let key = self.key_bytes;
|
||||
let encrypted = match self.mode {
|
||||
WriteEncryptionMode::SinglepartObjectKey => variant::encrypt_under_object_key(reader, key),
|
||||
WriteEncryptionMode::Singlepart { base_nonce } => variant::encrypt_singlepart(reader, key, base_nonce),
|
||||
WriteEncryptionMode::MultipartLegacy {
|
||||
base_nonce,
|
||||
multipart_part_number,
|
||||
} => variant::encrypt_part(reader, key, base_nonce, multipart_part_number),
|
||||
WriteEncryptionMode::MultipartObjectKey { multipart_part_number } => {
|
||||
variant::encrypt_part_under_object_key(reader, key, multipart_part_number)
|
||||
}
|
||||
};
|
||||
HashReader::from_reader(encrypted, HashReader::SIZE_PRESERVE_LAYER, actual_size, None, None, false)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -148,6 +176,19 @@ impl WritePlan {
|
||||
|
||||
let delegate_inner_etag = self.compression.is_none() && reader.is_etag_reader();
|
||||
let encrypted = self.encryption.is_some();
|
||||
let s3_content_etag = self.encryption.is_some_and(|enc| enc.s3_content_etag);
|
||||
if s3_content_etag {
|
||||
// The incoming hash may be disabled or use a bucket-specific algorithm.
|
||||
// Hash the original stream so every SSE-S3 write has the same MD5 contract.
|
||||
reader = HashReader::from_reader(
|
||||
rustfs_rio::EtagReader::new(reader, None),
|
||||
HashReader::SIZE_PRESERVE_LAYER,
|
||||
actual_size,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
)?;
|
||||
}
|
||||
if let Some(algorithm) = self.compression {
|
||||
reader = HashReader::from_reader(
|
||||
compression_reader(reader, algorithm, encrypted),
|
||||
@@ -159,7 +200,11 @@ impl WritePlan {
|
||||
)?;
|
||||
}
|
||||
|
||||
if let Some(encryption) = self.encryption {
|
||||
if let Some(encryption) = self.encryption
|
||||
&& encryption.s3_content_etag
|
||||
{
|
||||
reader = encryption.encrypt(reader, actual_size)?;
|
||||
} else if let Some(encryption) = self.encryption {
|
||||
let etag_nonce = match encryption.mode {
|
||||
WriteEncryptionMode::Singlepart { base_nonce } => base_nonce,
|
||||
WriteEncryptionMode::SinglepartObjectKey => [0u8; 12],
|
||||
@@ -170,25 +215,13 @@ impl WritePlan {
|
||||
};
|
||||
let protected_reader = rustfs_rio::EtagReader::new_encrypted(reader, encryption.key_bytes, etag_nonce)?
|
||||
.with_inner_etag_delegation(delegate_inner_etag);
|
||||
let key = encryption.key_bytes;
|
||||
let encrypt_reader = match encryption.mode {
|
||||
WriteEncryptionMode::SinglepartObjectKey => variant::encrypt_under_object_key(protected_reader, key),
|
||||
WriteEncryptionMode::Singlepart { base_nonce } => variant::encrypt_singlepart(protected_reader, key, base_nonce),
|
||||
WriteEncryptionMode::MultipartLegacy {
|
||||
base_nonce,
|
||||
multipart_part_number,
|
||||
} => variant::encrypt_part(protected_reader, key, base_nonce, multipart_part_number),
|
||||
WriteEncryptionMode::MultipartObjectKey { multipart_part_number } => {
|
||||
variant::encrypt_part_under_object_key(protected_reader, key, multipart_part_number)
|
||||
}
|
||||
};
|
||||
reader = HashReader::from_reader(encrypt_reader, HashReader::SIZE_PRESERVE_LAYER, actual_size, None, None, false)?;
|
||||
reader = encryption.encrypt(protected_reader, actual_size)?;
|
||||
}
|
||||
|
||||
// `ignore_value` deliberately avoids a second hasher over compressed or
|
||||
// encrypted bytes. The inner reader still validates the plaintext request
|
||||
// checksum while this outer reader exposes the request checksum context.
|
||||
reader.encrypted_etag = encrypted;
|
||||
reader.encrypted_etag = encrypted && !s3_content_etag;
|
||||
reader.add_non_trailing_checksum(checksum, true)?;
|
||||
reader.set_trailer(trailer);
|
||||
|
||||
@@ -205,6 +238,35 @@ mod tests {
|
||||
use std::io::Cursor;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn sse_s3_content_etag_hashes_plaintext_before_compression_and_encryption() {
|
||||
let data = b"same bytes through each write plan";
|
||||
let size = data.len() as i64;
|
||||
let mut control = HashReader::from_stream(Cursor::new(data), size, size, None, None, false).unwrap();
|
||||
control.read_to_end(&mut Vec::new()).await.unwrap();
|
||||
let expected = control.try_resolve_etag().unwrap();
|
||||
for encryption in [
|
||||
WriteEncryption::singlepart([1; 32], [2; 12]),
|
||||
WriteEncryption::singlepart_object_key([1; 32]),
|
||||
WriteEncryption::multipart([1; 32], [2; 12], 1),
|
||||
WriteEncryption::multipart_object_key([1; 32], 1),
|
||||
] {
|
||||
for compress in [false, true] {
|
||||
let mut plan = WritePlan::new().with_encryption(encryption.for_sse_type(SSEType::SseS3));
|
||||
if compress {
|
||||
plan = plan.with_compression(CompressionAlgorithm::default());
|
||||
}
|
||||
let source = HashReader::from_stream(Cursor::new(data), size, size, None, None, false).unwrap();
|
||||
let mut reader = plan.apply(source, size).unwrap();
|
||||
let mut stored = Vec::new();
|
||||
reader.read_to_end(&mut stored).await.unwrap();
|
||||
assert_ne!(stored, data);
|
||||
assert_eq!(reader.try_resolve_etag().as_ref(), Some(&expected));
|
||||
assert!(!reader.encrypted_etag, "a plaintext MD5 cannot attest an opaque ETag");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_plan_encryption_persists_protected_etags_for_every_mode() {
|
||||
let data = b"Salary 2026: 85000 EUR";
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::disk::{DiskAPI, DiskStore, FileReader};
|
||||
use crate::disk::{DiskAPI, DiskStore};
|
||||
use crate::erasure::codec::shard_buf::ShardBytes;
|
||||
use bytes::Bytes;
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
@@ -539,28 +539,19 @@ pub(crate) struct PartProofReader {
|
||||
sources: Vec<(DiskStore, String)>,
|
||||
volume: String,
|
||||
inline: Option<Bytes>,
|
||||
read_end: Option<u32>,
|
||||
cached: Mutex<ProofCache>,
|
||||
}
|
||||
|
||||
struct ProofWindow {
|
||||
next: u32,
|
||||
end: u32,
|
||||
reader: FileReader,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProofCache {
|
||||
records: std::collections::VecDeque<(u32, Bytes)>,
|
||||
preferred: usize,
|
||||
window: Option<ProofWindow>,
|
||||
}
|
||||
|
||||
// The root is checked against the complete descriptor during authentication.
|
||||
// A cache hit must carry the same geometry, part number, size and stripe count.
|
||||
type VerifiedStripeKey = (PartIntegrity, u32);
|
||||
const MAX_SHARED_CACHE_STRIPES: u32 = 4;
|
||||
const PROOF_WINDOW_STRIPES: u32 = 16;
|
||||
|
||||
static VERIFIED_STRIPE_RECORDS: std::sync::LazyLock<parking_lot::Mutex<std::collections::HashMap<VerifiedStripeKey, Bytes>>> =
|
||||
std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
|
||||
@@ -616,7 +607,6 @@ impl PartProofReader {
|
||||
disks: &[Option<DiskStore>],
|
||||
volume: &str,
|
||||
object: &str,
|
||||
read_end: Option<u32>,
|
||||
) -> io::Result<Arc<Self>> {
|
||||
part.validate().map_err(|_| corrupt())?;
|
||||
let mut sources = Vec::with_capacity(disks.len());
|
||||
@@ -658,7 +648,6 @@ impl PartProofReader {
|
||||
sources,
|
||||
volume: volume.to_owned(),
|
||||
inline,
|
||||
read_end,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
}))
|
||||
}
|
||||
@@ -666,10 +655,6 @@ impl PartProofReader {
|
||||
pub(crate) async fn record(&self, stripe: u32) -> io::Result<Bytes> {
|
||||
let offset = self.part.record_offset(stripe).map_err(|_| corrupt())?;
|
||||
let size = self.part.record_size();
|
||||
let end = self.read_end.unwrap_or(self.part.stripes).min(self.part.stripes);
|
||||
if stripe >= end {
|
||||
return Err(corrupt());
|
||||
}
|
||||
// Inline records are immutable and authenticated at construction.
|
||||
if let Some(inline) = &self.inline {
|
||||
return Ok(inline.slice(offset..offset + size));
|
||||
@@ -687,17 +672,8 @@ impl PartProofReader {
|
||||
let record = if let Some(record) = shared {
|
||||
record
|
||||
} else {
|
||||
let window = cached.window.take().filter(|window| window.next == stripe);
|
||||
let end = if share {
|
||||
stripe + 1
|
||||
} else {
|
||||
end.min(stripe.saturating_add(PROOF_WINDOW_STRIPES))
|
||||
};
|
||||
let (replica, record, next_window) = self
|
||||
.read_verified_record(stripe, offset, size, end, cached.preferred, window)
|
||||
.await?;
|
||||
let (replica, record) = self.read_verified_record(stripe, offset, size, cached.preferred).await?;
|
||||
cached.preferred = replica;
|
||||
cached.window = next_window;
|
||||
if share {
|
||||
put_verified_stripe_record(&self.part, stripe, record.clone());
|
||||
}
|
||||
@@ -715,81 +691,38 @@ impl PartProofReader {
|
||||
stripe: u32,
|
||||
offset: usize,
|
||||
size: usize,
|
||||
end: u32,
|
||||
preferred: usize,
|
||||
window: Option<ProofWindow>,
|
||||
) -> io::Result<(usize, Bytes, Option<ProofWindow>)> {
|
||||
) -> io::Result<(usize, Bytes)> {
|
||||
if self.sources.is_empty() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let read = |index: usize, window: Option<ProofWindow>| async move {
|
||||
let read = |index: usize| async move {
|
||||
let (disk, path) = &self.sources[index];
|
||||
tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
let open = async |end: u32, bytes: &mut [u8]| {
|
||||
let count = usize::try_from(end - stripe).map_err(|_| corrupt())?;
|
||||
let length = size.checked_mul(count).ok_or_else(corrupt)?;
|
||||
#[cfg(test)]
|
||||
crate::set_disk::disk_call_counters::record_proof_stream_open(path, index);
|
||||
let reader = disk
|
||||
.read_file_stream(&self.volume, path, offset, length)
|
||||
.await
|
||||
.map_err(crate::disk::error::terminal_read_error_to_io)?;
|
||||
let mut reader = if count > 1 && disk.is_local() {
|
||||
Box::new(tokio::io::BufReader::with_capacity(length, reader)) as FileReader
|
||||
} else {
|
||||
reader
|
||||
};
|
||||
reader.read_exact(bytes).await?;
|
||||
io::Result::Ok(reader)
|
||||
};
|
||||
let mut reader = disk
|
||||
.read_file_stream(&self.volume, path, offset, size)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let mut bytes = vec![0; size];
|
||||
let next = stripe + 1;
|
||||
let continued = window.is_some();
|
||||
let (end, result) = if let Some(mut window) = window {
|
||||
let result = window.reader.read_exact(&mut bytes).await.map(|_| window.reader);
|
||||
(window.end, result)
|
||||
} else {
|
||||
(end, open(end, &mut bytes).await)
|
||||
};
|
||||
let (end, reader) = match result {
|
||||
Ok(reader) => (end, reader),
|
||||
// A truncated window or broken continuation can leave the
|
||||
// current record readable through a fresh exact request.
|
||||
Err(error)
|
||||
if (continued || end > next)
|
||||
&& !matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) =>
|
||||
{
|
||||
(next, open(next, &mut bytes).await?)
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
reader.read_exact(&mut bytes).await?;
|
||||
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
|
||||
let window = (next < end).then_some(ProofWindow { next, end, reader });
|
||||
io::Result::Ok((index, Bytes::from(bytes), window))
|
||||
io::Result::Ok((index, Bytes::from(bytes)))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?
|
||||
};
|
||||
let primary = read(preferred, window);
|
||||
tokio::pin!(primary);
|
||||
let mut primary_pending = match tokio::time::timeout(std::time::Duration::from_millis(50), primary.as_mut()).await {
|
||||
Ok(Ok(record)) => return Ok(record),
|
||||
Ok(_) => false,
|
||||
Err(_) => true,
|
||||
};
|
||||
let mut replicas: FuturesUnordered<_> = (0..self.sources.len())
|
||||
.filter(|&index| index != preferred)
|
||||
.map(|index| read(index, None))
|
||||
.collect();
|
||||
while primary_pending || !replicas.is_empty() {
|
||||
let result = tokio::select! {
|
||||
result = &mut primary, if primary_pending => {
|
||||
primary_pending = false;
|
||||
result
|
||||
let mut pending = FuturesUnordered::new();
|
||||
pending.push(read(preferred));
|
||||
tokio::select! {
|
||||
result = pending.next() => {
|
||||
if let Some(Ok(Ok(record))) = result {
|
||||
return Ok(record);
|
||||
}
|
||||
Some(result) = replicas.next() => result,
|
||||
};
|
||||
if let Ok(record) = result {
|
||||
}
|
||||
() = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
|
||||
}
|
||||
pending.extend((0..self.sources.len()).filter(|&index| index != preferred).map(read));
|
||||
while let Some(result) = pending.next().await {
|
||||
if let Ok(Ok(record)) = result {
|
||||
return Ok(record);
|
||||
}
|
||||
}
|
||||
@@ -909,7 +842,7 @@ pub(crate) async fn verify_deep_parts(
|
||||
let read_timeout = crate::disk::disk_store::get_object_disk_read_timeout();
|
||||
for (part_index, part) in expected.parts.iter().enumerate() {
|
||||
let commitment = part.integrity.as_ref().ok_or(DiskError::FileCorrupt)?;
|
||||
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object, None).map_err(DiskError::from)?;
|
||||
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object).map_err(DiskError::from)?;
|
||||
if commitment.stripes == 0 && commitment.root != commitment.root_digest(&commitment.padding_digest(0)) {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
@@ -1049,7 +982,6 @@ pub(crate) async fn restore_proof_replicas(
|
||||
sources: disks.iter().flatten().map(|disk| (disk.clone(), path.clone())).collect(),
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let prepared = PreparedIntegrity::copy_from(&proof).await.map_err(DiskError::from)?;
|
||||
@@ -1134,7 +1066,6 @@ mod tests {
|
||||
sources: vec![],
|
||||
volume: "bucket".to_owned(),
|
||||
inline: Some(bytes),
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
let mut verifier = ShardVerifier::new(proof, 0, 0, None).expect("verifier");
|
||||
@@ -1155,7 +1086,6 @@ mod tests {
|
||||
let proof = PartProofReader {
|
||||
part: prepared.part,
|
||||
inline: Some(index),
|
||||
read_end: None,
|
||||
sources: Vec::new(),
|
||||
volume: String::new(),
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
@@ -1213,14 +1143,14 @@ mod tests {
|
||||
let mut shortened = part.clone();
|
||||
shortened.size = 8;
|
||||
shortened.stripes = 1;
|
||||
let mismatched_reader = PartProofReader::new(shortened, &[], &[], "bucket", "object", None)
|
||||
.expect("the altered descriptor is structurally valid");
|
||||
let mismatched_reader =
|
||||
PartProofReader::new(shortened, &[], &[], "bucket", "object").expect("the altered descriptor is structurally valid");
|
||||
assert!(
|
||||
mismatched_reader.verify(0, 0, shards[0]).await.is_err(),
|
||||
"a matching generation and root must not admit a shortened part"
|
||||
);
|
||||
|
||||
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object", None).expect("matching descriptor");
|
||||
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object").expect("matching descriptor");
|
||||
cached_reader.verify(0, 0, shards[0]).await.expect("cached verify");
|
||||
invalidate_verified_stripe_records(part.generation);
|
||||
assert!(get_verified_stripe_record(&part, 0).is_none());
|
||||
@@ -1244,7 +1174,6 @@ mod tests {
|
||||
sources: Vec::new(),
|
||||
volume: "bucket".to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
|
||||
@@ -1265,128 +1194,6 @@ mod tests {
|
||||
assert!(err.to_string().contains("shard integrity verification failed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proof_stream_reuses_bounded_windows_and_recovers_from_damaged_replicas() {
|
||||
use crate::set_disk::disk_call_counters;
|
||||
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
|
||||
let disks = store.pools[0].disk_set[0].get_local_disks().await;
|
||||
let volume = "proof-window";
|
||||
let path = "part.integrity";
|
||||
let mut builder = IntegrityBuilder::new(IntegrityLayout::new(1, 1, 8, false).expect("layout"), 1).expect("builder");
|
||||
for _ in 0..20 {
|
||||
builder.push([b"abcdefgh".as_slice(); 2].into_iter()).await.expect("stripe");
|
||||
}
|
||||
let prepared = builder.finish(160).await.expect("index");
|
||||
let bytes = prepared.inline_bytes().expect("small proof index");
|
||||
let part = prepared.part;
|
||||
let sources: Vec<_> = disks.into_iter().flatten().map(|disk| (disk, path.to_owned())).collect();
|
||||
assert_eq!(sources.len(), 2);
|
||||
for (disk, path) in &sources {
|
||||
disk.make_volume(volume).await.expect("create volume");
|
||||
disk.write_all(volume, path, bytes.clone())
|
||||
.await
|
||||
.expect("write full proof index");
|
||||
}
|
||||
|
||||
let proof = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: vec![sources[0].clone()],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: Some(19),
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let calls = disk_call_counters::observe(path);
|
||||
for stripe in 2..19 {
|
||||
proof.verify(stripe, 0, b"abcdefgh").await.expect("verify requested stripe");
|
||||
}
|
||||
assert!(proof.cached.lock().await.window.is_none(), "the range ends inside the part");
|
||||
assert!(proof.record(19).await.is_err(), "the request must not fetch a stripe outside its range");
|
||||
assert_eq!(calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN), 2, "17 stripes need two streams");
|
||||
drop(calls);
|
||||
|
||||
let (mut stalled_writer, stalled_reader) = tokio::io::duplex(64);
|
||||
let hedged = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: sources.clone(),
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache {
|
||||
window: Some(ProofWindow {
|
||||
next: 2,
|
||||
end: 18,
|
||||
reader: Box::new(stalled_reader),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
hedged
|
||||
.verify(2, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("a healthy replica must replace a stalled continuation");
|
||||
assert_eq!(hedged.cached.lock().await.preferred, 1);
|
||||
assert_eq!(
|
||||
stalled_writer
|
||||
.write_u8(0)
|
||||
.await
|
||||
.expect_err("the losing continuation must be dropped")
|
||||
.kind(),
|
||||
io::ErrorKind::BrokenPipe
|
||||
);
|
||||
|
||||
let missing_path = "missing-part.integrity";
|
||||
let missing = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: vec![(sources[0].0.clone(), missing_path.to_owned())],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let calls = disk_call_counters::observe(missing_path);
|
||||
assert!(missing.record(2).await.is_err(), "a missing sidecar cannot authenticate the record");
|
||||
assert_eq!(
|
||||
calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN),
|
||||
1,
|
||||
"a shorter read cannot open a missing file"
|
||||
);
|
||||
drop(calls);
|
||||
|
||||
let short_end = part.record_offset(4).expect("end of shortened index");
|
||||
let corrupt_offset = part.record_offset(3).expect("record offset");
|
||||
let mut damaged = bytes[..short_end].to_vec();
|
||||
damaged[corrupt_offset] ^= 1;
|
||||
sources[0]
|
||||
.0
|
||||
.write_all(volume, path, Bytes::from(damaged))
|
||||
.await
|
||||
.expect("damage preferred replica");
|
||||
let degraded = PartProofReader {
|
||||
part,
|
||||
sources: vec![sources[0].clone()],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
degraded
|
||||
.verify(2, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("intact record in a truncated replica");
|
||||
{
|
||||
let cached = degraded.cached.lock().await;
|
||||
assert_eq!(cached.preferred, 0, "a truncated suffix must not reject a valid requested record");
|
||||
assert!(cached.window.is_none());
|
||||
}
|
||||
let degraded = PartProofReader { sources, ..degraded };
|
||||
degraded
|
||||
.verify(3, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("recover the corrupt record from another replica");
|
||||
assert_eq!(degraded.cached.lock().await.preferred, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spilled_index_write_verify_and_restore_proof_replicas_round_trip() {
|
||||
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
|
||||
|
||||
@@ -26,10 +26,6 @@ use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use tokio::sync::{Mutex, Notify, OwnedRwLockReadGuard};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Internal metadata suffix preserving an object's initial logical body revision
|
||||
/// across pool data movement (`rebalance` / `decommission`).
|
||||
pub const LOGICAL_BODY_REVISION_SUFFIX: &str = "logical-body-revision-v1";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NamespaceLockFence {
|
||||
signals: Arc<Vec<Arc<rustfs_lock::distributed_lock::LockLostSignal>>>,
|
||||
@@ -1647,14 +1643,6 @@ impl ObjectOptions {
|
||||
self.version_id.is_some() || !self.versioned || self.version_suspended
|
||||
}
|
||||
|
||||
/// Version slot replaced by a PUT. A fresh named version has no predecessor.
|
||||
pub(crate) fn replaced_version_id(&self) -> crate::error::Result<Option<Uuid>> {
|
||||
if let Some(id) = self.version_id.as_deref() {
|
||||
return Ok(Some(Uuid::parse_str(id)?));
|
||||
}
|
||||
Ok(self.overwrites_existing_version().then(Uuid::nil))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn add_namespace_lock_lost_signal(&mut self, signal: Arc<rustfs_lock::distributed_lock::LockLostSignal>) {
|
||||
#[cfg(test)]
|
||||
@@ -1757,10 +1745,6 @@ impl ObjectOptions {
|
||||
.unwrap_or(ReplicationStatusType::Empty)
|
||||
}
|
||||
|
||||
pub(crate) fn is_inbound_multipart_replica(&self) -> bool {
|
||||
self.replication_request || self.delete_marker_replication_status() == ReplicationStatusType::Replica
|
||||
}
|
||||
|
||||
pub fn put_replication_state(&self) -> ReplicationState {
|
||||
if self
|
||||
.delete_replication
|
||||
@@ -1899,8 +1883,6 @@ pub struct ObjectInfo {
|
||||
/// published by the same upload. Callers must not repeat quota, replication,
|
||||
/// lifecycle, or object-created side effects for that response.
|
||||
pub multipart_completion_replayed: bool,
|
||||
/// Logical usage observed under the object locks for this PUT.
|
||||
pub put_usage: Option<crate::data_usage::PutUsageReceipt>,
|
||||
/// Previous current version's size observed during `rename_data` commit.
|
||||
pub backfilled_old_current_size: Option<crate::disk::OldCurrentSize>,
|
||||
/// Persisted EC block size of a local version, projected from its erasure
|
||||
@@ -1951,7 +1933,6 @@ impl Default for ObjectInfo {
|
||||
replication_decision: String::new(),
|
||||
checksum: None,
|
||||
multipart_completion_replayed: false,
|
||||
put_usage: None,
|
||||
backfilled_old_current_size: None,
|
||||
ec_block_size: None,
|
||||
}
|
||||
@@ -1997,7 +1978,6 @@ impl Clone for ObjectInfo {
|
||||
replication_decision: self.replication_decision.clone(),
|
||||
checksum: self.checksum.clone(),
|
||||
multipart_completion_replayed: self.multipart_completion_replayed,
|
||||
put_usage: self.put_usage,
|
||||
backfilled_old_current_size: self.backfilled_old_current_size,
|
||||
ec_block_size: self.ec_block_size,
|
||||
expires: self.expires,
|
||||
@@ -2318,16 +2298,6 @@ impl ObjectInfo {
|
||||
.unwrap_or_else(|_| self.size.max(0))
|
||||
}
|
||||
|
||||
/// Logical body revision preserved across pool data movement (`rebalance` /
|
||||
/// `decommission`), falling back to physical `data_dir` when no internal
|
||||
/// logical revision marker is present.
|
||||
pub fn logical_body_revision(&self) -> Option<Uuid> {
|
||||
rustfs_utils::http::get_consistent_str(&self.user_defined, LOGICAL_BODY_REVISION_SUFFIX)
|
||||
.and_then(|value| Uuid::parse_str(value.trim()).ok())
|
||||
.filter(|id| !id.is_nil())
|
||||
.or_else(|| self.data_dir.filter(|id| !id.is_nil()))
|
||||
}
|
||||
|
||||
pub fn from_file_info(fi: &FileInfo, bucket: &str, object: &str, versioned: bool) -> ObjectInfo {
|
||||
let mut version_id = fi.version_id;
|
||||
|
||||
|
||||
@@ -22,27 +22,22 @@ use std::time::Duration;
|
||||
///
|
||||
/// Callers cannot fabricate a guard without acquiring its namespace lock.
|
||||
///
|
||||
/// ```compile_fail,E0451
|
||||
/// ```compile_fail
|
||||
/// use rustfs_ecstore::api::object::WriteCommitGuard;
|
||||
/// use std::sync::Arc;
|
||||
///
|
||||
/// fn fabricate(guard: Arc<rustfs_lock::NamespaceLockGuard>) -> WriteCommitGuard {
|
||||
/// WriteCommitGuard { bucket: "bucket".into(), object: "object".into(), guard, backend: None }
|
||||
/// }
|
||||
/// let guard = WriteCommitGuard {
|
||||
/// bucket: "bucket".into(),
|
||||
/// object: "object".into(),
|
||||
/// guards: Arc::new(Vec::new()),
|
||||
/// };
|
||||
/// ```
|
||||
#[doc(hidden)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WriteCommitGuard {
|
||||
bucket: Arc<str>,
|
||||
object: Arc<str>,
|
||||
guard: Arc<rustfs_lock::NamespaceLockGuard>,
|
||||
backend: Option<BorrowedWriteBackend>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum BorrowedWriteBackend {
|
||||
Object(rustfs_lock::namespace::WriteLockBackend),
|
||||
Version,
|
||||
guards: Arc<Vec<Arc<rustfs_lock::NamespaceLockGuard>>>,
|
||||
}
|
||||
|
||||
impl WriteCommitGuard {
|
||||
@@ -51,42 +46,27 @@ impl WriteCommitGuard {
|
||||
lock: &rustfs_lock::NamespaceLockWrapper,
|
||||
timeout: Duration,
|
||||
) -> std::result::Result<Self, rustfs_lock::LockError> {
|
||||
let guard = Arc::new(lock.get_write_lock_extending(timeout, &[]).await?);
|
||||
let guard = Arc::new(lock.get_write_lock(timeout).await?);
|
||||
let key = lock.resource();
|
||||
let mut owner = Self::from_guard(guard, &key.bucket, &key.object);
|
||||
owner.backend = Some(if key.version.is_none() {
|
||||
BorrowedWriteBackend::Object(lock.write_backend())
|
||||
} else {
|
||||
BorrowedWriteBackend::Version
|
||||
});
|
||||
Ok(owner)
|
||||
Ok(Self::from_guard(guard, &key.bucket, &key.object))
|
||||
}
|
||||
|
||||
pub(crate) fn from_guard(guard: Arc<rustfs_lock::NamespaceLockGuard>, bucket: &str, object: &str) -> Self {
|
||||
Self {
|
||||
bucket: bucket.into(),
|
||||
object: object_name_disk_identity(object).as_ref().into(),
|
||||
guard,
|
||||
backend: None,
|
||||
guards: Arc::new(vec![guard]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the loss signal of the namespace owner retained by acquisition.
|
||||
#[doc(hidden)]
|
||||
pub fn lock_lost_signal(&self) -> Option<Arc<rustfs_lock::distributed_lock::LockLostSignal>> {
|
||||
self.guard.lock_lost_signal()
|
||||
self.guards.first().and_then(|guard| guard.lock_lost_signal())
|
||||
}
|
||||
|
||||
pub fn is_lock_lost(&self) -> bool {
|
||||
self.guard.is_lock_lost() || self.guard.is_released()
|
||||
}
|
||||
|
||||
fn owners_for(guards: &[Self], bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
guards
|
||||
.iter()
|
||||
.filter(|guard| guard.matches(bucket, object))
|
||||
.map(|guard| Arc::clone(&guard.guard))
|
||||
.collect()
|
||||
self.guards.iter().any(|guard| guard.is_lock_lost() || guard.is_released())
|
||||
}
|
||||
|
||||
/// Namespace locks key the disk identity of the name (see `new_ns_lock`),
|
||||
@@ -170,13 +150,6 @@ impl WriteCommitContext {
|
||||
matches!(self, Self::Borrowed(_))
|
||||
}
|
||||
|
||||
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
match self {
|
||||
Self::Borrowed(guards) => WriteCommitGuard::owners_for(guards, bucket, object),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_lock_lost(&self) -> bool {
|
||||
matches!(self, Self::Borrowed(guards) if guards.iter().any(WriteCommitGuard::is_lock_lost))
|
||||
}
|
||||
@@ -187,62 +160,24 @@ impl WriteCommitContext {
|
||||
}
|
||||
|
||||
impl ObjectOptions {
|
||||
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
match self.write_lock_context.as_ref().map(|context| &context.mode) {
|
||||
Some(WriteLockMode::Borrowed(guards)) => WriteCommitGuard::owners_for(guards, bucket, object),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn borrows_fixed_write_lock(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
lock: &rustfs_lock::NamespaceLockWrapper,
|
||||
) -> Result<bool> {
|
||||
let Some(WriteLockContext {
|
||||
mode: WriteLockMode::Borrowed(guards),
|
||||
}) = self.write_lock_context.as_ref()
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut borrowed = false;
|
||||
for guard in guards.iter().filter(|guard| guard.matches(bucket, object)) {
|
||||
if let Some(backend) = &guard.backend {
|
||||
if !matches!(backend, BorrowedWriteBackend::Object(held) if held.matches(lock)) {
|
||||
return Err(Error::InvalidArgument(
|
||||
bucket.to_owned(),
|
||||
object.to_owned(),
|
||||
"borrowed write guard does not own the fixed object namespace".to_owned(),
|
||||
));
|
||||
}
|
||||
if guard.is_lock_lost() {
|
||||
return Err(Error::NamespaceLockQuorumUnavailable {
|
||||
mode: "put_object_outer_lock",
|
||||
bucket: bucket.to_owned(),
|
||||
object: object.to_owned(),
|
||||
required: 1,
|
||||
achieved: 0,
|
||||
});
|
||||
}
|
||||
borrowed = true;
|
||||
}
|
||||
}
|
||||
Ok(borrowed)
|
||||
}
|
||||
|
||||
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
|
||||
self.add_namespace_lock_guard(&guard.guard);
|
||||
for owner in guard.guards.iter() {
|
||||
self.add_namespace_lock_guard(owner);
|
||||
}
|
||||
let mut guards = match self.write_lock_context.as_ref() {
|
||||
Some(WriteLockContext {
|
||||
mode: WriteLockMode::Borrowed(existing),
|
||||
}) => existing.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if !guards
|
||||
.iter()
|
||||
.any(|held| Arc::ptr_eq(&held.guard, &guard.guard) && held.matches(&guard.bucket, &guard.object))
|
||||
{
|
||||
if let Some(existing) = guards.iter_mut().find(|held| held.matches(&guard.bucket, &guard.object)) {
|
||||
let owners = Arc::make_mut(&mut existing.guards);
|
||||
for owner in guard.guards.iter() {
|
||||
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
|
||||
owners.push(Arc::clone(owner));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
guards.push(guard.clone());
|
||||
}
|
||||
self.no_lock = true;
|
||||
|
||||
@@ -207,16 +207,13 @@ impl ListReadBudget {
|
||||
}
|
||||
}
|
||||
|
||||
fn weight(&self, fanout: usize) -> usize {
|
||||
// Admit a full walk even when its fanout exceeds the configured budget.
|
||||
fanout.max(1).min(self.capacity)
|
||||
}
|
||||
|
||||
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
|
||||
if self.capacity == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let weight = u32::try_from(self.weight(fanout)).unwrap_or(u32::MAX);
|
||||
// A single walk must remain admissible even when the topology exceeds
|
||||
// the configured budget. Tokio accepts at most u32::MAX in one grant.
|
||||
let weight = u32::try_from(fanout.max(1).min(self.capacity)).unwrap_or(u32::MAX);
|
||||
self.permits
|
||||
.clone()
|
||||
.acquire_many_owned(weight)
|
||||
@@ -423,8 +420,6 @@ pub struct InstanceContext {
|
||||
/// caller (for example, an S3 client disconnect) cannot stop them between
|
||||
/// their on-disk steps. Shutdown waits for them after the HTTP drain.
|
||||
detached_mutations: TaskTracker,
|
||||
/// Limits v1 settlements that may outlive a successful object response.
|
||||
pub(crate) v1_quota_settlement_slots: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl InstanceContext {
|
||||
@@ -496,12 +491,6 @@ impl InstanceContext {
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn list_read_budget_has_capacity(&self, fanout: usize) -> Option<bool> {
|
||||
self.list_read_budget
|
||||
.get()
|
||||
.map(|budget| budget.permits.available_permits() >= budget.weight(fanout))
|
||||
}
|
||||
|
||||
/// Build a context bound to a specific lock manager.
|
||||
///
|
||||
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
|
||||
@@ -564,7 +553,6 @@ impl InstanceContext {
|
||||
transition_transaction_recovery_stores: std::sync::Mutex::new(HashSet::new()),
|
||||
tier_delete_journal_recovery_wakeup: tokio::sync::Notify::new(),
|
||||
detached_mutations: TaskTracker::new(),
|
||||
v1_quota_settlement_slots: Arc::new(Semaphore::new(64)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -588,14 +576,6 @@ impl InstanceContext {
|
||||
/// the mutation, together with the locks and guards it owns, never stops
|
||||
/// between two of its on-disk steps because its caller went away.
|
||||
pub(crate) async fn run_detached_mutation<F>(&self, mutation: F) -> Result<F::Output, tokio::task::JoinError>
|
||||
where
|
||||
F: std::future::Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
{
|
||||
self.spawn_detached_mutation(mutation).await
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_detached_mutation<F>(&self, mutation: F) -> tokio::task::JoinHandle<F::Output>
|
||||
where
|
||||
F: std::future::Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
@@ -610,7 +590,7 @@ impl InstanceContext {
|
||||
let context = rustfs_io_metrics::s3_http_metrics::current_s3_http_operation_context();
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
let mutation = rustfs_io_metrics::s3_http_metrics::with_s3_http_operation_context(context, mutation);
|
||||
self.detached_mutations.spawn(mutation.in_current_span())
|
||||
self.detached_mutations.spawn(mutation.in_current_span()).await
|
||||
}
|
||||
|
||||
/// Wait up to `timeout` for every detached mutation to finish. Returns
|
||||
@@ -1595,16 +1575,8 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_read_budget_zero_preserves_unbounded_configuration() {
|
||||
let ctx = InstanceContext::new();
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(1), None);
|
||||
ctx.list_read_budget.set(ListReadBudget::new(0)).expect("fresh context");
|
||||
assert!(
|
||||
ctx.acquire_list_read_budget(usize::MAX)
|
||||
.await
|
||||
.expect("disabled budget")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(usize::MAX), Some(true));
|
||||
let budget = ListReadBudget::new(0);
|
||||
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1639,8 +1611,6 @@ mod tests {
|
||||
let other = InstanceContext::new();
|
||||
other.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
|
||||
let held = first.acquire_list_read_budget(4).await.expect("first context");
|
||||
assert_eq!(same.list_read_budget_has_capacity(4), Some(false));
|
||||
assert_eq!(other.list_read_budget_has_capacity(4), Some(true));
|
||||
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
|
||||
assert!(futures::poll!(&mut waiter).is_pending());
|
||||
assert!(
|
||||
@@ -1652,18 +1622,6 @@ mod tests {
|
||||
);
|
||||
drop(held);
|
||||
assert!(waiter.await.expect("shared context resumed").is_some());
|
||||
assert_eq!(same.list_read_budget_has_capacity(4), Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_read_budget_reports_capacity_for_the_requested_fanout() {
|
||||
let ctx = InstanceContext::new();
|
||||
ctx.list_read_budget.set(ListReadBudget::new(64)).expect("fresh context");
|
||||
let held = ctx.acquire_list_read_budget(48).await.expect("first walk");
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(16), Some(true));
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(false));
|
||||
drop(held);
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -833,13 +833,11 @@ impl BitrotReaderSetup {
|
||||
disks: &[Option<DiskStore>],
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
stripes: std::ops::Range<usize>,
|
||||
first_stripe: usize,
|
||||
) -> std::io::Result<()> {
|
||||
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
|
||||
let Some(expected) = expected else { return Ok(()) };
|
||||
let first_stripe = stripes.start;
|
||||
let end_stripe = u32::try_from(stripes.end).map_err(std::io::Error::other)?;
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(end_stripe))?;
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
|
||||
for (index, reader) in self.readers.iter_mut().enumerate() {
|
||||
if let Some(reader) = reader {
|
||||
let advanced = self.deferred_stripe_handles[index]
|
||||
@@ -7973,7 +7971,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
pub(crate) fn evaluate_write_precondition(
|
||||
oi: Result<impl std::borrow::Borrow<ObjectInfo>>,
|
||||
oi: Result<ObjectInfo>,
|
||||
http_preconditions: &HTTPPreconditions,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
@@ -7981,7 +7979,6 @@ impl SetDisks {
|
||||
) -> Option<StorageError> {
|
||||
match oi {
|
||||
Ok(oi) => {
|
||||
let oi = oi.borrow();
|
||||
// Ordinary writes may proceed past a top-level delete marker;
|
||||
// data movement and guarded internal writes must preserve it.
|
||||
if oi.delete_marker {
|
||||
@@ -7995,8 +7992,8 @@ impl SetDisks {
|
||||
object,
|
||||
);
|
||||
}
|
||||
if should_prevent_write(oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
|
||||
&& !crate::data_movement::can_replace_stale_data_movement_target(oi, opts)
|
||||
if should_prevent_write(&oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
|
||||
&& !crate::data_movement::can_replace_stale_data_movement_target(&oi, opts)
|
||||
{
|
||||
return Some(StorageError::PreconditionFailed);
|
||||
}
|
||||
@@ -8383,7 +8380,6 @@ pub(crate) mod disk_call_counters {
|
||||
pub const KIND_METADATA_SLOWTAIL_FAULT: &str = "metadata_slowtail_fault";
|
||||
pub const KIND_INLINE_SHARD_OPEN: &str = "inline_shard_open";
|
||||
pub const KIND_DISK_SHARD_OPEN: &str = "disk_shard_open";
|
||||
pub const KIND_PROOF_STREAM_OPEN: &str = "proof_stream_open";
|
||||
/// Body verification, direct shard assembly, and erasure decoder entry points.
|
||||
pub const KIND_BODY_DECODE: &str = "body_decode";
|
||||
|
||||
@@ -8457,10 +8453,6 @@ pub(crate) mod disk_call_counters {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_proof_stream_open(path: &str, replica: usize) {
|
||||
record(path, KIND_PROOF_STREAM_OPEN, replica);
|
||||
}
|
||||
|
||||
/// RAII scope that observes call counts for a single `object`. Counts recorded
|
||||
/// while the scope is alive — including those recorded inside spawned tasks —
|
||||
/// are queryable; the scope clears its own counts on drop.
|
||||
|
||||
@@ -46,7 +46,7 @@ struct FileInfoQuorumKey {
|
||||
|
||||
impl SetDisks {
|
||||
/// Read one key's complete version stack without enumerating its parent.
|
||||
pub(crate) async fn read_object_version_history(
|
||||
pub(crate) async fn read_object_versions_for_lifecycle(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
|
||||
@@ -138,7 +138,6 @@ use rustfs_io_metrics::{
|
||||
use rustfs_lock::LockClient;
|
||||
#[cfg(test)]
|
||||
use rustfs_lock::LockManager;
|
||||
use rustfs_lock::distributed_lock::same_write_voters;
|
||||
use rustfs_lock::fast_lock::types::LockResult;
|
||||
use rustfs_lock::{FastLockGuard, NamespaceLock, NamespaceLockGuard, NamespaceLockWrapper, ObjectKey};
|
||||
use rustfs_madmin::heal_commands::{HealDriveInfo, HealResultItem, Infos};
|
||||
@@ -508,12 +507,9 @@ fn release_materialized_read_lock(bucket: &str, object: &str, read_lock_guard: O
|
||||
drop(read_lock_guard);
|
||||
}
|
||||
|
||||
const MULTIPART_GENERATED_VERSION_SUFFIX: &str = "multipart-generated-version-id";
|
||||
|
||||
pub(crate) fn strip_internal_multipart_metadata(metadata: &mut HashMap<String, String>) {
|
||||
metadata.remove(RUSTFS_MULTIPART_BUCKET_KEY);
|
||||
metadata.remove(RUSTFS_MULTIPART_OBJECT_KEY);
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, MULTIPART_GENERATED_VERSION_SUFFIX);
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, SUFFIX_BUCKET_INCARNATION_ID);
|
||||
}
|
||||
|
||||
@@ -4959,6 +4955,17 @@ pub(crate) fn same_distributed_lock_domain(left: &[Arc<dyn LockClient>], right:
|
||||
.all(|right_client| left.iter().any(|left_client| Arc::ptr_eq(left_client, right_client)))
|
||||
}
|
||||
|
||||
// Reusing a held writer additionally requires the same quorum, so repeated
|
||||
// clients must not give different weight to an otherwise identical domain.
|
||||
fn same_distributed_lock_quorum(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
|
||||
!left.is_empty()
|
||||
&& left.len() == right.len()
|
||||
&& left.iter().all(|client| {
|
||||
left.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
|
||||
&& right.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
|
||||
})
|
||||
}
|
||||
|
||||
const ERASURE_CACHE_MAX_ENTRIES: usize = 32;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
@@ -5584,10 +5591,18 @@ impl SetDisks {
|
||||
.with_attempt(attempt))
|
||||
}
|
||||
|
||||
async fn object_write_namespace_lock(&self, op: &str, bucket: &str, object: &str) -> Result<NamespaceLockWrapper> {
|
||||
let mut lock = self.new_ns_lock(bucket, object).await?;
|
||||
if op == "put_object_commit" {
|
||||
lock.order_object_writes();
|
||||
}
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
async fn acquire_write_lock_diag(&self, op: &'static str, bucket: &str, object: &str) -> Result<ObjectLockDiagGuard> {
|
||||
crate::hp_guard!("SetDisks::acquire_write_lock");
|
||||
let diag_enabled = is_object_lock_diag_enabled();
|
||||
let ns_lock = self.new_ns_lock(bucket, object).await?;
|
||||
let ns_lock = self.object_write_namespace_lock(op, bucket, object).await?;
|
||||
let acquire_start = Instant::now();
|
||||
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
|
||||
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
|
||||
@@ -5630,7 +5645,7 @@ impl SetDisks {
|
||||
) -> Result<ObjectLockDiagGuard> {
|
||||
crate::hp_guard!("SetDisks::acquire_write_lock");
|
||||
let diag_enabled = is_object_lock_diag_enabled();
|
||||
let ns_lock = self.new_ns_lock(bucket, object).await?;
|
||||
let ns_lock = self.object_write_namespace_lock(op, bucket, object).await?;
|
||||
let acquire_start = Instant::now();
|
||||
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
|
||||
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
|
||||
@@ -5945,7 +5960,7 @@ impl SetDisks {
|
||||
(false, false) => Arc::ptr_eq(&self.local_lock_manager, &other.local_lock_manager),
|
||||
// Distributed lock clients receive the raw ObjectKey; the pool
|
||||
// namespace is not part of the key stored by their backends.
|
||||
(true, true) => same_write_voters(&self.lockers, &other.lockers),
|
||||
(true, true) => same_distributed_lock_quorum(&self.lockers, &other.lockers),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -10477,10 +10492,13 @@ mod tests {
|
||||
let a: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
let b: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
let c: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
assert!(same_write_voters(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
|
||||
assert!(!same_write_voters(&[a.clone(), b.clone()], &[a.clone(), c]));
|
||||
assert!(!same_write_voters(&[a.clone(), a.clone(), b.clone()], &[a.clone(), b.clone(), b]));
|
||||
assert!(!same_write_voters(&[], &[]));
|
||||
assert!(same_distributed_lock_quorum(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
|
||||
assert!(!same_distributed_lock_quorum(&[a.clone(), b.clone()], &[a.clone(), c]));
|
||||
assert!(!same_distributed_lock_quorum(
|
||||
&[a.clone(), a.clone(), b.clone()],
|
||||
&[a.clone(), b.clone(), b]
|
||||
));
|
||||
assert!(!same_distributed_lock_quorum(&[], &[]));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -22,8 +22,7 @@ use crate::disk::{
|
||||
};
|
||||
use crate::error::StorageError;
|
||||
use crate::set_disk::SetDisks;
|
||||
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
|
||||
use futures::future::{join_all, try_join_all};
|
||||
use futures::future::join_all;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
@@ -600,98 +599,6 @@ fn causal_transaction_order(states: &BTreeMap<Uuid, Vec<DeleteRecoveryInspection
|
||||
}
|
||||
|
||||
impl SetDisks {
|
||||
/// With the lifecycle fence held by the caller, check the exact set without
|
||||
/// repairing payloads or settling delete transactions.
|
||||
pub(crate) async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> crate::error::Result<bool> {
|
||||
let first = {
|
||||
let disks = self.disks.read().await;
|
||||
disks
|
||||
.iter()
|
||||
.flatten()
|
||||
.find(|disk| disk.is_local())
|
||||
.or_else(|| disks.iter().flatten().next())
|
||||
.cloned()
|
||||
};
|
||||
let Some(first) = first else {
|
||||
return Ok(false);
|
||||
};
|
||||
let missing = async |disk: &DiskStore| match disk
|
||||
.read_version("", bucket, object, "", &crate::disk::ReadOptions::default())
|
||||
.await
|
||||
{
|
||||
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) => Ok(true),
|
||||
Ok(_) => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
if !missing(&first).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
// Lock order matches delete recovery and multi-pool decommission:
|
||||
// lifecycle, fixed/target raw object, decommission capacity, transaction, then inventory validation.
|
||||
let (fixed_guard, object_guard, capacity_guard) = if let Some(store) = capacity_store {
|
||||
Box::pin(async {
|
||||
let (fixed_guard, target_guard) = store.acquire_external_read_namespace(bucket, object, self).await?;
|
||||
let capacity_guard = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
crate::error::Result::Ok((Some(fixed_guard), target_guard, Some(capacity_guard)))
|
||||
})
|
||||
.await?
|
||||
} else {
|
||||
let namespace = self.new_ns_lock(bucket, object).await?;
|
||||
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
|
||||
(None, Some(object_guard), None)
|
||||
};
|
||||
let transaction_guard = self.acquire_delete_transaction_lock(bucket, object).await?;
|
||||
let disks = self.get_disks_internal().await;
|
||||
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
|
||||
return Ok(false);
|
||||
}
|
||||
// The fast rejection is a hint. Read every member under both locks
|
||||
// before accepting a candidate absence.
|
||||
if try_join_all(disks.iter().flatten().map(missing)).await?.contains(&false) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// A recoverable transaction or legacy backup can restore the object.
|
||||
// Require complete, empty discovery on every disk. No inspection or
|
||||
// settlement is needed for this read-only path.
|
||||
let budget = crate::object_api::DeleteRecoveryWorkBudget::for_disks(disks.len());
|
||||
let transactions = try_join_all(
|
||||
disks
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|disk| discover_bounded(disk, bucket, object, &budget)),
|
||||
)
|
||||
.await?;
|
||||
if transactions.iter().any(|transactions| !transactions.is_empty()) {
|
||||
return Ok(false);
|
||||
}
|
||||
// Do not hold the registry read guard across RPC or disk I/O. A
|
||||
// topology writer may have replaced a member while the probe ran.
|
||||
let current = self.disks.read().await;
|
||||
let namespace_alive = fixed_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& object_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& capacity_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost());
|
||||
Ok(current.len() == disks.len()
|
||||
&& current.iter().zip(&disks).all(|(current, probed)| {
|
||||
current
|
||||
.as_ref()
|
||||
.zip(probed.as_ref())
|
||||
.is_some_and(|(current, probed)| Arc::ptr_eq(current, probed))
|
||||
})
|
||||
&& namespace_alive
|
||||
&& !transaction_guard.is_lock_lost())
|
||||
}
|
||||
|
||||
/// Publication follows the ordinary metadata quorum. Once a publication is
|
||||
/// attempted, response loss must never trigger blind rollback.
|
||||
pub(in crate::set_disk) async fn publish_delete_commit(
|
||||
@@ -2725,9 +2632,6 @@ mod tests {
|
||||
for shape in ["live-backup", "foreign", "partial-history", "damaged-data", "causal-cycle"] {
|
||||
let bucket = "recover-marker-source-guards";
|
||||
let (dirs, store) = isolated_store_over_temp_disks().await;
|
||||
store.pools[0].stop_endpoint_monitor_for_test().await;
|
||||
store.background_cancel_token().expect("fixture background token").cancel();
|
||||
tokio::task::yield_now().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
store
|
||||
.make_bucket(
|
||||
@@ -2748,7 +2652,7 @@ mod tests {
|
||||
set.disks.write().await[3] = None;
|
||||
let payload = vec![72; 1024 * 1024];
|
||||
let source = put(&store, bucket, &payload, true).await.unwrap();
|
||||
let marker = store
|
||||
store
|
||||
.delete_object(
|
||||
bucket,
|
||||
"object",
|
||||
@@ -2759,17 +2663,6 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.expect("publish marker while one member lacks the source version");
|
||||
let marker_id = marker.version_id.expect("the delete marker has a version ID");
|
||||
for absent in [source, marker_id] {
|
||||
assert_eq!(
|
||||
disks[3]
|
||||
.read_version("", bucket, "object", &absent.to_string(), &ReadOptions::default())
|
||||
.await
|
||||
.expect_err("the disconnected member must lack the source and marker"),
|
||||
DiskError::FileVersionNotFound,
|
||||
"{shape}: unexpected result reading version {absent}"
|
||||
);
|
||||
}
|
||||
set.disks.write().await[3] = Some(disks[3].clone());
|
||||
let mut first_info = disks[3]
|
||||
.read_version("", bucket, "object", &first.to_string(), &ReadOptions::default())
|
||||
@@ -2802,14 +2695,7 @@ mod tests {
|
||||
DeleteOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("remove the oldest member of the returning disk's history");
|
||||
assert_eq!(
|
||||
disks[3]
|
||||
.read_version("", bucket, "object", &oldest.to_string(), &ReadOptions::default())
|
||||
.await
|
||||
.expect_err("the returning disk's history must be incomplete before heal"),
|
||||
DiskError::FileVersionNotFound
|
||||
);
|
||||
.unwrap();
|
||||
}
|
||||
"damaged-data" => {
|
||||
// Three metadata sources meet write quorum, but corrupting
|
||||
|
||||
@@ -31,37 +31,11 @@ use std::sync::Arc;
|
||||
#[path = "heal_lock_wait_tests.rs"]
|
||||
mod heal_lock_wait_tests;
|
||||
|
||||
struct ExternalHealCommit {
|
||||
namespace: Option<crate::store::ObjectLockDiagGuard>,
|
||||
capacity: rustfs_lock::NamespaceLockGuard,
|
||||
}
|
||||
|
||||
impl ExternalHealCommit {
|
||||
fn is_lock_lost(&self) -> bool {
|
||||
self.capacity.is_lock_lost() || self.namespace.as_ref().is_some_and(|owner| owner.is_lock_lost())
|
||||
}
|
||||
}
|
||||
|
||||
enum ReadRepairWriteGuard {
|
||||
Set(Box<ObjectLockDiagGuard>),
|
||||
External(Arc<ExternalHealCommit>),
|
||||
}
|
||||
|
||||
impl ReadRepairWriteGuard {
|
||||
fn is_lock_lost(&self) -> bool {
|
||||
match self {
|
||||
Self::Set(guard) => guard.is_lock_lost(),
|
||||
Self::External(guard) => guard.is_lock_lost(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct ExplicitVersionHeal<'a> {
|
||||
opts: &'a HealOpts,
|
||||
allow_regeneration: bool,
|
||||
preserve_unrepairable: bool,
|
||||
capacity_store: Option<&'a crate::store::ECStore>,
|
||||
commit_fence: Option<&'a (dyn Fn() -> bool + Sync)>,
|
||||
namespace_owner: Option<&'a Arc<dyn Send + Sync>>,
|
||||
retirement: Option<&'a MarkerRetirementContext<'a>>,
|
||||
@@ -964,7 +938,6 @@ impl SetDisks {
|
||||
opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: None,
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -1050,29 +1023,6 @@ impl SetDisks {
|
||||
.with_attempt(attempt))
|
||||
}
|
||||
|
||||
async fn admit_external_heal_commit(
|
||||
&self,
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
no_lock: bool,
|
||||
) -> Result<Arc<ExternalHealCommit>> {
|
||||
let namespace = if no_lock {
|
||||
None
|
||||
} else {
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_target_lock_attempted();
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
};
|
||||
let capacity = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
Ok(Arc::new(ExternalHealCommit { namespace, capacity }))
|
||||
}
|
||||
|
||||
async fn acquire_revalidated_read_repair_commit_lock(
|
||||
&self,
|
||||
disks: &[Option<DiskStore>],
|
||||
@@ -1080,24 +1030,14 @@ impl SetDisks {
|
||||
object: &str,
|
||||
version_id: &str,
|
||||
expected_fingerprint: ReadRepairCommitFingerprint,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> disk::error::Result<Option<ReadRepairWriteGuard>> {
|
||||
) -> disk::error::Result<Option<ObjectLockDiagGuard>> {
|
||||
#[cfg(test)]
|
||||
pause_read_repair(bucket, object, ReadRepairPausePhase::Commit).await;
|
||||
|
||||
let write_lock_wait_start = std::time::Instant::now();
|
||||
let guard = if let Some(store) = capacity_store {
|
||||
ReadRepairWriteGuard::External(
|
||||
self.admit_external_heal_commit(store, bucket, object, false)
|
||||
.await
|
||||
.map_err(|error| error.narrow_to_disk().unwrap_or_else(DiskError::other))?,
|
||||
)
|
||||
} else {
|
||||
ReadRepairWriteGuard::Set(Box::new(
|
||||
self.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
|
||||
.await?,
|
||||
))
|
||||
};
|
||||
let guard = self
|
||||
.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
|
||||
.await?;
|
||||
let write_lock_wait_ms = u64::try_from(write_lock_wait_start.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
|
||||
let revalidation_start = std::time::Instant::now();
|
||||
@@ -1148,7 +1088,6 @@ impl SetDisks {
|
||||
opts,
|
||||
allow_regeneration: allow_explicit_version_regen,
|
||||
preserve_unrepairable,
|
||||
capacity_store,
|
||||
commit_fence,
|
||||
namespace_owner,
|
||||
retirement,
|
||||
@@ -1874,14 +1813,7 @@ impl SetDisks {
|
||||
.integrity
|
||||
.as_ref()
|
||||
.map(|part| {
|
||||
PartProofReader::new(
|
||||
part.clone(),
|
||||
&parts_metadata,
|
||||
&latest_disks,
|
||||
bucket,
|
||||
object,
|
||||
None,
|
||||
)
|
||||
PartProofReader::new(part.clone(), &parts_metadata, &latest_disks, bucket, object)
|
||||
})
|
||||
.transpose()?;
|
||||
// Cover the complete encoded shard, including a logical
|
||||
@@ -2128,7 +2060,6 @@ impl SetDisks {
|
||||
object,
|
||||
version_id,
|
||||
expected_fingerprint,
|
||||
capacity_store,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -3799,7 +3730,6 @@ impl SetDisks {
|
||||
opts: &opts,
|
||||
allow_regeneration: false,
|
||||
preserve_unrepairable: true,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(can_commit),
|
||||
namespace_owner,
|
||||
retirement: None,
|
||||
@@ -3837,21 +3767,6 @@ impl SetDisks {
|
||||
opts: &HealOpts,
|
||||
absence: &mut Option<HealedObjectAbsence>,
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
self.heal_object_for_store(bucket, object, version_id, opts, absence, proof, None)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn heal_object_for_store(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
version_id: &str,
|
||||
opts: &HealOpts,
|
||||
absence: &mut Option<HealedObjectAbsence>,
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
*absence = None;
|
||||
if opts.read_repair && !opts.no_lock && !opts.dry_run && !opts.remove && !has_suffix(object, SLASH_SEPARATOR) {
|
||||
@@ -3860,15 +3775,6 @@ impl SetDisks {
|
||||
// peer cannot hold an exclusive write lock across read-repair timeouts
|
||||
// and stall foreground bucket reads), without performing destructive
|
||||
// cleanup or producing an authoritative absence proof.
|
||||
if let Some(store) = capacity_store {
|
||||
let probe = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
drop(probe);
|
||||
}
|
||||
let can_commit = || proof.retirement.is_none_or(|context| !context.lifecycle_guard.is_lock_lost());
|
||||
let mut read_opts = *opts;
|
||||
loop {
|
||||
@@ -3881,7 +3787,6 @@ impl SetDisks {
|
||||
opts: &read_opts,
|
||||
allow_regeneration: false,
|
||||
preserve_unrepairable: true,
|
||||
capacity_store,
|
||||
commit_fence: Some(&can_commit),
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -3901,22 +3806,7 @@ impl SetDisks {
|
||||
return Ok((result, error.map(Into::into)));
|
||||
}
|
||||
}
|
||||
let external = match capacity_store {
|
||||
Some(store) => {
|
||||
let guard = self.admit_external_heal_commit(store, bucket, object, opts.no_lock).await?;
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_operation_started(store.id);
|
||||
Some(guard)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let _write_lock_guard = if let Some(external) = &external {
|
||||
external
|
||||
.namespace
|
||||
.as_ref()
|
||||
.and_then(|guard| guard.target_write_guard())
|
||||
.cloned()
|
||||
} else if !opts.no_lock {
|
||||
let _write_lock_guard = if !opts.no_lock {
|
||||
let ns_lock = self
|
||||
.new_ns_lock(bucket, object)
|
||||
.await
|
||||
@@ -3952,8 +3842,7 @@ impl SetDisks {
|
||||
None
|
||||
};
|
||||
let locks_lost = || {
|
||||
external.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|
||||
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
};
|
||||
let mut recovery_removed_version = false;
|
||||
@@ -4115,7 +4004,7 @@ impl SetDisks {
|
||||
let commit_fence = || !locks_lost();
|
||||
let namespace_owner = _write_lock_guard
|
||||
.as_ref()
|
||||
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone(), external.clone())) as Arc<dyn Send + Sync>);
|
||||
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone())) as Arc<dyn Send + Sync>);
|
||||
let (result, err) = pin_object_heal_future(|| {
|
||||
self.heal_object_with_explicit_version_regen(
|
||||
bucket,
|
||||
@@ -4125,7 +4014,6 @@ impl SetDisks {
|
||||
opts: &inner_opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&commit_fence),
|
||||
namespace_owner: namespace_owner.as_ref(),
|
||||
retirement: proof.retirement,
|
||||
@@ -4150,7 +4038,6 @@ impl SetDisks {
|
||||
opts: &inner_opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&commit_fence),
|
||||
namespace_owner: namespace_owner.as_ref(),
|
||||
retirement: proof.retirement,
|
||||
@@ -7006,7 +6893,6 @@ mod heal_result_report_tests {
|
||||
opts: &opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&can_commit),
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -11454,50 +11340,6 @@ mod heal_result_report_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn multipool_read_repair_stages_with_shared_ownership() {
|
||||
let (_dirs, store, _peer) = crate::services::rebalance::test_two_pool_stores(None).await;
|
||||
let bucket = "multipool-shared-read-repair";
|
||||
let key = "entry";
|
||||
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
let target = store.pools[1].get_disks_by_key(key);
|
||||
let seeded = target
|
||||
.put_object(bucket, key, &mut PutObjReader::from_vec(b"body".to_vec()), &ObjectOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let (_pause, started, release) = ReadRepairPauseScope::install_at(bucket, key, super::ReadRepairPausePhase::Data);
|
||||
let repair = tokio::spawn(async move {
|
||||
store
|
||||
.heal_object_with_proof(
|
||||
bucket,
|
||||
key,
|
||||
"",
|
||||
&HealOpts {
|
||||
pool: Some(1),
|
||||
read_repair: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), started.notified())
|
||||
.await
|
||||
.expect("enter read repair under the shared object lock");
|
||||
let visible = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(2),
|
||||
target.get_object_info(bucket, key, &ObjectOptions::default()),
|
||||
)
|
||||
.await
|
||||
.expect("read while repair is staging")
|
||||
.unwrap();
|
||||
assert_eq!(visible.etag, seeded.etag);
|
||||
release.notify_one();
|
||||
let outcome = repair.await.unwrap().unwrap();
|
||||
assert!(outcome.error.is_none());
|
||||
assert!(outcome.absence.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn read_repair_storage_entry_keeps_readers_available_during_reconstruction() {
|
||||
@@ -12112,12 +11954,7 @@ mod shard_identity_tests {
|
||||
..options.clone()
|
||||
};
|
||||
let range_start = size / 5 + 17;
|
||||
let block_size = target_meta[0].erasure.block_size;
|
||||
let range_end = if size > 2 * block_size {
|
||||
2 * block_size - 1
|
||||
} else {
|
||||
size / 2 + 99
|
||||
};
|
||||
let range_end = size / 2 + 99;
|
||||
for (range, expected_body, options) in [
|
||||
(None, expected.as_slice(), &options),
|
||||
(
|
||||
@@ -12198,97 +12035,6 @@ mod shard_identity_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_aligned_range_reads_before_truncated_suffix() {
|
||||
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
|
||||
let bucket = "protected-range-boundary";
|
||||
let object = "truncated-suffix";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create fixture bucket");
|
||||
}
|
||||
let mut expected = vec![0; 3 * 1024 * 1024 + 17];
|
||||
for (index, block) in expected.chunks_mut(4096).enumerate() {
|
||||
block.fill(u8::try_from(index % 251).expect("fixture byte"));
|
||||
}
|
||||
let options = ObjectOptions {
|
||||
shard_integrity_write_mode: Some(crate::object_api::ShardIntegrityWriteMode::Protected),
|
||||
no_lock: true,
|
||||
versioned: true,
|
||||
suppress_read_repair: true,
|
||||
..Default::default()
|
||||
};
|
||||
set.put_object(bucket, object, &mut PutObjReader::from_vec(expected.clone()), &options)
|
||||
.await
|
||||
.expect("write protected fixture");
|
||||
|
||||
let mut read_range = None;
|
||||
for (disk, dir) in disks.iter().zip(&dirs) {
|
||||
let info = disk
|
||||
.read_version("", bucket, object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("read committed version");
|
||||
let part = info.parts[0].integrity.as_ref().expect("independent commitment");
|
||||
assert!(part.stripes > 2);
|
||||
let codec = crate::erasure::coding::Erasure::try_new_with_options(
|
||||
info.erasure.data_blocks,
|
||||
info.erasure.parity_blocks,
|
||||
info.erasure.block_size,
|
||||
info.uses_legacy_checksum,
|
||||
)
|
||||
.expect("committed layout");
|
||||
let range = codec.block_size + 7..2 * codec.block_size;
|
||||
let hash_size = info.erasure.get_checksum_info(1).algorithm.size();
|
||||
let valid_len = u64::try_from(2 * (codec.shard_size() + hash_size)).expect("test shard length");
|
||||
let path = dir
|
||||
.path()
|
||||
.join(bucket)
|
||||
.join(object)
|
||||
.join(info.data_dir.expect("external part").to_string())
|
||||
.join("part.1");
|
||||
tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.await
|
||||
.expect("open committed shard")
|
||||
.set_len(valid_len)
|
||||
.await
|
||||
.expect("remove only the unrequested suffix");
|
||||
read_range = Some(range);
|
||||
}
|
||||
let range = read_range.expect("fixture has disks");
|
||||
let mut reader = set
|
||||
.get_object_reader(
|
||||
bucket,
|
||||
object,
|
||||
Some(HTTPRangeSpec {
|
||||
start: i64::try_from(range.start).expect("fixture range start"),
|
||||
end: i64::try_from(range.end - 1).expect("fixture range end"),
|
||||
is_suffix_length: false,
|
||||
}),
|
||||
Default::default(),
|
||||
&options,
|
||||
)
|
||||
.await
|
||||
.expect("aligned protected Range must ignore the truncated suffix");
|
||||
let mut body = Vec::new();
|
||||
reader
|
||||
.stream
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.expect("read the verified aligned range");
|
||||
assert_eq!(body, expected[range]);
|
||||
|
||||
if let Ok(mut full) = set
|
||||
.get_object_reader(bucket, object, None, Default::default(), &options)
|
||||
.await
|
||||
{
|
||||
assert!(
|
||||
full.stream.read_to_end(&mut Vec::new()).await.is_err(),
|
||||
"a full GET must reject the truncated object"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_inline_donor_repair_and_late_external_get() {
|
||||
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(4, 0, 2).await;
|
||||
|
||||
@@ -33,22 +33,22 @@ use super::super::{
|
||||
Arc, Bytes, CompletePart, Cursor, DATA_MOVEMENT_MULTIPART_PREFIX, DiskError, DiskStore, EVENT_SET_DISK_MULTIPART, Error,
|
||||
FileInfo, FileMeta, GLOBAL_MIN_PART_SIZE, HashAlgorithm, HashMap, HashReader, HashSet, HealChannelPriority, Instant,
|
||||
LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_SET_DISK, ListMultipartsInfo, ListPartsInfo, MAX_PARTS_COUNT,
|
||||
MULTIPART_GENERATED_VERSION_SUFFIX, MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA,
|
||||
MULTIPART_WRITE_QUORUM_WRITER_SETUP, MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence,
|
||||
OBJECT_OP_IGNORED_ERRS, ObjectInfo, ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo,
|
||||
PutObjReader, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY,
|
||||
Result, SLASH_SEPARATOR, SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID,
|
||||
SUFFIX_COMPRESSION_SIZE, SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID,
|
||||
SUFFIX_RESTORE_WORKER_LOCK, SetDisks, SmallWritePath, StorageError, Uuid, WriteLayout,
|
||||
check_object_lock_for_deletion_with_state, classify_multipart_part_write_path, coding, complete_multipart_part_error,
|
||||
complete_multipart_part_error_result, complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug,
|
||||
disk, error, file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str,
|
||||
is_err_object_not_found, is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure,
|
||||
multipart_part_logical_size, parts_after_marker, path_join_buf, prepare_complete_multipart_parts,
|
||||
record_compression_total_memory, record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs,
|
||||
remove_header_map, replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout,
|
||||
restore_commit_operation_id_from_metadata, restore_operation_id_from_metadata, should_persist_encryption_original_size,
|
||||
strip_internal_multipart_metadata, to_object_err, warn,
|
||||
MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA, MULTIPART_WRITE_QUORUM_WRITER_SETUP,
|
||||
MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence, OBJECT_OP_IGNORED_ERRS, ObjectInfo,
|
||||
ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo, PutObjReader, RUSTFS_META_MULTIPART_BUCKET,
|
||||
RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY, Result, SLASH_SEPARATOR,
|
||||
SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID, SUFFIX_COMPRESSION_SIZE,
|
||||
SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID, SUFFIX_RESTORE_WORKER_LOCK, SetDisks,
|
||||
SmallWritePath, StorageError, Uuid, WriteLayout, check_object_lock_for_deletion_with_state,
|
||||
classify_multipart_part_write_path, coding, complete_multipart_part_error, complete_multipart_part_error_result,
|
||||
complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug, disk, error,
|
||||
file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str, is_err_object_not_found,
|
||||
is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure, multipart_part_logical_size,
|
||||
parts_after_marker, path_join_buf, prepare_complete_multipart_parts, record_compression_total_memory,
|
||||
record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs, remove_header_map,
|
||||
replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout, restore_commit_operation_id_from_metadata,
|
||||
restore_operation_id_from_metadata, should_persist_encryption_original_size, strip_internal_multipart_metadata,
|
||||
to_object_err, warn,
|
||||
};
|
||||
use super::bitrot_self_verify::{
|
||||
BitrotSelfVerifyTarget, WrittenBitrotShards, drop_failed_writer_disks, verify_written_bitrot_shards,
|
||||
@@ -62,7 +62,6 @@ use super::object::{
|
||||
use crate::api::config::storageclass;
|
||||
use crate::bucket::metadata_sys::ObjectLockConfigState;
|
||||
use crate::bucket::quota::reservation;
|
||||
#[cfg(test)]
|
||||
use crate::bucket::replication::ReplicationStatusType;
|
||||
use crate::crash_inject::{self, CrashPoint};
|
||||
#[cfg(test)]
|
||||
@@ -906,8 +905,6 @@ pub enum MultipartCommitPause {
|
||||
PutPartAfterRename,
|
||||
AbortBeforeDelete,
|
||||
AbortAfterDelete,
|
||||
#[cfg(test)]
|
||||
BeforeConditionalNamespace,
|
||||
BeforeLockLost,
|
||||
BeforeQuotaRename,
|
||||
BeforeTransactionEpochVerify,
|
||||
@@ -4247,7 +4244,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_PART_CHECKSUMS);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_DATA_MOVEMENT_UPLOAD);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
rustfs_utils::http::metadata_compat::remove_str(
|
||||
&mut user_defined,
|
||||
@@ -4297,19 +4293,18 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
|
||||
let data_dir = Uuid::new_v4();
|
||||
fi.data_dir = Some(data_dir);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX);
|
||||
fi.version_id = match &opts.version_id {
|
||||
Some(id) => Some(Uuid::parse_str(id)?),
|
||||
None if opts.versioned => {
|
||||
let id = Uuid::new_v4();
|
||||
insert_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX, format!("{data_dir}/{id}"));
|
||||
Some(id)
|
||||
}
|
||||
None => None,
|
||||
fi.version_id = if let Some(vid) = &opts.version_id {
|
||||
Some(Uuid::parse_str(vid)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if opts.versioned && opts.version_id.is_none() {
|
||||
fi.version_id = Some(Uuid::new_v4());
|
||||
}
|
||||
|
||||
let data_dir = Uuid::new_v4();
|
||||
fi.data_dir = Some(data_dir);
|
||||
if crate::object_api::legacy_encrypted_range_seek_enabled()
|
||||
&& !opts.no_lock
|
||||
&& should_persist_encryption_original_size(&user_defined)
|
||||
@@ -4491,6 +4486,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
result
|
||||
}
|
||||
|
||||
// complete_multipart_upload finished
|
||||
#[tracing::instrument(level = "trace", skip(self))]
|
||||
async fn complete_multipart_upload(
|
||||
self: Arc<Self>,
|
||||
@@ -4499,21 +4495,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
upload_id: &str,
|
||||
uploaded_parts: Vec<CompletePart>,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<ObjectInfo> {
|
||||
self.complete_multipart_upload_with_store(bucket, object, upload_id, uploaded_parts, opts, None)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl SetDisks {
|
||||
pub(crate) async fn complete_multipart_upload_with_store(
|
||||
self: Arc<Self>,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
upload_id: &str,
|
||||
uploaded_parts: Vec<CompletePart>,
|
||||
opts: &ObjectOptions,
|
||||
multipool_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<ObjectInfo> {
|
||||
crate::hp_guard!("SetDisks::complete_multipart_upload");
|
||||
let write_context = WriteCommitContext::from_options(opts, bucket, object, false)?;
|
||||
@@ -4523,9 +4504,8 @@ impl SetDisks {
|
||||
let range_seek_rollout_enabled =
|
||||
crate::object_api::legacy_encrypted_range_seek_enabled() && write_context.acquires_namespace();
|
||||
let mut object_lock_guard = None;
|
||||
let mut store_object_guards: Option<Arc<[crate::store::ObjectLockDiagGuard]>> = None;
|
||||
let has_lost_store_lock =
|
||||
|guards: &[crate::store::ObjectLockDiagGuard]| guards.iter().any(crate::store::ObjectLockDiagGuard::is_lock_lost);
|
||||
let mut decommission_object_lock_guard = None;
|
||||
let mut decommission_target_lock_covered = false;
|
||||
let mut decommission_capacity_guard = None;
|
||||
|
||||
// Lock order: lifecycle -> metadata transaction -> object namespace -> upload.
|
||||
@@ -4546,62 +4526,44 @@ impl SetDisks {
|
||||
opts
|
||||
};
|
||||
|
||||
// Conditional publication requires namespace locking. Ordinary writes retain
|
||||
// the selected set's namespace when deployment-wide locking is disabled.
|
||||
let multipool_locks =
|
||||
multipool_store.filter(|_| opts.http_preconditions.is_some() || !self.ctx.lock_manager().is_disabled());
|
||||
let target_covered = if let Some(store) = multipool_locks.or(opts.decommission_capacity_admission.as_deref()) {
|
||||
if opts.http_preconditions.is_some() {
|
||||
if write_context.acquires_namespace() {
|
||||
object_lock_guard = Some(
|
||||
self.acquire_write_lock_diag("complete_multipart_upload_precondition", bucket, object)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(err) = self.check_write_precondition(bucket, object, opts).await {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
|
||||
}
|
||||
if multipool_locks.is_some() {
|
||||
#[cfg(test)]
|
||||
if opts.http_preconditions.is_some() {
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeConditionalNamespace).await;
|
||||
}
|
||||
store_object_guards = Some(
|
||||
Box::pin(store.acquire_physical_object_write_locks(
|
||||
"complete_multipart_upload_commit",
|
||||
bucket,
|
||||
object,
|
||||
write_context.borrowed_write_guards(bucket, object),
|
||||
))
|
||||
.await?
|
||||
.into(),
|
||||
);
|
||||
true
|
||||
} else if write_context.acquires_namespace() {
|
||||
let guard = store.acquire_external_commit_namespace(bucket, object, &self).await?;
|
||||
store_object_guards = Some(Arc::new([guard]));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if write_context.acquires_namespace() && !target_covered {
|
||||
let (object_guard, target_lock_covered, capacity_guard) = store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
!write_context.acquires_namespace() || object_lock_guard.is_some(),
|
||||
DecommissionCapacityAdmission::ExistingMultipart,
|
||||
)
|
||||
.await?;
|
||||
decommission_object_lock_guard = object_guard;
|
||||
decommission_target_lock_covered = target_lock_covered;
|
||||
decommission_capacity_guard = capacity_guard;
|
||||
}
|
||||
if write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered {
|
||||
object_lock_guard = Some(
|
||||
self.acquire_write_lock_diag("complete_multipart_upload_commit", bucket, object)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
let conditional_current = match multipool_store {
|
||||
Some(store) if opts.http_preconditions.is_some() => {
|
||||
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
|
||||
}
|
||||
Some(_) => None,
|
||||
None => {
|
||||
if opts.http_preconditions.is_some()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
let mut upload_guard = self
|
||||
.acquire_multipart_upload_write_lock("complete_multipart_upload_commit", bucket, object, upload_id, opts)
|
||||
.await?;
|
||||
@@ -4743,13 +4705,6 @@ impl SetDisks {
|
||||
ensure_multipart_bucket_lifecycle_lock_held(bucket, object, opts)?;
|
||||
}
|
||||
let source_condition = capture_source_condition(bucket, object, &upload_id_path, &fi, Uuid::new_v4())?;
|
||||
// A marker copied from a prior object cannot establish how this upload's version was assigned.
|
||||
let generated_version = get_consistent_str(&fi.metadata, MULTIPART_GENERATED_VERSION_SUFFIX).and_then(|marker| {
|
||||
source_condition
|
||||
.lineage
|
||||
.original_version_id
|
||||
.filter(|id| marker == format!("{}/{id}", source_condition.lineage.original_data_dir))
|
||||
});
|
||||
let preserved_encrypted_etag = preserves_staged_encrypted_etag_proof(&fi, opts, expected_restore_operation_id);
|
||||
let upload_data_dir = source_condition.lineage.original_data_dir.to_string();
|
||||
// The source generation remains in the captured precondition. Its
|
||||
@@ -4775,7 +4730,9 @@ impl SetDisks {
|
||||
// and heterogeneous replication clients can send an authorized
|
||||
// REPLICA status on Complete without repeating the source-request
|
||||
// marker, so either authenticated parser result is sufficient.
|
||||
if !opts.is_inbound_multipart_replica() {
|
||||
let authorized_inbound_replica =
|
||||
opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica;
|
||||
if !authorized_inbound_replica {
|
||||
fi.metadata
|
||||
.retain(|key, _| !key.eq_ignore_ascii_case(metadata_keys::REPLICATION_STATUS));
|
||||
for suffix in [
|
||||
@@ -4838,8 +4795,8 @@ impl SetDisks {
|
||||
// source's null version, so its completion keeps the null version,
|
||||
// exactly like the single-PUT path (rustfs/rustfs#8747). Any other
|
||||
// completion in a versioned bucket gets a concrete version.
|
||||
let replicated_null_version =
|
||||
fi.version_id.is_none_or(|version_id| version_id.is_nil()) && opts.is_inbound_multipart_replica();
|
||||
let replicated_null_version = fi.version_id.is_none_or(|version_id| version_id.is_nil())
|
||||
&& (opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica);
|
||||
if opts.restore_copyback {
|
||||
require_multipart_restore_target(opts, fi.version_id)?;
|
||||
} else if opts.versioned && replicated_null_version {
|
||||
@@ -4859,23 +4816,6 @@ impl SetDisks {
|
||||
} else {
|
||||
fi.version_id = None;
|
||||
}
|
||||
let predecessors = match multipool_store {
|
||||
Some(store) => {
|
||||
let current = if opts.http_preconditions.is_some() {
|
||||
conditional_current
|
||||
} else {
|
||||
// An unconditional replay returns before it needs the current head.
|
||||
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
|
||||
};
|
||||
// A version already visible under this UUID is an overwrite, even
|
||||
// if Create generated it. Legacy uploads can also name a historical version.
|
||||
let target = fi.version_id.unwrap_or_default();
|
||||
let matches_head = current.as_ref().is_some_and(|info| info.version_id == Some(target));
|
||||
let replaced = (matches_head || Some(target) != generated_version).then_some(target);
|
||||
Some(Box::pin(store.resolve_put_predecessors(bucket, object, opts, current, replaced)).await?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let write_quorum = fi.write_quorum(self.default_write_quorum());
|
||||
let read_quorum = fi.read_quorum(self.default_read_quorum());
|
||||
|
||||
@@ -5292,9 +5232,6 @@ impl SetDisks {
|
||||
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
|
||||
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
|
||||
strip_internal_multipart_metadata(&mut fi.metadata);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
if opts.restore_copyback {
|
||||
insert_str(
|
||||
&mut fi.metadata,
|
||||
@@ -5311,11 +5248,7 @@ impl SetDisks {
|
||||
fi.size = object_size as i64;
|
||||
fi.mod_time = opts.mod_time;
|
||||
if fi.mod_time.is_none() {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
fi.mod_time = Some(match &predecessors {
|
||||
Some(predecessors) => predecessors.commit_time(now)?,
|
||||
None => now,
|
||||
});
|
||||
fi.mod_time = Some(OffsetDateTime::now_utc());
|
||||
}
|
||||
|
||||
// etag
|
||||
@@ -5394,9 +5327,11 @@ impl SetDisks {
|
||||
// other read failures must leave the upload retryable rather than
|
||||
// committing inbound metadata without the LWW check.
|
||||
//
|
||||
// Create can name the version to replace without repeating it at Complete.
|
||||
// Reuse the locked cross-pool predecessor when available. Replication
|
||||
// judges the destination set's version and metadata together.
|
||||
// The same read enforces the commit-time WORM gate on the staged
|
||||
// `fi.version_id`, which the completion request does not name. An
|
||||
// ordinary upload stages a fresh UUID and finds no version here;
|
||||
// `opts.restore_copyback` and `opts.data_movement` run their stricter
|
||||
// checks below.
|
||||
let snapshot_state = opts.object_lock_config_snapshot.as_deref().map(|snapshot| snapshot.state());
|
||||
let need_worm_lookup = !opts.data_movement
|
||||
&& !opts.restore_copyback
|
||||
@@ -5407,35 +5342,28 @@ impl SetDisks {
|
||||
if (need_worm_lookup || replication_lww_applicable)
|
||||
&& let Some(version_id) = target_version_id
|
||||
{
|
||||
let local;
|
||||
let existing = match &predecessors {
|
||||
Some(predecessors) => Ok(predecessors.replaced().filter(|info| !info.delete_marker)),
|
||||
None => {
|
||||
local = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
local.as_ref().map(Some).map_err(Clone::clone)
|
||||
}
|
||||
};
|
||||
match existing {
|
||||
Ok(Some(existing)) => {
|
||||
match self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(existing) => {
|
||||
if !opts.data_movement && !opts.restore_copyback && !crate::bucket::utils::is_meta_bucketname(bucket) {
|
||||
let effective_state = snapshot_state.unwrap_or(&ObjectLockConfigState::ConfirmedAbsent);
|
||||
if check_object_lock_for_deletion_with_state(effective_state, existing, false)?.is_some() {
|
||||
if check_object_lock_for_deletion_with_state(effective_state, &existing, false)?.is_some() {
|
||||
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
|
||||
effective_state,
|
||||
existing,
|
||||
&existing,
|
||||
opts,
|
||||
&fi.metadata,
|
||||
)? {
|
||||
@@ -5469,7 +5397,9 @@ impl SetDisks {
|
||||
#[cfg(test)]
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5528,7 +5458,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
drop(object_lock_guard.take());
|
||||
drop(store_object_guards.take());
|
||||
drop(decommission_object_lock_guard.take());
|
||||
drop(decommission_capacity_guard.take());
|
||||
if let Err(err) = self
|
||||
.delete_all_with_quorum(RUSTFS_META_MULTIPART_BUCKET, &upload_id_path, write_quorum)
|
||||
@@ -5554,11 +5484,10 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
if replication_lww_applicable {
|
||||
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(existing);
|
||||
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(&existing);
|
||||
crate::set_disk::ops::object::merge_replication_metadata_lww(&mut fi.metadata, &stored, opts);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
// A null delete marker has no protected payload to replace.
|
||||
Err(StorageError::MethodNotAllowed) if version_id.is_nil() => {}
|
||||
// Version absent: a fresh version id or the first replication
|
||||
@@ -5616,7 +5545,9 @@ impl SetDisks {
|
||||
#[cfg(test)]
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5728,7 +5659,9 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5766,7 +5699,7 @@ impl SetDisks {
|
||||
// Recheck decommission capacity only after those locks, and retain the
|
||||
// guard through the durable rename below.
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = multipool_store.or(opts.decommission_capacity_admission.as_deref())
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
store
|
||||
@@ -5803,12 +5736,9 @@ impl SetDisks {
|
||||
copy_publication_controls(&fi.metadata, &mut metadata.metadata)?;
|
||||
}
|
||||
|
||||
let put_usage = predecessors.as_deref().map(|previous| previous.usage_receipt()).transpose()?;
|
||||
let quota_old_size = if quota_context.is_enforced() {
|
||||
if opts.data_movement {
|
||||
quota_new_size
|
||||
} else if let Some(usage) = &put_usage {
|
||||
usage.replaced_size()
|
||||
} else {
|
||||
reservation::replaced_logical_size(&self, bucket, object, opts).await?
|
||||
}
|
||||
@@ -5877,8 +5807,7 @@ impl SetDisks {
|
||||
let commit_capacity_scope_token = opts.capacity_scope_token;
|
||||
let commit_object_lock_guard = object_lock_guard.take().map(Arc::new);
|
||||
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
|
||||
let commit_store_object_guards = store_object_guards;
|
||||
let multipool_publication = multipool_locks.is_some();
|
||||
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take().map(Arc::new);
|
||||
let commit_decommission_capacity_guard = decommission_capacity_guard.take().map(Arc::new);
|
||||
// CompleteMultipartUpload is an S3 publication boundary: after a
|
||||
// successful response, the object must be immediately readable and
|
||||
@@ -5891,7 +5820,7 @@ impl SetDisks {
|
||||
let write_context = Arc::new(write_context);
|
||||
let mut _object_lock_guard = commit_object_lock_guard;
|
||||
let _object_lock_config_snapshot = commit_object_lock_config_snapshot;
|
||||
let mut _store_object_guards = commit_store_object_guards;
|
||||
let mut _decommission_object_lock_guard = commit_decommission_object_lock_guard;
|
||||
let mut _upload_guard = upload_guard.map(Arc::new);
|
||||
let mut _decommission_capacity_guard = commit_decommission_capacity_guard;
|
||||
let mut quota_reservation = quota_reservation;
|
||||
@@ -5921,7 +5850,9 @@ impl SetDisks {
|
||||
if quota_reservation.is_lock_lost()
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| commit_namespace_lock_fence
|
||||
.as_ref()
|
||||
@@ -5973,7 +5904,9 @@ impl SetDisks {
|
||||
if quota_reservation.is_lock_lost()
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| commit_namespace_lock_fence
|
||||
.as_ref()
|
||||
@@ -6021,7 +5954,7 @@ impl SetDisks {
|
||||
let multipart_commit_owner = crate::set_disk::core::io_primitives::MultipartLogicalGuards::new((
|
||||
write_context.clone(),
|
||||
_object_lock_guard.clone(),
|
||||
_store_object_guards.clone(),
|
||||
_decommission_object_lock_guard.clone(),
|
||||
_upload_guard.clone(),
|
||||
_decommission_capacity_guard.clone(),
|
||||
commit_namespace_lock_fence.clone(),
|
||||
@@ -6136,9 +6069,6 @@ impl SetDisks {
|
||||
.await;
|
||||
|
||||
drop(_object_lock_guard.take()); // release the object lock before multipart cleanup IO.
|
||||
if multipool_publication {
|
||||
drop(_store_object_guards.take());
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pause_multipart_commit(&commit_bucket, &commit_object, MultipartCommitPause::AfterObjectPublication).await;
|
||||
@@ -6202,7 +6132,6 @@ impl SetDisks {
|
||||
|
||||
let mut obj_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
|
||||
obj_info.backfilled_old_current_size = old_current_size;
|
||||
obj_info.put_usage = put_usage;
|
||||
Ok(obj_info)
|
||||
};
|
||||
|
||||
|
||||
@@ -4699,7 +4699,7 @@ impl SetDisks {
|
||||
data: &mut PutObjReader,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, None)
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -4718,23 +4718,10 @@ impl SetDisks {
|
||||
// The owned publication capability supplies the exact target write
|
||||
// domain at commit time; the generic PUT path must not reacquire it.
|
||||
opts.no_lock = true;
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence), None)
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stage the stream locally, then resolve the logical predecessor under the cross-pool publication locks.
|
||||
pub(crate) fn put_object_in_store<'a>(
|
||||
&'a self,
|
||||
bucket: &'a str,
|
||||
object: &'a str,
|
||||
data: &'a mut PutObjReader,
|
||||
opts: &'a ObjectOptions,
|
||||
store: &'a ECStore,
|
||||
use_multipool_predecessors: bool,
|
||||
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, Some((store, use_multipool_predecessors)))
|
||||
}
|
||||
|
||||
fn put_object_with_old_current_size_boxed<'a>(
|
||||
&'a self,
|
||||
bucket: &'a str,
|
||||
@@ -4742,9 +4729,8 @@ impl SetDisks {
|
||||
data: &'a mut PutObjReader,
|
||||
opts: &'a ObjectOptions,
|
||||
publication_fence: Option<RemoteTuplePublicationFence>,
|
||||
commit_store: Option<(&'a ECStore, bool)>,
|
||||
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
|
||||
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence, commit_store))
|
||||
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence))
|
||||
}
|
||||
|
||||
async fn put_object_with_old_current_size_inner(
|
||||
@@ -4754,15 +4740,8 @@ impl SetDisks {
|
||||
data: &mut PutObjReader,
|
||||
opts: &ObjectOptions,
|
||||
mut publication_fence: Option<RemoteTuplePublicationFence>,
|
||||
commit_store: Option<(&ECStore, bool)>,
|
||||
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
|
||||
let write_context = WriteCommitContext::from_options(opts, bucket, object, publication_fence.is_some())?;
|
||||
let store = commit_store.map(|(store, _)| store);
|
||||
let multipool_store = commit_store.and_then(|(store, check)| check.then_some(store));
|
||||
let capacity_store = match store {
|
||||
Some(store) => (!store.single_pool()).then_some(store),
|
||||
None => opts.decommission_capacity_admission.as_deref(),
|
||||
};
|
||||
let protect_write = opts.shard_integrity_write_enabled();
|
||||
let source_bucket_incarnation_id = match opts.expected_bucket_incarnation_id {
|
||||
Some(incarnation_id) => Some(incarnation_id),
|
||||
@@ -4810,21 +4789,21 @@ impl SetDisks {
|
||||
let disks = self.get_disks_internal().await;
|
||||
|
||||
let mut object_lock_guard = None;
|
||||
let mut decommission_object_lock_guard: Vec<crate::store::ObjectLockDiagGuard> = Vec::new();
|
||||
let mut decommission_object_lock_guard = None;
|
||||
let mut decommission_target_lock_covered = false;
|
||||
let mut decommission_capacity_guard = None;
|
||||
let mut bucket_lifecycle_guard = None;
|
||||
let mut publication_commit_guard: Option<RemoteTuplePublicationCommitGuard> = None;
|
||||
|
||||
// This pre-body check is advisory fast-fail only: the authoritative
|
||||
// precondition evaluation happens under the commit namespace lock
|
||||
// below, so the namespace write lock must NOT be taken here — holding
|
||||
// it across client-paced body ingestion starves concurrent reads of
|
||||
// the same object into lock-timeout 503s (rustfs/backlog#2074).
|
||||
// Data movement skips the advisory read: its staleness predicate is
|
||||
// only meaningful at commit time. Multi-pool conditional
|
||||
// PUTs run a cross-pool advisory check in ECStore before pool selection.
|
||||
// only meaningful at commit time.
|
||||
if opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& multipool_store.is_none()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
@@ -4913,9 +4892,6 @@ impl SetDisks {
|
||||
&mut user_defined,
|
||||
crate::object_api::ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX,
|
||||
);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
if crate::io_support::rio::encryption_frame_v2_enabled()
|
||||
&& !opts.preserve_ciphertext
|
||||
&& !opts.data_movement
|
||||
@@ -5445,14 +5421,7 @@ impl SetDisks {
|
||||
deferred_commit_opts = opts.clone();
|
||||
let expected = source_bucket_incarnation_id
|
||||
.ok_or_else(|| Error::other("destructive PUT is missing its bucket incarnation"))?;
|
||||
let initialized_store;
|
||||
let store = match store {
|
||||
Some(store) => store,
|
||||
None => {
|
||||
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
|
||||
&initialized_store
|
||||
}
|
||||
};
|
||||
let store = metadata_sys::object_store_in(&self.ctx).await?;
|
||||
let snapshot = match opts.bucket_lifecycle_lock_fence.as_ref() {
|
||||
Some(fence) => store.object_lock_config_snapshot_under_lifecycle_fence(bucket, fence).await?,
|
||||
None => store.object_lock_config_snapshot_for_single_put(bucket).await?,
|
||||
@@ -5464,7 +5433,7 @@ impl SetDisks {
|
||||
deferred_commit_opts.object_lock_config_snapshot = Some(snapshot);
|
||||
deferred_commit_opts.defer_put_object_lock_snapshot = false;
|
||||
&deferred_commit_opts
|
||||
} else if capacity_store.is_some()
|
||||
} else if opts.decommission_capacity_admission.is_some()
|
||||
&& write_context.acquires_namespace()
|
||||
&& metadata_sys::needs_commit_metadata_snapshot(&self.ctx, bucket, opts)
|
||||
{
|
||||
@@ -5482,31 +5451,36 @@ impl SetDisks {
|
||||
opts
|
||||
};
|
||||
|
||||
let multipool_locks = multipool_store.filter(|_| !self.ctx.lock_manager().is_disabled());
|
||||
#[cfg(test)]
|
||||
if let Some(store) = capacity_store {
|
||||
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
|
||||
}
|
||||
let (object_guard, target_lock_covered, capacity_guard) = store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
!write_context.acquires_namespace() || object_lock_guard.is_some(),
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?;
|
||||
decommission_object_lock_guard = object_guard;
|
||||
decommission_target_lock_covered = target_lock_covered;
|
||||
decommission_capacity_guard = capacity_guard;
|
||||
}
|
||||
if multipool_locks.is_some()
|
||||
|| publication_fence.is_some()
|
||||
|| (write_context.acquires_namespace() && object_lock_guard.is_none())
|
||||
if publication_fence.is_some()
|
||||
|| (write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered)
|
||||
{
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pause_put_object_commit(bucket, object, PutObjectCommitPause::BeforeNamespace).await;
|
||||
if let Some(expected_incarnation_id) = source_bucket_incarnation_id
|
||||
&& opts.bucket_lifecycle_lock_fence.is_none()
|
||||
{
|
||||
let initialized_store;
|
||||
let store = match store {
|
||||
Some(store) => store,
|
||||
None => {
|
||||
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
|
||||
&initialized_store
|
||||
}
|
||||
};
|
||||
bucket_lifecycle_guard = Some(
|
||||
store
|
||||
metadata_sys::object_store_in(&self.ctx)
|
||||
.await?
|
||||
.acquire_bucket_incarnation_fence(bucket, expected_incarnation_id)
|
||||
.await?,
|
||||
);
|
||||
@@ -5529,27 +5503,8 @@ impl SetDisks {
|
||||
.await?;
|
||||
opts = &pre_lock_commit_opts;
|
||||
}
|
||||
if let Some(store) = multipool_locks {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_pending(bucket, object);
|
||||
decommission_object_lock_guard = Box::pin(store.acquire_physical_object_write_locks(
|
||||
"put_object_commit",
|
||||
bucket,
|
||||
object,
|
||||
write_context.borrowed_write_guards(bucket, object),
|
||||
))
|
||||
.await?;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_acquired(bucket, object);
|
||||
} else if let Some(fence) = publication_fence.take() {
|
||||
if let Some(fence) = publication_fence.take() {
|
||||
publication_commit_guard = Some(fence.into_commit_guard(self.pool_index, bucket, object).await?);
|
||||
} else if let Some(store) = capacity_store {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_pending(bucket, object);
|
||||
decommission_object_lock_guard
|
||||
.push(Box::pin(store.acquire_external_commit_namespace(bucket, object, self)).await?);
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_acquired(bucket, object);
|
||||
} else {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
{
|
||||
@@ -5572,16 +5527,11 @@ impl SetDisks {
|
||||
let namespace_lock_acquired_to_commit_ready_started = rustfs_io_metrics::put_stage_timer();
|
||||
let commit_ready_precondition_and_timestamp_started = rustfs_io_metrics::put_stage_timer();
|
||||
|
||||
let put_predecessors = if let Some(store) = multipool_store {
|
||||
Some(Box::pin(store.multipool_put_predecessors(bucket, object, opts)).await?)
|
||||
} else {
|
||||
if opts.http_preconditions.is_some()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
None
|
||||
};
|
||||
if opts.http_preconditions.is_some()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
if bucket == RUSTFS_META_BUCKET
|
||||
&& object == "pool.bin"
|
||||
@@ -5645,11 +5595,7 @@ impl SetDisks {
|
||||
// the same object. Internal callers with an explicit timestamp keep
|
||||
// their supplied value.
|
||||
if opts.mod_time.is_none() {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let commit_time = Some(match &put_predecessors {
|
||||
Some(predecessors) => predecessors.commit_time(now)?,
|
||||
None => now,
|
||||
});
|
||||
let commit_time = Some(OffsetDateTime::now_utc());
|
||||
for pfi in &mut parts_metadatas {
|
||||
pfi.mod_time = commit_time;
|
||||
for part in &mut pfi.parts {
|
||||
@@ -5664,27 +5610,26 @@ impl SetDisks {
|
||||
|
||||
if let Some(expected) = opts.expected_current_version_id.as_deref() {
|
||||
let expected_version_lookup_started = rustfs_io_metrics::put_stage_timer();
|
||||
let current_version = match &put_predecessors {
|
||||
Some(predecessors) => predecessors.current().and_then(|info| info.version_id),
|
||||
None => match self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(info) => info.version_id,
|
||||
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => None,
|
||||
Err(err) => return Err(err),
|
||||
},
|
||||
};
|
||||
if current_version.map(|version| version.to_string()).as_deref() != Some(expected) {
|
||||
let current = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
if is_err_object_not_found(&err) || is_err_version_not_found(&err) {
|
||||
StorageError::PreconditionFailed
|
||||
} else {
|
||||
err
|
||||
}
|
||||
})?;
|
||||
if current.version_id.map(|version| version.to_string()).as_deref() != Some(expected) {
|
||||
return Err(StorageError::PreconditionFailed);
|
||||
}
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
@@ -5710,29 +5655,22 @@ impl SetDisks {
|
||||
&& !is_meta_bucketname(bucket)
|
||||
{
|
||||
let explicit_version_lookup_started = rustfs_io_metrics::put_stage_timer();
|
||||
let local;
|
||||
let current = match &put_predecessors {
|
||||
Some(predecessors) => Ok(predecessors.replaced()),
|
||||
None => {
|
||||
local = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_owned()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
local.as_ref().map(Some).map_err(Clone::clone)
|
||||
}
|
||||
};
|
||||
let current = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
match current {
|
||||
Ok(Some(existing)) => {
|
||||
Ok(existing) => {
|
||||
let object_lock_config = opts
|
||||
.object_lock_config_snapshot
|
||||
.as_deref()
|
||||
@@ -5745,12 +5683,12 @@ impl SetDisks {
|
||||
// stay immutable: commit only the LWW-judged metadata
|
||||
// categories via `update_object_meta_with_opts`.
|
||||
let is_locked =
|
||||
check_object_lock_for_deletion_with_state(object_lock_config.state(), existing, false)?.is_some();
|
||||
check_object_lock_for_deletion_with_state(object_lock_config.state(), &existing, false)?.is_some();
|
||||
if is_locked {
|
||||
let inbound_metadata = &parts_metadatas[response_metadata_slot].metadata;
|
||||
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
|
||||
object_lock_config.state(),
|
||||
existing,
|
||||
&existing,
|
||||
opts,
|
||||
inbound_metadata,
|
||||
)? {
|
||||
@@ -5825,8 +5763,8 @@ impl SetDisks {
|
||||
});
|
||||
}
|
||||
if decommission_object_lock_guard
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "put_object_external_namespace",
|
||||
@@ -5882,7 +5820,7 @@ impl SetDisks {
|
||||
// more recently on this site is kept instead of being
|
||||
// overwritten by the inbound replication metadata.
|
||||
if replication_lww_applicable(opts) {
|
||||
let stored = stored_replication_category_metadata(existing);
|
||||
let stored = stored_replication_category_metadata(&existing);
|
||||
let mut merged = parts_metadatas[response_metadata_slot].metadata.clone();
|
||||
if merge_replication_metadata_lww(&mut merged, &stored, opts) {
|
||||
for (pfi, disk) in parts_metadatas.iter_mut().zip(shuffle_disks.iter()) {
|
||||
@@ -5893,7 +5831,6 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
// A null delete marker has no protected payload to replace.
|
||||
Err(StorageError::MethodNotAllowed) if version_id == Uuid::nil().to_string() => {}
|
||||
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {}
|
||||
@@ -5960,17 +5897,14 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
let decommission_capacity_fence_started = rustfs_io_metrics::put_stage_timer();
|
||||
if let Some(store) = capacity_store {
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
);
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::core::pools::notify_decommission_external_object_capacity_probe_acquired(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_capacity_probe_release(store.id).await;
|
||||
}
|
||||
}
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_DECOMMISSION_CAPACITY_FENCE,
|
||||
@@ -5982,8 +5916,8 @@ impl SetDisks {
|
||||
// against the decommission capacity ledger; holding this guard
|
||||
// through rename_data keeps the namespace -> capacity order.
|
||||
if decommission_object_lock_guard
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "put_object_external_namespace",
|
||||
@@ -6093,10 +6027,6 @@ impl SetDisks {
|
||||
);
|
||||
|
||||
let quota_reserve_started = rustfs_io_metrics::put_stage_timer();
|
||||
let put_usage = put_predecessors
|
||||
.as_deref()
|
||||
.map(|previous| previous.usage_receipt())
|
||||
.transpose()?;
|
||||
let (quota_old_size, quota_new_size) = if quota_context.is_enforced() {
|
||||
let new_size = match replication_quota_size {
|
||||
Some(size) => size,
|
||||
@@ -6106,8 +6036,6 @@ impl SetDisks {
|
||||
};
|
||||
let old_size = if opts.data_movement {
|
||||
new_size
|
||||
} else if let Some(usage) = &put_usage {
|
||||
usage.replaced_size()
|
||||
} else {
|
||||
reservation::replaced_logical_size(self, bucket, object, opts).await?
|
||||
};
|
||||
@@ -6158,7 +6086,7 @@ impl SetDisks {
|
||||
let commit_tmp_dir = tmp_dir.clone();
|
||||
let commit_rollback_receipt = rollback_receipt.clone();
|
||||
let commit_object_lock_guard = object_lock_guard.take();
|
||||
let commit_decommission_object_lock_guard = std::mem::take(&mut decommission_object_lock_guard);
|
||||
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take();
|
||||
let commit_publication_guard = publication_commit_guard.take();
|
||||
let commit_bucket_lifecycle_guard = bucket_lifecycle_guard.take();
|
||||
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
|
||||
@@ -6170,7 +6098,7 @@ impl SetDisks {
|
||||
// remote leases.
|
||||
let commit_owns_namespace_guard = write_context.has_borrowed_owner()
|
||||
|| commit_object_lock_guard.is_some()
|
||||
|| !commit_decommission_object_lock_guard.is_empty()
|
||||
|| commit_decommission_object_lock_guard.is_some()
|
||||
|| commit_publication_guard.is_some();
|
||||
let commit_write_completion = opts.write_completion;
|
||||
let bound_rename_dispatch = commit_write_completion == crate::object_api::WriteCompletion::TailDrained
|
||||
@@ -6255,8 +6183,8 @@ impl SetDisks {
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _publication_guard
|
||||
.as_ref()
|
||||
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
|
||||
@@ -6329,8 +6257,8 @@ impl SetDisks {
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _publication_guard
|
||||
.as_ref()
|
||||
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
|
||||
@@ -6571,7 +6499,7 @@ impl SetDisks {
|
||||
let publication_guard = _publication_guard.take();
|
||||
let bucket_lifecycle_guard = _bucket_lifecycle_guard.take();
|
||||
let object_lock_config_snapshot = _object_lock_config_snapshot.take();
|
||||
let decommission_object_lock_guard = std::mem::take(&mut _decommission_object_lock_guard);
|
||||
let decommission_object_lock_guard = _decommission_object_lock_guard.take();
|
||||
let decommission_capacity_guard = _decommission_capacity_guard.take();
|
||||
let cleanup_bucket = commit_bucket.clone();
|
||||
let cleanup_object = commit_object.clone();
|
||||
@@ -7068,8 +6996,7 @@ impl SetDisks {
|
||||
|
||||
let completion = repair_result.map(|()| {
|
||||
let object_info_build_started = rustfs_io_metrics::put_stage_timer();
|
||||
let mut object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
|
||||
object_info.put_usage = put_usage;
|
||||
let object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_HELD_OBJECT_INFO_BUILD,
|
||||
object_info_build_started,
|
||||
@@ -10882,21 +10809,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
};
|
||||
let mut replacement_metadata = (*src_info.user_defined).clone();
|
||||
rustfs_filemeta::shard_integrity::clear_integrity_metadata(&mut replacement_metadata);
|
||||
rustfs_utils::http::metadata_compat::remove_str(
|
||||
&mut replacement_metadata,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
);
|
||||
if !src_info.version_only
|
||||
&& let Some(value) =
|
||||
rustfs_utils::http::get_consistent_str(&fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX)
|
||||
.filter(|val| Uuid::parse_str(val.trim()).ok().is_some_and(|id| !id.is_nil()))
|
||||
{
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut replacement_metadata,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
value.to_owned(),
|
||||
);
|
||||
}
|
||||
if src_info.version_only {
|
||||
// Shared shard files retain the selected version's persisted framing.
|
||||
let suffix = crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX;
|
||||
@@ -11423,7 +11335,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
// Only a concrete generation with a different identity is stale.
|
||||
if let Some(expected) = dobj.expected_identity
|
||||
&& (gerr.is_none() || matches!(gerr.as_ref(), Some(StorageError::MethodNotAllowed)))
|
||||
&& ((goi.data_dir != expected.data_dir && goi.logical_body_revision() != expected.data_dir)
|
||||
&& (goi.data_dir != expected.data_dir
|
||||
|| goi.mod_time != expected.mod_time
|
||||
|| goi.delete_marker != expected.delete_marker)
|
||||
{
|
||||
@@ -11664,12 +11576,9 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
let mut vers = Vec::with_capacity(vers_map.len());
|
||||
|
||||
for (_, mut fi_vers) in vers_map {
|
||||
// Apply explicit removals before creating markers. Every versioned
|
||||
// marker has its own response ID and must reach the disk quorum.
|
||||
fi_vers.versions.sort_by_key(|a| a.deleted);
|
||||
|
||||
if let Some(index) = fi_vers.versions.iter().position(|fi| fi.deleted) {
|
||||
fi_vers.versions.truncate(index + 1);
|
||||
}
|
||||
|
||||
vers.push(fi_vers);
|
||||
}
|
||||
|
||||
@@ -31539,7 +31448,7 @@ mod degraded_missing_delete_tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn degraded_missing_delete_versioned_batch_commits_markers() {
|
||||
async fn degraded_versioned_batch_persists_each_reported_marker_for_repeated_keys() {
|
||||
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration;
|
||||
|
||||
let (_dirs, disks, set) = hermetic_set_disks_isolated(3).await;
|
||||
@@ -31547,6 +31456,21 @@ mod degraded_missing_delete_tests {
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create fixture bucket");
|
||||
}
|
||||
let original = set
|
||||
.put_object(
|
||||
bucket,
|
||||
"existing",
|
||||
&mut PutObjReader::from_vec(b"original".to_vec()),
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
write_completion: crate::object_api::WriteCompletion::TailDrained,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("put a version before the batch")
|
||||
.version_id
|
||||
.expect("versioned put has a version ID");
|
||||
disks[0].force_offline_for_test();
|
||||
let snapshot = Arc::new(DeleteReplicationConfigSnapshot::from_configs_for_test(
|
||||
PersistedVersioningConfiguration {
|
||||
@@ -31555,7 +31479,7 @@ mod degraded_missing_delete_tests {
|
||||
},
|
||||
None,
|
||||
));
|
||||
let names = ["absent", "never/created/deep/key"];
|
||||
let names = ["absent", "existing", "never/created/deep/key", "absent", "existing", "absent"];
|
||||
let (deleted, errors) = set
|
||||
.delete_objects(
|
||||
bucket,
|
||||
@@ -31575,9 +31499,11 @@ mod degraded_missing_delete_tests {
|
||||
.await;
|
||||
assert!(errors.iter().all(Option::is_none), "versioned missing batch must succeed: {errors:?}");
|
||||
assert_eq!(deleted.len(), names.len());
|
||||
let mut markers = std::collections::HashSet::new();
|
||||
for (result, name) in deleted.iter().zip(names) {
|
||||
assert!(result.delete_marker);
|
||||
let version = result.delete_marker_version_id.expect("marker identity must be reported");
|
||||
assert!(markers.insert(version), "each versioned deletion creates its own marker");
|
||||
for disk in disks.iter().skip(1) {
|
||||
let persisted = disk
|
||||
.read_version("", bucket, name, &version.to_string(), &crate::disk::ReadOptions::default())
|
||||
@@ -31587,6 +31513,14 @@ mod degraded_missing_delete_tests {
|
||||
assert_eq!(persisted.version_id, Some(version));
|
||||
}
|
||||
}
|
||||
for disk in disks.iter().skip(1) {
|
||||
let data = disk
|
||||
.read_version("", bucket, "existing", &original.to_string(), &crate::disk::ReadOptions::default())
|
||||
.await
|
||||
.expect("original data version");
|
||||
assert!(!data.deleted);
|
||||
assert_eq!(data.version_id, Some(original));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1550,7 +1550,7 @@ impl SetDisks {
|
||||
.await?;
|
||||
if let Some(expected) = part.integrity.as_ref() {
|
||||
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(1))?;
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
|
||||
for (index, reader) in readers.iter_mut().enumerate() {
|
||||
if let Some(reader) = reader {
|
||||
reader.set_integrity(ShardVerifier::new(Arc::clone(&proof), index, 0, None)?)?;
|
||||
@@ -1618,7 +1618,7 @@ impl SetDisks {
|
||||
erasure.data_shards,
|
||||
)
|
||||
.await;
|
||||
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0..1)?;
|
||||
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0)?;
|
||||
let reader_setup_elapsed = reader_setup_stage_start.elapsed();
|
||||
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
|
||||
rustfs_io_metrics::record_get_object_stage_duration_by_size(
|
||||
@@ -2987,9 +2987,8 @@ impl SetDisks {
|
||||
let frame_size = read_frame_size_for_file_info(fi, erasure)?;
|
||||
let checksum_algo = part_checksum_algorithm(fi, part_number);
|
||||
let use_mmap_read = object_mmap_read_enabled();
|
||||
let shard_size = erasure.shard_size();
|
||||
let till_offset = erasure.shard_file_offset(part_offset, part_length, part_size);
|
||||
let read_offset = (part_offset / erasure.block_size) * shard_size;
|
||||
let read_offset = (part_offset / erasure.block_size) * erasure.shard_size();
|
||||
let read_length = till_offset.saturating_sub(read_offset);
|
||||
|
||||
let stage_metrics_enabled = rustfs_io_metrics::get_stage_metrics_enabled();
|
||||
@@ -3009,7 +3008,7 @@ impl SetDisks {
|
||||
part_number,
|
||||
read_offset,
|
||||
read_length,
|
||||
shard_size,
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
@@ -3031,14 +3030,7 @@ impl SetDisks {
|
||||
.iter()
|
||||
.find(|part| part.number == part_number)
|
||||
.and_then(|part| part.integrity.as_ref());
|
||||
reader_setup.bind_integrity(
|
||||
expected,
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
object,
|
||||
read_offset / shard_size..till_offset.div_ceil(shard_size),
|
||||
)?;
|
||||
reader_setup.bind_integrity(expected, files, disks, bucket, object, part_offset / erasure.block_size)?;
|
||||
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READER_SETUP, reader_setup_stage_start);
|
||||
|
||||
let available_shards = reader_setup.available_shards();
|
||||
@@ -3490,14 +3482,7 @@ async fn setup_multipart_part_readers(
|
||||
)
|
||||
.await;
|
||||
if setup
|
||||
.bind_integrity(
|
||||
spec.integrity.as_ref(),
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
object,
|
||||
spec.read_offset / shard_size..spec.read_offset.saturating_add(spec.read_length).div_ceil(shard_size),
|
||||
)
|
||||
.bind_integrity(spec.integrity.as_ref(), files, disks, bucket, object, spec.read_offset / shard_size)
|
||||
.is_err()
|
||||
{
|
||||
setup = BitrotReaderSetup::new(disks.len());
|
||||
|
||||
@@ -169,13 +169,21 @@ impl SetDisks {
|
||||
.clone()
|
||||
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
||||
let version_id = expected.version_id.map(|v| v.to_string());
|
||||
let decommission_object_lock_guard =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
opts.no_lock,
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
None
|
||||
(None, false, None)
|
||||
};
|
||||
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
|
||||
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
|
||||
Some(
|
||||
self.acquire_write_lock_diag("restore_finalize_metadata", bucket, object)
|
||||
.await?,
|
||||
@@ -183,15 +191,15 @@ impl SetDisks {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
Some(
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
);
|
||||
}
|
||||
let read_opts = ObjectOptions {
|
||||
version_id,
|
||||
versioned: opts.versioned,
|
||||
@@ -278,13 +286,21 @@ impl SetDisks {
|
||||
.clone()
|
||||
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
||||
let version_id = expected.version_id.map(|v| v.to_string());
|
||||
let decommission_object_lock_guard =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
opts.no_lock,
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
None
|
||||
(None, false, None)
|
||||
};
|
||||
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
|
||||
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
|
||||
Some(
|
||||
self.acquire_write_lock_diag("restore_cleanup_metadata", bucket, object)
|
||||
.await?,
|
||||
@@ -292,15 +308,15 @@ impl SetDisks {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
Some(
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
);
|
||||
}
|
||||
let read_opts = ObjectOptions {
|
||||
version_id,
|
||||
versioned: opts.versioned,
|
||||
|
||||
@@ -861,6 +861,15 @@ impl ECStore {
|
||||
sys.read().await.get(bucket).await
|
||||
}
|
||||
|
||||
/// Returns the metadata system that owns this store's bucket configuration.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error when this store has not initialized its metadata system.
|
||||
pub async fn instance_bucket_metadata_sys(&self) -> Result<metadata_sys::BucketMetadataSys> {
|
||||
let sys = metadata_sys::require_bucket_metadata_sys_in(&self.ctx)?;
|
||||
Ok(sys.read().await.clone())
|
||||
}
|
||||
|
||||
/// Snapshots this instance's cached bucket metadata without disk IO.
|
||||
///
|
||||
/// # Errors
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
use super::ECStore;
|
||||
use crate::bucket::utils::is_meta_bucketname;
|
||||
use crate::disk::{DeleteTransactionId, Disk, DiskAPI, DiskStore, error::DiskError, local::DiscoverySession};
|
||||
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
|
||||
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
|
||||
use rand::RngExt as _;
|
||||
use rustfs_heal_contracts::heal_channel::HealOpts;
|
||||
@@ -29,15 +29,13 @@ use std::sync::{
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tokio::time::{Instant, MissedTickBehavior};
|
||||
use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use uuid::Uuid;
|
||||
|
||||
const HINT_CAPACITY: usize = 1_024;
|
||||
const DISCOVERY_PAGE_SIZE: u32 = 128;
|
||||
const PAGES_PER_PASS: usize = 8;
|
||||
const MAX_ACTIVE_DISCOVERY_CURSORS: usize = 32;
|
||||
const DISCOVERY_PAGE_WAIT: Duration = Duration::from_millis(100);
|
||||
const DISCOVERY_PAGE_STALL: Duration = Duration::from_secs(30);
|
||||
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
|
||||
const LOG_SUBSYSTEM_DELETE_RECOVERY: &str = "delete_recovery";
|
||||
const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status";
|
||||
@@ -470,50 +468,18 @@ struct LocalSource {
|
||||
available: bool,
|
||||
}
|
||||
|
||||
impl LocalSource {
|
||||
fn same_disk(&self, other: &Self) -> bool {
|
||||
self.pool == other.pool && self.set == other.set && Arc::ptr_eq(&self.disk, &other.disk)
|
||||
}
|
||||
}
|
||||
|
||||
struct DiscoveryPage {
|
||||
incarnation: Uuid,
|
||||
transactions: Vec<DeleteTransactionId>,
|
||||
next: Option<DiscoverySession>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum BucketDiscovery {
|
||||
#[default]
|
||||
Unstarted,
|
||||
Paused(DiscoverySession),
|
||||
InFlight(BoxFuture<'static, crate::disk::error::Result<DiscoveryPage>>),
|
||||
}
|
||||
|
||||
struct BucketScan {
|
||||
bucket: String,
|
||||
incarnation: Option<Uuid>,
|
||||
discovery: BucketDiscovery,
|
||||
cursor: Option<DeleteRecoveryCursor>,
|
||||
pending: VecDeque<String>,
|
||||
}
|
||||
|
||||
impl BucketScan {
|
||||
fn has_progress(&self) -> bool {
|
||||
!matches!(self.discovery, BucketDiscovery::Unstarted) || !self.pending.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskScan {
|
||||
source: LocalSource,
|
||||
buckets: Option<VecDeque<BucketScan>>,
|
||||
}
|
||||
|
||||
impl DiskScan {
|
||||
fn front_bucket(&self) -> Option<&BucketScan> {
|
||||
self.buckets.as_ref()?.front()
|
||||
}
|
||||
}
|
||||
|
||||
fn admit_discovered_keys(hints: &DeleteRecoveryHints, source: &LocalSource, bucket: &mut BucketScan) {
|
||||
while let Some(object) = bucket.pending.front() {
|
||||
if !hints.register_discovered(DeleteRecoveryKey {
|
||||
@@ -565,8 +531,11 @@ impl RecoveryPass {
|
||||
}
|
||||
}
|
||||
}
|
||||
let contains_source =
|
||||
|inventory: &[LocalSource], source: &LocalSource| inventory.iter().any(|current| current.same_disk(source));
|
||||
let contains_source = |inventory: &[LocalSource], source: &LocalSource| {
|
||||
inventory.iter().any(|current| {
|
||||
current.pool == source.pool && current.set == source.set && Arc::ptr_eq(¤t.disk, &source.disk)
|
||||
})
|
||||
};
|
||||
if sources.len() != self.sources.len() || self.sources.iter().any(|source| !contains_source(&sources, source)) {
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
@@ -578,10 +547,12 @@ impl RecoveryPass {
|
||||
.iter()
|
||||
.filter(|source| {
|
||||
source.available
|
||||
&& !self
|
||||
.sources
|
||||
.iter()
|
||||
.any(|previous| previous.available && previous.same_disk(source))
|
||||
&& !self.sources.iter().any(|previous| {
|
||||
previous.available
|
||||
&& Arc::ptr_eq(&previous.disk, &source.disk)
|
||||
&& previous.pool == source.pool
|
||||
&& previous.set == source.set
|
||||
})
|
||||
})
|
||||
.map(|source| (source.pool, source.set))
|
||||
.collect();
|
||||
@@ -596,39 +567,42 @@ impl RecoveryPass {
|
||||
fn defer(&mut self, mut scan: DiskScan) {
|
||||
if let Some(buckets) = scan.buckets.as_mut() {
|
||||
for bucket in buckets {
|
||||
bucket.discovery = BucketDiscovery::Unstarted;
|
||||
bucket.cursor = None;
|
||||
bucket.incarnation = None;
|
||||
}
|
||||
}
|
||||
let same_scope = |other: &DiskScan| {
|
||||
scan.source.same_disk(&other.source)
|
||||
&& scan.front_bucket().map(|bucket| &bucket.bucket) == other.front_bucket().map(|bucket| &bucket.bucket)
|
||||
scan.source.pool == other.source.pool
|
||||
&& scan.source.set == other.source.set
|
||||
&& scan.source.disk.to_string() == other.source.disk.to_string()
|
||||
&& scan
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.bucket)
|
||||
== other
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.bucket)
|
||||
};
|
||||
if let Some(failed) = scan.front_bucket() {
|
||||
// A full sweep may have listed this bucket before the retry failed.
|
||||
// Keep the failed scope's backoff for all still-unopened copies.
|
||||
self.scans.retain_mut(|queued| {
|
||||
if queued.source.same_disk(&scan.source)
|
||||
&& let Some(buckets) = queued.buckets.as_mut()
|
||||
{
|
||||
buckets.retain(|bucket| bucket.bucket != failed.bucket || bucket.has_progress());
|
||||
!buckets.is_empty()
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
if !self.deferred.iter().any(|(_, pending)| same_scope(pending)) {
|
||||
self.deferred.push_back((Instant::now() + INVENTORY_INTERVAL, scan));
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant, cancel: &CancellationToken) {
|
||||
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant) {
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
let active_cursor = |scan: &DiskScan| scan.front_bucket().is_some_and(BucketScan::has_progress);
|
||||
let active_cursor = |scan: &DiskScan| {
|
||||
scan.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.is_some_and(|bucket| bucket.cursor.is_some() || !bucket.pending.is_empty())
|
||||
};
|
||||
if self.scans.iter().filter(|scan| active_cursor(scan)).count() >= MAX_ACTIVE_DISCOVERY_CURSORS {
|
||||
// Bound the number of directory stacks we keep open while rotating
|
||||
// across disks. Finish existing walks before opening another bucket.
|
||||
// Keep room for exact-key recovery and other discovery callers in
|
||||
// the disk API's bounded session table. Finish existing cursors
|
||||
// before starting another bucket; queued sources retain their place.
|
||||
if let Some(index) = self.scans.iter().position(active_cursor) {
|
||||
self.scans.rotate_left(index);
|
||||
}
|
||||
@@ -637,28 +611,14 @@ impl RecoveryPass {
|
||||
if scan.buckets.is_none() {
|
||||
match tokio::time::timeout_at(deadline, scan.source.disk.list_volumes()).await {
|
||||
Ok(Ok(volumes)) => {
|
||||
// A retry that has yet to open its bucket can cover the full
|
||||
// scope for this generation, without bypassing its backoff.
|
||||
let unopened_retries: HashSet<_> = self
|
||||
.scans
|
||||
.iter()
|
||||
.chain(self.deferred.iter().map(|(_, retry)| retry))
|
||||
.filter(|retry| retry.source.same_disk(&scan.source))
|
||||
.filter_map(|retry| retry.buckets.as_ref())
|
||||
.flatten()
|
||||
.filter(|bucket| !bucket.has_progress())
|
||||
.map(|bucket| bucket.bucket.as_str())
|
||||
.collect();
|
||||
scan.buckets = Some(
|
||||
volumes
|
||||
.into_iter()
|
||||
.filter(|volume| {
|
||||
!is_meta_bucketname(&volume.name) && !unopened_retries.contains(volume.name.as_str())
|
||||
})
|
||||
.filter(|volume| !is_meta_bucketname(&volume.name))
|
||||
.map(|volume| BucketScan {
|
||||
bucket: volume.name,
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
cursor: None,
|
||||
pending: VecDeque::new(),
|
||||
})
|
||||
.collect(),
|
||||
@@ -674,7 +634,7 @@ impl RecoveryPass {
|
||||
{
|
||||
let had_pending = !bucket.pending.is_empty();
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if !bucket.pending.is_empty() || (had_pending && matches!(bucket.discovery, BucketDiscovery::Unstarted)) {
|
||||
if !bucket.pending.is_empty() || (had_pending && bucket.cursor.is_none()) {
|
||||
if !bucket.pending.is_empty() {
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
@@ -683,104 +643,47 @@ impl RecoveryPass {
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Finish an older cursor before the new sweep revisits that
|
||||
// bucket. A different bucket may proceed once the disk is idle.
|
||||
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_))
|
||||
&& self
|
||||
.scans
|
||||
.iter()
|
||||
.filter(|other| other.source.same_disk(&scan.source))
|
||||
.filter_map(DiskScan::front_bucket)
|
||||
.any(|other| {
|
||||
matches!(other.discovery, BucketDiscovery::InFlight(_))
|
||||
|| (!bucket.has_progress() && other.bucket == bucket.bucket && other.has_progress())
|
||||
})
|
||||
{
|
||||
buckets.push_front(bucket);
|
||||
self.scans.push_back(scan);
|
||||
return;
|
||||
}
|
||||
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_)) {
|
||||
let store = Arc::clone(store);
|
||||
let incarnation = bucket.incarnation;
|
||||
let disk = Arc::clone(&scan.source.disk);
|
||||
let volume = bucket.bucket.clone();
|
||||
let cancel = cancel.child_token();
|
||||
let session = match std::mem::take(&mut bucket.discovery) {
|
||||
BucketDiscovery::Paused(session) => Some(session),
|
||||
_ => None,
|
||||
};
|
||||
bucket.discovery = BucketDiscovery::InFlight(Box::pin(async move {
|
||||
let _cancel_on_drop = cancel.clone().drop_guard();
|
||||
let (volume, incarnation) = match incarnation {
|
||||
Some(incarnation) => (volume, incarnation),
|
||||
None => {
|
||||
// Finish the quorum read and release its metadata guard even
|
||||
// while the discovery scheduler is polling other disks.
|
||||
let lookup = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let incarnation =
|
||||
tokio::time::timeout(DISCOVERY_BUDGET, store.bucket_incarnation_id_from_disk(&volume))
|
||||
.await
|
||||
.map_err(|_| DiskError::Timeout)?
|
||||
.map_err(DiskError::other)?;
|
||||
Ok::<_, DiskError>((volume, incarnation))
|
||||
}));
|
||||
lookup.await.map_err(DiskError::other)??
|
||||
}
|
||||
};
|
||||
// A stalled disk must not prevent later sweeps on healthy disks.
|
||||
let (transactions, next) = tokio::time::timeout(DISCOVERY_PAGE_STALL, async move {
|
||||
match disk.as_ref() {
|
||||
Disk::Local(local) => {
|
||||
local
|
||||
.advance_background_delete_discovery(volume, session, DISCOVERY_PAGE_SIZE, cancel)
|
||||
.await
|
||||
}
|
||||
#[cfg(feature = "dst")]
|
||||
Disk::Sim(sim) => sim
|
||||
.discover_delete_transactions(&volume, None, None, DISCOVERY_PAGE_SIZE)
|
||||
.await
|
||||
.map(|page| (page.transactions, None)),
|
||||
Disk::Remote(_) => Err(DiskError::DiskNotFound),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DiskError::Timeout)??;
|
||||
Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions,
|
||||
next,
|
||||
})
|
||||
}));
|
||||
}
|
||||
if let BucketDiscovery::InFlight(page) = &mut bucket.discovery {
|
||||
let wait_until = deadline.min(Instant::now() + DISCOVERY_PAGE_WAIT);
|
||||
match tokio::time::timeout_at(wait_until, page.as_mut()).await {
|
||||
Ok(Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions,
|
||||
next,
|
||||
})) => {
|
||||
bucket.incarnation = Some(incarnation);
|
||||
bucket.pending = transactions.into_iter().map(|transaction| transaction.object).collect();
|
||||
bucket.discovery = next.map_or(BucketDiscovery::Unstarted, BucketDiscovery::Paused);
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if !matches!(bucket.discovery, BucketDiscovery::Unstarted) || !bucket.pending.is_empty() {
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
if bucket.incarnation.is_none() {
|
||||
match tokio::time::timeout_at(deadline, store.bucket_incarnation_id_from_disk(&bucket.bucket)).await {
|
||||
Ok(Ok(incarnation)) => bucket.incarnation = Some(incarnation),
|
||||
_ => {
|
||||
self.defer(DiskScan {
|
||||
source: scan.source.clone(),
|
||||
buckets: Some(VecDeque::from([bucket])),
|
||||
});
|
||||
if !buckets.is_empty() {
|
||||
self.scans.push_back(scan);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
// Native calls can run past a scheduling window. Poll the
|
||||
// same page next time, including any evidence it has found.
|
||||
}
|
||||
}
|
||||
match tokio::time::timeout_at(
|
||||
deadline,
|
||||
scan.source
|
||||
.disk
|
||||
.discover_delete_transactions(&bucket.bucket, None, bucket.cursor.take(), DISCOVERY_PAGE_SIZE),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(page)) => {
|
||||
bucket.pending = page.transactions.into_iter().map(|transaction| transaction.object).collect();
|
||||
bucket.cursor = page.next;
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if bucket.cursor.is_some() || !bucket.pending.is_empty() {
|
||||
// Keep one bounded page until its keys are admitted;
|
||||
// unopened buckets cannot displace its continuation.
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Retry only this source, never a full healthy tree
|
||||
// because another disk is offline or a cursor expired.
|
||||
self.defer(DiskScan {
|
||||
source: scan.source.clone(),
|
||||
buckets: Some(VecDeque::from([bucket])),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if scan.buckets.as_ref().is_some_and(|buckets| !buckets.is_empty()) {
|
||||
@@ -796,6 +699,24 @@ impl RecoveryPass {
|
||||
}
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
// Renew only this worker's bounded local cursors before any await.
|
||||
// Backpressure and a slow canonical rollback must not erase progress.
|
||||
for scan in &mut self.scans {
|
||||
if let Some(bucket) = scan.buckets.as_mut().and_then(|buckets| buckets.front_mut())
|
||||
&& let Some(cursor) = bucket.cursor.as_ref()
|
||||
{
|
||||
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;
|
||||
hints.request_rescan();
|
||||
}
|
||||
}
|
||||
}
|
||||
let discovery_deadline = Instant::now() + DISCOVERY_BUDGET;
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
@@ -810,21 +731,12 @@ impl RecoveryPass {
|
||||
}
|
||||
if let Some(generation) = hints.rescan() {
|
||||
self.scan_generation = Some(generation);
|
||||
// A due retry may already have a live page even though the
|
||||
// previous full sweep completed. Keep it ahead of fresh work.
|
||||
for source in &self.sources {
|
||||
let inventory_queued = self
|
||||
.scans
|
||||
.iter()
|
||||
.chain(self.deferred.iter().map(|(_, retry)| retry))
|
||||
.any(|scan| scan.buckets.is_none() && scan.source.same_disk(source));
|
||||
if !inventory_queued {
|
||||
self.scans.push_back(DiskScan {
|
||||
source: source.clone(),
|
||||
buckets: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.scans = self
|
||||
.sources
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|source| DiskScan { source, buckets: None })
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
for _ in 0..self.deferred.len() {
|
||||
@@ -841,7 +753,7 @@ impl RecoveryPass {
|
||||
}
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
_ = self.discover_page(store, discovery_deadline, cancel) => {}
|
||||
_ = self.discover_page(store, discovery_deadline) => {}
|
||||
}
|
||||
}
|
||||
if self.scans.is_empty()
|
||||
@@ -1626,180 +1538,6 @@ mod tests {
|
||||
assert!(pass.scans.is_empty());
|
||||
assert!(store.ctx.delete_recovery_hints().rescan().is_none());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_slow_bucket_identity_does_not_block_other_disks() {
|
||||
let healthy = "runtime-healthy-identity";
|
||||
let blocked = "runtime-blocked-identity";
|
||||
let (_dirs, store, disks) = fixture(healthy).await;
|
||||
store
|
||||
.make_bucket(blocked, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create second bucket");
|
||||
prepare(&store, &disks, healthy).await;
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(healthy)
|
||||
.await
|
||||
.expect("healthy bucket incarnation");
|
||||
let writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked)
|
||||
.await
|
||||
.expect("hold the blocked bucket's metadata write lock");
|
||||
let key = DeleteRecoveryKey {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
bucket: healthy.to_owned(),
|
||||
object: "object".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.scans
|
||||
.extend([blocked, healthy].into_iter().enumerate().map(|(index, bucket)| DiskScan {
|
||||
source: LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[index].clone(),
|
||||
available: true,
|
||||
},
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
assert!(!hints.is_pending(&key), "the key must be discovered by the healthy scan");
|
||||
tokio::time::timeout(Duration::from_secs(2), pass.discover(&store, &cancel))
|
||||
.await
|
||||
.expect("identity lookup yields to independent disk work");
|
||||
|
||||
assert!(hints.is_pending(&key), "the healthy disk discovers its journal while metadata is locked");
|
||||
assert!(pass.deferred.is_empty(), "the scheduler keeps the waiting page");
|
||||
assert!(matches!(
|
||||
pass.scans.front().and_then(DiskScan::front_bucket),
|
||||
Some(BucketScan { bucket, discovery: BucketDiscovery::InFlight(_), .. }) if bucket == blocked
|
||||
));
|
||||
|
||||
drop(writer);
|
||||
let writer = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked),
|
||||
)
|
||||
.await
|
||||
.expect("the parked discovery page must not keep the metadata guard held")
|
||||
.expect("reacquire the bucket's metadata write lock");
|
||||
drop(writer);
|
||||
pass.discover(&store, &cancel).await;
|
||||
assert!(pass.scans.is_empty(), "the original identity lookup resumes through the native page");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_rescan_keeps_an_inflight_retry_page() {
|
||||
let bucket = "runtime-rescan-retry";
|
||||
let (_dirs, store, disks) = fixture(bucket).await;
|
||||
let source = LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[0].clone(),
|
||||
available: true,
|
||||
};
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(bucket)
|
||||
.await
|
||||
.expect("bucket incarnation");
|
||||
let discovered = DeleteRecoveryKey {
|
||||
pool: source.pool,
|
||||
set: source.set,
|
||||
bucket: bucket.to_owned(),
|
||||
object: "found-in-retry".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.sources.push(source.clone());
|
||||
pass.scans.push_back(DiskScan {
|
||||
source,
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
discovery: BucketDiscovery::InFlight(Box::pin(std::future::ready(Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions: vec![DeleteTransactionId {
|
||||
object: discovered.object.clone(),
|
||||
transaction: Uuid::new_v4(),
|
||||
}],
|
||||
next: None,
|
||||
})))),
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
pass.discover(&store, &CancellationToken::new()).await;
|
||||
|
||||
assert!(hints.is_pending(&discovered), "a fresh sweep must admit the in-flight retry result");
|
||||
assert!(pass.scans.is_empty(), "the fresh sweep also completes");
|
||||
assert!(hints.rescan().is_none(), "the new generation is acknowledged");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_rescan_respects_the_retry_backoff() {
|
||||
let bucket = "runtime-rescan-backoff";
|
||||
let (_dirs, store, disks) = fixture(bucket).await;
|
||||
prepare(&store, &disks, bucket).await;
|
||||
let source = LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[0].clone(),
|
||||
available: true,
|
||||
};
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(bucket)
|
||||
.await
|
||||
.expect("bucket incarnation");
|
||||
let discovered = DeleteRecoveryKey {
|
||||
pool: source.pool,
|
||||
set: source.set,
|
||||
bucket: bucket.to_owned(),
|
||||
object: "object".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.sources.push(source.clone());
|
||||
pass.scans.push_back(DiskScan {
|
||||
source: source.clone(),
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
pass.defer(DiskScan {
|
||||
source,
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
let cancel = CancellationToken::new();
|
||||
pass.discover(&store, &cancel).await;
|
||||
|
||||
assert!(!hints.is_pending(&discovered), "the full sweep must not bypass the bucket retry");
|
||||
assert!(hints.rescan().is_none(), "the deferred bucket does not block the full sweep");
|
||||
let (ready, _) = pass.deferred.front_mut().expect("pending bucket retry");
|
||||
*ready = Instant::now();
|
||||
pass.discover(&store, &cancel).await;
|
||||
|
||||
assert!(hints.is_pending(&discovered), "the due retry still reads the hidden preparation");
|
||||
assert!(pass.deferred.is_empty(), "the retry settled its discovery obligation");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_blocked_capacity_yields_until_periodic_sweep() {
|
||||
let (_dirs, store, _disks) = fixture("runtime-blocked-sweep").await;
|
||||
@@ -2224,24 +1962,6 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_continues_current_bucket_before_opening_later_buckets() {
|
||||
async fn finish_page(pass: &mut RecoveryPass, store: &Arc<ECStore>, cancel: &CancellationToken) {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
assert!(Instant::now() < deadline, "discovery page did not return");
|
||||
pass.discover_page(store, deadline, cancel).await;
|
||||
if !matches!(
|
||||
pass.scans
|
||||
.front()
|
||||
.and_then(|scan| scan.buckets.as_ref())
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.discovery),
|
||||
Some(BucketDiscovery::InFlight(_))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let bucket = "runtime-cursor-progress";
|
||||
let (dirs, store, disks) = fixture(bucket).await;
|
||||
let other = "runtime-after-large";
|
||||
@@ -2263,12 +1983,11 @@ mod tests {
|
||||
buckets: Some(VecDeque::from([bucket, other].map(|bucket| BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
cursor: None,
|
||||
pending: VecDeque::new(),
|
||||
}))),
|
||||
});
|
||||
let cancel = CancellationToken::new();
|
||||
finish_page(&mut pass, &store, &cancel).await;
|
||||
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
|
||||
let first = pass.scans[0]
|
||||
.buckets
|
||||
.as_ref()
|
||||
@@ -2276,44 +1995,8 @@ mod tests {
|
||||
.front()
|
||||
.expect("current bucket");
|
||||
assert_eq!(first.bucket, bucket);
|
||||
assert!(
|
||||
matches!(first.discovery, BucketDiscovery::Paused(_)),
|
||||
"raw entry budget must leave a continuation"
|
||||
);
|
||||
let Disk::Local(local) = disks[0].as_ref() else {
|
||||
panic!("expected a local drive");
|
||||
};
|
||||
let lease = local
|
||||
.get_disk()
|
||||
.lock_delete_discovery_bucket(bucket)
|
||||
.await
|
||||
.expect("hold bucket lease");
|
||||
pass.discover_page(&store, Instant::now(), &cancel).await;
|
||||
assert!(
|
||||
pass.deferred.is_empty(),
|
||||
"the scheduling deadline must not discard a page waiting on the disk"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
pass.scans[0]
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.discovery),
|
||||
Some(BucketDiscovery::InFlight(_))
|
||||
),
|
||||
"the original page and its continuation stay owned across the deadline"
|
||||
);
|
||||
let volumes = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
crate::disk::with_background_disk_io(cancel.clone(), local.list_volumes()),
|
||||
)
|
||||
.await
|
||||
.expect("another background operation can use the disk while discovery waits for its bucket lease")
|
||||
.expect("list volumes under background admission");
|
||||
assert!(volumes.iter().any(|volume| volume.name == other));
|
||||
drop(lease);
|
||||
finish_page(&mut pass, &store, &cancel).await;
|
||||
assert!(first.cursor.is_some(), "raw entry budget must leave a continuation");
|
||||
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
|
||||
assert_eq!(
|
||||
pass.scans[0]
|
||||
.buckets
|
||||
@@ -2325,25 +2008,5 @@ mod tests {
|
||||
other,
|
||||
"the second page completes instead of cycling through unopened buckets"
|
||||
);
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
pass.scan_generation = Some(hints.rescan().expect("scan obligation before the stall"));
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(other)
|
||||
.await
|
||||
.expect("source incarnation");
|
||||
pass.scans[0].buckets.as_mut().expect("open inventory")[0].incarnation = Some(incarnation);
|
||||
let _lease = local
|
||||
.get_disk()
|
||||
.lock_delete_discovery_bucket(other)
|
||||
.await
|
||||
.expect("hold bucket lease");
|
||||
tokio::time::pause();
|
||||
pass.discover_page(&store, Instant::now(), &cancel).await;
|
||||
tokio::time::advance(DISCOVERY_PAGE_STALL).await;
|
||||
pass.next_inventory = Some(Instant::now() + INVENTORY_INTERVAL);
|
||||
pass.discover(&store, &cancel).await;
|
||||
assert_eq!(pass.deferred.len(), 1, "a genuinely stalled source is deferred");
|
||||
assert!(pass.scan_generation.is_none(), "the stall cannot pin subsequent sweeps");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -592,53 +592,6 @@ impl ECStore {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Check whether an unversioned MRF target is absent from its original set.
|
||||
/// A true result requires every configured drive and no pending delete recovery.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if storage cannot establish identity, locks, or complete reads.
|
||||
pub async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
|
||||
) -> Result<bool> {
|
||||
use rustfs_common::mrf_channel::MrfKind;
|
||||
|
||||
let (Some(scope), None, MrfKind::PartialWrite) = (anchor.scope, anchor.version_id, anchor.kind) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let bucket = anchor.bucket.as_ref();
|
||||
let object = anchor.object.as_ref();
|
||||
if anchor.bucket_incarnation_id.is_nil()
|
||||
|| self.ctx.lock_manager().is_disabled()
|
||||
|| super::utils::is_reserved_or_invalid_bucket(bucket, false)
|
||||
|| object.ends_with('/')
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let pool_index = scope.pool_index as usize;
|
||||
let set_index = scope.set_index as usize;
|
||||
let opts = HealOpts {
|
||||
pool: Some(pool_index),
|
||||
set: Some(set_index),
|
||||
..Default::default()
|
||||
};
|
||||
let bucket_guard = self
|
||||
.acquire_bucket_incarnation_fence(bucket, anchor.bucket_incarnation_id)
|
||||
.await?;
|
||||
let pool = self
|
||||
.pools
|
||||
.get(pool_index)
|
||||
.ok_or_else(|| invalid_heal_pool_index(pool_index, self.pools.len()))?;
|
||||
if self.pool_meta.read().await.is_suspended(pool_index) {
|
||||
return Ok(false);
|
||||
}
|
||||
let set = pool.get_disks_for_heal_object(object, &opts)?;
|
||||
let capacity_store = (!self.single_pool()).then_some(self);
|
||||
let absent = set.probe_mrf_unversioned_absence(bucket, object, capacity_store).await?;
|
||||
self.validate_bucket_incarnation_fence(&bucket_guard, bucket)?;
|
||||
Ok(absent)
|
||||
}
|
||||
|
||||
async fn acquire_heal_format_fence(
|
||||
&self,
|
||||
) -> Result<(
|
||||
@@ -1500,10 +1453,24 @@ impl ECStore {
|
||||
Err(err) => vec![Err(err)],
|
||||
}
|
||||
} else {
|
||||
let capacity_store = (!self.single_pool()).then_some(self);
|
||||
let futures = heal_pools
|
||||
.iter()
|
||||
.map(|pool| pool.heal_object_with_absence(bucket, &object, version_id, opts, proof, capacity_store));
|
||||
let mut futures = Vec::with_capacity(heal_pools.len());
|
||||
for pool in heal_pools {
|
||||
let pool_idx = pool.pool_idx;
|
||||
let pool_object = object.clone();
|
||||
let opts = *opts;
|
||||
futures.push(self.run_external_decommission_capacity_heal(
|
||||
pool_idx,
|
||||
bucket,
|
||||
&object,
|
||||
opts,
|
||||
move |opts| async move {
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_operation_started(store_id);
|
||||
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, proof)
|
||||
.await
|
||||
},
|
||||
));
|
||||
}
|
||||
join_all(futures).await
|
||||
};
|
||||
|
||||
@@ -1557,7 +1524,7 @@ impl ECStore {
|
||||
version_id
|
||||
};
|
||||
let (before, error, absence) = pool
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
|
||||
.await?;
|
||||
let target = pool.get_disks_for_heal_object(POOL_META_NAME, opts)?;
|
||||
let owns_replica = Arc::ptr_eq(&target, &pool.get_disks_by_key(POOL_META_NAME));
|
||||
@@ -1576,7 +1543,7 @@ impl ECStore {
|
||||
return Ok((before, Some(error), None));
|
||||
}
|
||||
let (mut after, error, _) = pool
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
|
||||
.await?;
|
||||
after.before = before.before;
|
||||
if guard.is_lock_lost() {
|
||||
@@ -4374,11 +4341,6 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn targeted_heal_is_blocked_by_exact_fit_decommission_reservation() {
|
||||
use rustfs_common::mrf_channel::{
|
||||
MrfDurableRepairAnchor, MrfIngressResult, MrfIntent, MrfKind, MrfScope, release_mrf_intent,
|
||||
try_rearm_mrf_replay_intent,
|
||||
};
|
||||
|
||||
let (_temp_dirs, store, _other_store) = test_two_pool_stores(None).await;
|
||||
let bucket = format!("heal-capacity-{}", Uuid::new_v4().simple());
|
||||
let object = "targeted-heal.bin";
|
||||
@@ -4387,34 +4349,6 @@ mod tests {
|
||||
.await
|
||||
.expect("heal capacity bucket should be created");
|
||||
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(&bucket)
|
||||
.await
|
||||
.expect("MRF probe bucket incarnation should be readable");
|
||||
let mut intent = MrfIntent {
|
||||
bucket: Arc::from(bucket.as_str()),
|
||||
object: Arc::from("absent-mrf-target.bin"),
|
||||
version_id: None,
|
||||
kind: MrfKind::PartialWrite,
|
||||
scope: Some(MrfScope {
|
||||
pool_index: 1,
|
||||
set_index: 0,
|
||||
}),
|
||||
lease: None,
|
||||
enqueued_at_ms: 0,
|
||||
attempts: 0,
|
||||
delete_marker_purge: None,
|
||||
};
|
||||
assert_eq!(try_rearm_mrf_replay_intent(&mut intent), MrfIngressResult::Enqueued);
|
||||
let anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("MRF probe anchor should be valid");
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
|
||||
.await
|
||||
.expect("unreserved MRF probe should finish")
|
||||
.expect("unreserved MRF probe should be admitted"),
|
||||
"an absent target should be proven before the reservation"
|
||||
);
|
||||
|
||||
let target_set = store.pools[1].get_disks(0);
|
||||
let mut reader = PutObjReader::from_vec(b"targeted heal body".to_vec());
|
||||
target_set
|
||||
@@ -4465,15 +4399,6 @@ mod tests {
|
||||
assert_eq!(reservation.targets[0].reserved_physical_bytes, 60);
|
||||
}
|
||||
|
||||
let probe = tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
|
||||
.await
|
||||
.expect("reserved-target MRF admission should finish");
|
||||
release_mrf_intent(&intent);
|
||||
assert!(
|
||||
matches!(probe, Err(Error::SlowDown)),
|
||||
"reserved-target MRF probe must remain capacity-blocked: {probe:?}"
|
||||
);
|
||||
|
||||
let (_, err) = store
|
||||
.handle_heal_object(
|
||||
&bucket,
|
||||
|
||||
@@ -6119,351 +6119,6 @@ mod tests {
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
async fn stage_multipart_on_first_pool(
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
bytes: &[u8],
|
||||
opts: &ObjectOptions,
|
||||
) -> (String, Vec<crate::storage_api_contracts::multipart::CompletePart>) {
|
||||
use crate::storage_api_contracts::multipart::CompletePart;
|
||||
|
||||
let pool = &store.pools[0];
|
||||
let upload = pool
|
||||
.new_multipart_upload(bucket, key, opts)
|
||||
.await
|
||||
.expect("stage upload in pool 0");
|
||||
let part = pool
|
||||
.put_object_part(bucket, key, &upload.upload_id, 1, &mut PutObjReader::from_vec(bytes.to_vec()), opts)
|
||||
.await
|
||||
.expect("stage the part");
|
||||
(
|
||||
upload.upload_id,
|
||||
vec![CompletePart {
|
||||
part_num: part.part_num,
|
||||
etag: part.etag,
|
||||
..Default::default()
|
||||
}],
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
async fn seed_multipart_predecessors(
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
named_predecessor: bool,
|
||||
) -> (ObjectInfo, ObjectInfo) {
|
||||
store
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket");
|
||||
store
|
||||
.update_bucket_metadata_config(
|
||||
bucket,
|
||||
crate::bucket::metadata::OBJECT_LOCK_CONFIG,
|
||||
b"<ObjectLockConfiguration><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>".to_vec(),
|
||||
)
|
||||
.await
|
||||
.expect("enable Object Lock");
|
||||
let peer = &store.pools[1];
|
||||
let old = peer
|
||||
.put_object(
|
||||
bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(vec![1; 20]),
|
||||
&ObjectOptions {
|
||||
versioned: named_predecessor,
|
||||
user_defined: HashMap::from([(
|
||||
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
|
||||
"ON".to_owned(),
|
||||
)]),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write protected predecessor in pool 1");
|
||||
let head = peer
|
||||
.put_object(
|
||||
bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(vec![2; 10]),
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write a newer unprotected version in pool 1");
|
||||
(old, head)
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn unconditional_multipart_checks_the_historical_null_for_object_lock_and_quota() {
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-null-predecessor", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("mpu-null-{}", Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, false).await;
|
||||
let mut opts = ObjectOptions {
|
||||
version_suspended: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(opts.set_quota_admission(30, 30));
|
||||
let (upload, parts) = stage_multipart_on_first_pool(&store, &bucket, key, &[3; 20], &opts).await;
|
||||
let denied = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &opts)
|
||||
.await
|
||||
.expect_err("the historical null is under legal hold in pool 1");
|
||||
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
|
||||
let null = ObjectOptions {
|
||||
version_id: Some(Uuid::nil().to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
store.pools[1]
|
||||
.get_object_info(&bucket, key, &null)
|
||||
.await
|
||||
.expect("preserved null")
|
||||
.etag,
|
||||
old.etag
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("unchanged head")
|
||||
.version_id,
|
||||
head.version_id
|
||||
);
|
||||
store.pools[1]
|
||||
.get_disks_by_key(key)
|
||||
.put_object_metadata(
|
||||
&bucket,
|
||||
key,
|
||||
&ObjectOptions {
|
||||
eval_metadata: Some(HashMap::from([(
|
||||
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
|
||||
"OFF".to_owned(),
|
||||
)])),
|
||||
..null
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("release the legal hold on the historical null");
|
||||
let completed = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &opts)
|
||||
.await
|
||||
.expect("retry the same upload and replace 20 bytes in a full bucket");
|
||||
assert!(completed.version_id.is_none_or(|id| id.is_nil()));
|
||||
assert_ne!(completed.etag, old.etag);
|
||||
assert!(completed.mod_time > head.mod_time);
|
||||
assert_eq!(completed.put_usage.expect("replacement usage").replaced_size(), 20);
|
||||
assert_eq!(
|
||||
store.pools[1]
|
||||
.get_object_info(
|
||||
&bucket,
|
||||
key,
|
||||
&ObjectOptions {
|
||||
version_id: Some(head.version_id.expect("named head").to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.expect("preserved named version")
|
||||
.etag,
|
||||
head.etag
|
||||
);
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn multipart_reads_remote_history_only_for_an_explicit_named_replacement() {
|
||||
use crate::disk::lifecycle_test_io::Observer;
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-named-predecessor", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("mpu-named-{}", Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, true).await;
|
||||
let old_id = old.version_id.expect("named predecessor");
|
||||
let opts = ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (explicit, explicit_parts) = stage_multipart_on_first_pool(
|
||||
&store,
|
||||
&bucket,
|
||||
key,
|
||||
b"replace the retained version",
|
||||
&ObjectOptions {
|
||||
version_id: Some(old_id.to_string()),
|
||||
..opts.clone()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let (fresh, fresh_parts) = stage_multipart_on_first_pool(&store, &bucket, key, b"new version", &opts).await;
|
||||
let reads = Observer::new(&bucket);
|
||||
let condition = ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: Some(head.etag.expect("current ETag")),
|
||||
..Default::default()
|
||||
}),
|
||||
..opts.clone()
|
||||
};
|
||||
let completed = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &fresh, fresh_parts, &condition)
|
||||
.await
|
||||
.expect("publish a fresh named version beside a retained historical version");
|
||||
let id = completed.version_id.expect("fresh UUID");
|
||||
assert_ne!(id, old_id);
|
||||
assert_ne!(Some(id), head.version_id);
|
||||
assert_eq!(completed.put_usage.expect("usage for fresh version").replaced_size(), 0);
|
||||
assert!(
|
||||
reads.snapshot().reads.iter().all(|name| name != key),
|
||||
"a live head proves a fresh version appends without reading the complete history"
|
||||
);
|
||||
let denied = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &explicit, explicit_parts, &opts)
|
||||
.await
|
||||
.expect_err("the version requested at initiation remains protected");
|
||||
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
|
||||
assert!(
|
||||
reads.snapshot().reads.iter().any(|name| name == key),
|
||||
"an explicit historical replacement must be located before publication"
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("preserved fresh head")
|
||||
.version_id,
|
||||
Some(id)
|
||||
);
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn conditional_multipart_matches_the_current_pool_and_rechecks_concurrent_writes() {
|
||||
use crate::set_disk::{MultipartCommitBarrier, MultipartCommitPause};
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
|
||||
let if_match = |info: &ObjectInfo| ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: Some(info.etag.clone().expect("object ETag")),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "conditional-mpu-writes", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("conditional-mpu-{}", uuid::Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket");
|
||||
let write_peer = async |body: &[u8], mod_time| {
|
||||
store.pools[1]
|
||||
.put_object(
|
||||
&bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(body.to_vec()),
|
||||
&ObjectOptions {
|
||||
mod_time: Some(mod_time),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write on the other pool")
|
||||
};
|
||||
let future_time = OffsetDateTime::now_utc() + time::Duration::hours(1);
|
||||
let existing = write_peer(b"old", future_time).await;
|
||||
let (upload, parts) =
|
||||
stage_multipart_on_first_pool(&store, &bucket, key, b"first completion", &ObjectOptions::default()).await;
|
||||
let first = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&existing))
|
||||
.await
|
||||
.expect("match the object in pool 1 and publish the upload in pool 0");
|
||||
assert!(first.mod_time > existing.mod_time);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("current completion")
|
||||
.etag,
|
||||
first.etag
|
||||
);
|
||||
|
||||
let (upload, parts) =
|
||||
stage_multipart_on_first_pool(&store, &bucket, key, b"retryable completion", &ObjectOptions::default()).await;
|
||||
let paused = MultipartCommitBarrier::install(&bucket, key, MultipartCommitPause::BeforeConditionalNamespace);
|
||||
let complete = tokio::spawn({
|
||||
let (store, bucket, upload, parts, condition) =
|
||||
(store.clone(), bucket.clone(), upload.clone(), parts.clone(), if_match(&first));
|
||||
async move {
|
||||
store
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &condition)
|
||||
.await
|
||||
}
|
||||
});
|
||||
paused.wait_until_paused().await;
|
||||
let winner = write_peer(b"concurrent write", future_time + time::Duration::seconds(1)).await;
|
||||
drop(paused);
|
||||
assert_eq!(
|
||||
complete
|
||||
.await
|
||||
.expect("completion task")
|
||||
.expect_err("the concurrent write changed the current ETag"),
|
||||
StorageError::PreconditionFailed
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("concurrent winner")
|
||||
.etag,
|
||||
winner.etag
|
||||
);
|
||||
let retry = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &if_match(&winner))
|
||||
.await
|
||||
.expect("retry the same staged upload with the current ETag");
|
||||
assert!(retry.mod_time > winner.mod_time);
|
||||
let replay = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&retry))
|
||||
.await
|
||||
.expect("a matching condition may replay the published upload");
|
||||
assert!(replay.multipart_completion_replayed);
|
||||
assert_eq!(replay.data_dir, retry.data_dir);
|
||||
assert!(replay.put_usage.is_none());
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
@@ -22162,6 +21817,66 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn bulk_delete_releases_completed_keys_while_an_unrelated_disk_transaction_waits() {
|
||||
let temp = tempfile::tempdir().expect("temporary store");
|
||||
let root = temp.path().canonicalize().expect("canonical disk root");
|
||||
let (_ctx, store, _shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(&root, "batch-key-lifetime", &[1])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("batch-lock-{}", uuid::Uuid::new_v4());
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket");
|
||||
for key in ["a-done", "z-held"] {
|
||||
let mut body = PutObjReader::from_vec(b"before delete".to_vec());
|
||||
store
|
||||
.put_object(&bucket, key, &mut body, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("seed object");
|
||||
}
|
||||
let disk = root.join("pool0/set0/disk0").join(&bucket);
|
||||
let held_path = disk.join("z-held");
|
||||
let done_meta = disk.join("a-done/xl.meta");
|
||||
assert!(done_meta.is_file() && held_path.join("xl.meta").is_file());
|
||||
let held = crate::disk::os::acquire_metadata_mutation_lease(&held_path, None).await;
|
||||
let keys: Vec<_> = std::iter::once("a-done".to_owned())
|
||||
.chain((0..32).map(|i| format!("middle-{i:02}")))
|
||||
.chain(std::iter::once("z-held".to_owned()))
|
||||
.collect();
|
||||
let objects = keys
|
||||
.iter()
|
||||
.map(|name| crate::storage_api_contracts::object::ObjectToDelete {
|
||||
object_name: name.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let service = Arc::clone(&store);
|
||||
let name = bucket.clone();
|
||||
let deletion = tokio::spawn(async move { service.delete_objects(&name, objects, ObjectOptions::default()).await });
|
||||
let completed_key = tokio::time::timeout(Duration::from_secs(12), async {
|
||||
while tokio::fs::try_exists(&done_meta).await.expect("observe completed key") {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let lock = store.handle_new_ns_lock(&bucket, "a-done").await.expect("completed key lock");
|
||||
lock.get_write_lock_quiet(Duration::from_secs(30))
|
||||
.await
|
||||
.expect("reuse completed key");
|
||||
})
|
||||
.await;
|
||||
assert!(held_path.join("xl.meta").is_file(), "the held object must stay intact");
|
||||
drop(held);
|
||||
let (deleted, errors) = deletion.await.expect("join bulk delete");
|
||||
assert!(errors.iter().all(Option::is_none), "{errors:?}");
|
||||
assert_eq!(
|
||||
deleted.iter().map(|v| &v.object_name).collect::<Vec<_>>(),
|
||||
keys.iter().collect::<Vec<_>>()
|
||||
);
|
||||
assert!(completed_key.is_ok(), "a stalled disk transaction kept an unrelated completed key locked");
|
||||
}
|
||||
|
||||
// #6898: a DeleteObjects request dropped between the per-disk commit and the
|
||||
// cleanup pass (client disconnect) must not leave metadata-less residue.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1438,7 +1438,19 @@ impl ECStore {
|
||||
.acquire_object_read_lock_if_needed("lifecycle_versions", bucket, &disk_object, &mut opts)
|
||||
.await?;
|
||||
|
||||
let versions = self.read_object_version_history(bucket, object, &[]).await?;
|
||||
// As with version listings, include every physical set: migration can
|
||||
// leave a key's history in more than its current hash destination.
|
||||
let reads = self
|
||||
.pools
|
||||
.iter()
|
||||
.flat_map(|pool| &pool.disk_set)
|
||||
.map(|set| set.read_object_versions_for_lifecycle(bucket, object));
|
||||
let mut entries = Vec::new();
|
||||
for result in join_all(reads).await {
|
||||
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
if self.pools.is_empty()
|
||||
|| bucket_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| opts
|
||||
@@ -1450,34 +1462,6 @@ impl ECStore {
|
||||
{
|
||||
return Err(Error::PreconditionFailed);
|
||||
}
|
||||
let versioned = versioning.versioned(object);
|
||||
Ok(versions
|
||||
.iter()
|
||||
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) async fn read_object_version_history(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
retired: &[usize],
|
||||
) -> Result<Vec<rustfs_filemeta::FileInfo>> {
|
||||
// As with version listings, include every physical set: migration can
|
||||
// leave a key's history in more than its current hash destination.
|
||||
let reads = self
|
||||
.pools
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| !retired.contains(index))
|
||||
.flat_map(|(_, pool)| &pool.disk_set)
|
||||
.map(|set| set.read_object_version_history(bucket, object));
|
||||
let mut entries = Vec::new();
|
||||
for result in join_all(reads).await {
|
||||
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
let mut entries = entries.into_iter();
|
||||
let Some(mut entry) = entries.next() else {
|
||||
return Ok(Vec::new());
|
||||
@@ -1485,7 +1469,15 @@ impl ECStore {
|
||||
if entries.len() > 0 {
|
||||
merge_object_entry_versions(&mut entry, entries, log_listing_merge_corruption)?;
|
||||
}
|
||||
Ok(entry.file_info_versions(bucket)?.versions)
|
||||
// This projection excludes tier free-version bookkeeping but retains
|
||||
// pending version purges for the evaluator's replication safeguards.
|
||||
let versions = entry.file_info_versions(bucket)?;
|
||||
let versioned = versioning.versioned(object);
|
||||
Ok(versions
|
||||
.versions
|
||||
.iter()
|
||||
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn inner_list_object_versions_with_projection(
|
||||
@@ -1580,18 +1572,6 @@ impl ECStore {
|
||||
})
|
||||
}
|
||||
|
||||
fn list_read_fanout(&self) -> usize {
|
||||
self.pools.iter().fold(0usize, |total, pool| {
|
||||
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the local budget can fit one full listing walk at the time of sampling.
|
||||
/// Returns `None` until a listing walk initializes the budget.
|
||||
pub fn list_read_budget_has_capacity(&self) -> Option<bool> {
|
||||
self.ctx.list_read_budget_has_capacity(self.list_read_fanout())
|
||||
}
|
||||
|
||||
pub async fn list_path(self: Arc<Self>, o: &ListPathOptions) -> Result<ListPage> {
|
||||
// tracing::warn!("list_path opt {:?}", &o);
|
||||
|
||||
@@ -1645,11 +1625,10 @@ impl ECStore {
|
||||
if o.transient {
|
||||
o.create = false;
|
||||
}
|
||||
o.read_budget = self
|
||||
.ctx
|
||||
.acquire_list_read_budget(self.list_read_fanout())
|
||||
.await
|
||||
.map_err(Error::other)?;
|
||||
let fanout = self.pools.iter().fold(0usize, |total, pool| {
|
||||
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
|
||||
});
|
||||
o.read_budget = self.ctx.acquire_list_read_budget(fanout).await.map_err(Error::other)?;
|
||||
|
||||
let log_context = ListPathLogContext::from_options(&o);
|
||||
|
||||
@@ -2737,7 +2716,7 @@ fn merge_object_entry_versions(
|
||||
let equivalent = if info.delete_marker && previous_info.delete_marker {
|
||||
super::object::is_equivalent_data_movement_delete_marker(&info, previous_info)
|
||||
} else {
|
||||
crate::data_movement::equivalent_listed_object_versions(&info, previous_info)
|
||||
crate::data_movement::is_equivalent_data_movement_object_identity(&info, previous_info, true, true)
|
||||
};
|
||||
if !equivalent {
|
||||
return Err(corrupt("version_identity_conflict"));
|
||||
@@ -9106,15 +9085,7 @@ mod test {
|
||||
let first = test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 4, 2)]);
|
||||
let second = rewrite_test_version(
|
||||
test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 6, 2)]),
|
||||
|version| {
|
||||
let object = version.object.as_mut().expect("object version");
|
||||
let original = object.data_dir.replace(Uuid::from_u128(42)).expect("source data directory");
|
||||
rustfs_utils::http::insert_bytes(
|
||||
&mut object.meta_sys,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
original.to_string().into_bytes(),
|
||||
);
|
||||
},
|
||||
|version| version.object.as_mut().expect("object version").data_dir = Some(Uuid::from_u128(42)),
|
||||
);
|
||||
let forward = merge_test_object_entries(vec![first.clone(), second.clone()])
|
||||
.await
|
||||
|
||||
@@ -217,33 +217,6 @@ async fn lifecycle_exact_matches_listing_for_complete_version_groups() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_usage_counts_live_versions_hidden_by_a_current_marker() {
|
||||
let (dirs, store, bucket, _) = fixture(2).await;
|
||||
let key = "masked";
|
||||
let marker = FileInfo {
|
||||
name: key.into(),
|
||||
deleted: true,
|
||||
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_001).expect("marker timestamp")),
|
||||
..Default::default()
|
||||
};
|
||||
seed(&dirs[..4], &bucket, key, std::slice::from_ref(&marker)).await;
|
||||
let current = ObjectInfo::from_file_info(&marker, &bucket, key, true);
|
||||
for had_live_version in [false, true] {
|
||||
if had_live_version {
|
||||
seed(&dirs[4..], &bucket, key, &[version(key, Some(Uuid::new_v4()), 1_700_000_000)]).await;
|
||||
}
|
||||
let previous = store
|
||||
.resolve_put_predecessors(&bucket, key, &ObjectOptions::default(), Some(current.clone()), Some(Uuid::nil()))
|
||||
.await
|
||||
.expect("resolve all live versions under the marker");
|
||||
assert_eq!(
|
||||
previous.usage_receipt().expect("version usage"),
|
||||
crate::data_usage::PutUsageReceipt::from_predecessors(had_live_version, Some(¤t)).expect("fixture usage")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lifecycle_exact_merges_pools_and_more_than_one_page_of_versions() {
|
||||
let (dirs, store, bucket, incarnation) = fixture(2).await;
|
||||
|
||||
@@ -712,7 +712,7 @@ impl ECStore {
|
||||
}
|
||||
if opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, &opts).await
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, &opts, false).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
@@ -1340,12 +1340,32 @@ impl ECStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn check_write_precondition(&self, bucket: &str, object: &str, opts: &ObjectOptions) -> Option<StorageError> {
|
||||
async fn check_write_precondition(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
opts: &ObjectOptions,
|
||||
require_all_pools: bool,
|
||||
) -> Option<StorageError> {
|
||||
let mut lookup_opts = opts.clone();
|
||||
let http_preconditions = lookup_opts.http_preconditions?;
|
||||
lookup_opts.http_preconditions = None;
|
||||
lookup_opts.no_lock = true;
|
||||
let oi = self.get_object_info_for_delete(bucket, object, &lookup_opts).await;
|
||||
let oi = if require_all_pools {
|
||||
lookup_opts.metadata_cache_safe = false;
|
||||
lookup_opts.metadata_cache_fence_proof = None;
|
||||
lookup_opts.suppress_read_repair = true;
|
||||
// Only completion uses this branch, after validating bucket and object.
|
||||
let encoded_object = encode_dir_object_ref(object);
|
||||
self.get_latest_object_info_for_conditional_write(bucket, encoded_object.as_ref(), &lookup_opts)
|
||||
.await
|
||||
.and_then(|(info, _)| {
|
||||
lookup_opts.precondition_check(&info)?;
|
||||
Ok(info)
|
||||
})
|
||||
} else {
|
||||
self.get_object_info_for_delete(bucket, object, &lookup_opts).await
|
||||
};
|
||||
crate::set_disk::SetDisks::evaluate_write_precondition(oi, &http_preconditions, bucket, object, opts)
|
||||
}
|
||||
|
||||
@@ -1401,36 +1421,33 @@ impl ECStore {
|
||||
.await;
|
||||
return enqueue_transition_after_write(self.as_ref(), result, LcEventSrc::S3CompleteMultipartUpload, opts).await;
|
||||
}
|
||||
let multipool_store = (!opts.skip_decommissioned
|
||||
&& !opts.skip_rebalancing
|
||||
&& !opts.restore_copyback
|
||||
&& !opts.is_inbound_multipart_replica()
|
||||
&& self.uses_multipool_put_commit(bucket, object, opts).await?)
|
||||
.then_some(self.as_ref());
|
||||
if multipool_store.is_none()
|
||||
&& opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
if opts.http_preconditions.is_some() && !opts.data_movement {
|
||||
// Preserve explicitly scoped internal reads and borrowed-lock callers.
|
||||
let require_all_pools =
|
||||
!opts.replication_request && !opts.no_lock && !opts.skip_decommissioned && !opts.skip_rebalancing;
|
||||
if let Some(err) = self.check_write_precondition(bucket, object, opts, require_all_pools).await {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
let complete = |pool_idx: usize, parts| {
|
||||
Box::pin(
|
||||
self.pools[pool_idx]
|
||||
.get_disks_by_key(object)
|
||||
.complete_multipart_upload_with_store(bucket, object, upload_id, parts, opts, multipool_store),
|
||||
)
|
||||
};
|
||||
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
|
||||
Ok(pool_idx) => complete(pool_idx, uploaded_parts).await,
|
||||
Ok(pool_idx) => {
|
||||
self.pools[pool_idx]
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts, opts)
|
||||
.await
|
||||
}
|
||||
// The staging upload is already gone. The completed object lives on
|
||||
// the pool that published it; other pools answer InvalidUploadID.
|
||||
Err(err) if is_err_invalid_upload_id(&err) => {
|
||||
let mut missing = err;
|
||||
let mut found = None;
|
||||
for pool_idx in self.existing_multipart_pool_order().await {
|
||||
match complete(pool_idx, uploaded_parts.clone()).await {
|
||||
match self.pools[pool_idx]
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts.clone(), opts)
|
||||
.await
|
||||
{
|
||||
Ok(info) => {
|
||||
found = Some(Ok(info));
|
||||
break;
|
||||
|
||||
+403
-1259
File diff suppressed because it is too large
Load Diff
@@ -876,25 +876,6 @@ impl ECStore {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Completed sources have passed the terminal empty-pool verification and can
|
||||
/// be removed from the deployment. Active, failed and canceled sources remain readable.
|
||||
pub(super) async fn completed_decommission_pools(&self) -> Vec<usize> {
|
||||
self.pool_meta
|
||||
.read()
|
||||
.await
|
||||
.pools
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, status)| {
|
||||
status
|
||||
.decommission
|
||||
.as_ref()
|
||||
.filter(|info| info.complete && !info.failed && !info.canceled && info.unresolved_entries.is_empty())
|
||||
.map(|_| idx)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Observe every pool for a conditional-write preflight. This does not
|
||||
/// hold the namespace locks needed to prove a condition at publication.
|
||||
pub(super) async fn get_latest_object_info_for_conditional_write(
|
||||
@@ -923,14 +904,9 @@ impl ECStore {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let completed = if require_all_pools && !is_meta_bucketname(bucket) {
|
||||
self.completed_decommission_pools().await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut futures = Vec::with_capacity(self.pools.len());
|
||||
for (idx, pool) in self.pools.iter().enumerate() {
|
||||
if completed.contains(&idx) || suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
|
||||
if suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -308,12 +308,12 @@ async fn replica_write_with_waiting_metadata_writer(multipart: bool) {
|
||||
.new_ns_lock(".rustfs.sys", &format!("bucket-targets/{bucket}/transaction.lock"))
|
||||
.await
|
||||
.expect("create metadata writer");
|
||||
let writer = lock.get_write_lock(Duration::from_secs(5));
|
||||
let writer = lock.get_write_lock(Duration::from_secs(30));
|
||||
tokio::pin!(writer);
|
||||
// Leave the writer registered while the replica continues. A second read
|
||||
// acquisition would queue behind this writer, which needs our first read.
|
||||
assert!(futures::poll!(&mut writer).is_pending());
|
||||
timeout(Duration::from_secs(2), async {
|
||||
let commit = async {
|
||||
if let Some((upload_id, parts)) = upload {
|
||||
store
|
||||
.clone()
|
||||
@@ -323,10 +323,13 @@ async fn replica_write_with_waiting_metadata_writer(multipart: bool) {
|
||||
let mut data = PutObjReader::from_vec(b"replicated version".to_vec());
|
||||
store.put_object(bucket, "object", &mut data, &opts).await
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("replica must reuse its metadata read lock instead of waiting behind the writer")
|
||||
.expect("replica PUT should commit");
|
||||
};
|
||||
// The queued writer bounds a recursive read. Disk publication may take longer on a busy filesystem.
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = &mut writer => panic!("metadata writer finished before the replica committed under its snapshot"),
|
||||
result = commit => result.expect("replica PUT should commit"),
|
||||
};
|
||||
assert!(futures::poll!(&mut writer).is_pending(), "the snapshot must still fence metadata updates");
|
||||
let read_opts = ObjectOptions {
|
||||
version_id: opts.version_id.clone(),
|
||||
|
||||
@@ -19,6 +19,7 @@ use thiserror::Error;
|
||||
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
|
||||
|
||||
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
|
||||
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
|
||||
|
||||
/// Custom error type for heal operations
|
||||
/// This enum defines various error variants that can occur during
|
||||
@@ -56,10 +57,6 @@ pub enum Error {
|
||||
#[error("Heal task execution failed: {message}")]
|
||||
TaskExecutionFailed { message: String },
|
||||
|
||||
/// The storage result could not authorize discharge of a durable partial write.
|
||||
#[error("Missing exact storage proof for durable MRF repair {target}: {reason}")]
|
||||
MrfStorageProofUnavailable { target: String, reason: &'static str },
|
||||
|
||||
/// Only the qualified MRF Deep check may produce this terminal result.
|
||||
#[error("Independent verification unavailable for legacy object {target}; durable MRF responsibility retained")]
|
||||
LegacyMrfUnverified { target: String },
|
||||
@@ -242,10 +239,11 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
|
||||
| Error::ReplacementNamespaceChanged
|
||||
| Error::TransientSkip { .. }
|
||||
| Error::BucketDiscoveryIncomplete => HealErrorClass::Transient,
|
||||
Error::LegacyMrfUnverified { .. } | Error::MrfStorageProofUnavailable { .. } => HealErrorClass::Permanent,
|
||||
Error::LegacyMrfUnverified { .. } => HealErrorClass::Permanent,
|
||||
Error::Storage(error) => classify_storage_error(error),
|
||||
Error::Disk(error) => classify_disk_error(error),
|
||||
Error::Io(error) => classify_io_error(error),
|
||||
Error::TaskExecutionFailed { message } if message.starts_with(MRF_MISSING_PROOF_PREFIX) => HealErrorClass::Permanent,
|
||||
Error::TaskExecutionFailed { message } | Error::Other(message) => {
|
||||
classify_error_display(message).unwrap_or(HealErrorClass::Permanent)
|
||||
}
|
||||
|
||||
@@ -2317,13 +2317,6 @@ impl HealManager {
|
||||
self.storage.mrf_bucket_incarnation_retired(bucket, expected).await
|
||||
}
|
||||
|
||||
pub(super) async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
|
||||
) -> Result<bool> {
|
||||
self.storage.probe_mrf_unversioned_absence(anchor).await
|
||||
}
|
||||
|
||||
async fn submit_heal_request_with_receipt_alias_and_mrf_notice(
|
||||
&self,
|
||||
mut request: HealRequest,
|
||||
|
||||
@@ -2176,10 +2176,6 @@ fn only_typed_mrf_result_can_pause_unverified_legacy() {
|
||||
Err(Error::TaskExecutionFailed {
|
||||
message: "Missing exact storage proof for durable MRF repair display only".to_owned(),
|
||||
}),
|
||||
Err(Error::MrfStorageProofUnavailable {
|
||||
target: "file not found".to_owned(),
|
||||
reason: "storage receipt did not verify the requested identity and disposition",
|
||||
}),
|
||||
Err(Error::TaskCancelled),
|
||||
Err(Error::TaskTimeout),
|
||||
] {
|
||||
|
||||
@@ -57,9 +57,6 @@ use partial_write::{PartialWrites, ResponsibilityCheckpoint};
|
||||
|
||||
const MRF_LIFECYCLE_CONTROL_CAPACITY: usize = 128;
|
||||
const MRF_JOURNAL_DISK_CONCURRENCY: usize = 4;
|
||||
const MRF_HELD_ABSENCE_PROBE_INTERVAL: Duration = Duration::from_secs(1);
|
||||
const MRF_HELD_ABSENCE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MRF_LIFECYCLE_LIST_MAX_LIMIT: usize = 256;
|
||||
|
||||
static GLOBAL_MRF_LIFECYCLE_SENDER: std::sync::OnceLock<mpsc::Sender<MrfLifecycleCommand>> = std::sync::OnceLock::new();
|
||||
@@ -1038,29 +1035,6 @@ async fn submit_mrf_heal_request(
|
||||
Ok(receipt.result)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
struct MrfCheckpointRecords {
|
||||
authoritative: Vec<u8>,
|
||||
legacy: Vec<u8>,
|
||||
lifecycle: Vec<ResponsibilityCheckpoint>,
|
||||
}
|
||||
|
||||
impl MrfCheckpointRecords {
|
||||
fn append(&mut self, intent: &MrfIntent) -> Option<&[u8]> {
|
||||
let start = self.authoritative.len();
|
||||
if !encode_intent(intent, &mut self.authoritative) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
return None;
|
||||
}
|
||||
let encoded = &self.authoritative[start..];
|
||||
if intent.kind == MrfKind::MetadataCorruption || intent.scope.is_none() {
|
||||
self.legacy.extend_from_slice(encoded);
|
||||
}
|
||||
Some(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
struct MrfRuntime {
|
||||
queue: MrfQueue,
|
||||
partial_writes: PartialWrites,
|
||||
@@ -1436,17 +1410,20 @@ impl MrfRuntime {
|
||||
self.publish_metrics();
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> MrfCheckpointRecords {
|
||||
let mut snapshot = MrfCheckpointRecords::default();
|
||||
for intent in self.queue.intents() {
|
||||
let _ = snapshot.append(intent);
|
||||
fn snapshot(&self) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut authoritative = Vec::new();
|
||||
let mut legacy = Vec::new();
|
||||
for intent in self.queue.intents().chain(self.partial_writes.intents()) {
|
||||
let scoped_identity =
|
||||
!matches!(intent.kind, rustfs_common::mrf_channel::MrfKind::MetadataCorruption) && intent.scope.is_some();
|
||||
if !encode_intent(intent, &mut authoritative) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
}
|
||||
if !scoped_identity && !encode_intent(intent, &mut legacy) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
}
|
||||
}
|
||||
// Bind the lifecycle record to the exact published bytes, including
|
||||
// the record CRC, without running the codec a second time.
|
||||
snapshot.lifecycle = self
|
||||
.partial_writes
|
||||
.checkpoint_records(|intent| snapshot.append(intent).map(|bytes| sha2::Sha256::digest(bytes).into()));
|
||||
snapshot
|
||||
(authoritative, legacy)
|
||||
}
|
||||
|
||||
async fn flush(&mut self) -> bool {
|
||||
@@ -1458,31 +1435,29 @@ impl MrfRuntime {
|
||||
if self.partial_writes.pending_lifecycle_transition.is_some() {
|
||||
return self.flush_pending_lifecycle(None).await;
|
||||
}
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle,
|
||||
} = self.snapshot();
|
||||
if lifecycle.len() != self.partial_writes.depth() {
|
||||
return false;
|
||||
}
|
||||
let (authoritative, legacy) = self.snapshot();
|
||||
let lifecycle_byte_limit = self.config.journal_max_bytes.saturating_mul(4);
|
||||
let lifecycle_checkpoint = if lifecycle.is_empty() {
|
||||
let lifecycle_checkpoint = if self.partial_writes.depth() == 0 {
|
||||
None
|
||||
} else {
|
||||
let Some(checkpoint) = encode_mrf_lifecycle_checkpoint(
|
||||
self.lifecycle_format_version,
|
||||
self.checkpoint_owner,
|
||||
self.next_checkpoint_sequence,
|
||||
lifecycle,
|
||||
lifecycle_byte_limit,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
Some(checkpoint)
|
||||
let records = self.partial_writes.checkpoint_records(intent_digest);
|
||||
(records.len() == self.partial_writes.depth())
|
||||
.then(|| {
|
||||
encode_mrf_lifecycle_checkpoint(
|
||||
self.lifecycle_format_version,
|
||||
self.checkpoint_owner,
|
||||
self.next_checkpoint_sequence,
|
||||
records,
|
||||
lifecycle_byte_limit,
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
};
|
||||
let lifecycle_ready = self.partial_writes.depth() == 0 || lifecycle_checkpoint.is_some();
|
||||
let (committed_persisted, committed_on_disk) = if authoritative.is_empty() {
|
||||
(true, false)
|
||||
} else if !lifecycle_ready {
|
||||
(false, false)
|
||||
} else {
|
||||
match snapshot::publish_committed_snapshot_with_companion(
|
||||
&journal_disks().await,
|
||||
@@ -1512,8 +1487,14 @@ impl MrfRuntime {
|
||||
}
|
||||
}
|
||||
};
|
||||
self.finish_flush(&authoritative, &legacy, committed_persisted, committed_on_disk)
|
||||
.await
|
||||
self.finish_flush(
|
||||
&authoritative,
|
||||
&legacy,
|
||||
committed_persisted,
|
||||
committed_on_disk,
|
||||
lifecycle_checkpoint.is_some(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn pending_lifecycle_commit_matches(
|
||||
@@ -1560,14 +1541,7 @@ impl MrfRuntime {
|
||||
.clamp(Duration::from_secs(5), Duration::from_secs(60));
|
||||
let intent = pending.intent.clone();
|
||||
let record = pending.record.clone();
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle: mut records,
|
||||
} = self.snapshot();
|
||||
if records.len() != self.partial_writes.depth() {
|
||||
return false;
|
||||
}
|
||||
let mut records = self.partial_writes.checkpoint_records(intent_digest);
|
||||
let Some(current) = records.iter_mut().find(|current| {
|
||||
current.responsibility_id == record.responsibility_id && current.intent_digest == record.intent_digest
|
||||
}) else {
|
||||
@@ -1589,14 +1563,15 @@ impl MrfRuntime {
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let (authoritative, legacy) = self.snapshot();
|
||||
// A lost publication result must not regenerate the body or downgrade
|
||||
// the owner. An exact committed readback resolves it without new writes.
|
||||
let already_committed = match self.pending_lifecycle_commit_matches(&authoritative, &lifecycle).await {
|
||||
Ok(committed) => committed,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let authoritative = if already_committed {
|
||||
authoritative
|
||||
let (authoritative, lifecycle) = if already_committed {
|
||||
(authoritative, lifecycle)
|
||||
} else {
|
||||
let proof = match proof {
|
||||
Some(proof) => proof,
|
||||
@@ -1661,7 +1636,7 @@ impl MrfRuntime {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
authoritative
|
||||
(authoritative, lifecycle)
|
||||
};
|
||||
if !self.partial_writes.restore_state(&intent, &record) {
|
||||
return false;
|
||||
@@ -1672,7 +1647,8 @@ impl MrfRuntime {
|
||||
self.next_checkpoint_sequence = self.next_checkpoint_sequence.saturating_add(1);
|
||||
self.journal_on_disk = true;
|
||||
self.dirty = true;
|
||||
self.finish_flush(&authoritative, &legacy, true, true).await
|
||||
self.finish_flush(&authoritative, &legacy, true, true, !lifecycle.is_empty())
|
||||
.await
|
||||
}
|
||||
|
||||
async fn finish_flush(
|
||||
@@ -1681,6 +1657,7 @@ impl MrfRuntime {
|
||||
legacy: &[u8],
|
||||
committed_persisted: bool,
|
||||
committed_on_disk: bool,
|
||||
lifecycle_ready: bool,
|
||||
) -> bool {
|
||||
let authoritative_persisted = write_journal(MRF_SCOPED_JOURNAL_PATH, authoritative).await;
|
||||
if !authoritative.is_empty() {
|
||||
@@ -1699,7 +1676,7 @@ impl MrfRuntime {
|
||||
}
|
||||
all_deleted
|
||||
} else {
|
||||
committed_persisted
|
||||
lifecycle_ready && committed_persisted
|
||||
};
|
||||
// Keep dirty until the committed checkpoint, authoritative snapshot,
|
||||
// and compatibility mirror have all been accepted; otherwise a
|
||||
@@ -1874,20 +1851,22 @@ impl MrfRuntime {
|
||||
.chain(self.partial_writes.anchors())
|
||||
.cloned()
|
||||
.collect();
|
||||
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
|
||||
let legacy = rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for_buckets(&buckets);
|
||||
if rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events(&mut anchors) != 0 {
|
||||
let remaining: HashSet<_> = anchors.into_iter().collect();
|
||||
let previous_replay_anchor_count = self.durable_replay_anchors.len();
|
||||
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
|
||||
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
|
||||
let partial_writes_changed = self.partial_writes.retain_unproven(&remaining);
|
||||
self.dirty |= replay_anchors_changed || partial_writes_changed;
|
||||
let mut buckets: Vec<Arc<str>> = anchors.iter().map(|anchor| anchor.bucket.clone()).collect();
|
||||
buckets.sort_unstable();
|
||||
buckets.dedup();
|
||||
for bucket in &buckets {
|
||||
rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events_for(bucket.as_ref(), &mut anchors);
|
||||
}
|
||||
// Exact discharge takes precedence over held notices from this batch.
|
||||
for event in legacy {
|
||||
if self.partial_writes.park_unverified_legacy(&event.anchor) {
|
||||
self.dirty = true;
|
||||
let remaining: HashSet<_> = anchors.into_iter().collect();
|
||||
let previous_replay_anchor_count = self.durable_replay_anchors.len();
|
||||
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
|
||||
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
|
||||
self.dirty |= replay_anchors_changed || self.partial_writes.retain_unproven(&remaining);
|
||||
for bucket in buckets {
|
||||
for event in rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for(bucket.as_ref()) {
|
||||
if self.partial_writes.park_unverified_legacy(&event.anchor) {
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.publish_metrics();
|
||||
@@ -2410,9 +2389,6 @@ async fn run_mrf_consumer_with_stop(
|
||||
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
|
||||
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
|
||||
let mut held_probe = tokio::task::JoinSet::new();
|
||||
let mut retirement_probe = tokio::task::JoinSet::new();
|
||||
let mut next_held_probe = tokio::time::Instant::now();
|
||||
|
||||
loop {
|
||||
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
|
||||
@@ -2528,61 +2504,8 @@ async fn run_mrf_consumer_with_stop(
|
||||
runtime.flush().await;
|
||||
}
|
||||
}
|
||||
Some(result) = retirement_probe.join_next(), if !retirement_probe.is_empty() => {
|
||||
let result = match result {
|
||||
Ok((generation, Ok(Ok(true)))) => {
|
||||
runtime.partial_writes.note_bucket_retired(&generation);
|
||||
"proved"
|
||||
}
|
||||
Ok((_, Ok(Ok(false)))) => "retained",
|
||||
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
|
||||
Ok((_, Err(_))) => "timed_out",
|
||||
};
|
||||
counter!("rustfs_heal_mrf_bucket_retirement_probe_total", "result" => result).increment(1);
|
||||
}
|
||||
Some(result) = held_probe.join_next(), if !held_probe.is_empty() => {
|
||||
let result = match result {
|
||||
Ok((anchor, Ok(Ok(true)))) => {
|
||||
if runtime.partial_writes.note_held_absence_proof(anchor) {
|
||||
"proved"
|
||||
} else {
|
||||
"superseded"
|
||||
}
|
||||
}
|
||||
Ok((_, Ok(Ok(false)))) => "retained",
|
||||
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
|
||||
Ok((_, Err(_))) => "timed_out",
|
||||
};
|
||||
counter!("rustfs_heal_mrf_held_absence_probe_total", "result" => result).increment(1);
|
||||
}
|
||||
_ = flush_tick.tick() => {
|
||||
let now = tokio::time::Instant::now();
|
||||
let can_probe = runtime.replay_readable && held_probe.is_empty() && now >= next_held_probe;
|
||||
let (retirement, held) = runtime.partial_writes.plan_maintenance(
|
||||
runtime.replay_readable && retirement_probe.is_empty(),
|
||||
can_probe,
|
||||
);
|
||||
if let Some(generation) = retirement {
|
||||
let manager = manager.clone();
|
||||
retirement_probe.spawn(async move {
|
||||
let outcome = tokio::time::timeout(
|
||||
MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT,
|
||||
manager.mrf_bucket_incarnation_retired(&generation.0, generation.1),
|
||||
).await;
|
||||
(generation, outcome)
|
||||
});
|
||||
}
|
||||
if let Some(anchor) = held {
|
||||
next_held_probe = tokio::time::Instant::now() + MRF_HELD_ABSENCE_PROBE_INTERVAL;
|
||||
let manager = manager.clone();
|
||||
held_probe.spawn(async move {
|
||||
let outcome = tokio::time::timeout(
|
||||
MRF_HELD_ABSENCE_PROBE_TIMEOUT,
|
||||
manager.probe_mrf_unversioned_absence(&anchor),
|
||||
).await;
|
||||
(anchor, outcome)
|
||||
});
|
||||
}
|
||||
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
|
||||
runtime.discharge_durable_replay_anchors();
|
||||
match tick_action(
|
||||
runtime.dirty,
|
||||
@@ -3240,11 +3163,7 @@ mod tests {
|
||||
backoff_until: None,
|
||||
};
|
||||
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy: legacy_mirror,
|
||||
..
|
||||
} = runtime.snapshot();
|
||||
let (authoritative, legacy_mirror) = runtime.snapshot();
|
||||
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
|
||||
let (legacy_mirror_decoded, legacy_mirror_truncated) = decode_journal(&legacy_mirror);
|
||||
assert_eq!(authoritative_truncated, 0, "W13 authoritative scoped mirror must decode cleanly");
|
||||
@@ -4366,24 +4285,10 @@ mod tests {
|
||||
runtime_checkpoint: None,
|
||||
backoff_until: None,
|
||||
};
|
||||
runtime
|
||||
.admit_partial_write(scoped.clone(), Some(Uuid::new_v4()))
|
||||
.expect("admit scoped responsibility");
|
||||
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
|
||||
assert_eq!(runtime.queue.try_push_typed(compat.clone()), MrfQueuePushResult::Enqueued);
|
||||
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle,
|
||||
} = runtime.snapshot();
|
||||
let plain_bytes = encoded_payload(&compat);
|
||||
let scoped_bytes = encoded_payload(&scoped);
|
||||
assert_eq!(legacy, plain_bytes, "mirror reuses the exact unscoped bytes");
|
||||
assert_eq!(authoritative, [plain_bytes, scoped_bytes].concat());
|
||||
let (_, consumed) = decode_one(&authoritative).expect("decode first record");
|
||||
let durable_digest: [u8; 32] = sha2::Sha256::digest(&authoritative[consumed..]).into();
|
||||
assert_eq!(lifecycle.len(), 1);
|
||||
assert_eq!(lifecycle[0].intent_digest, durable_digest);
|
||||
let (authoritative, legacy) = runtime.snapshot();
|
||||
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
|
||||
assert_eq!(authoritative_truncated, 0);
|
||||
assert_eq!(authoritative_decoded.len(), 2);
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
use super::{
|
||||
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfLegacyRiskAcceptanceRequest, MrfQueueKey,
|
||||
queue_key, submit_mrf_heal_request,
|
||||
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfLegacyRiskAcceptanceRequest, MrfQueueKey, queue_key,
|
||||
submit_mrf_heal_request,
|
||||
};
|
||||
use rustfs_common::mrf_channel::{
|
||||
MrfDurableAdmissionError, MrfIngressResult, MrfVerifiedRepairDisposition, MrfVerifiedRepairEvent, release_mrf_intent,
|
||||
@@ -22,7 +22,7 @@ use rustfs_common::mrf_channel::{
|
||||
};
|
||||
use rustfs_heal_contracts::heal_channel::HealAdmissionResult;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque, hash_map::Entry};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::time::Instant;
|
||||
@@ -34,11 +34,7 @@ const MAX_OPERATOR_REFERENCE_BYTES: usize = 256;
|
||||
const LIFECYCLE_CHECKPOINT_RECORD_OVERHEAD_BYTES: usize = 256;
|
||||
const MAX_UNVERIFIED_RETRY_BACKOFF: Duration = Duration::from_secs(60);
|
||||
const MRF_RETIREMENT_PROOF_RECHECK_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const MRF_HELD_ABSENCE_RECHECK_INTERVAL: Duration = Duration::from_secs(60);
|
||||
const MRF_IDENTITY_PROBE_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
const MRF_DISPATCH_IDENTITY_START_BUDGET: Duration = Duration::from_secs(1);
|
||||
|
||||
pub(super) type BucketGeneration = (Arc<str>, Uuid);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
struct PartialWriteKey {
|
||||
@@ -295,7 +291,7 @@ pub(super) struct PartialWrites {
|
||||
retry_index: HashSet<PartialWriteKey>,
|
||||
identity_probe_order: VecDeque<PartialWriteKey>,
|
||||
identity_probe_index: HashSet<PartialWriteKey>,
|
||||
retirement_checks: HashMap<BucketGeneration, (Instant, bool)>,
|
||||
retirement_checks: HashMap<(Arc<str>, Uuid), (Instant, bool)>,
|
||||
unresolved_generation_candidate: Option<PartialWriteKey>,
|
||||
pub(super) pending_lifecycle_transition: Option<PendingLifecycleTransition>,
|
||||
bytes: usize,
|
||||
@@ -416,106 +412,69 @@ impl PartialWrites {
|
||||
self.entries.values().filter_map(|entry| entry.anchor.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn plan_maintenance(
|
||||
&mut self,
|
||||
probe_retirement: bool,
|
||||
probe_held: bool,
|
||||
) -> (Option<BucketGeneration>, Option<MrfDurableRepairAnchor>) {
|
||||
let now = Instant::now();
|
||||
let mut due_generation = None;
|
||||
let mut held = None;
|
||||
let mut generations = HashMap::new();
|
||||
for (key, entry) in &mut self.entries {
|
||||
pub(super) async fn note_retired_generation_proofs(&mut self, manager: &HealManager) {
|
||||
let mut intents_by_generation: HashMap<(Arc<str>, Uuid), Vec<&MrfIntent>> = HashMap::new();
|
||||
for entry in self.entries.values() {
|
||||
if !entry.persisted {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = entry.source_bucket_incarnation_id else {
|
||||
let Some(source_incarnation) = entry.source_bucket_incarnation_id else {
|
||||
continue;
|
||||
};
|
||||
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source) {
|
||||
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source_incarnation) {
|
||||
continue;
|
||||
}
|
||||
let bucket = &entry.intent.bucket;
|
||||
let retirement = match generations.entry((bucket.as_ref(), source)) {
|
||||
Entry::Occupied(previous) => previous.into_mut(),
|
||||
Entry::Vacant(generation) => {
|
||||
let (next, retired) = *self.retirement_checks.entry((bucket.clone(), source)).or_insert((now, false));
|
||||
if probe_retirement
|
||||
&& !retired
|
||||
&& next <= now
|
||||
&& due_generation.as_ref().is_none_or(|(_, _, due)| next < *due)
|
||||
{
|
||||
due_generation = Some((bucket.clone(), source, next));
|
||||
}
|
||||
generation.insert(retired.then(Vec::new))
|
||||
}
|
||||
};
|
||||
if let Some(anchors) = retirement {
|
||||
if let Some(anchor) = MrfDurableRepairAnchor::from_intent(&entry.intent, source) {
|
||||
// The retirement record also covers responsibilities that
|
||||
// never reached object-heal admission.
|
||||
if entry.anchor.as_ref() != Some(&anchor) {
|
||||
entry.anchor = Some(anchor.clone());
|
||||
}
|
||||
anchors.push(anchor);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if probe_held
|
||||
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
|
||||
&& entry.intent.kind == MrfKind::PartialWrite
|
||||
&& entry.intent.scope.is_some()
|
||||
&& entry.intent.version_id.is_none_or(|version| version == [0; 16])
|
||||
&& !entry.intent.object.ends_with('/')
|
||||
&& entry.next_attempt <= now
|
||||
&& held.is_none_or(|(_, due)| entry.next_attempt < due)
|
||||
{
|
||||
held = Some((key, entry.next_attempt));
|
||||
}
|
||||
intents_by_generation
|
||||
.entry((entry.intent.bucket.clone(), source_incarnation))
|
||||
.or_default()
|
||||
.push(&entry.intent);
|
||||
}
|
||||
|
||||
self.retirement_checks
|
||||
.retain(|(bucket, incarnation), _| generations.contains_key(&(bucket.as_ref(), *incarnation)));
|
||||
for anchor in generations.into_values().flatten().flatten() {
|
||||
publish_mrf_absence(anchor);
|
||||
}
|
||||
.retain(|generation, _| intents_by_generation.contains_key(generation));
|
||||
let now = Instant::now();
|
||||
for ((bucket, incarnation), intents) in intents_by_generation {
|
||||
let retired = match self.retirement_checks.get(&(bucket.clone(), incarnation)) {
|
||||
Some((_, true)) => true,
|
||||
Some((checked_at, false))
|
||||
if now.saturating_duration_since(*checked_at) < MRF_RETIREMENT_PROOF_RECHECK_INTERVAL =>
|
||||
{
|
||||
false
|
||||
}
|
||||
_ => {
|
||||
let retired = manager
|
||||
.mrf_bucket_incarnation_retired(bucket.as_ref(), incarnation)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
self.retirement_checks.insert((bucket.clone(), incarnation), (now, retired));
|
||||
retired
|
||||
}
|
||||
};
|
||||
if !retired {
|
||||
continue;
|
||||
}
|
||||
|
||||
let retirement = due_generation.and_then(|(bucket, source, _)| {
|
||||
let generation = (bucket, source);
|
||||
self.retirement_checks.get_mut(&generation)?.0 = now + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL;
|
||||
Some(generation)
|
||||
});
|
||||
let held_key = held.map(|(key, _)| key.clone());
|
||||
let held = held_key.and_then(|key| {
|
||||
let entry = self.entries.get_mut(&key)?;
|
||||
let anchor = MrfDurableRepairAnchor::from_intent(&entry.intent, key.source_bucket_incarnation_id?)?;
|
||||
entry.next_attempt = now + MRF_HELD_ABSENCE_RECHECK_INTERVAL;
|
||||
entry.anchor = Some(anchor.clone());
|
||||
Some(anchor)
|
||||
});
|
||||
(retirement, held)
|
||||
}
|
||||
|
||||
pub(super) fn note_bucket_retired(&mut self, generation: &BucketGeneration) {
|
||||
if let Some((_, retired)) = self.retirement_checks.get_mut(generation) {
|
||||
*retired = true;
|
||||
for intent in intents {
|
||||
let Some(anchor) = MrfDurableRepairAnchor::from_intent(intent, incarnation)
|
||||
.filter(|anchor| anchor.bucket_incarnation_id == incarnation)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
|
||||
kind: anchor.kind,
|
||||
bucket: anchor.bucket,
|
||||
object: anchor.object,
|
||||
version_id: anchor.version_id,
|
||||
scope: anchor.scope,
|
||||
delete_marker_purge: anchor.delete_marker_purge,
|
||||
lease: Some(anchor.lease),
|
||||
bucket_incarnation_id: anchor.bucket_incarnation_id,
|
||||
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn note_held_absence_proof(&self, anchor: MrfDurableRepairAnchor) -> bool {
|
||||
let key = PartialWriteKey::from_anchor(&anchor);
|
||||
if self.entries.get(&key).is_some_and(|entry| {
|
||||
entry.persisted
|
||||
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
|
||||
&& entry.anchor.as_ref() == Some(&anchor)
|
||||
}) {
|
||||
publish_mrf_absence(anchor);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn park_unverified_legacy(&mut self, anchor: &MrfDurableRepairAnchor) -> bool {
|
||||
self.park(
|
||||
anchor,
|
||||
@@ -591,7 +550,7 @@ impl PartialWrites {
|
||||
|
||||
pub(super) fn checkpoint_records(
|
||||
&self,
|
||||
mut digest_for: impl FnMut(&MrfIntent) -> Option<[u8; 32]>,
|
||||
digest_for: impl Fn(&MrfIntent) -> Option<[u8; 32]>,
|
||||
) -> Vec<ResponsibilityCheckpoint> {
|
||||
self.entries
|
||||
.values()
|
||||
@@ -1057,17 +1016,15 @@ impl PartialWrites {
|
||||
return lifecycle_changed;
|
||||
}
|
||||
let in_flight = manager.try_in_flight_durable_mrf_anchors();
|
||||
let identity_cutoff = Instant::now() + MRF_DISPATCH_IDENTITY_START_BUDGET;
|
||||
let mut observed_buckets = HashMap::new();
|
||||
for key in &ready {
|
||||
let Some(entry) = self.entries.get_mut(key) else {
|
||||
for key in ready {
|
||||
let Some(entry) = self.entries.get_mut(&key) else {
|
||||
continue;
|
||||
};
|
||||
entry.next_attempt = Instant::now() + config.admission_backoff;
|
||||
if entry.attempt_in_flight
|
||||
&& let Some(in_flight) = in_flight.as_ref()
|
||||
{
|
||||
if entry.anchor.as_ref().is_some_and(|anchor| in_flight.contains(anchor)) {
|
||||
entry.next_attempt = Instant::now() + config.admission_backoff;
|
||||
continue;
|
||||
}
|
||||
// A terminal attempt without proof remains owned by the journal.
|
||||
@@ -1075,26 +1032,10 @@ impl PartialWrites {
|
||||
entry.defer_unverified_attempt(Instant::now(), config.admission_backoff);
|
||||
continue;
|
||||
}
|
||||
// The observation belongs to this batch. The storage repair
|
||||
// still acquires its own fence for the expected incarnation.
|
||||
let observed = if let Some(purge) = entry.intent.delete_marker_purge.as_ref() {
|
||||
Some(purge.bucket_incarnation_id)
|
||||
} else {
|
||||
let bucket = key.identity.bucket.as_ref();
|
||||
match observed_buckets.entry(bucket) {
|
||||
Entry::Occupied(observation) => *observation.get(),
|
||||
Entry::Vacant(observation) => {
|
||||
if Instant::now() >= identity_cutoff {
|
||||
// Leave unexamined work due in the rotated retry queue.
|
||||
continue;
|
||||
}
|
||||
let incarnation = manager.mrf_bucket_incarnation_id(bucket).await.ok().flatten();
|
||||
*observation.insert(incarnation)
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(anchor) = observed.and_then(|incarnation| MrfDurableRepairAnchor::from_intent(&entry.intent, incarnation))
|
||||
{
|
||||
// The bucket can be deleted and recreated while an obligation is
|
||||
// parked, so every dispatch must compare against a fresh identity.
|
||||
if let Ok(Some(anchor)) = manager.durable_mrf_repair_anchor(&entry.intent).await {
|
||||
entry.anchor = Some(anchor.clone());
|
||||
if let Some(source_bucket_incarnation_id) = entry.source_bucket_incarnation_id
|
||||
&& source_bucket_incarnation_id != anchor.bucket_incarnation_id
|
||||
{
|
||||
@@ -1112,7 +1053,6 @@ impl PartialWrites {
|
||||
lifecycle_changed = true;
|
||||
continue;
|
||||
}
|
||||
entry.anchor = Some(anchor.clone());
|
||||
// Proofless legacy results stay owned by the durable journal;
|
||||
// the lifecycle checkpoint determines whether this process
|
||||
// retries or waits for an explicit operator action.
|
||||
@@ -1261,20 +1201,6 @@ impl PartialWrites {
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_mrf_absence(anchor: MrfDurableRepairAnchor) {
|
||||
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
|
||||
kind: anchor.kind,
|
||||
bucket: anchor.bucket,
|
||||
object: anchor.object,
|
||||
version_id: anchor.version_id,
|
||||
scope: anchor.scope,
|
||||
delete_marker_purge: anchor.delete_marker_purge,
|
||||
lease: Some(anchor.lease),
|
||||
bucket_incarnation_id: anchor.bucket_incarnation_id,
|
||||
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
|
||||
});
|
||||
}
|
||||
|
||||
fn validate_operator_audit_fields(actor: &str, reason: &str, reference: &str, request_id: Uuid) -> Result<(), &'static str> {
|
||||
if request_id.is_nil() || actor.trim().is_empty() || actor.len() > MAX_OPERATOR_ACTOR_BYTES {
|
||||
return Err("operator identity or request id is invalid");
|
||||
@@ -2754,10 +2680,9 @@ mod tests {
|
||||
.admit_with_source_incarnation(item.clone(), Some(incarnation), 1, 8192)
|
||||
.expect("retain exact old-generation responsibility");
|
||||
partial_writes.mark_persisted();
|
||||
assert!(
|
||||
partial_writes.anchors().next().is_none(),
|
||||
"this responsibility has not reached object-heal admission"
|
||||
);
|
||||
let key = PartialWriteKey::new(&item, Some(incarnation));
|
||||
let anchor = MrfDurableRepairAnchor::from_intent(&item, incarnation).expect("exact retirement anchor");
|
||||
partial_writes.entries.get_mut(&key).expect("durable responsibility").anchor = Some(anchor);
|
||||
|
||||
assert!(
|
||||
!manager
|
||||
@@ -2771,7 +2696,7 @@ mod tests {
|
||||
.await
|
||||
.expect("normal bucket deletion publishes durable retirement evidence");
|
||||
|
||||
retirement_tests::check_retirement_once(&mut partial_writes, manager.as_ref()).await;
|
||||
partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
|
||||
let config = MrfConsumerConfig::default();
|
||||
let mut runtime = MrfRuntime {
|
||||
partial_writes,
|
||||
|
||||
@@ -27,6 +27,7 @@ use std::sync::atomic::{AtomicU8, Ordering};
|
||||
struct RetirementCall {
|
||||
bucket: String,
|
||||
incarnation: Uuid,
|
||||
at: Instant,
|
||||
object_refs: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -37,7 +38,6 @@ struct RetirementStorage {
|
||||
calls: Mutex<Vec<RetirementCall>>,
|
||||
result: AtomicU8,
|
||||
delay: Duration,
|
||||
started: tokio::sync::Notify,
|
||||
}
|
||||
|
||||
impl RetirementStorage {
|
||||
@@ -47,7 +47,6 @@ impl RetirementStorage {
|
||||
calls: Mutex::new(Vec::new()),
|
||||
result: AtomicU8::new(0),
|
||||
delay,
|
||||
started: tokio::sync::Notify::new(),
|
||||
}
|
||||
}
|
||||
fn calls(&self) -> Vec<RetirementCall> {
|
||||
@@ -61,9 +60,9 @@ impl HealStorageAPI for RetirementStorage {
|
||||
self.calls.lock().expect("retirement calls").push(RetirementCall {
|
||||
bucket: bucket.to_string(),
|
||||
incarnation: expected,
|
||||
at: Instant::now(),
|
||||
object_refs: self.watched.iter().map(Arc::strong_count).collect(),
|
||||
});
|
||||
self.started.notify_one();
|
||||
if !self.delay.is_zero() {
|
||||
tokio::time::sleep(self.delay).await;
|
||||
}
|
||||
@@ -152,19 +151,6 @@ fn expected_event(entry: &Responsibility, source: Uuid) -> MrfVerifiedRepairEven
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn check_retirement_once(writes: &mut PartialWrites, manager: &HealManager) {
|
||||
if let Some(generation) = writes.plan_maintenance(true, false).0 {
|
||||
if manager
|
||||
.mrf_bucket_incarnation_retired(&generation.0, generation.1)
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
{
|
||||
writes.note_bucket_retired(&generation);
|
||||
}
|
||||
writes.plan_maintenance(false, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_true_cache() {
|
||||
let bucket = format!("retirement-cost-{}", Uuid::new_v4());
|
||||
@@ -198,7 +184,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let original = writes.checkpoint_records(super::super::super::intent_digest);
|
||||
let started = Instant::now();
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 1);
|
||||
assert_eq!(
|
||||
storage.calls()[0].object_refs,
|
||||
@@ -206,29 +192,26 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
"the actual retirement storage callback must not see N eagerly owned anchor object handles"
|
||||
);
|
||||
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
|
||||
assert_eq!(
|
||||
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
|
||||
(started + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false)
|
||||
);
|
||||
assert_eq!(writes.retirement_checks[&(Arc::from(bucket.as_str()), source)], (started, false));
|
||||
tokio::time::advance(Duration::from_millis(4999)).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 1, "cached false does not query or refresh its timestamp");
|
||||
storage.result.store(2, Ordering::Relaxed);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
let failed_at = Instant::now();
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 2, "the exact TTL boundary must recheck");
|
||||
assert_eq!(
|
||||
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
|
||||
(failed_at + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false),
|
||||
(failed_at, false),
|
||||
"I/O error is cached false"
|
||||
);
|
||||
tokio::time::advance(Duration::from_millis(4999)).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 2);
|
||||
storage.result.store(1, Ordering::Relaxed);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 3);
|
||||
assert!(storage.calls().iter().all(|call| call.object_refs == baseline));
|
||||
let expected = writes
|
||||
@@ -242,7 +225,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
"proofs preserve exact fields and entry order"
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(100)).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 3, "true is sticky while the eligible generation remains");
|
||||
assert_eq!(
|
||||
take_mrf_verified_repair_events_for(&bucket),
|
||||
@@ -257,39 +240,52 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn retirement_selects_the_oldest_due_generation_and_groups_exact_proofs() {
|
||||
async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
|
||||
let bucket = format!("retirement-clock-{}", Uuid::new_v4());
|
||||
let sources = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()];
|
||||
let sources = [Uuid::new_v4(), Uuid::new_v4()];
|
||||
let mut writes = PartialWrites::default();
|
||||
for (index, source) in sources[..2].iter().enumerate() {
|
||||
for (index, source) in sources.iter().enumerate() {
|
||||
admit(&mut writes, &bucket, &format!("object-{index}-a"), Some(*source), true);
|
||||
admit(&mut writes, &bucket, &format!("object-{index}-b"), Some(*source), true);
|
||||
}
|
||||
let first = writes.plan_maintenance(true, false).0.expect("first due generation");
|
||||
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(3)));
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let started = Instant::now();
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 2);
|
||||
assert!(
|
||||
writes.plan_maintenance(false, false).0.is_none(),
|
||||
"a busy worker reserves no other generation"
|
||||
writes.retirement_checks.values().all(|value| *value == (started, false)),
|
||||
"every group stores the single time captured before either await"
|
||||
);
|
||||
assert_eq!(
|
||||
storage
|
||||
.calls()
|
||||
.iter()
|
||||
.map(|call| (&call.bucket, call.incarnation))
|
||||
.collect::<HashSet<_>>()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
admit(&mut writes, &bucket, "new-generation", Some(sources[2]), true);
|
||||
let second = writes.plan_maintenance(true, false).0.expect("next due generation");
|
||||
let third = writes.plan_maintenance(true, false).0.expect("newly seen generation");
|
||||
assert_ne!(first.1, second.1);
|
||||
assert_eq!(third.1, sources[2]);
|
||||
assert!(
|
||||
writes.plan_maintenance(true, false).0.is_none(),
|
||||
"every issued lookup observes its cooldown"
|
||||
storage.calls()[0].at < storage.calls()[1].at,
|
||||
"the callback really spans different instants"
|
||||
);
|
||||
let next = Instant::now();
|
||||
assert!(next.duration_since(started) >= Duration::from_secs(6));
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 4, "both false groups expire from the same pre-await timestamp");
|
||||
assert!(writes.retirement_checks.values().all(|value| *value == (next, false)));
|
||||
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
|
||||
writes.note_bucket_retired(&first);
|
||||
writes.note_bucket_retired(&second);
|
||||
writes.plan_maintenance(false, false);
|
||||
storage.result.store(1, Ordering::Relaxed);
|
||||
// The preceding callbacks took six seconds, so both false entries expire.
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 6);
|
||||
let events = take_mrf_verified_repair_events_for(&bucket);
|
||||
assert_eq!(events.len(), 4);
|
||||
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
|
||||
assert_eq!(events[0].bucket_incarnation_id, events[1].bucket_incarnation_id);
|
||||
assert_eq!(events[2].bucket_incarnation_id, events[3].bucket_incarnation_id);
|
||||
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
|
||||
for source in [first.1, second.1] {
|
||||
for source in sources {
|
||||
let actual = events
|
||||
.iter()
|
||||
.filter(|event| event.bucket_incarnation_id == source)
|
||||
@@ -299,15 +295,14 @@ async fn retirement_selects_the_oldest_due_generation_and_groups_exact_proofs()
|
||||
.entries
|
||||
.values()
|
||||
.filter(|entry| entry.source_bucket_incarnation_id == Some(source))
|
||||
.map(|entry| {
|
||||
assert!(entry.anchor.is_some(), "an undispatched responsibility needs an exact anchor");
|
||||
expected_event(entry, source)
|
||||
})
|
||||
.map(|entry| expected_event(entry, source))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(actual, expected, "each generation keeps the exact current lease and entry order");
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"each original generation group remains contiguous and keeps its entry order"
|
||||
);
|
||||
assert_eq!(storage.calls().iter().filter(|call| call.incarnation == source).count(), 3);
|
||||
}
|
||||
tokio::time::advance(MRF_RETIREMENT_PROOF_RECHECK_INTERVAL).await;
|
||||
assert_eq!(writes.plan_maintenance(true, false).0, Some(third));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -352,7 +347,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
|
||||
}
|
||||
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::ZERO));
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(writes.retirement_checks.len(), 1);
|
||||
assert!(writes.retirement_checks.contains_key(&(Arc::from(bucket.as_str()), valid)));
|
||||
assert!(storage.calls().is_empty(), "the only eligible generation uses its sticky true cache");
|
||||
@@ -361,7 +356,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
|
||||
vec![expected_event(&writes.entries[&valid_key], valid)]
|
||||
);
|
||||
writes.entries.remove(&valid_key);
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert!(
|
||||
writes.retirement_checks.is_empty(),
|
||||
"None and ineligible entries cannot keep an old cache generation alive"
|
||||
@@ -371,9 +366,8 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
|
||||
.get_mut(&unpersisted_key)
|
||||
.expect("activate persisted source")
|
||||
.persisted = true;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 1, "a newly eligible source needs a real retirement lookup");
|
||||
assert_eq!(storage.calls()[0].bucket, bucket);
|
||||
assert_eq!(storage.calls()[0].incarnation, unpersisted);
|
||||
assert_eq!(
|
||||
writes
|
||||
@@ -394,112 +388,12 @@ async fn retirement_cancellation_cannot_publish_an_unfinished_retirement() {
|
||||
storage.result.store(1, Ordering::Relaxed);
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(1), check_retirement_once(&mut writes, &manager))
|
||||
tokio::time::timeout(Duration::from_secs(1), writes.note_retired_generation_proofs(&manager))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(storage.calls().len(), 1);
|
||||
assert!(writes.retirement_checks.values().all(|(_, retired)| !retired));
|
||||
assert!(writes.retirement_checks.is_empty());
|
||||
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
|
||||
assert_eq!(writes.checkpoint_records(super::super::super::intent_digest), original);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn held_absence_probe_rotates_due_keys_and_rejects_a_superseded_lease() {
|
||||
let bucket = format!("held-probe-{}", Uuid::new_v4());
|
||||
let source = Uuid::new_v4();
|
||||
let mut writes = PartialWrites::default();
|
||||
let first = admit(&mut writes, &bucket, "first", Some(source), true);
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
let second = admit(&mut writes, &bucket, "second", Some(source), true);
|
||||
let uncommitted = admit(&mut writes, &bucket, "uncommitted", Some(source), false);
|
||||
for key in [&first, &second, &uncommitted] {
|
||||
let entry = writes.entries.get_mut(key).expect("retained entry");
|
||||
entry.state = ResponsibilityState::HeldUnverifiedLegacy {
|
||||
bucket_incarnation_id: source,
|
||||
since_ms: 0,
|
||||
};
|
||||
}
|
||||
assert!(writes.plan_maintenance(false, false).1.is_none());
|
||||
let old = writes.plan_maintenance(false, true).1.expect("oldest due hold");
|
||||
assert_eq!(old.object.as_ref(), "first");
|
||||
let next = writes.plan_maintenance(false, true).1.expect("second due hold");
|
||||
assert_eq!(next.object.as_ref(), "second");
|
||||
assert!(writes.plan_maintenance(false, true).1.is_none());
|
||||
|
||||
let mut replacement = writes.entries[&first].intent.clone();
|
||||
replacement.lease = None;
|
||||
writes
|
||||
.admit_with_source_incarnation(replacement, Some(source), 256, usize::MAX)
|
||||
.expect("admit new write");
|
||||
writes.mark_persisted();
|
||||
assert!(
|
||||
!writes.note_held_absence_proof(old),
|
||||
"an older incarnation lease cannot clear a new write"
|
||||
);
|
||||
assert!(writes.note_held_absence_proof(next.clone()));
|
||||
let events = take_mrf_verified_repair_events_for(&bucket);
|
||||
assert_eq!(events.len(), 1);
|
||||
assert!(next.is_proven_by(&events[0]));
|
||||
assert_eq!(writes.depth(), 3, "proof recording precedes durable discharge");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn stalled_retirement_lookup_does_not_delay_durable_admission() {
|
||||
use super::super::super::{MrfDurableSubmission, run_mrf_consumer_with_stop};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
let _env = rustfs_test_utils::TestECStoreEnv::builder()
|
||||
.prefix("mrf_retirement_ack")
|
||||
.build()
|
||||
.await;
|
||||
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(60)));
|
||||
let manager = Arc::new(HealManager::new_without_root_recovery_for_test(storage.clone(), None));
|
||||
let (_best_effort, hints) = mpsc::channel(1);
|
||||
let (durable, submissions) = mpsc::channel(2);
|
||||
let (_lifecycle, commands) = mpsc::channel(1);
|
||||
let stop = tokio_util::sync::CancellationToken::new();
|
||||
let worker = tokio::spawn(run_mrf_consumer_with_stop(manager, hints, submissions, commands, Some(stop.clone())));
|
||||
|
||||
let source = Uuid::new_v4();
|
||||
let submit = |object| {
|
||||
let (response, receipt) = oneshot::channel();
|
||||
(
|
||||
MrfDurableSubmission {
|
||||
intent: intent(object),
|
||||
source_bucket_incarnation_id: Some(source),
|
||||
response,
|
||||
},
|
||||
receipt,
|
||||
)
|
||||
};
|
||||
|
||||
let (first, first_receipt) = submit("first-ack");
|
||||
durable.send(first).await.expect("enqueue first durable write");
|
||||
tokio::time::timeout(Duration::from_secs(3), first_receipt)
|
||||
.await
|
||||
.expect("first checkpoint receipt deadline")
|
||||
.expect("consumer receipt")
|
||||
.expect("first checkpoint");
|
||||
tokio::time::timeout(Duration::from_secs(3), storage.started.notified())
|
||||
.await
|
||||
.expect("the background retirement lookup must actually start");
|
||||
|
||||
let (second, second_receipt) = submit("second-ack");
|
||||
durable
|
||||
.send(second)
|
||||
.await
|
||||
.expect("enqueue another durable write during the stalled lookup");
|
||||
let second_result = tokio::time::timeout(Duration::from_secs(3), second_receipt).await;
|
||||
stop.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(3), worker)
|
||||
.await
|
||||
.expect("shutdown must cancel the outstanding read")
|
||||
.expect("consumer joins");
|
||||
second_result
|
||||
.expect("the pending retirement lookup cannot block the checkpoint")
|
||||
.expect("consumer receipt")
|
||||
.expect("second checkpoint");
|
||||
assert_eq!(storage.calls().len(), 1, "one retirement lookup can be in flight");
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
#[derive(Clone, Copy)]
|
||||
enum Lookup {
|
||||
Identity(Option<Uuid>),
|
||||
DelayedIdentity(Uuid, Duration),
|
||||
PermissionDenied,
|
||||
Quorum,
|
||||
Transport,
|
||||
@@ -45,10 +44,6 @@ impl HealStorageAPI for ProbeStorage {
|
||||
let lookup = *self.lookup.lock().expect("lookup outcome");
|
||||
match lookup {
|
||||
Lookup::Identity(value) => Ok(value),
|
||||
Lookup::DelayedIdentity(value, duration) => {
|
||||
tokio::time::sleep(duration).await;
|
||||
Ok(Some(value))
|
||||
}
|
||||
Lookup::PermissionDenied => Err(Error::Io(std::io::ErrorKind::PermissionDenied.into())),
|
||||
Lookup::Quorum => Err(Error::Storage(EcstoreError::ErasureReadQuorum)),
|
||||
Lookup::Transport => Err(Error::Io(std::io::ErrorKind::ConnectionReset.into())),
|
||||
@@ -884,7 +879,7 @@ fn unknown_source_deleted_bucket_writer_lost_result_is_resolved_by_exact_commit_
|
||||
let record = pending.record.clone();
|
||||
runtime.partial_writes.pending_lifecycle_transition = Some(pending);
|
||||
let sequence = runtime.next_checkpoint_sequence;
|
||||
let payload = runtime.snapshot().authoritative;
|
||||
let (payload, _) = runtime.snapshot();
|
||||
let lifecycle = encode_mrf_lifecycle_checkpoint(
|
||||
2,
|
||||
runtime.checkpoint_owner,
|
||||
@@ -1014,114 +1009,3 @@ fn unknown_source_deleted_bucket_writer_failed_mirror_cannot_downgrade_a_committ
|
||||
assert_eq!(retried.records, committed.records);
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn durable_dispatch_reads_one_incarnation_per_bucket_and_refreshes_the_next_batch() {
|
||||
let source = Uuid::new_v4();
|
||||
let storage = Arc::new(ProbeStorage {
|
||||
lookup: Mutex::new(Lookup::Identity(Some(source))),
|
||||
calls: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let mut writes = PartialWrites::default();
|
||||
let config = MrfConsumerConfig::default();
|
||||
|
||||
for index in 0..32 {
|
||||
writes
|
||||
.admit_with_source_incarnation(intent(&format!("batch-{index}")), Some(source), 64, usize::MAX)
|
||||
.expect("admit a distinct responsibility in the same bucket");
|
||||
}
|
||||
let mut other = intent("another-bucket");
|
||||
other.bucket = Arc::from("other-bucket");
|
||||
writes
|
||||
.admit_with_source_incarnation(other, Some(source), 64, usize::MAX)
|
||||
.expect("admit a responsibility in a different bucket");
|
||||
writes.mark_persisted();
|
||||
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(manager.get_queue_length().await, 33);
|
||||
|
||||
let changed = Uuid::new_v4();
|
||||
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(changed));
|
||||
let next = intent("next-batch");
|
||||
let key = PartialWriteKey::new(&next, Some(source));
|
||||
writes
|
||||
.admit_with_source_incarnation(next, Some(source), 64, usize::MAX)
|
||||
.expect("admit another responsibility from the original incarnation");
|
||||
writes.mark_persisted();
|
||||
assert!(writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(manager.get_queue_length().await, 33);
|
||||
assert!(matches!(
|
||||
writes.entries[&key].state,
|
||||
ResponsibilityState::BucketIncarnationChanged {
|
||||
source_bucket_incarnation_id,
|
||||
observed_bucket_incarnation_id,
|
||||
..
|
||||
} if source_bucket_incarnation_id == source && observed_bucket_incarnation_id == changed
|
||||
));
|
||||
assert!(writes.entries[&key].anchor.is_none(), "the replacement incarnation cannot own this lease");
|
||||
*storage.lookup.lock().expect("lookup outcome") = Lookup::PermissionDenied;
|
||||
for object in ["failed-first", "failed-second"] {
|
||||
writes
|
||||
.admit_with_source_incarnation(intent(object), Some(source), 64, usize::MAX)
|
||||
.expect("admit a due responsibility");
|
||||
}
|
||||
writes.mark_persisted();
|
||||
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 4, "a failed lookup is shared within the batch");
|
||||
assert_eq!(manager.get_queue_length().await, 33, "a failed lookup authorizes no additional work");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn durable_dispatch_completes_slow_reads_and_leaves_unexamined_work_due() {
|
||||
let source = Uuid::new_v4();
|
||||
let storage = Arc::new(ProbeStorage {
|
||||
lookup: Mutex::new(Lookup::DelayedIdentity(source, Duration::from_secs(3))),
|
||||
calls: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let mut writes = PartialWrites::default();
|
||||
let config = MrfConsumerConfig::default();
|
||||
let first = intent("slow-first");
|
||||
let first_key = PartialWriteKey::new(&first, Some(source));
|
||||
let same = intent("slow-second");
|
||||
let same_key = PartialWriteKey::new(&same, Some(source));
|
||||
let mut later = intent("later");
|
||||
later.bucket = Arc::from("later-bucket");
|
||||
let later_key = PartialWriteKey::new(&later, Some(source));
|
||||
let mut purge = intent("purge");
|
||||
purge.kind = MrfKind::DeleteMarkerPurge;
|
||||
purge.version_id = Some([1; 16]);
|
||||
purge.delete_marker_purge = rustfs_common::mrf_channel::MrfDeleteMarkerPurge::new(source, source, [2; 32], vec![3]);
|
||||
for item in [first, same, later, purge] {
|
||||
writes
|
||||
.admit_with_source_incarnation(item, Some(source), 8, usize::MAX)
|
||||
.expect("admit a persisted responsibility");
|
||||
}
|
||||
writes.mark_persisted();
|
||||
let later_due = writes.entries[&later_key].next_attempt;
|
||||
let start = Instant::now();
|
||||
assert!(
|
||||
!tokio::time::timeout(Duration::from_secs(4), writes.dispatch_collecting_lifecycle_change(&manager, &config))
|
||||
.await
|
||||
.expect("bucket identity wait is bounded")
|
||||
);
|
||||
assert!(start.elapsed() >= Duration::from_secs(3), "give the in-progress lookup time to finish");
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 1, "share the slow lookup and defer unseen buckets");
|
||||
assert!(writes.entries[&first_key].attempt_in_flight);
|
||||
assert!(writes.entries[&same_key].attempt_in_flight);
|
||||
assert_eq!(writes.entries[&later_key].consecutive_unverified_attempts, 0);
|
||||
assert_eq!(writes.entries[&later_key].next_attempt, later_due);
|
||||
assert_eq!(
|
||||
manager.get_queue_length().await,
|
||||
3,
|
||||
"the lookup covers both objects and the marker carries its own incarnation"
|
||||
);
|
||||
|
||||
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(source));
|
||||
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
|
||||
assert!(writes.entries[&later_key].attempt_in_flight);
|
||||
assert_eq!(manager.get_queue_length().await, 4);
|
||||
}
|
||||
|
||||
@@ -537,42 +537,3 @@ fn empty_events_real_consumer_stop_retains_unresolved_journal() {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors() {
|
||||
if isolated("lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors") {
|
||||
return;
|
||||
}
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("runtime")
|
||||
.block_on(async {
|
||||
let (_env, _manager, mut runtime, anchor) = bound_runtime().await;
|
||||
let previous = runtime.runtime_checkpoint;
|
||||
let authoritative = read_journal(MRF_SCOPED_JOURNAL_PATH).await;
|
||||
let legacy = read_journal(MRF_JOURNAL_PATH).await;
|
||||
assert!(authoritative.is_some(), "fixture has a published authoritative mirror");
|
||||
|
||||
let mut hint = partial_intent("next-bucket");
|
||||
hint.kind = MrfKind::DecodeFailure;
|
||||
hint.scope = None;
|
||||
runtime.admit_best_effort(hint);
|
||||
runtime
|
||||
.admit_partial_write(partial_intent("next-bucket"), Some(anchor.bucket_incarnation_id))
|
||||
.expect("admit a new durable responsibility");
|
||||
let original_limit = runtime.config.journal_max_bytes;
|
||||
runtime.config.journal_max_bytes = 1;
|
||||
assert!(!runtime.flush().await, "an oversized companion cannot acknowledge publication");
|
||||
assert_eq!(runtime.runtime_checkpoint, previous);
|
||||
assert_eq!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
|
||||
assert_eq!(read_journal(MRF_JOURNAL_PATH).await, legacy);
|
||||
assert!(runtime.dirty, "the next flush must retain pending work");
|
||||
|
||||
runtime.config.journal_max_bytes = original_limit;
|
||||
assert!(runtime.flush().await, "the prior state remains retryable");
|
||||
assert_ne!(runtime.runtime_checkpoint, previous);
|
||||
assert_ne!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
|
||||
assert_ne!(read_journal(MRF_JOURNAL_PATH).await, legacy);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -582,10 +582,6 @@ pub trait HealStorageAPI: Send + Sync {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn probe_mrf_unversioned_absence(&self, _anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Heal object using ecstore
|
||||
async fn heal_object(
|
||||
&self,
|
||||
@@ -1419,26 +1415,6 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn probe_mrf_unversioned_absence(&self, anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
|
||||
let Some(scope) = anchor.scope else {
|
||||
return Ok(false);
|
||||
};
|
||||
let opts = HealOpts {
|
||||
pool: Some(scope.pool_index as usize),
|
||||
set: Some(scope.set_index as usize),
|
||||
..Default::default()
|
||||
};
|
||||
let store = self.live_ecstore();
|
||||
run_background_object(
|
||||
self.admission.as_ref(),
|
||||
|| store.physical_heal_plan(&anchor.object, &opts).map_err(Error::Storage),
|
||||
&opts,
|
||||
|_| true,
|
||||
boxed_object_operation(|| async { store.probe_mrf_unversioned_absence(anchor).await.map_err(Error::Storage) }),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_object_meta(&self, bucket: &str, object: &str) -> Result<Option<HealObjectInfo>> {
|
||||
debug!(
|
||||
target: "rustfs::heal::storage",
|
||||
|
||||
@@ -513,35 +513,37 @@ impl HealTask {
|
||||
);
|
||||
let receipt_missing = storage_result.receipt.is_none();
|
||||
if !self.record_verified_storage_receipt(&expected, storage_result.receipt).await {
|
||||
let item = &storage_result.item;
|
||||
// A legacy heal can restore redundancy without verifying the original
|
||||
// content. Only the complete report for the selected version can park it.
|
||||
let proof_rejection = if !receipt_missing {
|
||||
Some("storage receipt did not verify the requested identity and disposition")
|
||||
} else if !item.legacy_identity_unverified {
|
||||
Some("storage returned no verified receipt or legacy identity observation")
|
||||
} else if !item
|
||||
.resolved_version_id
|
||||
.is_some_and(|resolved| match version_id.filter(|version| !version.is_empty()) {
|
||||
let ok_drive_state = DriveState::Ok.to_string();
|
||||
let selected_version_matches = storage_result.item.resolved_version_id.is_some_and(|resolved| {
|
||||
let requested = version_id.filter(|version| !version.is_empty());
|
||||
match requested {
|
||||
Some(requested) => Uuid::parse_str(requested).is_ok_and(|version| version.as_bytes() == &resolved),
|
||||
None => resolved == [0; 16],
|
||||
})
|
||||
{
|
||||
Some("selected version does not match")
|
||||
} else if item.drives_reported() != Some(item.disk_count) || item.before.drives.len() != item.disk_count {
|
||||
Some("drive report is incomplete")
|
||||
} else {
|
||||
item.before.drives.iter().zip(&item.after.drives).find_map(|(before, after)| {
|
||||
if before.endpoint != after.endpoint {
|
||||
Some("drive report endpoints changed")
|
||||
} else if after.state != DriveState::Ok.to_str() {
|
||||
Some("a reported drive is not healthy")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
if proof_rejection.is_none() {
|
||||
}
|
||||
});
|
||||
// A completed legacy repair can restore redundancy without proving
|
||||
// original content. Keep the same durable responsibility as an
|
||||
// already-healthy Deep result, including when this attempt repaired
|
||||
// a shard. Storage errors and invalid receipts never qualify.
|
||||
let healthy_legacy = receipt_missing
|
||||
&& storage_result.item.legacy_identity_unverified
|
||||
&& selected_version_matches
|
||||
&& storage_result.item.drives_healed().is_some()
|
||||
&& storage_result.item.after.drives.len() == storage_result.item.disk_count
|
||||
&& storage_result
|
||||
.item
|
||||
.before
|
||||
.drives
|
||||
.iter()
|
||||
.zip(&storage_result.item.after.drives)
|
||||
.all(|(before, after)| before.endpoint == after.endpoint)
|
||||
&& storage_result
|
||||
.item
|
||||
.after
|
||||
.drives
|
||||
.iter()
|
||||
.all(|drive| drive.state == ok_drive_state);
|
||||
if healthy_legacy {
|
||||
self.outcome.write().await.record(HealObjectOutcome {
|
||||
deep_check_observed: false,
|
||||
quorum_selected_data_dir: None,
|
||||
@@ -551,10 +553,14 @@ impl HealTask {
|
||||
});
|
||||
}
|
||||
self.record_result_item(storage_result.item).await;
|
||||
let target = format!("{bucket}/{object}");
|
||||
return Err(match proof_rejection {
|
||||
Some(reason) => Error::MrfStorageProofUnavailable { target, reason },
|
||||
None => Error::LegacyMrfUnverified { target },
|
||||
return Err(if healthy_legacy {
|
||||
Error::LegacyMrfUnverified {
|
||||
target: format!("{bucket}/{object}"),
|
||||
}
|
||||
} else {
|
||||
Error::TaskExecutionFailed {
|
||||
message: format!("{}{bucket}/{object}", crate::error::MRF_MISSING_PROOF_PREFIX),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -3338,18 +3338,13 @@ async fn durable_mrf_grace_remains_owned_by_the_responsibility() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn durable_mrf_unverified_object_names_cannot_change_retry_classification() {
|
||||
for object in ["ordinary", "timed out", "network error", "file not found"] {
|
||||
for object in ["ordinary", "timed out", "network error"] {
|
||||
let (task, _) = mrf_task_for_item(object, HealResultItem::default());
|
||||
let error = task
|
||||
.execute()
|
||||
.await
|
||||
.expect_err("missing proof must retain the responsibility");
|
||||
assert!(
|
||||
matches!(crate::error::classify_heal_error(&error), crate::error::HealErrorClass::Permanent),
|
||||
"case={object}: {error}"
|
||||
);
|
||||
assert!(!error.is_recoverable_heal(), "case={object}: {error}");
|
||||
assert!(!error.is_object_absent(), "case={object}: {error}");
|
||||
assert!(!error.is_recoverable_heal(), "object name must not change retry classification: {object}");
|
||||
assert_eq!(task.get_outcome().await.counters.healed, 0);
|
||||
}
|
||||
}
|
||||
@@ -3485,25 +3480,6 @@ async fn mrf_legacy_pause_requires_storage_owned_healthy_deep_result() {
|
||||
assert_eq!(opts[0].scan_mode, HealScanMode::Deep);
|
||||
} else {
|
||||
assert!(matches!(task.get_status().await, HealTaskStatus::Failed { .. }), "case={case}");
|
||||
let reason = match case {
|
||||
"text_only" => "storage returned no verified receipt or legacy identity observation",
|
||||
"empty" | "unaligned" | "wrong_disk_count" => "drive report is incomplete",
|
||||
"unhealthy" => "a reported drive is not healthy",
|
||||
"wrong_endpoint" => "drive report endpoints changed",
|
||||
"wrong_version" | "unknown_version" | "versioned_mismatch" => "selected version does not match",
|
||||
"receipt" => "storage receipt did not verify the requested identity and disposition",
|
||||
"storage_error" | "dry_run" => continue,
|
||||
_ => panic!("unexpected case {case}"),
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
&error,
|
||||
Error::MrfStorageProofUnavailable { target, reason: actual }
|
||||
if target == "bucket-a/object" && *actual == reason
|
||||
),
|
||||
"case={case}: {error:?}"
|
||||
);
|
||||
assert!(error.to_string().ends_with(reason), "case={case}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -737,176 +737,6 @@ async fn degraded_deleted_partial_write_is_discharged_by_an_absence_proof_inner(
|
||||
.await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_unversioned_partial_write_is_discharged_automatically_after_delete() {
|
||||
const STACK_SIZE: usize = 8 * 1024 * 1024;
|
||||
std::thread::Builder::new()
|
||||
.name("mrf-held-absence".to_owned())
|
||||
.stack_size(STACK_SIZE)
|
||||
.spawn(|| {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.thread_stack_size(STACK_SIZE)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("held absence runtime should build");
|
||||
runtime.block_on(held_unversioned_partial_write_is_discharged_automatically_after_delete_inner());
|
||||
})
|
||||
.expect("spawn held absence test thread")
|
||||
.join()
|
||||
.expect("held absence test thread should finish");
|
||||
}
|
||||
|
||||
async fn held_unversioned_partial_write_is_discharged_automatically_after_delete_inner() {
|
||||
use rustfs_common::mrf_channel::{MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfScope, try_rearm_mrf_replay_intent};
|
||||
use storage_api::integration::{DeleteOptions, NamespaceLocking as _, lookup_config_for_pools};
|
||||
|
||||
const BUCKET: &str = "held-absence";
|
||||
const OBJECT: &str = "chunks/held-then-deleted";
|
||||
temp_env::async_with_vars(
|
||||
[
|
||||
("RUSTFS_HEAL_MRF_ENABLE", Some("true")),
|
||||
("RUSTFS_SHARD_INTEGRITY_WRITE", Some("false")),
|
||||
("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", Some("false")),
|
||||
],
|
||||
async {
|
||||
let env = TestECStoreEnv::builder().disk_count(9).build().await;
|
||||
env.ecstore
|
||||
.set_storage_class(lookup_config_for_pools(&Default::default(), &[9]).expect("EC:3 for nine drives"));
|
||||
env.make_bucket(BUCKET, false).await;
|
||||
let set = env.ecstore.pools[0].get_disks(0);
|
||||
let manager = manager(&env);
|
||||
mrf_queue::spawn_mrf_consumer(manager.clone());
|
||||
let offline = set.disks.write().await[8].take();
|
||||
assert!(offline.is_some(), "the ninth drive must start connected");
|
||||
let payload = vec![7; 2 * 1024 * 1024];
|
||||
put(&env, BUCKET, OBJECT, &payload, false).await;
|
||||
assert!(snapshot_contains(OBJECT).await, "the degraded PUT must commit a durable obligation");
|
||||
set.disks.write().await[8] = offline;
|
||||
manager.start().await.expect("start the MRF manager");
|
||||
assert!(
|
||||
wait_until(|| async {
|
||||
mrf_queue::list_legacy_responsibilities(None, 32).await.is_ok_and(|listing| {
|
||||
listing
|
||||
.responsibilities
|
||||
.iter()
|
||||
.any(|row| row.bucket == BUCKET && row.object == OBJECT && row.status == "held_unverified_legacy")
|
||||
})
|
||||
})
|
||||
.await,
|
||||
"legacy repair must park the responsibility before the DELETE"
|
||||
);
|
||||
|
||||
let incarnation = env
|
||||
.ecstore
|
||||
.bucket_incarnation_id_from_disk(BUCKET)
|
||||
.await
|
||||
.expect("load the bucket incarnation");
|
||||
let mut intent = MrfIntent {
|
||||
bucket: Arc::from(BUCKET),
|
||||
object: Arc::from(OBJECT),
|
||||
version_id: None,
|
||||
kind: MrfKind::PartialWrite,
|
||||
scope: Some(MrfScope {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
}),
|
||||
lease: None,
|
||||
enqueued_at_ms: 0,
|
||||
attempts: 0,
|
||||
delete_marker_purge: None,
|
||||
};
|
||||
assert_eq!(
|
||||
try_rearm_mrf_replay_intent(&mut intent),
|
||||
rustfs_common::mrf_channel::MrfIngressResult::Enqueued
|
||||
);
|
||||
let mut anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("valid exact test anchor");
|
||||
let namespace = set.new_ns_lock(BUCKET, OBJECT).await.expect("object namespace lock");
|
||||
let writer = namespace
|
||||
.get_write_lock(Duration::from_secs(2))
|
||||
.await
|
||||
.expect("hold object write lock");
|
||||
assert!(
|
||||
!tokio::time::timeout(Duration::from_secs(2), env.ecstore.probe_mrf_unversioned_absence(&anchor))
|
||||
.await
|
||||
.expect("a present object must finish the probe while the writer owns its namespace")
|
||||
.expect("check the present object")
|
||||
);
|
||||
drop(writer);
|
||||
assert!(snapshot_contains(OBJECT).await, "a healthy legacy object cannot retire the obligation");
|
||||
|
||||
const PREPARED: &str = "chunks/prepared-delete";
|
||||
put(&env, BUCKET, PREPARED, &payload, false).await;
|
||||
let transaction = uuid::Uuid::new_v4();
|
||||
let disks = set.disks.read().await.clone();
|
||||
for disk in disks.iter().flatten() {
|
||||
disk.delete_version_recoverable(
|
||||
BUCKET,
|
||||
PREPARED,
|
||||
rustfs_filemeta::FileInfo {
|
||||
name: PREPARED.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
false,
|
||||
DeleteOptions {
|
||||
old_data_dir: Some(transaction),
|
||||
delete_recovery_bucket_incarnation: Some(incarnation),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("prepare the transaction without publishing its commit");
|
||||
assert!(matches!(
|
||||
disk.read_version("", BUCKET, PREPARED, "", &ReadOptions::default()).await,
|
||||
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound)
|
||||
));
|
||||
}
|
||||
let mut prepared = anchor.clone();
|
||||
prepared.object = Arc::from(PREPARED);
|
||||
assert!(
|
||||
!env.ecstore
|
||||
.probe_mrf_unversioned_absence(&prepared)
|
||||
.await
|
||||
.expect("inspect prepared delete"),
|
||||
"recovery evidence must prevent false absence when every live path is missing"
|
||||
);
|
||||
|
||||
env.ecstore
|
||||
.delete_object(BUCKET, OBJECT, ObjectOptions::default())
|
||||
.await
|
||||
.expect("delete the parked object");
|
||||
let offline = set.disks.write().await[8].take();
|
||||
assert!(
|
||||
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
|
||||
"one unavailable drive prevents exact absence verification"
|
||||
);
|
||||
set.disks.write().await[8] = offline;
|
||||
anchor.bucket_incarnation_id = uuid::Uuid::new_v4();
|
||||
assert!(
|
||||
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
|
||||
"another bucket incarnation cannot authorize absence"
|
||||
);
|
||||
assert!(
|
||||
wait_until(|| async { !snapshot_contains(OBJECT).await }).await,
|
||||
"a held responsibility with proven absence must clear automatically"
|
||||
);
|
||||
assert_eq!(
|
||||
manager.get_statistics().await.unverified_tasks,
|
||||
1,
|
||||
"absence probes must not enqueue another Deep heal"
|
||||
);
|
||||
assert!(
|
||||
env.ecstore
|
||||
.get_object_info(BUCKET, OBJECT, &ObjectOptions::default())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
manager.stop().await.expect("stop the MRF manager");
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn wait_until<F: FnMut() -> Fut, Fut: Future<Output = bool>>(mut probe: F) -> bool {
|
||||
tokio::time::timeout(Duration::from_secs(60), async {
|
||||
loop {
|
||||
|
||||
+107
-349
@@ -277,7 +277,6 @@ pub struct LockLostSignal {
|
||||
lost: AtomicBool,
|
||||
valid_until: Mutex<Option<Instant>>,
|
||||
notify: Notify,
|
||||
voters: Option<Box<(usize, Vec<Arc<LockLostSignal>>)>>,
|
||||
}
|
||||
|
||||
impl LockLostSignal {
|
||||
@@ -309,12 +308,6 @@ impl LockLostSignal {
|
||||
if self.lost.load(Ordering::SeqCst) {
|
||||
return true;
|
||||
}
|
||||
if let Some((quorum, votes)) = self.voters.as_deref()
|
||||
&& votes.iter().filter(|vote| !vote.is_lost()).count() < *quorum
|
||||
{
|
||||
self.mark_lost();
|
||||
return true;
|
||||
}
|
||||
let expired = match self.valid_until.lock() {
|
||||
Ok(deadline) => deadline.is_some_and(|valid_until| Instant::now() >= valid_until),
|
||||
Err(_) => true,
|
||||
@@ -327,22 +320,6 @@ impl LockLostSignal {
|
||||
|
||||
/// Resolves once the lock is declared lost (immediately if already lost).
|
||||
pub async fn notified(&self) {
|
||||
if let Some((_, votes)) = self.voters.as_deref() {
|
||||
let mut losses: FuturesUnordered<_> = votes.iter().map(|vote| Box::pin(vote.notified())).collect();
|
||||
loop {
|
||||
let notified = self.notify.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if self.is_lost() {
|
||||
break;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = notified => {}
|
||||
_ = losses.next() => {}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.notified_after_registration(|| {}).await;
|
||||
}
|
||||
|
||||
@@ -462,20 +439,6 @@ struct LockRefreshStats {
|
||||
refresh_errors: usize,
|
||||
}
|
||||
|
||||
/// One confirmed writer grant, renewed only by the guard that acquired it.
|
||||
#[derive(Clone, Debug)]
|
||||
struct WriteVote {
|
||||
client: Arc<dyn LockClient>,
|
||||
lock_id: LockId,
|
||||
lease: Arc<LockLostSignal>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WriteDomainOwnership {
|
||||
votes: Arc<[WriteVote]>,
|
||||
owners: Vec<Arc<crate::namespace::NamespaceLockGuard>>,
|
||||
}
|
||||
|
||||
/// A RAII guard for distributed locks that releases the lock asynchronously when dropped.
|
||||
#[derive(Debug)]
|
||||
pub struct DistributedLockGuard {
|
||||
@@ -491,7 +454,6 @@ pub struct DistributedLockGuard {
|
||||
refresh_task: Option<JoinHandle<()>>,
|
||||
/// Lock-loss signal, shared with the heartbeat task.
|
||||
lock_lost: Arc<LockLostSignal>,
|
||||
write_domain: Option<Box<WriteDomainOwnership>>,
|
||||
cache_fence_proof: Option<CacheFenceProof>,
|
||||
}
|
||||
|
||||
@@ -502,13 +464,7 @@ impl DistributedLockGuard {
|
||||
/// - `entries` is the full list of underlying leases that should be refreshed and released
|
||||
/// with this guard.
|
||||
/// - `heartbeat`: lease TTL, optional renewal cadence, quorum, and diagnostics.
|
||||
fn new(
|
||||
lock_id: LockId,
|
||||
entries: Vec<HeldLockEntry>,
|
||||
lock_type: LockType,
|
||||
heartbeat: LockHeartbeatConfig,
|
||||
track_write_votes: bool,
|
||||
) -> Self {
|
||||
fn new(lock_id: LockId, entries: Vec<HeldLockEntry>, lock_type: LockType, heartbeat: LockHeartbeatConfig) -> Self {
|
||||
record_lock_held_acquire(lock_type);
|
||||
let cache_fence_proof = (lock_type == LockType::Shared)
|
||||
.then(|| {
|
||||
@@ -525,34 +481,14 @@ impl DistributedLockGuard {
|
||||
None => lock_lost.mark_lost(),
|
||||
}
|
||||
// Non-renewable guards are fenced directly by LockLostSignal's deadline checks.
|
||||
let write_votes: Option<Arc<[WriteVote]>> = track_write_votes.then(|| {
|
||||
entries
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let lease = Arc::new(LockLostSignal::default());
|
||||
lease.set_valid_until(entry.valid_until);
|
||||
WriteVote {
|
||||
client: Arc::clone(&entry.client),
|
||||
lock_id: entry.lock_id.clone(),
|
||||
lease,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let refresh_task = heartbeat.interval.and_then(|_| {
|
||||
tokio::runtime::Handle::try_current().ok().map(|handle| {
|
||||
let entries = entries.clone();
|
||||
let lock_lost = lock_lost.clone();
|
||||
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost, write_votes.clone()))
|
||||
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost))
|
||||
})
|
||||
});
|
||||
Self {
|
||||
write_domain: write_votes.map(|votes| {
|
||||
Box::new(WriteDomainOwnership {
|
||||
votes,
|
||||
owners: Vec::new(),
|
||||
})
|
||||
}),
|
||||
lock_id,
|
||||
entries,
|
||||
lock_type,
|
||||
@@ -599,12 +535,7 @@ impl DistributedLockGuard {
|
||||
/// retain the previous deadline, so transient jitter is tolerated but an unconfirmed lease
|
||||
/// can never remain valid beyond its backend TTL. Waiting for a slow refresh is also fenced
|
||||
/// by the current quorum deadline.
|
||||
async fn run_heartbeat(
|
||||
mut entries: Vec<HeldLockEntry>,
|
||||
config: LockHeartbeatConfig,
|
||||
lock_lost: Arc<LockLostSignal>,
|
||||
write_votes: Option<Arc<[WriteVote]>>,
|
||||
) {
|
||||
async fn run_heartbeat(mut entries: Vec<HeldLockEntry>, config: LockHeartbeatConfig, lock_lost: Arc<LockLostSignal>) {
|
||||
let Some(interval) = config.interval else {
|
||||
return;
|
||||
};
|
||||
@@ -667,16 +598,10 @@ impl DistributedLockGuard {
|
||||
Ok(true) => {
|
||||
stats.refreshed += 1;
|
||||
entries[idx].valid_until = refresh_started.checked_add(config.ttl).unwrap_or(refresh_started);
|
||||
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
|
||||
vote.lease.set_valid_until(entries[idx].valid_until);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
stats.not_found += 1;
|
||||
entries[idx].valid_until = Instant::now();
|
||||
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
|
||||
vote.lease.mark_lost();
|
||||
}
|
||||
}
|
||||
Err(_) => stats.refresh_errors += 1,
|
||||
}
|
||||
@@ -689,18 +614,9 @@ impl DistributedLockGuard {
|
||||
&self.lock_id
|
||||
}
|
||||
|
||||
fn write_votes(&self) -> &[WriteVote] {
|
||||
self.write_domain.as_deref().map_or(&[], |domain| &domain.votes)
|
||||
}
|
||||
|
||||
/// Actual granted peer identities, which may differ from the logical guard ID.
|
||||
pub fn granted_lock_ids(&self) -> impl Iterator<Item = &LockId> {
|
||||
self.entries.iter().map(|entry| &entry.lock_id).chain(
|
||||
self.write_domain
|
||||
.iter()
|
||||
.filter(|domain| !domain.owners.is_empty())
|
||||
.flat_map(|domain| domain.votes.iter().map(|vote| &vote.lock_id)),
|
||||
)
|
||||
self.entries.iter().map(|entry| &entry.lock_id)
|
||||
}
|
||||
|
||||
/// Read-quorum cache-fence proof carried by this guard, when every required
|
||||
@@ -730,24 +646,12 @@ impl DistributedLockGuard {
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_write_votes(&mut self) {
|
||||
if let Some(domain) = self.write_domain.take() {
|
||||
self.lock_lost.mark_lost();
|
||||
if domain.owners.is_empty() {
|
||||
for vote in domain.votes.iter() {
|
||||
vote.lease.mark_lost();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Manually disarm the guard so dropping it won't release the lock.
|
||||
/// Call this if you explicitly released the lock elsewhere.
|
||||
pub fn disarm(&mut self) {
|
||||
// Stop renewing a lock the caller says it released elsewhere.
|
||||
self.stop_heartbeat();
|
||||
if !self.disarmed {
|
||||
self.invalidate_write_votes();
|
||||
record_lock_held_release(self.lock_type);
|
||||
}
|
||||
self.disarmed = true;
|
||||
@@ -774,7 +678,6 @@ impl DistributedLockGuard {
|
||||
|
||||
let entries = self.entries.iter().map(HeldLockEntry::release_entry).collect();
|
||||
DistributedLock::spawn_release_cleanup(entries, "distributed_lock_guard_release");
|
||||
self.invalidate_write_votes();
|
||||
|
||||
// Disarm to prevent double-release on drop
|
||||
self.disarmed = true;
|
||||
@@ -794,7 +697,7 @@ impl Drop for DistributedLockGuard {
|
||||
|
||||
/// Distributed lock handler for distributed use cases
|
||||
/// Uses quorum-based acquisition and aggregate lock ID mapping
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Debug)]
|
||||
pub struct DistributedLock {
|
||||
/// Lock clients for this namespace
|
||||
clients: Arc<[Arc<dyn LockClient>]>,
|
||||
@@ -802,6 +705,7 @@ pub struct DistributedLock {
|
||||
namespace: Arc<str>,
|
||||
/// Quorum size for exclusive/write operations
|
||||
quorum: usize,
|
||||
order_object_writes: bool,
|
||||
}
|
||||
|
||||
type LockAcquireTaskResult = (usize, Result<LockResponse>);
|
||||
@@ -841,20 +745,7 @@ struct LockAcquireQuorumResult {
|
||||
attempt_timed_out: bool,
|
||||
}
|
||||
|
||||
/// Whether both domains contain the same nonempty set of distinct write voters.
|
||||
pub fn same_write_voters(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
|
||||
!left.is_empty()
|
||||
&& left.len() == right.len()
|
||||
&& left.iter().enumerate().all(|(idx, client)| {
|
||||
!left[..idx].iter().any(|other| Arc::ptr_eq(client, other)) && right.iter().any(|other| Arc::ptr_eq(client, other))
|
||||
})
|
||||
}
|
||||
|
||||
impl DistributedLock {
|
||||
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
|
||||
self.quorum == other.quorum && same_write_voters(&self.clients, &other.clients)
|
||||
}
|
||||
|
||||
/// Create new distributed lock
|
||||
pub fn new(namespace: String, clients: Vec<Arc<dyn LockClient>>, quorum: usize) -> Self {
|
||||
Self::new_shared(namespace.into(), clients.into(), quorum)
|
||||
@@ -872,9 +763,14 @@ impl DistributedLock {
|
||||
clients,
|
||||
namespace,
|
||||
quorum: q,
|
||||
order_object_writes: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn order_object_writes(&mut self) {
|
||||
self.order_object_writes = true;
|
||||
}
|
||||
|
||||
/// Get namespace identifier
|
||||
pub fn namespace(&self) -> &str {
|
||||
&self.namespace
|
||||
@@ -909,14 +805,6 @@ impl DistributedLock {
|
||||
/// Acquire a lock and return a RAII guard
|
||||
#[hotpath::measure]
|
||||
pub(crate) async fn acquire_guard(&self, request: &LockRequest) -> Result<Option<DistributedLockGuard>> {
|
||||
self.acquire_guard_for_domain(request, false).await
|
||||
}
|
||||
|
||||
async fn acquire_guard_for_domain(
|
||||
&self,
|
||||
request: &LockRequest,
|
||||
track_write_votes: bool,
|
||||
) -> Result<Option<DistributedLockGuard>> {
|
||||
if self.clients.is_empty() {
|
||||
return Err(LockError::internal("No lock clients available"));
|
||||
}
|
||||
@@ -952,7 +840,6 @@ impl DistributedLock {
|
||||
individual_locks,
|
||||
request.lock_type,
|
||||
heartbeat,
|
||||
track_write_votes,
|
||||
)))
|
||||
} else {
|
||||
// Check if it's a timeout or quorum failure
|
||||
@@ -1017,109 +904,6 @@ impl DistributedLock {
|
||||
self.acquire_guard(&req).await
|
||||
}
|
||||
|
||||
/// Acquire this domain's write quorum, retaining any same-key peer leases
|
||||
/// already owned by the enclosing publication.
|
||||
pub(crate) async fn extend_write_lock(
|
||||
&self,
|
||||
resource: ObjectKey,
|
||||
owner: &str,
|
||||
timeout: Duration,
|
||||
held: &[Arc<crate::namespace::NamespaceLockGuard>],
|
||||
) -> Result<DistributedLockGuard> {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
for owner in held {
|
||||
if let NamespaceLockGuard::Standard(guard) = owner.as_ref()
|
||||
&& guard.lock_id.resource == resource
|
||||
&& !guard.disarmed
|
||||
&& guard.write_domain.is_none()
|
||||
&& guard
|
||||
.entries
|
||||
.iter()
|
||||
.any(|entry| self.clients.iter().any(|client| Arc::ptr_eq(client, &entry.client)))
|
||||
{
|
||||
return Err(LockError::invalid_handle(guard.lock_id.to_string()));
|
||||
}
|
||||
}
|
||||
let mut votes: Vec<WriteVote> = Vec::new();
|
||||
let mut missing = Vec::new();
|
||||
let mut owners = Vec::new();
|
||||
for client in self.clients.iter() {
|
||||
if votes.iter().any(|vote| Arc::ptr_eq(&vote.client, client)) || missing.iter().any(|peer| Arc::ptr_eq(peer, client))
|
||||
{
|
||||
return Err(LockError::internal("write lock domain has a duplicate voter"));
|
||||
}
|
||||
let grant = held.iter().find_map(|owner| match owner.as_ref() {
|
||||
NamespaceLockGuard::Standard(guard)
|
||||
if !guard.disarmed && !guard.is_lock_lost() && guard.lock_id.resource == resource =>
|
||||
{
|
||||
guard
|
||||
.write_votes()
|
||||
.iter()
|
||||
.find(|vote| Arc::ptr_eq(&vote.client, client) && !vote.lease.is_lost())
|
||||
.map(|vote| (owner, vote))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
if let Some((owner, vote)) = grant {
|
||||
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
|
||||
owners.push(Arc::clone(owner));
|
||||
}
|
||||
votes.push(vote.clone());
|
||||
} else {
|
||||
missing.push(Arc::clone(client));
|
||||
}
|
||||
}
|
||||
let request = LockRequest::new(resource.clone(), LockType::Exclusive, owner)
|
||||
.with_acquire_timeout(timeout)
|
||||
.with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
|
||||
if votes.is_empty() {
|
||||
return self
|
||||
.acquire_guard_for_domain(&request, true)
|
||||
.await?
|
||||
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout));
|
||||
}
|
||||
if votes.len() + missing.len() < self.quorum {
|
||||
return Err(LockError::QuorumNotReached {
|
||||
required: self.quorum,
|
||||
achieved: votes.len(),
|
||||
});
|
||||
}
|
||||
if votes.len() < self.quorum {
|
||||
let remaining = Self::new_shared(Arc::clone(&self.namespace), missing.into(), self.quorum - votes.len());
|
||||
let additional = remaining
|
||||
.acquire_guard_for_domain(&request, true)
|
||||
.await?
|
||||
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout))?;
|
||||
votes.extend(additional.write_votes().iter().cloned());
|
||||
owners.push(Arc::new(NamespaceLockGuard::Standard(additional)));
|
||||
}
|
||||
let live = votes.iter().filter(|vote| !vote.lease.is_lost()).count();
|
||||
if live < self.quorum {
|
||||
return Err(LockError::QuorumNotReached {
|
||||
required: self.quorum,
|
||||
achieved: live,
|
||||
});
|
||||
}
|
||||
let lock_lost = Arc::new(LockLostSignal {
|
||||
voters: Some(Box::new((self.quorum, votes.iter().map(|vote| Arc::clone(&vote.lease)).collect()))),
|
||||
..Default::default()
|
||||
});
|
||||
record_lock_held_acquire(LockType::Exclusive);
|
||||
Ok(DistributedLockGuard {
|
||||
lock_id: LockId::new_unique(&resource),
|
||||
entries: Vec::new(),
|
||||
lock_type: LockType::Exclusive,
|
||||
disarmed: false,
|
||||
refresh_task: None,
|
||||
lock_lost,
|
||||
cache_fence_proof: None,
|
||||
write_domain: Some(Box::new(WriteDomainOwnership {
|
||||
votes: votes.into(),
|
||||
owners,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
/// Convenience: acquire exclusive lock with expected contention logs suppressed
|
||||
#[hotpath::measure]
|
||||
pub async fn lock_guard_quiet(
|
||||
@@ -1426,7 +1210,6 @@ impl DistributedLock {
|
||||
entries,
|
||||
LockType::Exclusive,
|
||||
heartbeat,
|
||||
false,
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -2099,7 +1882,8 @@ impl DistributedLock {
|
||||
let mut attempt_request = request.clone();
|
||||
// Only retryable contention reaches another round. Give later writer
|
||||
// attempts enough queue time to outlast readers that entered the gap.
|
||||
let peer_wait_limit = if request.lock_type == LockType::Exclusive && attempt > 1 {
|
||||
let retrying_writer = attempt > 1 && request.lock_type == LockType::Exclusive;
|
||||
let peer_wait_limit = if retrying_writer {
|
||||
LOCK_PEER_WRITER_RETRY_TIMEOUT
|
||||
} else {
|
||||
LOCK_PEER_ACQUIRE_TIMEOUT
|
||||
@@ -2110,11 +1894,8 @@ impl DistributedLock {
|
||||
// A peer may grant promptly but deliver its response after its local
|
||||
// contention budget. Keep this round's owners until a response proves
|
||||
// quorum impossible or the caller's remaining budget expires.
|
||||
// On Exclusive contention retries (`attempt > 1`), serialize on the
|
||||
// canonical anchor voter (`clients[0]`) before fanning out to remaining
|
||||
// voters so N-node local-first split-votes do not livelock across rounds
|
||||
// while preserving 1-RTT initial fanout and 2s reader-outlast queue time.
|
||||
let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1;
|
||||
// Object writers also take the anchor on their first attempt.
|
||||
let serialize_on_anchor = retrying_writer || (self.order_object_writes && request.lock_type == LockType::Exclusive);
|
||||
let result = self
|
||||
.acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor)
|
||||
.await?;
|
||||
@@ -2228,14 +2009,17 @@ impl DistributedLock {
|
||||
fallback_lock_id: request.lock_id.clone(),
|
||||
};
|
||||
let mut next_client_index = 0usize;
|
||||
let initial_target = if anchor_serialized {
|
||||
1
|
||||
} else {
|
||||
required_quorum
|
||||
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
|
||||
.min(self.clients.len())
|
||||
};
|
||||
self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_target);
|
||||
let initial_fanout = required_quorum
|
||||
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
|
||||
.min(self.clients.len());
|
||||
// Hot object writers queue at the same first voter before taking partial grants on other voters.
|
||||
// The remaining voters are contacted on its response or the first hedge, whichever comes first.
|
||||
self.spawn_lock_requests_until(
|
||||
&mut round.pending,
|
||||
request,
|
||||
&mut next_client_index,
|
||||
if anchor_serialized { 1 } else { initial_fanout },
|
||||
);
|
||||
let mut last_failure = None;
|
||||
let mut last_failure_kind = None;
|
||||
let mut last_hard_failure_kind = None;
|
||||
@@ -2248,7 +2032,12 @@ impl DistributedLock {
|
||||
// Spread additional hedges across the existing attempt budget; fast
|
||||
// quorums still use only the initial quorum-plus-spare requests.
|
||||
let hedge_interval = request.acquire_timeout / voter_count;
|
||||
let hedge_timer = tokio::time::sleep(hedge_interval);
|
||||
let first_hedge = if anchor_serialized {
|
||||
request.acquire_timeout.min(quorum_timeout / 2)
|
||||
} else {
|
||||
hedge_interval
|
||||
};
|
||||
let hedge_timer = tokio::time::sleep(first_hedge);
|
||||
tokio::pin!(hedge_timer);
|
||||
|
||||
while !round.pending.is_empty() {
|
||||
@@ -2293,7 +2082,11 @@ impl DistributedLock {
|
||||
}
|
||||
_ = &mut hedge_timer, if next_client_index < self.clients.len() => {
|
||||
if start.elapsed() < quorum_timeout {
|
||||
let target_in_flight = round.pending.len().saturating_add(1);
|
||||
let target_in_flight = if anchor_serialized && next_client_index == 1 {
|
||||
initial_fanout
|
||||
} else {
|
||||
round.pending.len().saturating_add(1)
|
||||
};
|
||||
self.spawn_lock_requests_until(
|
||||
&mut round.pending, request, &mut next_client_index, target_in_flight,
|
||||
);
|
||||
@@ -2635,7 +2428,7 @@ mod batch_retry_tests;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
|
||||
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, HeldLockEntry, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
|
||||
LOCK_ACQUIRE_SPARE_HEDGES, LOCK_PEER_ACQUIRE_TIMEOUT, LOCK_PEER_WRITER_RETRY_TIMEOUT, LockAcquireFailureKind,
|
||||
LockLostSignal, UNLOCK_RETRY_ATTEMPTS, UNLOCK_RETRY_BACKOFF, is_definitive_lock_contention, is_remote_lock_rpc_failure,
|
||||
should_warn_lock_failure,
|
||||
@@ -2723,110 +2516,6 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extending_a_write_quorum_rejects_overlapping_untracked_owners() {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
let clients = stamped_voters(2);
|
||||
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
|
||||
let disjoint = DistributedLock::new("disjoint".into(), vec![clients[1].clone()], 1);
|
||||
let target = DistributedLock::new("target".into(), clients, 2);
|
||||
let key = ObjectKey::new("bucket", "object");
|
||||
let timeout = Duration::from_secs(10);
|
||||
let owner = fixed
|
||||
.lock_guard(key.clone(), "fixed", timeout, timeout)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let held = [Arc::new(NamespaceLockGuard::Standard(owner))];
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_millis(200),
|
||||
target.extend_write_lock(key.clone(), "extend", timeout, &held),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(result, Err(LockError::InvalidHandle { .. })));
|
||||
assert!(disjoint.extend_write_lock(key, "disjoint", timeout, &held).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overlapping_write_domains_reuse_only_live_same_key_grants() {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
let clients = stamped_voters(4);
|
||||
let fixed = DistributedLock::new("fixed".into(), clients[..3].to_vec(), 3);
|
||||
let target = DistributedLock::new("target".into(), clients[1..].to_vec(), 3);
|
||||
let key = ObjectKey::new("bucket", "catalog");
|
||||
let timeout = Duration::from_secs(1);
|
||||
let owner = fixed.extend_write_lock(key.clone(), "catalog", timeout, &[]).await.unwrap();
|
||||
let original: Vec<_> = owner.granted_lock_ids().cloned().collect();
|
||||
let fixed_guard = Arc::new(NamespaceLockGuard::Standard(owner));
|
||||
let held = [fixed_guard];
|
||||
let group = target.extend_write_lock(key.clone(), "put", timeout, &held).await.unwrap();
|
||||
assert_eq!(group.granted_lock_ids().count(), 3);
|
||||
assert_eq!(group.granted_lock_ids().filter(|id| original.contains(id)).count(), 2);
|
||||
drop(held);
|
||||
assert!(!group.is_lock_lost(), "the publication must retain its original owners");
|
||||
let different = ObjectKey::new("bucket", "another-key");
|
||||
let group = Arc::new(NamespaceLockGuard::Standard(group));
|
||||
let independent = target
|
||||
.extend_write_lock(different.clone(), "another", timeout, std::slice::from_ref(&group))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(independent.granted_lock_ids().all(|id| id.resource == different));
|
||||
let NamespaceLockGuard::Standard(group) = group.as_ref() else { unreachable!() };
|
||||
group.write_votes()[0].lease.mark_lost();
|
||||
assert!(group.is_lock_lost(), "the target requires every member of its three-vote quorum");
|
||||
tokio::time::timeout(timeout, group.lock_lost.notified()).await.unwrap();
|
||||
assert!(!independent.is_lock_lost());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn releasing_extended_quorum_wakes_waiters_and_preserves_borrowed_voter() {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
let clients = stamped_voters(2);
|
||||
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
|
||||
let target = DistributedLock::new("target".into(), clients.clone(), 2);
|
||||
let duplicate = DistributedLock::new("duplicate".into(), vec![clients[0].clone(), clients[0].clone()], 2);
|
||||
let key = ObjectKey::new("bucket", "release");
|
||||
let timeout = Duration::from_secs(1);
|
||||
let original = Arc::new(NamespaceLockGuard::Standard(
|
||||
fixed.extend_write_lock(key.clone(), "fixed", timeout, &[]).await.unwrap(),
|
||||
));
|
||||
let held = std::slice::from_ref(&original);
|
||||
assert!(
|
||||
duplicate
|
||||
.extend_write_lock(key.clone(), "target", timeout, held)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
for disarm in [false, true] {
|
||||
let mut group = target.extend_write_lock(key.clone(), "target", timeout, held).await.unwrap();
|
||||
let signal = group.lock_lost();
|
||||
let wait = signal.notified();
|
||||
tokio::pin!(wait);
|
||||
assert!(futures::poll!(&mut wait).is_pending());
|
||||
if disarm {
|
||||
group.disarm();
|
||||
} else {
|
||||
assert!(group.release());
|
||||
}
|
||||
tokio::time::timeout(timeout, wait)
|
||||
.await
|
||||
.expect("invalidate the active waiter");
|
||||
assert!(!original.is_lock_lost());
|
||||
let independent = DistributedLock::new("extra".into(), vec![clients[1].clone()], 1);
|
||||
let _extra = independent
|
||||
.extend_write_lock(key.clone(), "next", timeout, &[])
|
||||
.await
|
||||
.expect("dropping the supplementary lease must not depend on dropping the extended guard");
|
||||
}
|
||||
let regular = fixed
|
||||
.lock_guard(ObjectKey::new("bucket", "ordinary"), "ordinary", timeout, Duration::from_secs(30))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(regular.write_domain.is_none(), "ordinary locks do not track per-voter proofs");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_guard_exposes_complete_cache_fence_quorum_proof() {
|
||||
let lock = DistributedLock::new("cache-proof".to_owned(), stamped_voters(3), 2);
|
||||
@@ -3101,6 +2790,75 @@ mod tests {
|
||||
drop(guard);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_new_writer_leaves_other_voters_free_while_waiting_for_the_first_vote() {
|
||||
let peers: Vec<_> = (0..4)
|
||||
.map(|index| {
|
||||
let delay = if index == 0 {
|
||||
Duration::from_millis(30)
|
||||
} else {
|
||||
Duration::ZERO
|
||||
};
|
||||
Arc::new(SequencedClient::new(
|
||||
vec![AcquirePlan::Success { delay }],
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let mut lock = DistributedLock::new(
|
||||
"hot-write".to_owned(),
|
||||
peers.iter().map(|peer| peer.clone() as Arc<dyn LockClient>).collect(),
|
||||
3,
|
||||
);
|
||||
lock.order_object_writes();
|
||||
let writer = tokio::spawn(async move {
|
||||
let request = LockRequest::new(ObjectKey::new("bucket", "hot"), LockType::Exclusive, "writer")
|
||||
.with_acquire_timeout(Duration::from_secs(5));
|
||||
lock.acquire_guard(&request).await
|
||||
});
|
||||
while peers[0].requested_acquires.load(Ordering::SeqCst) == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
tokio::time::advance(Duration::from_millis(10)).await;
|
||||
assert!(
|
||||
peers[1..]
|
||||
.iter()
|
||||
.all(|peer| peer.requested_acquires.load(Ordering::SeqCst) == 0)
|
||||
);
|
||||
let guard = writer.await.expect("writer task").expect("acquire").expect("write quorum");
|
||||
assert_eq!(guard.entries.len(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn contended_write_retry_can_form_a_quorum_without_the_first_voter() {
|
||||
let peers = (0..4)
|
||||
.map(|index| {
|
||||
let delay = if index == 0 { Duration::from_secs(30) } else { Duration::ZERO };
|
||||
Arc::new(SequencedClient::new(
|
||||
vec![AcquirePlan::Success { delay }],
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
)) as Arc<dyn LockClient>
|
||||
})
|
||||
.collect();
|
||||
let lock = DistributedLock::new("hot-write-fallback".to_owned(), peers, 3);
|
||||
let budget = Duration::from_secs(2);
|
||||
let request =
|
||||
LockRequest::new(ObjectKey::new("bucket", "hot"), LockType::Exclusive, "writer").with_acquire_timeout(budget);
|
||||
let started = Instant::now();
|
||||
let votes = lock
|
||||
.acquire_lock_quorum_once_inner(&request, budget, true)
|
||||
.await
|
||||
.expect("retry round");
|
||||
assert!(votes.response.success);
|
||||
assert_eq!(votes.individual_locks.len(), 3);
|
||||
assert!(started.elapsed() < budget);
|
||||
DistributedLock::release_entries(
|
||||
votes.individual_locks.iter().map(HeldLockEntry::release_entry).collect(),
|
||||
"test_ordered_retry",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn fast_read_quorum_keeps_initial_fanout_bound() {
|
||||
let peers: Vec<_> = (0..8)
|
||||
|
||||
@@ -77,10 +77,6 @@ impl FastLockGuard {
|
||||
&self.key
|
||||
}
|
||||
|
||||
pub(crate) fn is_held_on(&self, shard: &Arc<LockShard>) -> bool {
|
||||
!self.released && self.shard.as_ref().is_some_and(|held| Arc::ptr_eq(held, shard))
|
||||
}
|
||||
|
||||
/// Get the lock mode (Shared or Exclusive)
|
||||
pub fn mode(&self) -> LockMode {
|
||||
self.mode
|
||||
|
||||
@@ -32,6 +32,7 @@ pub mod metrics;
|
||||
pub mod object_pool;
|
||||
pub mod optimized_notify;
|
||||
mod publication;
|
||||
pub(crate) use publication::applies as is_publication_fence;
|
||||
pub mod shard;
|
||||
pub mod state;
|
||||
pub mod types;
|
||||
|
||||
@@ -95,7 +95,7 @@ impl ObjectLockState {
|
||||
// Reset atomic state
|
||||
self.atomic_state = crate::fast_lock::state::AtomicLockState::new();
|
||||
|
||||
self.publication = std::sync::OnceLock::new();
|
||||
self.admission = std::sync::OnceLock::new();
|
||||
|
||||
// Clear owners
|
||||
*self.current_owner.write() = None;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
//! FIFO admission only for the bucket publication fence. Consecutive readers
|
||||
//! form a group; a later writer cannot overtake them, nor can later readers
|
||||
//! overtake a queued writer. This does not limit a current holder's I/O time.
|
||||
//! FIFO admission for bucket publication fences and contended ordinary writers.
|
||||
//! Fences enqueue both modes and group consecutive readers. Ordinary objects
|
||||
//! enqueue only writers, so their existing preference over readers is preserved.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::{collections::VecDeque, sync::Arc};
|
||||
@@ -14,24 +14,24 @@ use super::{
|
||||
types::{LockMode, ObjectKey, ObjectLockRequest},
|
||||
};
|
||||
|
||||
pub(super) fn applies(key: &ObjectKey) -> bool {
|
||||
pub(crate) fn applies(key: &ObjectKey) -> bool {
|
||||
key.version.is_none() && key.object.as_ref() == rustfs_common::table_catalog::TABLE_BUCKET_PUBLICATION_LOCK_PATH
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct PublicationQueue {
|
||||
pub(super) struct AdmissionQueue {
|
||||
entries: Mutex<VecDeque<(Arc<()>, LockMode)>>,
|
||||
pub(super) changed: Notify,
|
||||
}
|
||||
|
||||
pub(super) struct PublicationTicket {
|
||||
pub(super) struct AdmissionTicket {
|
||||
state: Arc<ObjectLockState>,
|
||||
pub(super) queue: Arc<PublicationQueue>,
|
||||
pub(super) queue: Arc<AdmissionQueue>,
|
||||
token: Arc<()>,
|
||||
mode: LockMode,
|
||||
}
|
||||
|
||||
impl PublicationTicket {
|
||||
impl AdmissionTicket {
|
||||
// Called while the shard map is locked. The waiter counter pins the map
|
||||
// entry until ticket destruction, including cancellation between polls.
|
||||
pub(super) fn new(state: Arc<ObjectLockState>, mode: LockMode) -> Option<Self> {
|
||||
@@ -42,10 +42,7 @@ impl PublicationTicket {
|
||||
if !counted {
|
||||
return None;
|
||||
}
|
||||
let queue = state
|
||||
.publication
|
||||
.get_or_init(|| Arc::new(PublicationQueue::default()))
|
||||
.clone();
|
||||
let queue = state.admission.get_or_init(|| Arc::new(AdmissionQueue::default())).clone();
|
||||
let token = Arc::new(());
|
||||
queue.entries.lock().push_back((token.clone(), mode));
|
||||
Some(Self {
|
||||
@@ -80,7 +77,7 @@ impl PublicationTicket {
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PublicationTicket {
|
||||
impl Drop for AdmissionTicket {
|
||||
fn drop(&mut self) {
|
||||
{
|
||||
let mut entries = self.queue.entries.lock();
|
||||
|
||||
@@ -21,7 +21,7 @@ use tokio::time::timeout;
|
||||
use crate::fast_lock::{
|
||||
metrics::ShardMetrics,
|
||||
object_pool::ObjectStatePool,
|
||||
publication::{self, PublicationTicket},
|
||||
publication::{self, AdmissionTicket},
|
||||
state::ObjectLockState,
|
||||
types::{LockMode, LockResult, ObjectKey, ObjectLockRequest},
|
||||
};
|
||||
@@ -85,38 +85,25 @@ pub struct LockShard {
|
||||
active_guards: parking_lot::Mutex<HashMap<u64, Option<ActiveGuardInfo>>>,
|
||||
}
|
||||
|
||||
/// Cancellation-safe waiter counter ticket.
|
||||
///
|
||||
/// Ensures waiting counters are decremented even if the waiting future
|
||||
/// is cancelled/dropped before the normal post-await path runs.
|
||||
struct WaiterCounterGuard {
|
||||
state: Arc<ObjectLockState>,
|
||||
mode: LockMode,
|
||||
incremented: bool,
|
||||
/// Keep a sleeping reader visible until its wait completes or is cancelled.
|
||||
struct WaitingReader<'a> {
|
||||
state: &'a ObjectLockState,
|
||||
counted: bool,
|
||||
}
|
||||
|
||||
impl WaiterCounterGuard {
|
||||
fn new(state: Arc<ObjectLockState>, mode: LockMode) -> Self {
|
||||
let incremented = match mode {
|
||||
LockMode::Shared => state.atomic_state.inc_readers_waiting(),
|
||||
LockMode::Exclusive => state.atomic_state.inc_writers_waiting(),
|
||||
};
|
||||
impl<'a> WaitingReader<'a> {
|
||||
fn new(state: &'a ObjectLockState) -> Self {
|
||||
Self {
|
||||
state,
|
||||
mode,
|
||||
incremented,
|
||||
counted: state.atomic_state.inc_readers_waiting(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WaiterCounterGuard {
|
||||
impl Drop for WaitingReader<'_> {
|
||||
fn drop(&mut self) {
|
||||
if !self.incremented {
|
||||
return;
|
||||
}
|
||||
match self.mode {
|
||||
LockMode::Shared => self.state.atomic_state.dec_readers_waiting(),
|
||||
LockMode::Exclusive => self.state.atomic_state.dec_writers_waiting(),
|
||||
if self.counted {
|
||||
self.state.atomic_state.dec_readers_waiting();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,7 +122,7 @@ impl LockShard {
|
||||
/// Acquire lock with fast path optimization
|
||||
pub async fn acquire_lock(&self, request: &ObjectLockRequest) -> Result<(), LockResult> {
|
||||
if publication::applies(&request.key) {
|
||||
return self.acquire_publication(request, Instant::now()).await;
|
||||
return self.acquire_queued(request, Instant::now(), request.acquire_timeout).await;
|
||||
}
|
||||
|
||||
// Try fast path first without sampling Instant::now()
|
||||
@@ -144,21 +131,31 @@ impl LockShard {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Slow path with waiting
|
||||
self.acquire_lock_slow_path(request, Instant::now()).await
|
||||
let started = Instant::now();
|
||||
let budget = self.calculate_adaptive_timeout(request);
|
||||
match request.mode {
|
||||
LockMode::Exclusive => self.acquire_queued(request, started, budget).await,
|
||||
LockMode::Shared => self.acquire_read_slow_path(request, started, budget).await,
|
||||
}
|
||||
}
|
||||
|
||||
fn publication_ticket(&self, request: &ObjectLockRequest) -> Option<PublicationTicket> {
|
||||
fn admission_ticket(&self, request: &ObjectLockRequest) -> Option<AdmissionTicket> {
|
||||
let mut objects = self.objects.write();
|
||||
let state = objects
|
||||
.entry(request.key.clone())
|
||||
.or_insert_with(|| Arc::new(*self.object_pool.acquire()))
|
||||
.clone();
|
||||
PublicationTicket::new(state, request.mode)
|
||||
// Pin the entry against cleanup until the ticket owns its waiter count.
|
||||
let objects = parking_lot::RwLockWriteGuard::downgrade(objects);
|
||||
#[cfg(test)]
|
||||
test_pause(TestPausePoint::SlowLookup, &request.key);
|
||||
let ticket = AdmissionTicket::new(state, request.mode);
|
||||
drop(objects);
|
||||
ticket
|
||||
}
|
||||
|
||||
async fn acquire_publication(&self, request: &ObjectLockRequest, started: Instant) -> Result<(), LockResult> {
|
||||
let Some(ticket) = self.publication_ticket(request) else {
|
||||
async fn acquire_queued(&self, request: &ObjectLockRequest, started: Instant, budget: Duration) -> Result<(), LockResult> {
|
||||
let Some(ticket) = self.admission_ticket(request) else {
|
||||
return Err(LockResult::Timeout);
|
||||
};
|
||||
let mut first_attempt = true;
|
||||
@@ -166,7 +163,7 @@ impl LockShard {
|
||||
// Register before checking so a release/cancellation cannot be lost
|
||||
// between the eligibility check and the notification wait.
|
||||
let notified = ticket.queue.changed.notified();
|
||||
let remaining = request.acquire_timeout.saturating_sub(started.elapsed());
|
||||
let remaining = budget.saturating_sub(started.elapsed());
|
||||
if !first_attempt && remaining.is_zero() {
|
||||
self.metrics.record_timeout();
|
||||
return Err(LockResult::Timeout);
|
||||
@@ -189,7 +186,7 @@ impl LockShard {
|
||||
// Batch acquisition must join the same queue, even for a no-wait
|
||||
// attempt. Dropping a failed ticket does not consume a queue turn.
|
||||
return self
|
||||
.publication_ticket(request)
|
||||
.admission_ticket(request)
|
||||
.is_some_and(|ticket| ticket.try_acquire(request));
|
||||
}
|
||||
// Early check to avoid unnecessary lock contention
|
||||
@@ -223,7 +220,7 @@ impl LockShard {
|
||||
// Try atomic acquisition
|
||||
let success = match request.mode {
|
||||
LockMode::Shared => state.try_acquire_shared_fast(&request.owner, request.lock_timeout),
|
||||
LockMode::Exclusive => state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout),
|
||||
LockMode::Exclusive => state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout),
|
||||
};
|
||||
drop(objects);
|
||||
|
||||
@@ -248,7 +245,7 @@ impl LockShard {
|
||||
#[cfg(test)]
|
||||
test_pause(TestPausePoint::FastWriteExisting, &request.key);
|
||||
|
||||
let acquired = state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout);
|
||||
let acquired = state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout);
|
||||
drop(objects);
|
||||
if acquired {
|
||||
return Some(state);
|
||||
@@ -257,7 +254,7 @@ impl LockShard {
|
||||
// Create new state from pool and acquire immediately
|
||||
let state_box = self.object_pool.acquire();
|
||||
let state = Arc::new(*state_box);
|
||||
if state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout) {
|
||||
if state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout) {
|
||||
objects.insert(request.key.clone(), state.clone());
|
||||
return Some(state);
|
||||
}
|
||||
@@ -267,11 +264,14 @@ impl LockShard {
|
||||
None
|
||||
}
|
||||
|
||||
/// Slow path with async waiting
|
||||
async fn acquire_lock_slow_path(&self, request: &ObjectLockRequest, start_time: Instant) -> Result<(), LockResult> {
|
||||
// Use adaptive timeout based on current load and request priority
|
||||
let adaptive_timeout = self.calculate_adaptive_timeout(request);
|
||||
let deadline = start_time + adaptive_timeout;
|
||||
/// Ordinary readers retain writer preference and the pooled notification path.
|
||||
async fn acquire_read_slow_path(
|
||||
&self,
|
||||
request: &ObjectLockRequest,
|
||||
started: Instant,
|
||||
budget: Duration,
|
||||
) -> Result<(), LockResult> {
|
||||
let deadline = started + budget;
|
||||
|
||||
let mut retry_count = 0u32;
|
||||
const MAX_RETRIES: u32 = 10;
|
||||
@@ -302,10 +302,7 @@ impl LockShard {
|
||||
|
||||
#[cfg(test)]
|
||||
test_pause(TestPausePoint::SlowLookup, &request.key);
|
||||
let success = match request.mode {
|
||||
LockMode::Shared => state.try_acquire_shared_fast(&request.owner, request.lock_timeout),
|
||||
LockMode::Exclusive => state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout),
|
||||
};
|
||||
let success = state.try_acquire_shared_fast(&request.owner, request.lock_timeout);
|
||||
drop(objects);
|
||||
(state, success)
|
||||
};
|
||||
@@ -325,30 +322,14 @@ impl LockShard {
|
||||
let remaining = deadline - Instant::now();
|
||||
|
||||
if retry_count < MAX_RETRIES && remaining > Duration::from_millis(10) {
|
||||
// For early retries, wait for a release notification bounded by
|
||||
// an exponential backoff. The bound (not a bare sleep) matters:
|
||||
// a plain `sleep` subscribes to nothing, so a release during
|
||||
// the backoff wakes nobody — `notify_writer`/`notify_readers`
|
||||
// are gated on the waiter counters, which a sleeper never
|
||||
// increments. Under N-writer same-key contention the lock sits
|
||||
// free while every loser sleeps out its full backoff, and the
|
||||
// ladder compounds superlinearly with N. The backoff cap still
|
||||
// protects against lost/stolen wakeups, exactly as
|
||||
// NOTIFY_WAIT_CAP does for the post-retry wait below.
|
||||
// Wait for a release during early backoff, with a cap in case
|
||||
// another key consumes the pooled notification.
|
||||
let backoff_ms = std::cmp::min(10 << retry_count, 100); // 10ms, 20ms, 40ms, 80ms, 100ms max
|
||||
let backoff_duration = Duration::from_millis(backoff_ms);
|
||||
|
||||
if backoff_duration < remaining {
|
||||
match request.mode {
|
||||
LockMode::Shared => {
|
||||
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Shared);
|
||||
let _ = timeout(backoff_duration, state.optimized_notify.wait_for_read()).await;
|
||||
}
|
||||
LockMode::Exclusive => {
|
||||
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Exclusive);
|
||||
let _ = timeout(backoff_duration, state.optimized_notify.wait_for_write()).await;
|
||||
}
|
||||
}
|
||||
let _reader = WaitingReader::new(&state);
|
||||
let _ = timeout(backoff_duration, state.optimized_notify.wait_for_read()).await;
|
||||
retry_count += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -358,21 +339,9 @@ impl LockShard {
|
||||
// notification wait, but bounded by NOTIFY_WAIT_CAP so a lost/stolen
|
||||
// wakeup cannot strand this waiter until the deadline.
|
||||
let wait = remaining.min(NOTIFY_WAIT_CAP);
|
||||
let wait_result = match request.mode {
|
||||
LockMode::Shared => {
|
||||
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Shared);
|
||||
timeout(wait, state.optimized_notify.wait_for_read()).await
|
||||
}
|
||||
LockMode::Exclusive => {
|
||||
let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Exclusive);
|
||||
timeout(wait, state.optimized_notify.wait_for_write()).await
|
||||
}
|
||||
};
|
||||
|
||||
// A capped-wait elapse is not a real timeout: loop back and re-try the
|
||||
// acquisition. The deadline check at the top of the loop is the single
|
||||
// source of truth for returning `Timeout`.
|
||||
let _ = wait_result;
|
||||
let _reader = WaitingReader::new(&state);
|
||||
// A capped wait only re-polls. The request deadline above decides timeout.
|
||||
let _ = timeout(wait, state.optimized_notify.wait_for_read()).await;
|
||||
retry_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ impl AtomicLockState {
|
||||
|
||||
/// Try to acquire exclusive lock (fast path)
|
||||
pub fn try_acquire_exclusive(&self) -> bool {
|
||||
if self.try_acquire_exclusive_raw() {
|
||||
if self.try_acquire_exclusive_raw(0) {
|
||||
self.update_access_time();
|
||||
true
|
||||
} else {
|
||||
@@ -129,19 +129,13 @@ impl AtomicLockState {
|
||||
}
|
||||
}
|
||||
|
||||
fn try_acquire_exclusive_raw(&self) -> bool {
|
||||
fn try_acquire_exclusive_raw(&self, blocked_waiters: u64) -> bool {
|
||||
loop {
|
||||
let current = self.state.load(Ordering::Acquire);
|
||||
|
||||
// Only ownership bits may block acquisition: no writer flag, no
|
||||
// active readers. The waiting counters are preserved, not
|
||||
// required to be zero — demanding a fully-zero word means a lock
|
||||
// with registered waiters can be acquired by *no one*, including
|
||||
// the waiters themselves (each sees the others' registration),
|
||||
// so contended acquisition only succeeds in windows where every
|
||||
// waiter happens to be unregistered. `try_acquire_shared` above
|
||||
// already masks correctly; this mirrors it.
|
||||
if (current & (WRITER_FLAG_MASK | READERS_MASK)) != 0 {
|
||||
// Admitted writers ignore waiters. A new writer also tests the
|
||||
// queued-writer bits in the same CAS that claims ownership.
|
||||
if (current & (WRITER_FLAG_MASK | READERS_MASK | blocked_waiters)) != 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -356,7 +350,7 @@ pub struct ObjectLockState {
|
||||
// First cache line: Most frequently accessed data
|
||||
/// Atomic state for fast operations
|
||||
pub atomic_state: AtomicLockState,
|
||||
pub(super) publication: OnceLock<Arc<super::publication::PublicationQueue>>,
|
||||
pub(super) admission: OnceLock<Arc<super::publication::AdmissionQueue>>,
|
||||
|
||||
// Second cache line: Notification mechanisms
|
||||
/// Notification for readers (traditional)
|
||||
@@ -400,7 +394,7 @@ impl ObjectLockState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
atomic_state: AtomicLockState::new(),
|
||||
publication: OnceLock::new(),
|
||||
admission: OnceLock::new(),
|
||||
read_notify: Notify::new(),
|
||||
write_notify: Notify::new(),
|
||||
optimized_notify: OptimizedNotify::new(),
|
||||
@@ -451,7 +445,15 @@ impl ObjectLockState {
|
||||
|
||||
/// Try fast path exclusive lock acquisition
|
||||
pub fn try_acquire_exclusive_fast(&self, owner: &Arc<str>, lock_timeout: Duration) -> bool {
|
||||
if !self.atomic_state.try_acquire_exclusive_raw() {
|
||||
self.try_acquire_exclusive_with_mask(owner, lock_timeout, 0)
|
||||
}
|
||||
|
||||
pub(super) fn try_acquire_unqueued_exclusive(&self, owner: &Arc<str>, lock_timeout: Duration) -> bool {
|
||||
self.try_acquire_exclusive_with_mask(owner, lock_timeout, WRITERS_WAITING_MASK)
|
||||
}
|
||||
|
||||
fn try_acquire_exclusive_with_mask(&self, owner: &Arc<str>, lock_timeout: Duration, blocked_waiters: u64) -> bool {
|
||||
if !self.atomic_state.try_acquire_exclusive_raw(blocked_waiters) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -476,7 +478,7 @@ impl ObjectLockState {
|
||||
} else {
|
||||
shared.remove(pos);
|
||||
}
|
||||
if let Some(queue) = self.publication.get() {
|
||||
if let Some(queue) = self.admission.get() {
|
||||
queue.changed.notify_waiters();
|
||||
}
|
||||
if shared.is_empty() {
|
||||
@@ -509,7 +511,7 @@ impl ObjectLockState {
|
||||
if self.atomic_state.release_exclusive() {
|
||||
*current = None;
|
||||
drop(current);
|
||||
if let Some(queue) = self.publication.get() {
|
||||
if let Some(queue) = self.admission.get() {
|
||||
queue.changed.notify_waiters();
|
||||
}
|
||||
// Notify waiters using optimized system - prefer writers over readers
|
||||
|
||||
@@ -32,6 +32,61 @@ mod fast_lock_tests {
|
||||
FastObjectLockManager::with_config(config)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_writers_cannot_barge_ahead_of_waiters() {
|
||||
let manager = create_test_manager();
|
||||
let key = ObjectKey::new("bucket", "ordinary");
|
||||
let holder = manager.acquire_write_lock(key.clone(), "holder").await.expect("hold the key");
|
||||
let first = manager.acquire_write_lock(key.clone(), "first");
|
||||
let second = manager.acquire_write_lock(key.clone(), "second");
|
||||
tokio::pin!(first, second);
|
||||
assert!(futures::poll!(&mut first).is_pending());
|
||||
assert!(futures::poll!(&mut second).is_pending());
|
||||
drop(holder);
|
||||
|
||||
// Poll the newcomer before allowing a notified waiter to run.
|
||||
let newcomer = manager.acquire_write_lock(key, "newcomer");
|
||||
tokio::pin!(newcomer);
|
||||
assert!(futures::poll!(&mut newcomer).is_pending(), "new writer overtook queued writers");
|
||||
assert!(futures::poll!(&mut second).is_pending(), "second writer overtook first");
|
||||
let first = first.await.expect("first writer progresses");
|
||||
assert!(futures::poll!(&mut newcomer).is_pending());
|
||||
drop(first);
|
||||
assert!(futures::poll!(&mut newcomer).is_pending(), "new writer overtook second");
|
||||
drop(second.await.expect("second writer progresses"));
|
||||
drop(newcomer.await.expect("last writer progresses"));
|
||||
assert_eq!(manager.current_lock_counts(), (0, 0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_writers_cannot_be_bypassed_by_a_batch_after_cancellation() {
|
||||
for all_or_nothing in [false, true] {
|
||||
let manager = create_test_manager();
|
||||
let key = ObjectKey::new("bucket", "ordinary");
|
||||
let holder = manager.acquire_read_lock(key.clone(), "reader").await.expect("hold the key");
|
||||
let mut cancelled = Box::pin(manager.acquire_write_lock(key.clone(), "cancelled"));
|
||||
let writer = manager.acquire_write_lock(key.clone(), "survivor");
|
||||
tokio::pin!(writer);
|
||||
assert!(futures::poll!(&mut cancelled).is_pending());
|
||||
assert!(futures::poll!(&mut writer).is_pending());
|
||||
drop(cancelled);
|
||||
drop(holder);
|
||||
|
||||
let batch = manager.acquire_locks_batch(
|
||||
crate::fast_lock::BatchLockRequest::new("batch")
|
||||
.add_write_lock(key)
|
||||
.with_all_or_nothing(all_or_nothing),
|
||||
);
|
||||
tokio::pin!(batch);
|
||||
assert!(futures::poll!(&mut batch).is_pending(), "batch overtook the surviving writer");
|
||||
drop(writer.await.expect("writer takes cancelled head's place"));
|
||||
let result = batch.await;
|
||||
assert!(result.all_acquired);
|
||||
drop(result);
|
||||
assert_eq!(manager.current_lock_counts(), (0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn try_with_config_returns_error_for_invalid_shard_count() {
|
||||
let config = LockConfig {
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::time::Duration;
|
||||
|
||||
/// Local lock handler using GlobalLockManager
|
||||
/// Directly uses FastObjectLockManager for high-performance local locking
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Debug)]
|
||||
pub struct LocalLock {
|
||||
/// Global lock manager for fast local locks
|
||||
manager: Arc<GlobalLockManager>,
|
||||
@@ -32,14 +32,6 @@ pub struct LocalLock {
|
||||
}
|
||||
|
||||
impl LocalLock {
|
||||
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.manager, &other.manager)
|
||||
}
|
||||
|
||||
pub(crate) fn holds_guard(&self, guard: &FastLockGuard) -> bool {
|
||||
matches!(self.manager.as_ref(), GlobalLockManager::Enabled(manager) if guard.is_held_on(manager.get_shard(guard.key())))
|
||||
}
|
||||
|
||||
/// Create new local lock
|
||||
pub fn new(namespace: String, manager: Arc<GlobalLockManager>) -> Self {
|
||||
Self::new_shared(namespace.into(), manager)
|
||||
|
||||
@@ -46,26 +46,22 @@ pub struct NamespaceLockWrapper {
|
||||
owner: String,
|
||||
}
|
||||
|
||||
/// Identifies the acquisition backend without granting access to other resources.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WriteLockBackend(NamespaceLock);
|
||||
|
||||
impl WriteLockBackend {
|
||||
pub fn matches(&self, lock: &NamespaceLockWrapper) -> bool {
|
||||
self.0.shares_write_backend(&lock.lock)
|
||||
}
|
||||
}
|
||||
|
||||
impl NamespaceLockWrapper {
|
||||
pub fn write_backend(&self) -> WriteLockBackend {
|
||||
WriteLockBackend(self.lock.clone())
|
||||
}
|
||||
|
||||
/// Create a new wrapper with the lock, resource, and owner
|
||||
pub fn new(lock: NamespaceLock, resource: ObjectKey, owner: String) -> Self {
|
||||
Self { lock, resource, owner }
|
||||
}
|
||||
|
||||
/// Order distributed object PUTs at a common voter before competing for the remaining votes.
|
||||
/// The table publication fence has its own FIFO on every voter.
|
||||
pub fn order_object_writes(&mut self) {
|
||||
if let NamespaceLock::Distributed(lock) = &mut self.lock
|
||||
&& !crate::fast_lock::is_publication_fence(&self.resource)
|
||||
{
|
||||
lock.order_object_writes();
|
||||
}
|
||||
}
|
||||
|
||||
/// Get lock owner identifier used for acquisition.
|
||||
pub fn owner(&self) -> &str {
|
||||
&self.owner
|
||||
@@ -87,36 +83,6 @@ impl NamespaceLockWrapper {
|
||||
self.lock.get_write_lock(self.resource.clone(), &self.owner, timeout).await
|
||||
}
|
||||
|
||||
/// Extend a publication's existing same-key grants to this write domain.
|
||||
///
|
||||
/// Acquire the initial distributed guard with this method and an empty slice
|
||||
/// so that individual grants can be reused. A local guard already covering
|
||||
/// this key, or an overlapping untracked distributed guard, returns an error
|
||||
/// immediately. The caller retains ownership of every guard in `held`.
|
||||
pub async fn get_write_lock_extending(
|
||||
&self,
|
||||
timeout: Duration,
|
||||
held: &[Arc<NamespaceLockGuard>],
|
||||
) -> crate::error::Result<NamespaceLockGuard> {
|
||||
match &self.lock {
|
||||
NamespaceLock::Distributed(lock) => lock
|
||||
.extend_write_lock(self.resource.clone(), &self.owner, timeout, held)
|
||||
.await
|
||||
.map(NamespaceLockGuard::Standard),
|
||||
NamespaceLock::Local(lock) => {
|
||||
for owner in held {
|
||||
if let NamespaceLockGuard::Fast(guard) = owner.as_ref()
|
||||
&& guard.key() == &self.resource
|
||||
&& lock.holds_guard(guard)
|
||||
{
|
||||
return Err(crate::LockError::already_locked(self.resource.to_string(), guard.owner().as_ref()));
|
||||
}
|
||||
}
|
||||
self.get_write_lock(timeout).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire write lock with expected contention logs suppressed
|
||||
pub async fn get_write_lock_quiet(
|
||||
&self,
|
||||
@@ -240,7 +206,7 @@ impl NamespaceLockGuard {
|
||||
|
||||
/// Namespace lock for managing locks by resource namespaces
|
||||
/// Supports DistributedLock and LocalLock
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Debug)]
|
||||
pub enum NamespaceLock {
|
||||
/// Distributed lock (distributed use case)
|
||||
Distributed(DistributedLock),
|
||||
@@ -249,15 +215,6 @@ pub enum NamespaceLock {
|
||||
}
|
||||
|
||||
impl NamespaceLock {
|
||||
/// Whether both handles acquire the same exclusive lock for a given resource.
|
||||
fn shares_write_backend(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Local(left), Self::Local(right)) => left.shares_write_backend(right),
|
||||
(Self::Distributed(left), Self::Distributed(right)) => left.shares_write_backend(right),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create new namespace lock with single client (local use case)
|
||||
/// Uses DistributedLock with quorum=1 for single client
|
||||
pub fn new(namespace: String, client: Arc<dyn LockClient>) -> Self {
|
||||
|
||||
@@ -22,43 +22,6 @@ use std::sync::{
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn borrowed_catalog_guard_requires_identical_write_backends() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let local = NamespaceLock::with_local_manager("first".into(), manager.clone());
|
||||
assert!(local.shares_write_backend(&NamespaceLock::with_local_manager("second".into(), manager)));
|
||||
let unrelated = NamespaceLock::with_local_manager("first".into(), Arc::new(GlobalLockManager::new()));
|
||||
assert!(!local.shares_write_backend(&unrelated));
|
||||
|
||||
let clients: Vec<Arc<dyn LockClient>> = vec![Arc::new(FailingClient), Arc::new(FailingClient)];
|
||||
let distributed = NamespaceLock::with_clients_and_quorum("first".into(), clients.clone(), 2);
|
||||
let reordered = vec![clients[1].clone(), clients[0].clone()];
|
||||
assert!(distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("second".into(), reordered, 2)));
|
||||
let repeated = NamespaceLock::with_clients_and_quorum("second".into(), vec![clients[0].clone(), clients[0].clone()], 2);
|
||||
assert!(!distributed.shares_write_backend(&repeated));
|
||||
assert!(!repeated.shares_write_backend(&repeated));
|
||||
assert!(!distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("first".into(), clients, 1)));
|
||||
assert!(!distributed.shares_write_backend(&local));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extending_a_local_write_rejects_only_the_held_key_and_manager() {
|
||||
let key = ObjectKey::new("bucket", "object");
|
||||
let manager = || Arc::new(GlobalLockManager::Enabled(Arc::new(crate::FastObjectLockManager::new())));
|
||||
let wrapper = |manager| {
|
||||
NamespaceLockWrapper::new(NamespaceLock::with_local_manager("local".into(), manager), key.clone(), "writer".into())
|
||||
};
|
||||
let original = wrapper(manager());
|
||||
let other = wrapper(manager());
|
||||
let timeout = Duration::from_secs(10);
|
||||
let held = [Arc::new(original.get_write_lock(timeout).await.unwrap())];
|
||||
let result = tokio::time::timeout(Duration::from_millis(200), original.get_write_lock_extending(timeout, &held))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(result, Err(LockError::AlreadyLocked { .. })));
|
||||
assert!(other.get_write_lock_extending(timeout, &held).await.is_ok());
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct FailingClient;
|
||||
|
||||
@@ -1071,6 +1034,42 @@ async fn test_namespace_lock_distributed_reclaims_expired_same_resource_after_fa
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn four_ingress_nodes_contending_for_one_hot_write_key() {
|
||||
let clients = (0..4)
|
||||
.map(|_| Arc::new(LocalClient::with_manager(Arc::new(GlobalLockManager::new()))) as Arc<dyn LockClient>)
|
||||
.collect::<Vec<_>>();
|
||||
let coordinators = (0..4)
|
||||
.map(|_| Arc::new(NamespaceLock::Distributed(DistributedLock::new("hot-key".to_owned(), clients.clone(), 3))))
|
||||
.collect::<Vec<_>>();
|
||||
let ready = Arc::new(tokio::sync::Barrier::new(32));
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let mut writers = tokio::task::JoinSet::new();
|
||||
for i in 0..32 {
|
||||
let coordinator = coordinators[i % coordinators.len()].clone();
|
||||
let ready = ready.clone();
|
||||
let active = active.clone();
|
||||
writers.spawn(async move {
|
||||
ready.wait().await;
|
||||
let guard = coordinator
|
||||
.get_write_lock(ObjectKey::new("bucket", "same-key"), &format!("writer-{i}"), Duration::from_secs(5))
|
||||
.await?;
|
||||
assert_eq!(active.fetch_add(1, Ordering::SeqCst), 0);
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
assert_eq!(active.fetch_sub(1, Ordering::SeqCst), 1);
|
||||
drop(guard);
|
||||
Ok::<(), crate::LockError>(())
|
||||
});
|
||||
}
|
||||
let mut completed = 0;
|
||||
while let Some(result) = writers.join_next().await {
|
||||
if result.expect("writer task").is_ok() {
|
||||
completed += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(completed, 32);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn four_node_failed_release_converges_without_replica_repair() {
|
||||
let managers = (0..4).map(|_| Arc::new(GlobalLockManager::new())).collect::<Vec<_>>();
|
||||
|
||||
@@ -415,10 +415,6 @@ pub struct AccountInfo {
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
pub struct BucketAccessInfo {
|
||||
pub name: String,
|
||||
/// Whether the snapshot view authorizes displaying initial progress for this bucket incarnation.
|
||||
/// Older servers and requests without `view=snapshot` leave this field absent.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub initial_scan: Option<bool>,
|
||||
/// Display-only accepted scan progress, never a replacement for total usage.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scan_progress: Option<BucketScanProgress>,
|
||||
@@ -458,14 +454,6 @@ pub struct BucketScanProgress {
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
/// Whether the sample lacks an authoritative complete sweep, when reported by the server.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub partial: Option<bool>,
|
||||
/// Whether every expected source completed and agreed, when reported by the server.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub converged: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
@@ -793,7 +781,6 @@ mod tests {
|
||||
assert!(!obj.contains_key("objects"));
|
||||
assert!(!obj.contains_key("object_sizes_histogram"));
|
||||
assert!(!obj.contains_key("object_versions_histogram"));
|
||||
assert!(!obj.contains_key("initial_scan"));
|
||||
assert!(!obj.contains_key("scan_progress"));
|
||||
assert!(!obj.contains_key("usage_value_state"));
|
||||
assert!(!obj.contains_key("usage_updated_at"));
|
||||
@@ -818,10 +805,6 @@ mod tests {
|
||||
"stage": "future_stage", "updated_at": 1000, "objects": null, "size": null,
|
||||
"sources_observed": 1, "sources_total": 2,
|
||||
});
|
||||
wire["initial_scan"] = serde_json::json!(true);
|
||||
wire["scan_progress"]["partial"] = serde_json::json!(true);
|
||||
wire["scan_progress"]["converged"] = serde_json::json!(false);
|
||||
wire["scan_progress"]["blocker"] = serde_json::json!("future_blocker");
|
||||
wire["usage_value_state"] = serde_json::json!("future_provenance");
|
||||
let bucket: BucketAccessInfo = serde_json::from_value(wire.clone()).expect("SDK accepts future diagnostic labels");
|
||||
assert_eq!(serde_json::to_value(bucket).expect("preserve diagnostic labels"), wire);
|
||||
@@ -1190,7 +1173,6 @@ mod tests {
|
||||
|
||||
let bucket_info = BucketAccessInfo {
|
||||
name: "test-bucket".to_string(),
|
||||
initial_scan: None,
|
||||
scan_progress: None,
|
||||
usage_value_state: None,
|
||||
usage_updated_at: None,
|
||||
|
||||
@@ -113,7 +113,6 @@ rustfs-common = { workspace = true }
|
||||
rustfs-heal-contracts = { workspace = true }
|
||||
rustfs-scanner-metrics = { workspace = true }
|
||||
rustfs-config = { workspace = true, features = ["observability"] }
|
||||
rustfs-data-usage = { workspace = true }
|
||||
# NOTE: This dependency on rustfs-ecstore is a known architectural limitation.
|
||||
# The obs crate imports types from ecstore for metrics collection.
|
||||
# Breaking this dependency would require defining traits in obs and
|
||||
|
||||
@@ -50,22 +50,28 @@ pub fn collect_bucket_metrics(buckets: &[BucketStats]) -> Vec<PrometheusMetric>
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let size_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_USAGE_BYTES_MD);
|
||||
let objects_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_OBJECTS_TOTAL_MD);
|
||||
let quota_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_QUOTA_BYTES_MD);
|
||||
let mut metrics = Vec::with_capacity(buckets.len() * 3);
|
||||
for bucket in buckets {
|
||||
let bucket_label: Cow<'static, str> = Cow::Owned(bucket.name.clone());
|
||||
|
||||
if let Some(size_bytes) = bucket.size_bytes {
|
||||
metrics.push(size_metric(size_bytes as f64).with_label("bucket", bucket_label.clone()));
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&BUCKET_USAGE_BYTES_MD, size_bytes as f64)
|
||||
.with_label("bucket", bucket_label.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(objects_count) = bucket.objects_count {
|
||||
metrics.push(objects_metric(objects_count as f64).with_label("bucket", bucket_label.clone()));
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&BUCKET_OBJECTS_TOTAL_MD, objects_count as f64)
|
||||
.with_label("bucket", bucket_label.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
metrics.push(quota_metric(bucket.quota_bytes as f64).with_label("bucket", bucket_label));
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&BUCKET_QUOTA_BYTES_MD, bucket.quota_bytes as f64)
|
||||
.with_label("bucket", bucket_label),
|
||||
);
|
||||
}
|
||||
|
||||
metrics
|
||||
|
||||
@@ -119,32 +119,36 @@ pub fn usage_since_last_update_seconds(last_update: Option<SystemTime>, now: Sys
|
||||
///
|
||||
/// Returns a vector of Prometheus metrics for bucket usage.
|
||||
pub fn collect_bucket_usage_metrics(stats: &[BucketUsageStats]) -> Vec<PrometheusMetric> {
|
||||
if stats.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let total_bytes = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_TOTAL_BYTES_MD);
|
||||
let objects = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECTS_TOTAL_MD);
|
||||
let versions = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_VERSIONS_COUNT_MD);
|
||||
let delete_markers = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_DELETE_MARKERS_COUNT_MD);
|
||||
let quota = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD);
|
||||
let size_distribution = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD);
|
||||
let version_distribution = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD);
|
||||
let mut metrics = Vec::with_capacity(stats.len() * 5);
|
||||
let mut metrics = Vec::new();
|
||||
|
||||
for stat in stats {
|
||||
let bucket_label = stat.bucket.clone();
|
||||
|
||||
metrics.push(total_bytes(stat.total_bytes as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(objects(stat.objects_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(versions(stat.versions_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(delete_markers(stat.delete_markers_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(quota(stat.quota_bytes as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_TOTAL_BYTES_MD, stat.total_bytes as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECTS_TOTAL_MD, stat.objects_count as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_VERSIONS_COUNT_MD, stat.versions_count as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_DELETE_MARKERS_COUNT_MD, stat.delete_markers_count as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD, stat.quota_bytes as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
|
||||
// Object size distribution per bucket
|
||||
for (range, count) in &stat.object_size_distribution {
|
||||
metrics.push(
|
||||
size_distribution(*count as f64)
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD, *count as f64)
|
||||
.with_label_owned(RANGE_LABEL, range.clone())
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
@@ -153,7 +157,7 @@ pub fn collect_bucket_usage_metrics(stats: &[BucketUsageStats]) -> Vec<Prometheu
|
||||
// Version count distribution per bucket
|
||||
for (range, count) in &stat.version_count_distribution {
|
||||
metrics.push(
|
||||
version_distribution(*count as f64)
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD, *count as f64)
|
||||
.with_label_owned(RANGE_LABEL, range.clone())
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
@@ -221,33 +225,8 @@ mod tests {
|
||||
let metrics = collect_bucket_usage_metrics(&stats);
|
||||
report_metrics(&metrics);
|
||||
|
||||
let expected = [
|
||||
(&*USAGE_BUCKET_TOTAL_BYTES_MD, stats[0].total_bytes, None),
|
||||
(&*USAGE_BUCKET_OBJECTS_TOTAL_MD, stats[0].objects_count, None),
|
||||
(&*USAGE_BUCKET_VERSIONS_COUNT_MD, stats[0].versions_count, None),
|
||||
(&*USAGE_BUCKET_DELETE_MARKERS_COUNT_MD, stats[0].delete_markers_count, None),
|
||||
(&*USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD, stats[0].quota_bytes, None),
|
||||
(&*USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD, 500, Some("0-1KB")),
|
||||
(&*USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD, 800, Some("1")),
|
||||
];
|
||||
assert_eq!(metrics.len(), expected.len());
|
||||
for (metric, (descriptor, value, range)) in metrics.iter().zip(expected) {
|
||||
assert!(matches!(metric.name, std::borrow::Cow::Borrowed(_)));
|
||||
assert_eq!(metric.name, descriptor.get_full_metric_name());
|
||||
assert_eq!(metric.help, descriptor.help);
|
||||
assert_eq!(metric.metric_type, descriptor.metric_type);
|
||||
assert_eq!(metric.value, value as f64);
|
||||
assert_eq!(metric.labels.len(), if range.is_some() { 2 } else { 1 });
|
||||
assert!(
|
||||
metric
|
||||
.labels
|
||||
.iter()
|
||||
.any(|(key, value)| *key == BUCKET_LABEL && value == "test-bucket")
|
||||
);
|
||||
if let Some(range) = range {
|
||||
assert!(metric.labels.iter().any(|(key, value)| *key == RANGE_LABEL && value == range));
|
||||
}
|
||||
}
|
||||
// 5 base metrics + 1 size distribution + 1 version distribution = 7
|
||||
assert_eq!(metrics.len(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user