Compare commits

..

10 Commits

Author SHA1 Message Date
唐小鸭 e6435510f8 test(sse): stop the black-box suite from overlooking two regressions
The known-deviation marker in MP-03 accepted any SSE headers that
contained the expected ones, so an unrelated extra header, the raw
customer key included, was still reported as the known deviation. It now
tolerates exactly the one documented difference and fails on anything
else.

The observation of a result document kept only the set of element names.
A wrong part size, a missing part or reordered parts in a listing changed
nothing, so a comparison between two binaries could not see them. It now
keeps every leaf with its value in document order and reduces only the
elements that vary between runs: upload ids, timestamps, markers and
ETags of encrypted objects.

`suite.py selftest` checks both offline, together with the rules of the
comparison. Against the previous observation code it fails on the three
listing cases. The comparison of this branch with its base still shows no
blocking difference in either build.
2026-11-22 22:43:02 +08:00
唐小鸭 5696c6f759 test(sse): add a black-box suite that compares two server binaries
Unit tests cannot show that moving SSE into its own crate left what a
client sees, and what lands on disk, unchanged. This suite drives a real
server process and can compare two binaries.

- 30 cases over six process configurations: no key source, a loaded and
  an invalid local master key, the Local KMS backend with per-key
  authorization off and enforced. They cover round trips and response
  headers, bucket default encryption, CopyObject, multipart uploads,
  run-time KMS stop and start, malformed requests and authorization.
- Every HTTP exchange inside a case is recorded as an observation:
  status, error code and message, SSE headers, response header names,
  body hash, and the encryption metadata key names stored for the
  object. `diff` compares two runs field by field against a closed list
  of accepted differences.
- `cross` has one binary write every stored form and another read the
  same data directory.
- A registered binary is pinned by SHA-256, and a run fails when the
  stored form does not match the build the binary was registered as.

Results for this branch against its base, default build: 93 verdicts and
252 exchanges equal, no blocking difference; the only accepted one is the
new `sse_local_master_key` startup event. Cross reads pass in both
directions, 42 objects each.

The suite also pins two behaviors that predate this branch. Multipart
responses for SSE-C uploads carry `x-amz-server-side-encryption: AES256`
besides the customer-key headers; MP-03 records that as a known deviation.
A `rio-v2` build cannot read back encrypted objects of roughly 64 to
128 KiB, or of 3 MiB and more, so under that build the comparison only
shows that both binaries fail the same cases.
2026-11-22 20:44:37 +08:00
唐小鸭 7c3732799e refactor(sse): let each keying mode own its stored record
One function wrote the stored metadata of every keying mode, and one
function read it back, each switching on the mode and the build inline.
Give a mode both directions of its own record instead.

- `core/keying/direct.rs` records and reads the Direct record
  (`record_customer_key_nonce`, `record_wrapped_data_key`,
  `read_wrapped_data_key`).
- `core/keying/object.rs` records and reads the sealed-key record in
  MinIO's slots (`record_sealed_customer_key`,
  `record_data_key_in_minio_slots`, `read_sealed_data_key`).
- `encryption_material_to_metadata` records the scheme and hands the key
  to the mode that formed it.
- `core/keying/stored.rs` reads in three named steps: the recognition
  order of the modes (`read_stored_data_key`), the choice of the
  provider that unwraps the data key (`unwrap_stored_data_key`), and the
  opening of the object key. A stored key carries its mode as
  `StoredKeyMode` rather than as an optional sealed key.

No behavior change. The stored metadata is identical for every
combination of scheme, mode, sealed key, key id, context, and size in
both builds, and the order of the read-side failures is preserved.
2026-11-22 17:09:24 +08:00
唐小鸭 adad36dc3b docs(sse): describe the module layout and its layer rules
Record in the crate instructions what the split settled: where startup
state, the entry points, the S3 layer, the keying layer, and the
data-key providers live, and the rules that keep them apart.

- `core/keying/` never imports from `core/s3/`; `core/s3/` reads stored
  metadata only through `core/keying/metadata.rs`.
- `rio-v2` conditional compilation stays under `core/keying/` and `kms/`.
- A new stored format is added under `core/keying/` without changes
  under `core/s3/`.
2026-11-22 17:09:24 +08:00
唐小鸭 83afcf52f7 refactor(sse): split the read path into S3 scheme and keying mode
The read entry points decided the scheme, authorized the key, and
recovered the object key in one function, with the SSE-C preamble and
the managed key resolution written out twice. Separate the steps.

- `core/keying/stored.rs` (new) recognizes how a stored object was keyed
  (`recognize_stored_managed_key`) and recovers its key
  (`open_under_customer_key`, `open_under_stored_data_key`). The unwrap
  body moves there unchanged.
- `core/s3/ssec.rs` gains `require_matching_ssec_key` and
  `stored_ssec_algorithm`, shared by the unwrap and the response-header
  paths.
- `core/read.rs` orders the steps: recognize, name the key, authorize,
  recover. Both read entry points resolve the key through one helper, so
  authorization and the response header cannot name different keys.
- `core/keying/` no longer imports from `core/s3/`: the request check
  `reject_kms_context_location_override` moves to `core/s3/headers.rs`,
  and the legacy SSE-C nonce hashes with `md5` directly.

`rio-v2` conditional compilation is now confined to `core/keying/` and
`kms/`. No behavior change: the order of checks on a read is preserved.
2026-11-22 17:09:23 +08:00
唐小鸭 bb044df449 refactor(sse): split the write path into S3 scheme and keying mode
The write entry points mixed two questions: which SSE scheme S3 asks for,
and how this build forms and stores the object key. Give each a home.

- `core/s3/scheme.rs` gains `resolve_write_scheme`, which validates the
  headers and resolves the request, then the bucket default, to a
  `WriteScheme`. PutObject and CreateMultipartUpload now share it; the
  second copy of that decision (`SseTypeV2`,
  `prepare_sse_configuration_v2`) is removed.
- `core/keying/` gains one constructor per key source
  (`new_key_under_customer_key`, `new_session_key_under_customer_key`,
  `new_key_under_data_key`) in each mode. `keying/mod.rs` is the only
  place that says which mode a build writes.
- `core/write.rs` only orders the steps and no longer carries any
  `rio-v2` conditional compilation.

No behavior change. A multipart session still validates the SSE-C key at
creation only in the mode that seals the session key under it.

`SseTypeV2` leaves the public surface; nothing outside the crate used it.
2026-11-22 17:09:23 +08:00
唐小鸭 3565ae1ddf refactor(sse): add an explicit startup step for process-level state
Give rustfs-sse one entry point, `startup::init`, for the state that is
fixed for the lifetime of the process. The server calls it where it used
to log the SSE-KMS key policy mode.

- Resolve the key policy enforcement switch once and log its mode.
- Check `RUSTFS_SSE_S3_MASTER_KEY` at startup and report it through the
  `sse_local_master_key` event as `loaded`, `not_set`, or `invalid`. An
  unusable value is logged as an error; startup still succeeds and
  requests fail exactly as before.
- Return a `StartupReport` so the caller can see both results. Repeated
  calls return the first report without logging again.

Anything that follows the KMS service state stays resolved per request:
the service follows configuration and can be started, restarted, or
stopped from the admin API while the process runs.

`get_local_sse_dek_provider` becomes synchronous, since it never awaited
anything. The "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3" line that was
logged when the key was first used is replaced by the startup event.
2026-11-22 17:09:23 +08:00
唐小鸭 cce3b0873d refactor(sse): split the crate root into core and kms modules
Move every item of the single-file crate into modules without changing
any of them:

- core/s3: what S3 defines for SSE (request headers, scheme selection,
  SSE-C validation, key-policy authorization)
- core/keying: how RustFS seals and records object keys (key material,
  direct and object-key forms, stored metadata, encryption context)
- core/{request,write,read,rewrap,audit}: the per-request entry points
- kms: data-key providers (KMS-backed, local master key, MinIO
  builtin-KMS ciphertext) and the provider registry

The rio-v2 only modules carry the feature gate at module level instead
of on each item. Inline tests move to a crate-level tests module. The
public surface is unchanged and is now an explicit re-export list in
lib.rs; visibility is otherwise tightened to pub(crate) or private.

Documentation that cited the old file now points at the module that
holds the symbol.
2026-11-22 17:09:23 +08:00
唐小鸭 6bb25182c9 refactor(sse): remove three unused configuration helpers
get_sse_type, sse_configuration_to_metadata and SseTypeV2::to_metadata have no caller in the crate, its tests, or the server. All three carried #[allow(unused)], which is what kept the compiler from reporting them.
2026-11-22 17:09:23 +08:00
唐小鸭 ceb8f49aae refactor(sse): extract server-side encryption into rustfs-sse crate
Move the SSE-S3 / SSE-KMS / SSE-C key resolution, metadata and authorization logic out of rustfs/src/storage/sse.rs into a new crates/sse (rustfs-sse) so its outward references are explicit.

The crate depends only on rustfs-config, rustfs-kms, rustfs-policy, rustfs-s3-types and rustfs-utils. It does not reach the storage engine, IAM, the gateway or the server binary; scripts/check_architecture_migration_rules.sh now pins that dependency set.

Everything the crate needs from the running server arrives through the SseHost port (current KMS service, KMS manager state, bucket default encryption, per-key authorization). The host is an explicit parameter on every entry point that needs it rather than a global, so a missing installation cannot silently fall back to the local key provider.

The crate reports failures as SseError, which carries the S3 error code. The KMS-to-S3 error mapping moves with it and rustfs/src/error.rs reuses it, so response codes and messages are unchanged. The source of an SSE-internal error is no longer wrapped in StorageError::Io.

rustfs/src/storage/sse.rs stays as the adapter: it implements the host, binds the entry points to this server and converts back to ApiError, and keeps the conversions that cross the engine boundary (read-side resolver, multipart completion gate, reader error mapping).

Tests split with the code. Four provider round-trips over rio streams move to storage/sse_test.rs because the crate does not depend on rio. Cross-crate test seams sit behind the test-util feature, enabled only from the rustfs dev-dependencies. The rio-v2 CI lane and cache warm-up now include -p rustfs-sse so the rio-v2-only SSE tests keep running.
2026-11-22 17:09:23 +08:00
389 changed files with 21101 additions and 40866 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-linux=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
sha256-darwin=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
sha256-linux=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
sha256-darwin=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=d5f2a266740f695cf6734965a4d25b390e669aaaa2fc87805c45e42de83f13ca
sha256-linux=448ac2ebd537def9f2a63b8961d80a6521f7ef05f952834ec997faed52bfb901
sha256-darwin=9ccb03f4139e99ec11a63810523d504df39191b86e74b28a72dd9a075682293b
sha256-linux=5ef052b03a03afbd00ebfcbbdcb754bbde414b7e6151aae3e2ee78024ce1d0b6
+1 -1
View File
@@ -1 +1 @@
sha256=a304838fe8ded98a781d7e2e1cf5b22a5cbc11ddfdc4fbaeea91149e5f88d699
sha256=fd5683273bba1eae3b4402a4e854a5d168ace845bd0e5fc801f8e336485a4394
+4 -5
View File
@@ -253,7 +253,7 @@ threads-required = "num-test-threads"
# peers complete durable IO. Reserve capacity from unrelated test processes;
# the shared fixture's durable_iam_state_ prefix keeps the whole family together.
[[profile.default.overrides]]
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::tests::durable_iam_state_/)'
threads-required = "num-test-threads"
# Real target-repair and rebalance-stop fixtures commit durable metadata while
@@ -582,7 +582,7 @@ threads-required = "num-test-threads"
# Keep the same IAM/state fixture capacity reservation in CI without changing the
# production lock deadline, internal concurrency, assertions, or retry policy.
[[profile.ci.overrides]]
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::tests::durable_iam_state_/)'
threads-required = "num-test-threads"
# Match the real admin fixture capacity reservation without retries or changes
@@ -731,7 +731,7 @@ test-group = 'ecstore-serial-flaky'
[profile.e2e-smoke]
default-filter = """
package(e2e_test) & (
test(/^(access_request_validation|delete_marker_migration_semantics|version_id_regression|list_objects_v2_pagination|list_object_versions_regression|list_objects_duplicates|list_buckets_double_slash|list_buckets_auth|list_buckets_iam_filter|leading_slash_key|special_chars|create_bucket_region|delete_objects_versioning|head_object_consistency|head_object_range|copy_object_metadata|copy_object_tagging|copy_source_invalid_date|content_encoding|compression|multipart_storage_class|multipart_upload_id|storage_class_capability|ssec_copy|anonymous_access|bucket_policy_check|presigned_negative|negative_sigv4|admin_auth|notification_webhook|tls_hot_reload|console_smoke|admin_iam_crud|admin_pools|sts_query_compat|data_usage)_test::|^fake_s3_target::/)
test(/^(delete_marker_migration_semantics|version_id_regression|list_objects_v2_pagination|list_object_versions_regression|list_objects_duplicates|list_buckets_double_slash|list_buckets_auth|list_buckets_iam_filter|leading_slash_key|special_chars|create_bucket_region|delete_objects_versioning|head_object_consistency|head_object_range|copy_object_metadata|copy_object_tagging|copy_source_invalid_date|content_encoding|compression|multipart_storage_class|multipart_upload_id|storage_class_capability|ssec_copy|anonymous_access|bucket_policy_check|presigned_negative|negative_sigv4|admin_auth|notification_webhook|tls_hot_reload|console_smoke|admin_iam_crud|admin_pools|sts_query_compat|data_usage)_test::|^fake_s3_target::/)
| test(/^replication_extension_test::(test_replication_check_succeeds_with_remote_target|test_replication_check_rejects_target_without_object_lock|test_set_remote_target_rejects_unversioned_source_bucket|test_replication_check_rejects_unversioned_source_bucket|test_replication_check_rejects_missing_replication_config|test_replication_check_rejects_invalid_bucket|test_set_remote_target_rejects_same_bucket_on_same_deployment|test_set_remote_target_rejects_unversioned_target_bucket|test_set_remote_target_update_requires_arn|test_set_remote_target_update_rejects_missing_target|test_set_remote_target_rejects_invalid_target_url|test_set_remote_target_rejects_self_signed_https_target_without_skip_tls_verify|test_set_remote_target_rejects_private_ca_https_target_without_ca_cert_pem|test_list_remote_targets_rejects_empty_bucket|test_list_remote_targets_rejects_invalid_bucket|test_remove_remote_target_rejects_missing_target|test_remove_remote_target_rejects_missing_arn|test_remove_remote_target_rejects_invalid_bucket|test_remove_remote_target_rejects_target_used_by_replication|test_delete_bucket_replication_removes_remote_target)$/)
| test(/^reliant::lifecycle::/)
| test(/^conditional_delete_objects_test::/)
@@ -960,11 +960,10 @@ path = "junit.xml"
# differential picks side A (shell-script stand-ins, no server, no reference
# binary). They already run on every pull request in e2e-smoke, so e2e-full
# excludes them to keep its selection digest unchanged.
# ACL admission protocol tests already run on every PR in e2e-smoke.
[profile.e2e-full]
default-filter = """
package(e2e_test)
& !test(/^(protocols|access_request_validation_test)::/)
& !test(/^protocols::/)
& !test(/^(admin_timeout_regression_test|cluster_concurrency_test|cluster_multidrive_pool_test|degraded_listing_availability_test|namespace_lock_quorum_test|object_lambda_test|stale_multipart_cleanup_cluster_test)::/)
& !test(/^distributed::/)
& !test(/^replication_extension_test::/)
+1
View File
@@ -57,6 +57,7 @@ rustfs-scanner 1392 20
rustfs-scanner-metrics 90 0
rustfs-security-governance 20 0
rustfs-signer 34 0
rustfs-sse 145 0
rustfs-storage-api 34 0
rustfs-targets 612 26
rustfs-test-utils 1 0
+2 -3
View File
@@ -6,9 +6,8 @@ runs:
- name: Install runtime tools
shell: bash
run: |
# These runners have no IPv6 route to the Git PPA inherited from the image.
sudo apt-get -o Acquire::ForceIPv4=true update
sudo apt-get -o Acquire::ForceIPv4=true install -y libssl-dev ripgrep
sudo apt-get update
sudo apt-get install -y libssl-dev ripgrep
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- name: Install cargo-nextest
-2
View File
@@ -22,8 +22,6 @@ Identify the tested commit and any local changes. When testing a prebuilt binary
List relevant checks not run and the remaining risk. Use the validation tier in AGENTS.md; do not run broader checks solely to fill this section. For documentation-only changes, list the applicable documentation checks. Use N/A only when verification is not applicable.
-->
**auto-testing regression coverage** <!-- For each issue-backed bug fix, give the added or extended case ID or PR link, the existing case ID/path and assertion that catches the bug, or "Skipped" with a brief reason. Omit this line for other changes, including documentation-only fixes. -->
## Impact
<!--
Describe user-facing, compatibility, API, deployment, configuration, or documentation impact. Use N/A when there is no expected impact.
-24
View File
@@ -523,30 +523,6 @@
"monitor_reason": "Event-driven or operator-requested work has no periodic freshness obligation.",
"origin": "baseline"
},
{
"workflow": ".github/workflows/agent-v1-protocol-regression.yml",
"name": "Agent v1 protocol regression",
"roles": [
"pr",
"push",
"manual"
],
"events": [
"pull_request",
"push",
"workflow_dispatch"
],
"cadence": "event",
"timezone": "UTC",
"schedule": [],
"owner": "@overtrue",
"policy": "active",
"monitor": "none",
"result_owner": "agent-v1-protocol-regression.yml",
"disposition": "validates Agent v1 schemas and fixture integrity",
"monitor_reason": "Runs on changes to the Agent v1 contract and on request.",
"origin": "added"
},
{
"workflow": ".github/workflows/connect-diagnostic-schedule-acceptance.yml",
"name": "Connect diagnostic scheduler receipt acceptance",
@@ -1,47 +0,0 @@
name: Agent v1 protocol regression
on:
pull_request:
paths:
- "protocol/agent/v1/**"
- "scripts/test_agent_v1_*.py"
- "scripts/verify_agent_v1_fixtures.py"
- "scripts/run_agent_v1_regression.sh"
- "rustfs/src/connect/diagnostics/job.rs"
- "rustfs/src/connect/diagnostics/job_delivery.rs"
- ".github/workflows/agent-v1-protocol-regression.yml"
push:
paths:
- "protocol/agent/v1/**"
- "scripts/test_agent_v1_*.py"
- "scripts/verify_agent_v1_fixtures.py"
- "scripts/run_agent_v1_regression.sh"
- "rustfs/src/connect/diagnostics/job.rs"
- "rustfs/src/connect/diagnostics/job_delivery.rs"
- ".github/workflows/agent-v1-protocol-regression.yml"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: agent-v1-protocol-${{ github.ref }}
cancel-in-progress: true
jobs:
protocol-regression:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
cache: pip
cache-dependency-path: protocol/agent/v1/requirements.txt
- name: Install test dependencies
run: python -m pip install -r protocol/agent/v1/requirements.txt
- name: Run Agent v1 contract regression suite
run: scripts/run_agent_v1_regression.sh
+1 -1
View File
@@ -231,7 +231,7 @@ jobs:
# --all-targets links the same test binaries as the reader lane.
CARGO_BUILD_JOBS: "2"
run: |
cargo build -p rustfs -p rustfs-ecstore --all-targets --features rio-v2
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in
+12 -2
View File
@@ -563,7 +563,7 @@ jobs:
run: chmod go-w "$(realpath "$HOME")"
- name: Run rio-v2 clippy lints
run: cargo clippy -p rustfs -p rustfs-ecstore --all-targets --features rio-v2 -- -D warnings
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 -- -D warnings
- name: Run rio-v2 feature tests
shell: bash
@@ -580,7 +580,7 @@ jobs:
rm -f target/nextest/ci/junit.xml
./scripts/ci/resource_sampler.sh start nextest-rio-v2
trap './scripts/ci/resource_sampler.sh stop' EXIT
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore --features rio-v2 \
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \
2>&1 | tee artifacts/workspace/nextest.log
cargo test -p rustfs --doc --features rio-v2
@@ -1370,6 +1370,15 @@ jobs:
# the intermediate 4-object plateau requires 4*lc_interval < 5*debug_day, i.e.
# debug_day > 8. A smaller value lets the Days=5 rule fire inside the Days=1
# poll window so the count collapses straight to 2 and the test fails (#4764).
#
# RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES=1 is also required. A compacted directory
# is only re-descended (and its objects re-evaluated for ILM) once every
# DATA_USAGE_UPDATE_DIR_CYCLES scanner cycles (default 16). At the accelerated
# RUSTFS_SCANNER_CYCLE=2 that is ~32s between evaluations, so a Days=1 object
# that becomes due at debug_day (10s) is not actually expired until the next
# ~32s boundary (~42s), landing just past the 4*lc_interval (40s) poll window
# and making the count stall at 6 (#4767). Forcing every-cycle re-descent
# evaluates ILM within ~2s of the due time, well inside the poll window.
s3-lifecycle-behavior-tests:
name: S3 Lifecycle Behavior Tests
# Also gated on e2e-tests, matching s3-implemented-tests: when the e2e smoke
@@ -1411,6 +1420,7 @@ jobs:
RUSTFS_ILM_PROCESS_TIME=1 \
RUSTFS_SCANNER_ENABLED=true \
RUSTFS_SCANNER_CYCLE=2 \
RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES=1 \
RUSTFS_SCANNER_START_DELAY_SECS=0 \
RUSTFS_API_STALE_UPLOADS_CLEANUP_INTERVAL=2s \
S3_PORT="${S3_PORT}" \
+6 -37
View File
@@ -1,7 +1,10 @@
name: S3-over-RDMA feature check
# Compile the optional RDMA features independently. The cuObject tests link
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
# The `nixl` and `cuobject` features are off in every other build, so the code
# behind them is compiled nowhere else. This job compiles the `nixl` half on
# Linux and runs rustfs-nixl's unit tests; nixl-sys builds through its stub
# fallback, so no NIXL SDK is needed.
# The cuObject half needs the NVIDIA cuObject SDK and is not compiled here.
# Not a required check and not part of the `Test and Lint` aggregate.
on:
@@ -9,7 +12,6 @@ on:
paths:
- "crates/nixl/**"
- "crates/cuobject/**"
- "crates/cuobject-sys/**"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
@@ -68,42 +70,9 @@ jobs:
- name: Run the rustfs-nixl unit tests
run: cargo test --locked -p rustfs-nixl --features sys
cuobject-check:
name: cuObject server SDK and unit tests
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-cuobject
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Check the cuObject crates without the NVIDIA SDK
run: cargo check --locked -p rustfs-cuobject -p rustfs-cuobject-sys
- name: Install the NVIDIA server SDK
working-directory: ${{ runner.temp }}
run: |
sudo apt-get update
sudo apt-get install --no-install-recommends -y libibverbs-dev librdmacm-dev
repo=https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64
for pkg in libcuobjserver libcuobjserver-dev; do
curl --fail --location --retry 3 "$repo/${pkg}_2.1.0.101-1_amd64.deb" -o "$pkg.deb"
done
sha256sum --check <<'DIGESTS'
39e6271118717e8e726233ae5ac29ee3b83e335e1fbe96b097bb458a4a52393a libcuobjserver.deb
73d4f187e58b784c7cf64633d7e76c2ac59dea5b475fd981cc6897c34cb9876f libcuobjserver-dev.deb
DIGESTS
sudo dpkg -i libcuobjserver.deb libcuobjserver-dev.deb
- name: Test the server bridge
run: cargo test --locked -p rustfs-cuobject --features server
alert-on-failure:
name: Alert on scheduled failure
needs: [nixl-check, cuobject-check]
needs: [nixl-check]
# Only scheduled runs open or update the tracking issue; pull-request and
# manual runs stay quiet.
if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure')
-12
View File
@@ -80,18 +80,6 @@ Do not commit one-shot plans, trackers, migration ledgers, benchmark snapshots,
Select checks from the final task-owned diff. Scoped `AGENTS.md` files may add a concrete path-specific check, but must not replace this tiering with a generic full-workspace gate.
### Issue Fixes and External Regression Coverage
After fixing a bug tracked by an issue and running the applicable local checks, ask the developer once per fixed issue whether to cover it in [rustfs/auto-testing](https://github.com/rustfs/auto-testing). Ask before opening or updating the fix PR, or before reporting completion if there is no PR. Reuse a choice already made for that fix. Investigation alone and documentation-only changes do not trigger this prompt.
When presenting the three choices, describe the failing scenario and the assertion that would catch it.
- **Add or extend a case.** Prefer extending an existing scenario when it can exercise the regression. Record the resulting case ID or auto-testing PR link.
- **Already covered.** Cite the existing auto-testing case ID or path and the assertion that would catch this bug.
- **Skip.** Record the developer's one-line reason and continue with the fix.
Record the choice in the PR's Verification section or in the completion report for work without a PR. All three choices retain the applicable RustFS verification requirements below.
### Documentation and Instructions
For prose, comments, agent instructions, and skill metadata that cannot affect runtime/build output:
+1 -1
View File
@@ -94,7 +94,7 @@ refactors.
|--------|--------------------------|----------------|
| Foundation | `checksums`, `common`, `config`, `data-usage`, `heal-contracts`, `scanner-metrics`, `utils` | Shared configuration, data-usage models, heal domain contracts, scanner telemetry types, utilities, and checksums. |
| I/O and storage | `concurrency`, `ecstore`, `filemeta`, `heal`, `io-core`, `io-metrics`, `lifecycle`, `lock`, `object-capacity`, `object-data-cache`, `replication`, `rio`, `rio-v2`, `s3-client`, `scanner`, `storage-api` | Erasure-coded object storage, metadata, recovery, lifecycle, replication, locking, cache, I/O pipelines, and the engine-side S3 client for remote tier/transition targets. |
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. |
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `sse`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, server-side encryption key resolution, TLS, and security contracts. |
| Protocols and contracts | `extension-schema`, `madmin`, `protos`, `protocols`, `s3-ops`, `s3-types`, `s3select-api`, `s3select-query` | Admin, inter-node, S3, S3 Select, and optional protocol contracts. |
| Operations and integration | `audit`, `notify`, `obs`, `targets`, `zip` | Auditing, observability, event delivery, notification targets, and archive support. |
| Test support | `e2e_test`, `test-utils` | End-to-end validation and shared test bootstrap utilities. |
+1 -2
View File
@@ -46,8 +46,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **SSE-C multipart and copy responses no longer carry `x-amz-server-side-encryption`**: `CreateMultipartUpload`, `UploadPart`, `UploadPartCopy` and `CompleteMultipartUpload` on an SSE-C upload, and `CopyObject` to an SSE-C destination, answered with `x-amz-server-side-encryption: AES256` next to the customer-key headers, so a client reading the response saw an SSE-S3 object. They now return only `x-amz-server-side-encryption-customer-algorithm` and `x-amz-server-side-encryption-customer-key-MD5`, as `PutObject`, `GetObject` and `HeadObject` already did. SSE-S3 and SSE-KMS responses are unchanged.
- **Vault KMS backends no longer fail when the server answers reads from a replica**: a Vault or OpenBao node that serves reads locally (an OpenBao standby, a Vault Enterprise performance standby) can return the state from before a write for a short while after acknowledging it. Against such a node the KV2 backend failed every key creation with `404 Key not found` while leaving the key stored without its description and tags, failed operations issued right after a create or update with `Key not found` or `Concurrent modification`, and the Transit backend failed a disable followed quickly by an enable. Key creation on the KV2 backend is now a single create-only write that carries the description and tags. Both backends now re-read a key record when the answer is older than a write the same RustFS node made in the previous five seconds, pause before re-reading after a lost check-and-set write and allow five attempts instead of three, and retry a Transit key delete that is refused because the deletion switch is not visible yet. A different RustFS node reading the same replica can still observe the earlier state until the replica catches up; see [OpenBao as the Vault KMS backend](docs/operations/kms-openbao-compatibility.md).
- **KMS keys could not be described by ARN through the path route**: `GET /rustfs/admin/v3/kms/keys/{key_id}` read the path segment verbatim, so a key id that has to be percent-encoded to fit in one segment — an AWS key ARN, with its `:` and `/` — was looked up, authorized and audited under its encoded spelling and answered `404`. The segment is now percent-decoded first; a segment that is not valid UTF-8 after decoding is refused with `400 InvalidArgument`. The `describe-key?keyId=` form was unaffected.
@@ -118,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Four-layer regression-prevention tests guard against silent feature deletion: compile-time module assertion, module-presence unit test, cross-module `Protocol` enum assertion, end-to-end SSH banner test against the running binary
### Changed
- **Startup reports the state of `RUSTFS_SSE_S3_MASTER_KEY`**: the server now checks the local SSE-S3 master key when it starts and logs one `sse_local_master_key` event with `state` `loaded`, `not_set`, or `invalid`. An unusable value used to surface only as a `400 InvalidRequest` on the first SSE-S3 request served without a KMS; it is now logged as an error at startup with the reason. Startup still succeeds and request behavior is unchanged. The line "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3 (KMS not configured)", logged when the key was first used, is replaced by this event.
- **Scanner bucket walkers are no longer tied to the disk count**: a new scanner key `walkers_per_disk` (`RUSTFS_SCANNER_WALKERS_PER_DISK`, `1` through `16`, default `1`) spawns that many bucket walkers per local disk of an erasure set, so a single-disk deployment can walk several buckets at once instead of one bucket, one object at a time. The walkers of one disk share its scanner admission, so a peer still sees one scan session per physical disk, and remote disks keep one walker. The walker count is what `max_concurrent_disk_scans` caps and the disk count stays the floor; the `disk_concurrency_budget` log line now reports `walkers_per_disk`, `walkers`, and the `reason` for the effective limit. The default keeps today's I/O profile because a local disk cannot yet report whether it is rotational; the design intends a higher default on flash once it can (`docs/architecture/scanner-per-bucket-convergence.md`). As groundwork for pacing, the raw-enumeration page writer inserts into its building page in place and commits pages without copying them, and a regression test pins the cost of recording 20,000 entries in one prefix so the quadratic bookkeeping removed by [#8114](https://github.com/rustfs/rustfs/pull/8114) (rustfs#8113) cannot return. No persisted format, protocol or admin API changes beyond the additional config key, which older releases preserve and ignore.
- **Encryption and KMS work merged since `1.0.0-rc.5`** (entries were missing from this section):
- **Persisted KMS configuration secrets** are sealed field-by-field with `RUSTFS_KMS_CONFIG_SECRET`. **When the variable is unset the secrets are persisted in cleartext and the server only warns** (`persisted KMS configuration carries cleartext secrets`); it never refuses the write. Set it, identically, on every node, and re-save the configuration to seal an existing one.
Generated
+60 -115
View File
@@ -2322,17 +2322,6 @@ dependencies = [
"x509-cert",
]
[[package]]
name = "codespan-reporting"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
@@ -2811,6 +2800,27 @@ dependencies = [
"subtle",
]
[[package]]
name = "cuobject"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "486fec9045f8057131bf4bba71fbb87bf9dd3e44f853622cf7fa42713f3a108c"
dependencies = [
"cuobject-sys",
"memmap2",
"thiserror 2.0.21",
]
[[package]]
name = "cuobject-sys"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edc615b2a037eb0d80180d202f809629155742db9c9e94b9f7696b1100a7d52f"
dependencies = [
"bindgen 0.73.2",
"cc",
]
[[package]]
name = "curve25519-dalek"
version = "4.1.3"
@@ -2854,68 +2864,6 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "cxx"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40"
dependencies = [
"cc",
"cxx-build",
"cxxbridge-cmd",
"cxxbridge-flags",
"cxxbridge-macro",
"foldhash 0.2.0",
"link-cplusplus",
]
[[package]]
name = "cxx-build"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f"
dependencies = [
"cc",
"codespan-reporting",
"indexmap 2.14.2",
"proc-macro2",
"quote",
"scratch",
"syn 3.0.10",
]
[[package]]
name = "cxxbridge-cmd"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2"
dependencies = [
"clap",
"codespan-reporting",
"indexmap 2.14.2",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "cxxbridge-flags"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a"
[[package]]
name = "cxxbridge-macro"
version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575"
dependencies = [
"indexmap 2.14.2",
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "darling"
version = "0.20.11"
@@ -4288,7 +4236,6 @@ dependencies = [
"rustfs-utils",
"rustls",
"s3s",
"s3s-sigv4",
"same-file",
"serde",
"serde-value",
@@ -4304,7 +4251,6 @@ dependencies = [
"tonic",
"tracing",
"tracing-subscriber",
"url",
"urlencoding",
"uuid",
"walkdir",
@@ -6478,15 +6424,6 @@ dependencies = [
"uuid",
]
[[package]]
name = "link-cplusplus"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"
dependencies = [
"cc",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -9480,7 +9417,7 @@ dependencies = [
"cfg-if",
"libc",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -10022,6 +9959,7 @@ dependencies = [
"rustfs-scanner-metrics",
"rustfs-security-governance",
"rustfs-signer",
"rustfs-sse",
"rustfs-storage-api",
"rustfs-targets",
"rustfs-test-utils",
@@ -10192,21 +10130,12 @@ name = "rustfs-cuobject"
version = "1.0.5"
dependencies = [
"bytes",
"cuobject",
"parking_lot 0.13.0",
"rustfs-cuobject-sys",
"thiserror 2.0.21",
"tokio",
]
[[package]]
name = "rustfs-cuobject-sys"
version = "1.0.5"
dependencies = [
"cxx",
"cxx-build",
"libc",
]
[[package]]
name = "rustfs-data-usage"
version = "1.0.5"
@@ -10396,7 +10325,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway"
version = "0.66.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"arc-swap",
"bytes",
@@ -10443,7 +10372,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-core"
version = "0.63.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"bytes",
"futures-core",
@@ -10464,7 +10393,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-dialect-rustfs-admin"
version = "0.13.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"bytes",
"form_urlencoded",
@@ -10478,7 +10407,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-http"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -10496,7 +10425,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-macros"
version = "0.1.4"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"proc-macro2",
"quote",
@@ -10506,7 +10435,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-sig"
version = "0.15.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"hmac 0.13.0",
"http 1.5.0",
@@ -10521,7 +10450,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-stream"
version = "0.2.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"bitflags 2.13.2",
"bytes",
@@ -10532,7 +10461,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-types"
version = "0.42.0+aws.2026-10-02"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"bytes",
"crc-fast",
@@ -10555,7 +10484,7 @@ dependencies = [
[[package]]
name = "rustfs-gateway-xml"
version = "0.4.0"
source = "git+https://github.com/rustfs/gateway.git?rev=810c39fa41347ea27d1b1310201b3f941f0e3310#810c39fa41347ea27d1b1310201b3f941f0e3310"
source = "git+https://github.com/rustfs/gateway.git?rev=60dcd2a55713dbcc9dbd6e165922e1a0df4473d7#60dcd2a55713dbcc9dbd6e165922e1a0df4473d7"
dependencies = [
"quick-xml 0.41.0",
]
@@ -10966,7 +10895,6 @@ dependencies = [
"tracing",
"tracing-subscriber",
"url",
"uuid",
]
[[package]]
@@ -11446,8 +11374,6 @@ dependencies = [
"rustfs-storage-api",
"rustfs-test-utils",
"rustfs-utils",
"rustix",
"same-file",
"serde",
"serde_json",
"serial_test",
@@ -11461,7 +11387,6 @@ dependencies = [
"tracing",
"tracing-subscriber",
"uuid",
"winapi-util",
]
[[package]]
@@ -11504,6 +11429,33 @@ dependencies = [
"url",
]
[[package]]
name = "rustfs-sse"
version = "1.0.5"
dependencies = [
"aes-gcm",
"async-trait",
"axum",
"base64-simd",
"chacha20poly1305",
"hmac 0.13.0",
"http 1.5.0",
"md-5",
"rand 0.10.4",
"rustfs-config",
"rustfs-kms",
"rustfs-policy",
"rustfs-s3-types",
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.1",
"temp-env",
"tempfile",
"tokio",
"tracing",
]
[[package]]
name = "rustfs-storage-api"
version = "1.0.5"
@@ -11711,7 +11663,6 @@ version = "1.0.5"
dependencies = [
"async-compression",
"futures",
"liblzma",
"rustfs-rio",
"rustfs-tokio-tar",
"serde",
@@ -12097,12 +12048,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "scratch"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2"
[[package]]
name = "scrypt"
version = "0.11.0"
+9 -10
View File
@@ -23,7 +23,6 @@ members = [
"crates/connect-symbol-catalog", # Release-only CPU profile symbol catalog generator
"crates/credentials", # Credential management system
"crates/crypto", # Cryptography and security features
"crates/cuobject-sys", # Native NVIDIA cuObject server SDK bindings
"crates/cuobject", # NVIDIA cuObject S3-over-RDMA staging and transfers (optional)
"crates/nixl", # NIXL/UCX S3-over-RDMA server side (optional)
"crates/ecstore", # Erasure coding storage implementation
@@ -61,6 +60,7 @@ members = [
"crates/security-governance", # Security governance contracts
"crates/extension-schema", # Extension schema contracts
"crates/signer", # client signer
"crates/sse", # S3 server-side encryption key resolution and metadata
"crates/storage-api", # Storage API contracts
"crates/test-utils", # Shared test bootstrap helpers (dev-dependency only)
"crates/targets", # Target-specific configurations and utilities
@@ -109,7 +109,6 @@ rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.5" }
rustfs-credentials = { path = "crates/credentials", version = "1.0.5" }
rustfs-crypto = { path = "crates/crypto", version = "1.0.5" }
rustfs-cuobject = { path = "crates/cuobject", version = "1.0.5" }
rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.5" }
rustfs-nixl = { path = "crates/nixl", version = "1.0.5" }
rustfs-ecstore = { path = "crates/ecstore", version = "1.0.5" }
rustfs-filemeta = { path = "crates/filemeta", version = "1.0.5" }
@@ -142,6 +141,7 @@ rustfs-scanner = { path = "crates/scanner", version = "1.0.5" }
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" }
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.5" }
rustfs-signer = { path = "crates/signer", version = "1.0.5" }
rustfs-sse = { path = "crates/sse", version = "1.0.5" }
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.5" }
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" }
rustfs-targets = { path = "crates/targets", version = "1.0.5" }
@@ -154,16 +154,16 @@ rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
# engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the
# gateway in this workspace; no crate may enable a `compat-s3s*` feature except
# the s3s-facing edge of the rustfs binary.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", 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 = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.66.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.66.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 = "810c39fa41347ea27d1b1310201b3f941f0e3310", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.13.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.13.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
@@ -315,8 +315,7 @@ hostname = "0.4.2"
ipnetwork = { version = "0.21.1" }
lazy_static = "1.5.1"
libc = "0.2.191"
cxx = "1"
cxx-build = "1"
cuobject = { version = "0.1.0", default-features = false }
libsystemd = "0.7.2"
local-ip-address = "0.6.13"
log = "0.4"
-3
View File
@@ -32,9 +32,6 @@ pub const DEFAULT_HEAL_BITROT_CYCLE_SECS: u64 = 30 * 24 * 60 * 60;
/// - Note: Enabling auto-heal can improve system resilience by automatically addressing issues, but may increase resource usage; evaluate based on your operational requirements.
pub const ENV_HEAL_AUTO_HEAL_ENABLE: &str = "RUSTFS_HEAL_AUTO_HEAL_ENABLE";
/// Colon-separated Linux mount roots for automatic replacement of data directories below a mount point.
pub const ENV_HEAL_REPLACEMENT_MOUNT_ROOTS: &str = "RUSTFS_HEAL_REPLACEMENT_MOUNT_ROOTS";
/// Environment variable name that specifies the heal queue size.
///
/// - Purpose: Set the maximum number of heal requests that can be queued.
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "rustfs-cuobject-sys"
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
description = "Native bindings to the NVIDIA cuObject server SDK"
links = "cuobjserver"
[lints]
workspace = true
[dependencies]
cxx = { workspace = true, optional = true }
libc = { workspace = true, optional = true }
[build-dependencies]
cxx-build = { workspace = true, optional = true }
[features]
server = ["dep:cxx", "dep:cxx-build", "dep:libc"]
-41
View File
@@ -1,41 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
fn main() {
#[cfg(feature = "server")]
build_server();
}
#[cfg(feature = "server")]
fn build_server() {
use std::{env, path::PathBuf};
println!("cargo:rerun-if-env-changed=CUOBJSERVER_ROOT");
for file in ["src/sdk.rs", "native/server.h", "native/server.cc"] {
println!("cargo:rerun-if-changed={file}");
}
let mut build = cxx_build::bridge("src/sdk.rs");
if let Some(root) = env::var_os("CUOBJSERVER_ROOT").map(PathBuf::from) {
build.include(root.join("include"));
for subdir in ["lib", "lib64"] {
println!("cargo:rustc-link-search=native={}", root.join(subdir).display());
}
}
build
.include(".")
.file("native/server.cc")
.std("c++17")
.compile("rustfs_cuobject_server");
println!("cargo:rustc-link-lib=cuobjserver");
}
-143
View File
@@ -1,143 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "rustfs-cuobject-sys/src/sdk.rs.h"
#include <cuobjserver.h>
#include <array>
#include <cerrno>
#include <limits>
#include <stdexcept>
#include <system_error>
#include <sys/mman.h>
namespace rustfs::cuobject {
class Server {
public:
Server(std::string address, std::uint16_t port, int channels, std::uint32_t depth)
: address_(std::move(address)) {
cuObjRDMATunable options;
if (channels > 0) options.setNumDcis(channels);
if (depth > 0) options.setCqDepth(depth);
sdk = std::make_unique<cuObjServer>(address_.c_str(), port, CUOBJ_PROTO_RDMA_DC_V1, options);
}
// The SDK may retain the address string through server teardown.
const std::string address_;
std::unique_ptr<cuObjServer> sdk;
};
std::uint32_t header_version() noexcept {
return CUOBJ_SERVER_MAJOR_VERSION * 1000 + CUOBJ_SERVER_MINOR_VERSION;
}
std::shared_ptr<Server> open_server(rust::Str addr, std::uint16_t port, int channels, std::uint32_t depth) {
return std::make_shared<Server>(std::string(addr), port, channels, depth);
}
class Buffer {
public:
std::shared_ptr<Server> owner;
std::shared_ptr<Buffer> base;
rdma_buffer* handle = nullptr;
void* mapping = MAP_FAILED;
std::size_t length = 0;
static void destroy(Buffer* buffer) noexcept {
try {
if (buffer->handle) {
if (buffer->base) buffer->owner->sdk->putRDMABufferFromSgList(buffer->handle);
else buffer->owner->sdk->deRegisterBuffer(buffer->handle);
}
} catch (...) {
// The SDK may still reference the mapping and its owning server.
return;
}
if (buffer->mapping != MAP_FAILED) munmap(buffer->mapping, buffer->length);
delete buffer;
}
};
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length) {
if (!server || !length) throw std::invalid_argument("invalid host registration");
auto buffer = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
buffer->owner = std::move(server);
buffer->length = length;
buffer->mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buffer->mapping == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "mmap");
buffer->handle = buffer->owner->sdk->registerBuffer(buffer->mapping, length);
if (!buffer->handle) throw std::runtime_error("NVIDIA memory registration failed");
return buffer;
}
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges) {
if (!base || base->base || ranges.empty() || ranges.size() > 10) throw std::invalid_argument("invalid scatter list");
auto list = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
list->owner = base->owner;
list->base = std::move(base);
std::vector<cuObjScatterGatherEntryWithOffset_t> entries;
entries.reserve(ranges.size());
for (auto range : ranges) {
if (!range.size || range.offset > list->base->length || range.size > list->base->length - range.offset ||
range.offset > std::numeric_limits<loff_t>::max() || range.size > SIZE_MAX - list->length)
throw std::invalid_argument("invalid scatter range");
entries.push_back({static_cast<loff_t>(range.offset), range.size});
list->length += range.size;
}
list->handle = list->owner->sdk->getRDMABufferFromSgList(list->base->handle, std::move(entries));
if (!list->handle) throw std::runtime_error("NVIDIA scatter list registration failed");
return list;
}
std::uint8_t* data(const Buffer& buffer) noexcept { return static_cast<std::uint8_t*>(buffer.mapping); }
std::size_t size(const Buffer& buffer) noexcept { return buffer.length; }
std::uint16_t lease_channel(const Server& server) { return server.sdk->allocateChannelId(); }
void release_channel(const Server& server, std::uint16_t channel) noexcept {
try { server.sdk->freeChannelId(channel); } catch (...) { /* SDK owns the channel. */ }
}
int completion_fd(const Server& server, std::uint16_t channel) noexcept {
try { return server.sdk->getCompletionFd(channel); } catch (...) { return -EIO; }
}
int drain(const Server& server, int fd, rust::Slice<Completion> out) noexcept {
std::array<cuObjAsyncEvent_t, 8> events{};
if (out.empty() || out.size() > events.size()) return -EINVAL;
try {
const int count = server.sdk->processCompletions(events.data(), static_cast<int>(out.size()), fd);
if (count > static_cast<int>(out.size())) return -EIO;
for (int i = 0; i < count; ++i) {
out[i] = {reinterpret_cast<std::uintptr_t>(events[i].async_handle), events[i].status};
}
return count;
} catch (...) { return -EIO; }
}
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept {
if (buffer.owner.get() != &server || !op.length || op.offset > buffer.length ||
op.length > buffer.length - op.offset || (buffer.base && (op.offset || op.length != buffer.length)))
return {-EINVAL, 0, false};
ibv_wc_status verbs = IBV_WC_SUCCESS;
bool submitted_to_sdk = false;
try {
const std::string key(op.key), token(op.token);
void* handle = reinterpret_cast<void*>(op.handle);
auto& sdk = *server.sdk;
submitted_to_sdk = true;
const ssize_t moved = op.put
? sdk.handlePutObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle)
: sdk.handleGetObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle);
return {moved, static_cast<int>(verbs), false};
} catch (...) { return {-EIO, static_cast<int>(verbs), submitted_to_sdk}; }
}
}
-40
View File
@@ -1,40 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "rust/cxx.h"
#include <cstddef>
#include <cstdint>
#include <memory>
namespace rustfs::cuobject {
class Server;
class Buffer;
struct Range;
struct Completion;
struct Operation;
struct Outcome;
std::uint32_t header_version() noexcept;
std::shared_ptr<Server> open_server(rust::Str address, std::uint16_t port, int channels, std::uint32_t depth);
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length);
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges);
std::uint8_t* data(const Buffer& buffer) noexcept;
std::size_t size(const Buffer& buffer) noexcept;
std::uint16_t lease_channel(const Server& server);
void release_channel(const Server& server, std::uint16_t channel) noexcept;
int completion_fd(const Server& server, std::uint16_t channel) noexcept;
int drain(const Server& server, int fd, rust::Slice<Completion> events) noexcept;
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept;
}
-149
View File
@@ -1,149 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Private ABI for the NVIDIA server SDK.
use cxx::SharedPtr;
use std::io;
use std::os::fd::{AsRawFd, RawFd};
#[cxx::bridge(namespace = "rustfs::cuobject")]
mod ffi {
#[derive(Clone, Copy, Debug)]
struct Range {
offset: usize,
size: usize,
}
#[derive(Clone, Copy, Default)]
struct Completion {
handle: usize,
status: isize,
}
struct Operation<'a> {
key: &'a str,
token: &'a str,
address: u64,
offset: usize,
length: usize,
channel: u16,
handle: usize,
put: bool,
}
struct Outcome {
count: isize,
verbs: i32,
uncertain: bool,
}
// SAFETY: native registrations own their server and mapping. Scatter views
// also own their base. The caller keeps DMA ranges exclusive until completion.
unsafe extern "C++" {
include!("native/server.h");
type Server;
type Buffer;
fn header_version() -> u32;
fn open_server(address: &str, port: u16, channels: i32, depth: u32) -> Result<SharedPtr<Server>>;
fn register_buffer(server: SharedPtr<Server>, length: usize) -> Result<SharedPtr<Buffer>>;
fn scatter_list(base: SharedPtr<Buffer>, ranges: &[Range]) -> Result<SharedPtr<Buffer>>;
fn size(buffer: &Buffer) -> usize;
fn data(buffer: &Buffer) -> *mut u8;
fn lease_channel(server: &Server) -> Result<u16>;
fn release_channel(server: &Server, channel: u16);
fn completion_fd(server: &Server, channel: u16) -> i32;
fn drain(server: &Server, fd: i32, events: &mut [Completion]) -> i32;
unsafe fn transfer(server: &Server, buffer: &Buffer, op: &Operation) -> Outcome;
}
}
// SAFETY: the SDK supports concurrent transfers on separately leased channels.
// Server and registration metadata stay immutable after construction. Sharing a
// handle gives no safe access to the host bytes.
unsafe impl Send for ffi::Server {}
unsafe impl Sync for ffi::Server {}
unsafe impl Send for ffi::Buffer {}
unsafe impl Sync for ffi::Buffer {}
pub use ffi::{Completion, Operation, Outcome, Range, data, header_version, open_server, register_buffer, scatter_list, size};
pub type ServerHandle = SharedPtr<ffi::Server>;
pub type BufferHandle = SharedPtr<ffi::Buffer>;
pub fn errno(status: isize) -> io::Error {
match status.checked_neg().and_then(|code| i32::try_from(code).ok()) {
Some(code) => io::Error::from_raw_os_error(code),
None => io::Error::other("invalid NVIDIA error status"),
}
}
pub struct Channel {
server: SharedPtr<ffi::Server>,
id: u16,
}
impl Channel {
pub fn lease(server: &SharedPtr<ffi::Server>) -> io::Result<Self> {
let id = ffi::lease_channel(server).map_err(io::Error::other)?;
if id == u16::MAX {
return Err(io::Error::from_raw_os_error(libc::EBUSY));
}
Ok(Self {
server: server.clone(),
id,
})
}
pub fn fd(&self) -> Option<CompletionFd> {
let fd = ffi::completion_fd(&self.server, self.id);
(fd >= 0).then(|| CompletionFd {
fd,
server: self.server.clone(),
})
}
/// Submits a transfer to the leased channel.
///
/// # Safety
/// The caller must exclusively own the local range, keep the remote token valid,
/// and retain the channel and registrations until the SDK confirms completion.
/// An unknown submission or undelivered completion must preserve those owners.
pub unsafe fn submit(&mut self, buffer: &ffi::Buffer, mut op: ffi::Operation<'_>) -> ffi::Outcome {
op.channel = self.id;
// SAFETY: the caller holds the range and the exclusive channel lease.
unsafe { ffi::transfer(&self.server, buffer, &op) }
}
}
impl Drop for Channel {
fn drop(&mut self) {
ffi::release_channel(&self.server, self.id);
}
}
pub struct CompletionFd {
fd: RawFd,
server: SharedPtr<ffi::Server>,
}
impl AsRawFd for CompletionFd {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl CompletionFd {
pub fn drain(&self, events: &mut [ffi::Completion]) -> io::Result<usize> {
let count = ffi::drain(&self.server, self.fd, events);
usize::try_from(count).map_err(|_| errno(count as isize))
}
}
+2 -2
View File
@@ -16,11 +16,11 @@ workspace = true
[dependencies]
bytes = { workspace = true, optional = true }
rustfs-cuobject-sys = { workspace = true, features = ["server"], optional = true }
cuobject = { workspace = true, default-features = false, optional = true }
parking_lot = { workspace = true, optional = true }
thiserror = { workspace = true, optional = true }
tokio = { workspace = true, features = ["net", "rt-multi-thread", "sync", "time"], optional = true }
[features]
# Compiles the cuObject server bindings (needs the NVIDIA cuObject SDK).
server = ["dep:bytes", "dep:rustfs-cuobject-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
server = ["dep:bytes", "dep:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
+224 -650
View File
File diff suppressed because it is too large Load Diff
+3 -72
View File
@@ -1235,66 +1235,23 @@ impl Serialize for DataUsageEntry {
where
S: serde::Serializer,
{
self.serialize_fields(serializer, &self.children, &self.replication_stats, &self.all_tier_stats)
}
}
struct OrderedUsageEntry<'a>(&'a DataUsageEntry);
impl Serialize for OrderedUsageEntry<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut children: Vec<_> = self.0.children.iter().collect();
children.sort_unstable();
// MessagePack decoders accept struct fields as positional sequences.
// Include the nested target and tier maps in stable order as well.
let replication = self.0.replication_stats.as_ref().map(|stats| {
let ReplicationAllStats {
targets,
replica_size,
replica_count,
} = stats;
let targets: std::collections::BTreeMap<_, _> = targets.iter().collect();
(targets, replica_size, replica_count)
});
let tiers = self.0.all_tier_stats.as_ref().map(|stats| {
let AllTierStats { tiers } = stats;
let tiers: std::collections::BTreeMap<_, _> = tiers.iter().collect();
(tiers,)
});
self.0.serialize_fields(serializer, &children, &replication, &tiers)
}
}
impl DataUsageEntry {
/// Stable MessagePack encoding for independently reusable scanner checkpoint pages.
pub fn ordered_encoding(&self) -> impl Serialize + '_ {
OrderedUsageEntry(self)
}
fn serialize_fields<S: serde::Serializer, C: Serialize, R: Serialize, T: Serialize>(
&self,
serializer: S,
children: &C,
replication: &R,
tiers: &T,
) -> Result<S::Ok, S::Error> {
// Keep entries map-encoded so older readers can ignore fields appended
// by newer scanner versions during rolling upgrades. The derived
// (array) encoding made any appended field a decode error for them.
let mut state = serializer.serialize_map(Some(
11 + usize::from(self.unknown_tier_stats.is_some()) + usize::from(self.tier_accounting_proof.is_some()),
))?;
state.serialize_entry("children", children)?;
state.serialize_entry("children", &self.children)?;
state.serialize_entry("size", &self.size)?;
state.serialize_entry("objects", &self.objects)?;
state.serialize_entry("versions", &self.versions)?;
state.serialize_entry("delete_markers", &self.delete_markers)?;
state.serialize_entry("obj_sizes", &self.obj_sizes)?;
state.serialize_entry("obj_versions", &self.obj_versions)?;
state.serialize_entry("replication_stats", replication)?;
state.serialize_entry("replication_stats", &self.replication_stats)?;
state.serialize_entry("compacted", &self.compacted)?;
state.serialize_entry("failed_objects", &self.failed_objects)?;
state.serialize_entry("all_tier_stats", tiers)?;
state.serialize_entry("all_tier_stats", &self.all_tier_stats)?;
// Keep the legacy no-unknown shape byte-for-byte stable. Once unknown
// accounting exists, append its map field before the optional proof.
if let Some(unknown_tier_stats) = self.unknown_tier_stats.as_ref() {
@@ -2577,32 +2534,6 @@ mod tests {
entry
}
#[test]
fn ordered_checkpoint_entry_round_trips_and_stays_identical_after_reload() {
let mut entry = DataUsageEntry::default();
let mut replication = ReplicationAllStats {
replica_size: 998,
replica_count: 3,
..Default::default()
};
let mut tiers = AllTierStats::default();
for index in 1..=32 {
let key = format!("source-{index}");
entry.children.insert(key.clone());
replication.targets.insert(key.clone(), ReplicationTargetUsage::default());
tiers.tiers.insert(key, TierStats::default());
}
entry.replication_stats = Some(replication);
entry.all_tier_stats = Some(tiers);
let bytes = rmp_serde::to_vec(&entry.ordered_encoding()).expect("encode ordered checkpoint");
let reloaded: DataUsageEntry = rmp_serde::from_slice(&bytes).expect("read with the existing codec");
assert_eq!(reloaded.children, entry.children);
let replicas = reloaded.replication_stats.as_ref().expect("replication stats");
assert_eq!((replicas.targets.len(), replicas.replica_size, replicas.replica_count), (32, 998, 3));
assert_eq!(reloaded.all_tier_stats.as_ref().expect("tier stats").tiers.len(), 32);
assert_eq!(rmp_serde::to_vec(&reloaded.ordered_encoding()).expect("encode reloaded entry"), bytes);
}
#[test]
fn tier_stats_survive_entry_merge() {
let mut left = tier_entry(
@@ -171,70 +171,6 @@ impl DataUsageBucketObservation {
}
impl DataUsageInfo {
/// Hide values that cannot be bound to the current storage-owned identity.
///
/// `incarnations` contains canonical non-nil identities read from storage;
/// a missing entry means identity was unavailable. Neither legacy values
/// without identity nor metadata read failures establish confirmed zero.
/// Changed responses are display-only and cannot authorize quota or writes.
/// If retained counters overflow, all values remain unknown.
/// Returns the number of canonical values removed.
pub fn retain_current_bucket_usage_for_admin(&mut self, incarnations: &HashMap<String, String>) -> usize {
let original_count = self.buckets_usage.len();
let original_observation_count = self.usage_snapshot_bucket_observations.len();
let matches_current = |bucket: &String, usage: &BucketUsageInfo| {
incarnations.get(bucket).is_some_and(|current| {
!current.is_empty()
&& current != "00000000-0000-0000-0000-000000000000"
&& usage.bucket_incarnation.as_ref() == Some(current)
})
};
self.buckets_usage.retain(|bucket, usage| matches_current(bucket, usage));
self.usage_snapshot_bucket_observations.retain(|bucket, observation| {
matches_current(bucket, &observation.usage)
&& observation
.sources
.iter()
.all(|source| incarnations.get(bucket) == Some(&source.bucket_incarnation))
});
if original_count == self.buckets_usage.len()
&& original_observation_count == self.usage_snapshot_bucket_observations.len()
{
return 0;
}
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
Some([
total[0].checked_add(usage.size)?,
total[1].checked_add(usage.objects_count)?,
total[2].checked_add(usage.versions_count)?,
total[3].checked_add(usage.delete_markers_count)?,
])
});
let [size, objects, versions, markers] = totals.unwrap_or_else(|| {
self.buckets_usage.clear();
self.usage_snapshot_bucket_observations.clear();
[0; 4]
});
self.bucket_sizes = self
.buckets_usage
.iter()
.map(|(bucket, usage)| (bucket.clone(), usage.size))
.collect();
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
self.objects_total_size = size;
self.objects_total_count = objects;
self.versions_total_count = versions;
self.delete_markers_total_count = markers;
self.replication_info.clear();
self.tier_stats = None;
self.unknown_tier_stats = None;
self.usage_snapshot_complete = false;
self.usage_snapshot_partial = true;
self.usage_snapshot_converged = Some(false);
self.usage_snapshot_admin_projection = true;
original_count.saturating_sub(self.buckets_usage.len())
}
/// Overlay validated companions on an owned admin response only.
///
/// `incarnations` must come from current storage metadata, not the companion.
@@ -321,110 +321,3 @@ fn provenance_and_companions_change_candidate_bytes_and_round_trip_as_maps() {
let restored: DataUsageInfo = rmp_serde::from_slice(&named).expect("read named map with additive fields");
assert_eq!(restored, canonical);
}
#[test]
fn current_identity_filter_preserves_an_unchanged_complete_snapshot() {
let mut candidate = snapshot();
let original = candidate.clone();
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&incarnations()), 0);
assert_eq!(candidate, original);
assert!(candidate.is_complete_bucket_usage_snapshot());
}
#[test]
fn current_identity_filter_hides_unbound_values_without_confirming_zero() {
for identity in [
None,
Some(""),
Some("corrupt"),
Some("00000000-0000-0000-0000-000000000000"),
Some("22222222-2222-4222-8222-222222222222"),
] {
let mut candidate = snapshot();
candidate.usage_snapshot_bucket_observations.clear();
candidate
.buckets_usage
.get_mut("bucket")
.expect("canonical")
.bucket_incarnation = identity.map(str::to_string);
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&incarnations()),
1,
"identity {identity:?}"
);
assert!(!candidate.buckets_usage.contains_key("bucket"));
assert!(!candidate.bucket_sizes.contains_key("bucket"));
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert!(candidate.usage_snapshot_admin_projection);
assert!(!candidate.is_complete_bucket_usage_snapshot());
assert!(!candidate.is_valid_partial_snapshot());
}
for current in ["", "00000000-0000-0000-0000-000000000000"] {
let mut candidate = snapshot();
candidate
.buckets_usage
.get_mut("bucket")
.expect("canonical")
.bucket_incarnation = Some(current.to_string());
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&HashMap::from([("bucket".to_string(), current.to_string())])),
1
);
assert!(candidate.usage_snapshot_admin_projection);
}
let mut candidate = snapshot();
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&HashMap::new()), 1);
assert!(candidate.usage_snapshot_bucket_observations.is_empty());
assert_eq!(candidate.usage_snapshot_converged, Some(false));
}
#[test]
fn current_identity_filter_keeps_healthy_buckets_and_recalculates_partial_totals() {
let mut candidate = snapshot();
candidate.buckets_usage.insert("cold".to_string(), usage(7));
candidate.buckets_count = 2;
candidate.bucket_sizes.insert("cold".to_string(), 7);
candidate.calculate_totals();
candidate.replication_info.insert("target".to_string(), Default::default());
candidate.tier_stats = Some(Default::default());
candidate.unknown_tier_stats = Some(Default::default());
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&HashMap::from([("cold".to_string(), INCARNATION.to_string())])),
1
);
assert_eq!(candidate.buckets_usage.len(), 1);
assert_eq!(candidate.buckets_usage["cold"].size, 7);
assert_eq!(candidate.bucket_sizes, HashMap::from([("cold".to_string(), 7)]));
assert_eq!(
(
candidate.buckets_count,
candidate.objects_total_size,
candidate.objects_total_count,
candidate.versions_total_count
),
(1, 7, 7, 7)
);
assert!(candidate.replication_info.is_empty());
assert!(candidate.tier_stats.is_none());
assert!(candidate.unknown_tier_stats.is_none());
assert!(candidate.usage_snapshot_admin_projection);
assert_eq!(candidate.usage_snapshot_converged, Some(false));
}
#[test]
fn current_identity_filter_overflow_leaves_totals_unknown() {
let mut candidate = snapshot();
candidate.buckets_usage.insert("large".to_string(), usage(u64::MAX));
candidate.buckets_usage.insert("small".to_string(), usage(1));
candidate.buckets_count = 3;
let current = HashMap::from([
("large".to_string(), INCARNATION.to_string()),
("small".to_string(), INCARNATION.to_string()),
]);
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&current), 3);
assert!(candidate.buckets_usage.is_empty());
assert!(candidate.bucket_sizes.is_empty());
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert!(candidate.usage_snapshot_admin_projection);
assert!(!candidate.is_complete_bucket_usage_snapshot());
}
-2
View File
@@ -140,8 +140,6 @@ clap = { workspace = true, features = ["derive", "env"] }
[dev-dependencies]
serde-value.workspace = true
s3s = { workspace = true, features = ["minio"] }
s3s-sigv4.workspace = true
url.workspace = true
async-compression = { workspace = true, features = ["tokio", "bzip2", "lz4", "xz"] }
aws-config = { workspace = true }
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
@@ -1,585 +0,0 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Exercise the production validator at the protocol boundary without importing the server crate.
#[path = "../../../rustfs/src/storage/authorization/admission/request_validation.rs"]
mod request_validation;
use async_trait::async_trait;
use http::{Extensions, HeaderMap, Method, Request, StatusCode, Uri};
use http_body_util::BodyExt;
use request_validation::{RequestViolation, validate_method_subresource};
use s3s::access::{S3Access, S3AccessContext};
use s3s::auth::SimpleAuth;
use s3s::dto::{
AbortMultipartUploadInput, AbortMultipartUploadOutput, DeleteBucketInput, DeleteBucketOutput, DeleteBucketPolicyInput,
DeleteBucketPolicyOutput, DeleteObjectInput, DeleteObjectOutput, DeleteObjectTaggingInput, DeleteObjectTaggingOutput,
GetBucketAclInput, GetBucketAclOutput, GetObjectAclInput, GetObjectAclOutput, GetObjectInput, GetObjectOutput,
HeadBucketInput, HeadBucketOutput, PutBucketAclInput, PutBucketAclOutput, PutObjectAclInput, PutObjectAclOutput,
StreamingBlob,
};
use s3s::host::SingleDomain;
use s3s::route::S3Route;
use s3s::service::{S3Service, S3ServiceBuilder};
use s3s::{Body, S3Request, S3Response, S3Result, s3_error};
use s3s_sigv4::{
AmzDate, EMPTY_STRING_SHA256_HASH, Payload, calculate_signature, create_canonical_request,
create_presigned_canonical_request, create_string_to_sign,
};
use std::sync::{Arc, Mutex};
use time::{OffsetDateTime, macros::format_description};
#[derive(Default)]
struct State {
object_deleted: bool,
bucket_deleted: bool,
calls: Vec<(&'static str, Option<String>)>,
}
#[derive(Clone, Default)]
struct ProbeS3(Arc<Mutex<State>>);
#[async_trait]
impl s3s::S3 for ProbeS3 {
async fn delete_object(&self, req: S3Request<DeleteObjectInput>) -> S3Result<S3Response<DeleteObjectOutput>> {
let mut state = self.0.lock().expect("probe state");
state.object_deleted = true;
state.calls.push(("DeleteObject", req.input.version_id));
Ok(S3Response::new(DeleteObjectOutput::default()))
}
async fn delete_bucket(&self, _: S3Request<DeleteBucketInput>) -> S3Result<S3Response<DeleteBucketOutput>> {
let mut state = self.0.lock().expect("probe state");
state.bucket_deleted = true;
state.calls.push(("DeleteBucket", None));
Ok(S3Response::new(DeleteBucketOutput::default()))
}
async fn get_object(&self, _: S3Request<GetObjectInput>) -> S3Result<S3Response<GetObjectOutput>> {
if self.0.lock().expect("probe state").object_deleted {
return Err(s3_error!(NoSuchKey));
}
Ok(S3Response::new(GetObjectOutput {
body: Some(StreamingBlob::from(Body::from("original object".to_owned()))),
..Default::default()
}))
}
async fn head_bucket(&self, _: S3Request<HeadBucketInput>) -> S3Result<S3Response<HeadBucketOutput>> {
if self.0.lock().expect("probe state").bucket_deleted {
return Err(s3_error!(NoSuchBucket));
}
Ok(S3Response::new(HeadBucketOutput::default()))
}
async fn delete_object_tagging(
&self,
req: S3Request<DeleteObjectTaggingInput>,
) -> S3Result<S3Response<DeleteObjectTaggingOutput>> {
self.0
.lock()
.expect("probe state")
.calls
.push(("DeleteObjectTagging", req.input.version_id));
Ok(S3Response::new(DeleteObjectTaggingOutput::default()))
}
async fn abort_multipart_upload(
&self,
req: S3Request<AbortMultipartUploadInput>,
) -> S3Result<S3Response<AbortMultipartUploadOutput>> {
self.0
.lock()
.expect("probe state")
.calls
.push(("AbortMultipartUpload", Some(req.input.upload_id)));
Ok(S3Response::new(AbortMultipartUploadOutput::default()))
}
async fn delete_bucket_policy(
&self,
_: S3Request<DeleteBucketPolicyInput>,
) -> S3Result<S3Response<DeleteBucketPolicyOutput>> {
self.0.lock().expect("probe state").calls.push(("DeleteBucketPolicy", None));
Ok(S3Response::new(DeleteBucketPolicyOutput::default()))
}
async fn get_object_acl(&self, _: S3Request<GetObjectAclInput>) -> S3Result<S3Response<GetObjectAclOutput>> {
self.0.lock().expect("probe state").calls.push(("GetObjectAcl", None));
Ok(S3Response::new(GetObjectAclOutput::default()))
}
async fn put_object_acl(&self, _: S3Request<PutObjectAclInput>) -> S3Result<S3Response<PutObjectAclOutput>> {
self.0.lock().expect("probe state").calls.push(("PutObjectAcl", None));
Ok(S3Response::new(PutObjectAclOutput::default()))
}
async fn get_bucket_acl(&self, _: S3Request<GetBucketAclInput>) -> S3Result<S3Response<GetBucketAclOutput>> {
self.0.lock().expect("probe state").calls.push(("GetBucketAcl", None));
Ok(S3Response::new(GetBucketAclOutput::default()))
}
async fn put_bucket_acl(&self, _: S3Request<PutBucketAclInput>) -> S3Result<S3Response<PutBucketAclOutput>> {
self.0.lock().expect("probe state").calls.push(("PutBucketAcl", None));
Ok(S3Response::new(PutBucketAclOutput::default()))
}
}
struct CustomRoute;
struct MethodValidation;
#[async_trait]
impl S3Access for MethodValidation {
async fn check(&self, context: &mut S3AccessContext<'_>) -> S3Result<()> {
validate_method_subresource(context.method(), context.uri().query()).map_err(|violation| match violation {
RequestViolation::DeleteAcl => s3_error!(MethodNotAllowed),
})
}
}
#[derive(Clone)]
struct CustomRouteMatched;
#[async_trait]
impl S3Route for CustomRoute {
fn is_match(&self, _: &Method, uri: &Uri, _: &HeaderMap, extensions: &mut Extensions) -> bool {
if uri.path() == "/custom" {
extensions.insert(CustomRouteMatched);
return true;
}
false
}
async fn check_access(&self, req: &mut S3Request<Body>) -> S3Result<()> {
assert!(req.extensions.get::<CustomRouteMatched>().is_some());
if req.headers.contains_key("x-test-deny") {
return Err(s3_error!(AccessDenied));
}
assert!(req.credentials.is_some(), "custom route retains verified credentials");
Ok(())
}
async fn call(&self, req: S3Request<Body>) -> S3Result<S3Response<Body>> {
assert!(req.extensions.get::<CustomRouteMatched>().is_some());
Ok(S3Response::new(Body::from("custom route".to_owned())))
}
}
fn service(virtual_host: bool) -> (S3Service, ProbeS3) {
let probe = ProbeS3::default();
let mut builder = S3ServiceBuilder::new(probe.clone());
builder.set_auth(SimpleAuth::from_single("test-key", "test-secret"));
builder.set_access(MethodValidation);
builder.set_route(CustomRoute);
let mut config = s3s::config::S3Config::default();
config.enable_sig_v2 = true;
config.normalize_forward_slash_path = true;
builder.set_config(Arc::new(s3s::config::StaticConfigProvider::new(Arc::new(config))));
if virtual_host {
builder.set_host(SingleDomain::new("s3.example.test").expect("test domain"));
}
(builder.build(), probe)
}
fn signed_request(method: Method, uri: &str, presigned: bool, secret: &str) -> Request<Body> {
signed_request_with_credentials(method, uri, presigned, "test-key", secret)
}
fn signed_request_with_credentials(method: Method, uri: &str, presigned: bool, access_key: &str, secret: &str) -> Request<Body> {
let uri: Uri = uri.parse().expect("test URI");
let host = uri.authority().expect("test authority").as_str();
let timestamp = OffsetDateTime::now_utc()
.format(format_description!("[year][month][day]T[hour][minute][second]Z"))
.expect("format SigV4 timestamp");
let date = AmzDate::parse(&timestamp).expect("test date");
let credential = format!("{access_key}/{}/us-east-1/s3/aws4_request", date.fmt_date());
let mut query: Vec<(String, String)> = url::form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes())
.into_owned()
.collect();
let mut request = Request::builder()
.method(method.clone())
.header("host", host)
.header("content-length", "0");
if presigned {
query.extend([
("X-Amz-Algorithm".into(), "AWS4-HMAC-SHA256".into()),
("X-Amz-Credential".into(), credential),
("X-Amz-Date".into(), timestamp),
("X-Amz-Expires".into(), "300".into()),
("X-Amz-SignedHeaders".into(), "host".into()),
]);
let canonical = create_presigned_canonical_request(method.as_str(), uri.path(), &query, [("host", host)]);
let to_sign = create_string_to_sign(&canonical, &date, "us-east-1", "s3");
query.push(("X-Amz-Signature".into(), calculate_signature(&to_sign, secret, &date, "us-east-1", "s3")));
let query = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(&query)
.finish();
request = request.uri(format!("http://{host}{}?{query}", uri.path()));
} else {
let canonical = create_canonical_request(
method.as_str(),
uri.path(),
&query,
[
("host", host),
("x-amz-content-sha256", EMPTY_STRING_SHA256_HASH),
("x-amz-date", &timestamp),
],
Payload::SingleChunk(EMPTY_STRING_SHA256_HASH),
);
let to_sign = create_string_to_sign(&canonical, &date, "us-east-1", "s3");
let signature = calculate_signature(&to_sign, secret, &date, "us-east-1", "s3");
request = request
.uri(uri.clone())
.header("x-amz-date", timestamp)
.header("x-amz-content-sha256", EMPTY_STRING_SHA256_HASH)
.header("authorization", format!("AWS4-HMAC-SHA256 Credential={credential}, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature={signature}"));
}
request.body(Body::empty()).expect("signed request")
}
async fn response(service: &S3Service, request: Request<Body>) -> (StatusCode, String) {
let response = service.call(request).await.expect("S3 service response");
let status = response.status();
let bytes = response.into_body().collect().await.expect("response body").to_bytes();
(status, String::from_utf8(bytes.to_vec()).expect("UTF-8 test response"))
}
#[tokio::test]
async fn delete_acl_preserves_objects_and_buckets_for_signed_requests() {
for virtual_host in [false, true] {
let base = if virtual_host {
"http://bucket.s3.example.test"
} else {
"http://s3.example.test/bucket"
};
for presigned in [false, true] {
let (service, probe) = service(virtual_host);
for path in ["", "/", "/key"] {
for query in [
"acl",
"acl=",
"%61cl",
"a%63l=anything",
"acl&acl=",
"acl&versionId=version-1",
"acl&tagging",
"acl&uploadId=upload-1",
] {
let uri = format!("{base}{path}?{query}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{uri}: {body}");
assert!(body.contains("<Code>MethodNotAllowed</Code>"), "{uri}: {body}");
}
let operation = if path == "/key" { "DeleteObject" } else { "DeleteBucket" };
let uri = format!("{base}{path}?acl&x-id={operation}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{uri}: {body}");
}
assert!(
probe.0.lock().expect("probe state").calls.is_empty(),
"refused requests must not reach S3 handlers"
);
let (status, body) =
response(&service, signed_request(Method::GET, &format!("{base}/key"), presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "original object");
let (status, _) =
response(&service, signed_request(Method::HEAD, &format!("{base}/"), presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK, "bucket must still exist");
}
}
}
#[tokio::test]
async fn delete_acl_keeps_signature_verification_before_method_rejection() {
let (service, probe) = service(false);
for presigned in [false, true] {
for query in ["acl", "versionId=version-1"] {
let uri = format!("http://s3.example.test/bucket/key?{query}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "wrong-secret")).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.contains("<Code>SignatureDoesNotMatch</Code>"), "{body}");
}
}
assert!(probe.0.lock().expect("probe state").calls.is_empty());
}
#[tokio::test]
async fn delete_acl_keeps_supported_s3_operations_and_parameters() {
for presigned in [false, true] {
for (method, path, operation, parameter) in [
(Method::DELETE, "/bucket/key", "DeleteObject", None),
(Method::DELETE, "/bucket/key?versionId=version-1", "DeleteObject", Some("version-1")),
(
Method::DELETE,
"/bucket/key?versionId=null&x-id=DeleteObject",
"DeleteObject",
Some("null"),
),
(Method::DELETE, "/bucket/key?custom=value&other=acl", "DeleteObject", None),
(Method::DELETE, "/bucket/key?ACL&acl-extra&%2561cl", "DeleteObject", None),
(
Method::DELETE,
"/bucket/key?tagging&versionId=version-1",
"DeleteObjectTagging",
Some("version-1"),
),
(Method::DELETE, "/bucket/key?uploadId=upload-1", "AbortMultipartUpload", Some("upload-1")),
(Method::DELETE, "/bucket", "DeleteBucket", None),
(Method::DELETE, "/bucket?policy", "DeleteBucketPolicy", None),
(Method::GET, "/bucket/key?acl", "GetObjectAcl", None),
(Method::PUT, "/bucket/key?acl", "PutObjectAcl", None),
(Method::GET, "/bucket?acl", "GetBucketAcl", None),
(Method::PUT, "/bucket?acl", "PutBucketAcl", None),
] {
let (service, probe) = service(false);
let uri = format!("http://s3.example.test{path}");
let (status, body) = response(&service, signed_request(method, &uri, presigned, "test-secret")).await;
assert!(status.is_success(), "{operation} {uri}: {status} {body}");
assert_eq!(probe.0.lock().expect("probe state").calls, [(operation, parameter.map(str::to_owned))]);
}
}
}
#[tokio::test]
async fn delete_acl_preserves_custom_route_matching_and_access() {
let (service, probe) = service(false);
for presigned in [false, true] {
let uri = "http://s3.example.test/custom?acl";
let (status, body) = response(&service, signed_request(Method::DELETE, uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "custom route");
let mut denied = signed_request(Method::DELETE, uri, presigned, "test-secret");
denied
.headers_mut()
.insert("x-test-deny", http::HeaderValue::from_static("true"));
let (status, body) = response(&service, denied).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.contains("<Code>AccessDenied</Code>"));
}
assert!(probe.0.lock().expect("probe state").calls.is_empty());
}
#[tokio::test]
async fn delete_acl_preserves_sigv2_header_and_query_authentication() {
for presigned in [false, true] {
for (query, secret, expected_status, expected_code) in [
("acl", "test-secret", StatusCode::METHOD_NOT_ALLOWED, Some("MethodNotAllowed")),
("acl", "wrong-secret", StatusCode::FORBIDDEN, Some("SignatureDoesNotMatch")),
("versionId=version-1", "test-secret", StatusCode::NO_CONTENT, None),
] {
let (service, probe) = service(false);
let date = OffsetDateTime::now_utc()
.format(format_description!(
"[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT"
))
.expect("format SigV2 HTTP date");
let request = Request::builder()
.method(Method::DELETE)
.uri(format!("http://s3.example.test/bucket/key?{query}"))
.header("host", "s3.example.test")
.header("content-length", "0")
.header("date", date)
.body(Body::empty())
.expect("SigV2 request");
let request = if presigned {
let mut request =
rustfs_signer::try_pre_sign_v2(request, "test-key", secret, 60, false).expect("presign SigV2 request");
let uri = request.uri().to_string();
let (prefix, signature) = uri.rsplit_once("&Signature=").expect("SigV2 signature");
let encoded = url::form_urlencoded::Serializer::new(String::new())
.append_pair("Signature", signature)
.finish();
*request.uri_mut() = format!("{prefix}&{encoded}").parse().expect("encoded SigV2 URI");
request
} else {
rustfs_signer::try_sign_v2(request, 0, "test-key", secret, false).expect("sign SigV2 request")
};
let (status, body) = response(&service, request).await;
assert_eq!(status, expected_status, "{query}: {body}");
if let Some(code) = expected_code {
assert!(body.contains(&format!("<Code>{code}</Code>")), "{body}");
assert!(probe.0.lock().expect("probe state").calls.is_empty());
} else {
assert_eq!(probe.0.lock().expect("probe state").calls, [("DeleteObject", Some("version-1".into()))]);
}
}
}
}
async fn live_delete(
env: &crate::common::RustFSTestEnvironment,
path: &str,
presigned: bool,
secret: &str,
) -> (StatusCode, String) {
let request =
signed_request_with_credentials(Method::DELETE, &format!("{}{path}", env.url), presigned, &env.access_key, secret);
let response = crate::common::local_http_client()
.delete(request.uri().to_string())
.headers(request.headers().clone())
.send()
.await
.expect("send signed DELETE to RustFS");
let status = response.status();
(status, response.text().await.expect("read DELETE response"))
}
#[tokio::test]
async fn delete_acl_admission_through_gateway_edge() {
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{BucketVersioningStatus, Tag, Tagging, VersioningConfiguration};
let mut env = crate::common::RustFSTestEnvironment::new()
.await
.expect("isolated S3 environment");
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_REGION", "us-east-1")])
.await
.expect("start RustFS");
let client = env.create_s3_client();
let bucket = "acl-admission";
let empty_bucket = "acl-admission-empty";
env.create_test_bucket(bucket).await.expect("create object bucket");
env.create_test_bucket(empty_bucket).await.expect("create empty bucket");
client
.put_bucket_versioning()
.bucket(bucket)
.versioning_configuration(
VersioningConfiguration::builder()
.status(BucketVersioningStatus::Enabled)
.build(),
)
.send()
.await
.expect("enable versioning");
let object = client
.put_object()
.bucket(bucket)
.key("key")
.body(ByteStream::from_static(b"original object"))
.send()
.await
.expect("create preserved object");
let version = object.version_id().expect("versioned object ID");
let version_query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("versionId", version)
.finish();
// The gateway wire parser refuses escaped parameter names before signature verification.
let encoded_path = format!("/{bucket}/key?%61cl&{version_query}");
let (status, body) = live_delete(&env, &encoded_path, false, &env.secret_key).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{encoded_path}: {body}");
assert!(body.contains("<Code>InvalidArgument</Code>"), "{body}");
for presigned in [false, true] {
// SigV4 canonicalization rejects repeated parameter names before admission.
let repeated_path = format!("/{bucket}/key?acl&acl=&tagging");
let (status, body) = live_delete(&env, &repeated_path, presigned, &env.secret_key).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{repeated_path}: {body}");
assert!(body.contains("<Code>AuthorizationHeaderMalformed</Code>"), "{body}");
for path in [
format!("/{empty_bucket}?acl"),
format!("/{bucket}/key?acl&{version_query}"),
format!("/{bucket}/key?acl&tagging"),
format!("/{bucket}/key?acl&uploadId=upload-1"),
] {
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{path}: {body}");
assert!(body.contains("<Code>MethodNotAllowed</Code>"), "{body}");
let (status, body) = live_delete(&env, &path, presigned, "wrong-secret").await;
assert_eq!(status, StatusCode::FORBIDDEN, "{path}: {body}");
assert!(body.contains("<Code>SignatureDoesNotMatch</Code>"), "{body}");
}
client
.head_bucket()
.bucket(empty_bucket)
.send()
.await
.expect("refused DELETE preserves empty bucket");
let current = client
.get_object()
.bucket(bucket)
.key("key")
.send()
.await
.expect("refused DELETE leaves the current object readable");
assert_eq!(current.version_id(), Some(version));
let body = current.body.collect().await.expect("read preserved object").into_bytes();
assert_eq!(body.as_ref(), b"original object");
client
.put_object_tagging()
.bucket(bucket)
.key("key")
.version_id(version)
.tagging(
Tagging::builder()
.tag_set(Tag::builder().key("test").value("acl").build().expect("tag"))
.build()
.expect("tagging"),
)
.send()
.await
.expect("set object tags");
let path = format!("/{bucket}/key?tagging&{version_query}");
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert!(status.is_success(), "{path}: {body}");
let tags = client
.get_object_tagging()
.bucket(bucket)
.key("key")
.version_id(version)
.send()
.await
.expect("read cleared tags");
assert!(tags.tag_set().is_empty());
let upload = client
.create_multipart_upload()
.bucket(bucket)
.key("upload")
.send()
.await
.expect("start multipart upload");
let query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("uploadId", upload.upload_id().expect("upload ID"))
.finish();
let path = format!("/{bucket}/upload?{query}");
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert!(status.is_success(), "{path}: {body}");
let uploads = client
.list_multipart_uploads()
.bucket(bucket)
.send()
.await
.expect("list remaining uploads");
assert!(uploads.uploads().is_empty());
}
let path = format!("/{bucket}/key?{version_query}");
let (status, body) = live_delete(&env, &path, false, &env.secret_key).await;
assert_eq!(status, StatusCode::NO_CONTENT, "{path}: {body}");
let versions = client
.list_object_versions()
.bucket(bucket)
.send()
.await
.expect("list remaining versions");
assert!(versions.versions().is_empty());
let (status, body) = live_delete(&env, &format!("/{empty_bucket}"), false, &env.secret_key).await;
assert_eq!(status, StatusCode::NO_CONTENT, "{body}");
env.stop_server();
}
+1 -52
View File
@@ -34,10 +34,7 @@
#[cfg(test)]
mod tests {
use crate::common::{
AdminTransport, RustFSTestEnvironment, admin_attach_user_policy_via, admin_create_user, admin_request_with_session_token,
init_logging, local_http_client, parse_assume_role_credentials,
};
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
use hmac::{Hmac, KeyInit as _, Mac};
use http::header::HOST;
use rustfs_s3_types::Body;
@@ -399,54 +396,6 @@ mod tests {
let (status, _) = signed_request(&env.url, http::Method::GET, ACCOUNT_INFO_PATH, None, user_ak, old_sk).await?;
assert!(status.is_client_error(), "the old secret must stop working, status: {status}");
env.stop_server();
drop(env);
console_session_rotates_the_iam_password_and_revokes_the_old_session().await
}
async fn console_session_rotates_the_iam_password_and_revokes_the_old_session() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server(vec![]).await?;
let user = "console-password-user";
let old_password = uuid::Uuid::new_v4().to_string();
let new_password = uuid::Uuid::new_v4().to_string();
admin_create_user(&env, user, &old_password).await?;
admin_attach_user_policy_via(AdminTransport::Signed, &env.url, &env.access_key, &env.secret_key, "readonly", user)
.await?;
let (status, response) = assume_role(&env.url, user, &old_password, None).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the current password must sign in");
let (session_key, session_secret, token) = parse_assume_role_credentials(&response)?;
let session_request = |method, path, body| {
admin_request_with_session_token(&env.url, method, path, body, &session_key, &session_secret, Some(&token))
};
let password_request = |current: &str| {
Some(serde_json::json!({ "current_secret_key": current, "new_secret_key": new_password }).to_string())
};
let (status, body) =
session_request(http::Method::POST, ACCOUNT_PASSWORD_PATH, password_request(&session_secret)).await?;
assert_eq!(
status,
reqwest::StatusCode::BAD_REQUEST,
"the session secret must not be accepted as the IAM password"
);
assert!(body.contains("InvalidRequest") && body.contains("the current secret key is incorrect"));
let (status, body) = session_request(http::Method::POST, ACCOUNT_PASSWORD_PATH, password_request(&old_password)).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the same session must accept the current IAM password");
assert_eq!(serde_json::from_str::<serde_json::Value>(&body)?["sessions_revoked"], 1);
let (status, _) = session_request(http::Method::GET, ACCOUNT_INFO_PATH, None).await?;
assert_eq!(status, reqwest::StatusCode::FORBIDDEN, "the pre-rotation session must be revoked");
let (status, _) = assume_role(&env.url, user, &old_password, None).await?;
assert_eq!(status, reqwest::StatusCode::FORBIDDEN, "the old password must no longer sign in");
let (status, response) = assume_role(&env.url, user, &new_password, None).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the new password must sign in");
parse_assume_role_credentials(&response)?;
env.stop_server();
Ok(())
}
-1
View File
@@ -36,7 +36,6 @@ mod replication_delete_marker_test;
mod replication_quota_test;
mod s3_basic_test;
mod s3_during_data_movement_test;
mod scanner_cluster_observation_test;
mod scanner_heal_topology_fixture;
mod scanner_heal_topology_test;
mod scanner_heal_topology_tier_test;
@@ -159,7 +159,6 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
let info_body = cluster_admin_ok(&dist.cluster, Method::GET, "/rustfs/admin/v3/info", None).await?;
let info: Value = serde_json::from_str(&info_body)?;
assert!(info.get("inventory").is_none(), "inventory requires explicit opt-in");
let servers = info["info"]["servers"]
.as_array()
.ok_or_else(|| format!("admin info omitted servers: {info}"))?;
@@ -201,24 +200,6 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
assert!(sample.finally, "node {node_idx} metrics sample was not terminal");
assert!(sample.errors.is_empty(), "node {node_idx} metrics reported errors: {:?}", sample.errors);
assert!(!sample.hosts.is_empty(), "node {node_idx} metrics omitted hosts");
assert!(sample.scanner_node.is_none(), "default metrics must not expose the internal peer sample");
wait_until(
Duration::from_secs(30),
|| async {
let frame: Value = serde_json::from_str(
&node_admin_body(&dist, node_idx, "/rustfs/admin/v3/realtime?scope=cluster&types=1&n=1").await?,
)?;
assert_eq!(frame["final"], true);
let summary = &frame["cluster_scanner"];
assert_eq!(summary["nodes_total"], 4, "known cluster membership");
assert!(summary["sampled_at"].as_str().is_some());
assert!(matches!(summary["state"].as_str(), Some("scanning" | "idle" | "unknown")));
assert_eq!(summary["current"].is_object(), summary["state"] == "scanning");
Ok(summary["nodes_responded"] == 4)
},
"every request node reaches the full scanner peer set",
)
.await?;
}
let targets_body = cluster_admin_ok(&dist.cluster, Method::GET, "/rustfs/admin/v3/audit/target/list", None).await?;
@@ -253,38 +234,6 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
"audit entry leaked the root secret key"
);
let pending = unique_bucket("inventory");
dist.create_bucket(&pending).await?;
let listed = dist.client(1)?.list_buckets().send().await?;
assert_eq!(listed.buckets().len(), 2, "expected the two test buckets");
wait_until(
Duration::from_secs(30),
|| async {
let body = node_admin_body(&dist, 1, "/rustfs/admin/v3/info?include=inventory").await?;
let response: Value = serde_json::from_str(&body)?;
let inventory: rustfs_madmin::ClusterInventory = serde_json::from_value(response["inventory"].clone())?;
if inventory.current_buckets != Some(2) {
return Ok(false);
}
match inventory.measured_buckets {
None | Some(0) => {
assert_eq!(inventory.measured_objects, None);
assert_eq!(inventory.measured_bytes, None);
}
Some(1 | 2) => {
assert!(inventory.measured_objects.is_some_and(|objects| objects <= 1));
}
Some(count) => panic!("measured {count} buckets across a two-bucket namespace"),
}
if inventory.measured_buckets != Some(2) {
assert_ne!(inventory.converged, Some(true));
}
Ok(true)
},
"inventory reflects the current namespace and reports scanner coverage independently",
)
.await?;
let result = verify_write_observations_during_peer_failure(&dist, &bucket).await;
collector.abort();
result
@@ -1,111 +0,0 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
use super::harness::{NODE_COUNT, TestResult, wait_until};
use super::scanner_peer_bucket_fixture::PeerBucketRun;
use crate::common::init_logging;
use futures::future::try_join_all;
use serde_json::Value;
use std::time::Duration;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
const CLUSTER_SCANNER: &str = "/rustfs/admin/v3/realtime?n=1&types=1&scope=cluster";
const OBSERVATION_TIMEOUT: Duration = Duration::from_secs(35);
async fn scanner_frames(run: &PeerBucketRun) -> TestResult<Vec<Value>> {
try_join_all((0..NODE_COUNT).map(|node| run.admin_json(node, CLUSTER_SCANNER))).await
}
fn full_sample(frame: &Value) -> bool {
frame["final"] == true
&& frame["cluster_scanner"]["nodes_total"] == NODE_COUNT
&& frame["cluster_scanner"]["nodes_responded"] == NODE_COUNT
}
#[tokio::test]
async fn followers_report_the_coordinators_active_progress_and_committed_completion() -> TestResult {
init_logging();
let mut run = PeerBucketRun::start("cluster-scanner-observation").await?;
let baseline = run.quiet_baseline().await?;
let leader = run.leader().await?;
let pid = run.pid(leader)?;
let hot = run.buckets[2].clone();
run.barrier.arm("before_start_snapshot", pid, None)?;
run.barrier.start_session(&run.buckets)?;
// All four child processes and the harness use the same host clock.
let written_after = OffsetDateTime::now_utc();
run.put(leader, &hot, "wake-cluster-observation", 149).await?;
let start = run.barrier.wait_stage("before_start_snapshot", pid, None, true).await?;
let epoch = start["detail"]["epoch"].as_u64().ok_or("start gate omitted epoch")?;
let cycle = start["detail"]["cycle"].as_u64().ok_or("start gate omitted cycle")?;
if baseline.scanner_epoch != Some(epoch) || baseline.scanner_cycle.is_none_or(|previous| previous >= cycle) {
return Err("controlled cycle did not follow the quiet baseline under the same coordinator".into());
}
run.barrier.arm("root_durable", pid, Some((epoch, cycle)))?;
run.barrier.release("before_start_snapshot", pid)?;
run.barrier
.wait_stage("root_durable", pid, Some((epoch, cycle)), true)
.await?;
// The leader is held after the real walk and before committing its cycle completion.
// Each ingress node maintains its own short-lived cluster sample cache.
let expected_leader = &run.dist.cluster.nodes[leader].url;
let active = wait_until(
OBSERVATION_TIMEOUT,
|| async {
let frames = scanner_frames(&run).await?;
let started = frames[leader]["cluster_scanner"]["current"]["started_at"].as_str();
let consistent = started.is_some()
&& frames.iter().all(|frame| {
let summary = &frame["cluster_scanner"];
let current = &summary["current"];
full_sample(frame)
&& summary["state"] == "scanning"
&& current["cycle"] == cycle
&& current["leader"].as_str() == Some(expected_leader.as_str())
&& current["started_at"].as_str() == started
&& current["objects_scanned"].as_u64().is_some_and(|objects| objects > 0)
});
if !consistent {
tracing::info!(
?frames,
cycle,
expected_leader,
"waiting for active scanner progress on every ingress node"
);
}
Ok(consistent)
},
"leader and all three followers report the identified active cycle with nonzero work",
)
.await;
run.barrier.disarm()?;
run.barrier.release("root_durable", pid)?;
active?;
wait_until(
OBSERVATION_TIMEOUT,
|| async {
let frames = scanner_frames(&run).await?;
let settled = frames.iter().all(|frame| {
let summary = &frame["cluster_scanner"];
full_sample(frame)
&& summary["state"] == "idle"
&& summary.get("current").is_none()
&& summary["last_attempt"]["cycle"] == cycle
&& summary["last_attempt"]["result"] == "success"
&& summary["last_success_at"].as_str().is_some_and(|value| {
OffsetDateTime::parse(value, &Rfc3339).is_ok_and(|completed| completed >= written_after)
})
});
if !settled {
tracing::info!(?frames, cycle, "waiting for the controlled scanner cycle to finish");
}
Ok(settled)
},
"every ingress node reports the completed cycle and an idle cluster scanner",
)
.await
}
-6
View File
@@ -12,9 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(test)]
mod access_request_validation_test;
#[cfg(test)]
mod storage_metric_ownership_test;
@@ -108,9 +105,6 @@ mod replication_target_matrix_test;
#[cfg(test)]
mod data_usage_test;
#[cfg(test)]
mod scanner_wide_directory_test;
// KMS-specific test modules
#[cfg(test)]
mod kms;
@@ -864,70 +864,6 @@ async fn test_webhook_event_delivery_and_filtering() -> TestResult {
Ok(())
}
#[tokio::test]
async fn test_webhook_subscriptions_follow_bucket_incarnation() -> TestResult {
init_logging();
let (endpoint, mut rx, collector) = spawn_event_collector().await?;
let allowed_origin = endpoint_origin(&endpoint)?;
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[(ENV_OUTBOUND_ALLOW_ORIGINS, allowed_origin.as_str())])
.await?;
enable_notify_module(&env).await?;
let target = "incarnation";
configure_webhook_target(&env, target, &endpoint).await?;
wait_for_target_registered(&env, target).await?;
let client = env.create_s3_client();
let bucket = "notify-incarnation";
let control_bucket = "notify-incarnation-control";
for name in [bucket, control_bucket] {
client.create_bucket().bucket(name).send().await?;
put_notification_config(&client, name, target, "events/", ".txt").await?;
}
let put = |bucket, key| {
client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from_static(b"event fixture"))
.send()
};
let wait = Duration::from_secs(20);
let original_key = "events/original.txt";
put(bucket, original_key).await?;
wait_for_event(&mut rx, original_key, "s3:ObjectCreated:", wait).await?;
assert!(client.delete_bucket().bucket(bucket).send().await.is_err());
let after_failed_delete = "events/retained.txt";
put(bucket, after_failed_delete).await?;
wait_for_event(&mut rx, after_failed_delete, "s3:ObjectCreated:", wait).await?;
for key in [original_key, after_failed_delete] {
client.delete_object().bucket(bucket).key(key).send().await?;
}
client.delete_bucket().bucket(bucket).send().await?;
client.create_bucket().bucket(bucket).send().await?;
let config = client.get_bucket_notification_configuration().bucket(bucket).send().await?;
assert!(config.queue_configurations().is_empty());
let new_key = "events/fresh.txt";
let sentinel_key = "events/sentinel.txt";
put(bucket, new_key).await?;
put(control_bucket, sentinel_key).await?;
let events = collect_until(&mut rx, sentinel_key, wait, Duration::from_secs(2)).await;
assert!(events.iter().any(|event| event_key(event).as_deref() == Some(sentinel_key)));
assert!(events.iter().all(|event| event_key(event).as_deref() != Some(new_key)));
put_notification_config(&client, bucket, target, "events/", ".txt").await?;
let subscribed_key = "events/subscribed.txt";
put(bucket, subscribed_key).await?;
wait_for_event(&mut rx, subscribed_key, "s3:ObjectCreated:", wait).await?;
env.stop_server();
collector.abort();
Ok(())
}
/// An event queued while the target endpoint rejects delivery survives on the
/// durable store and is redelivered once the endpoint comes back.
#[tokio::test]
@@ -1026,101 +962,3 @@ async fn test_webhook_redelivers_event_after_target_recovers() -> TestResult {
handle.abort();
Ok(())
}
#[tokio::test]
async fn test_webhook_metadata_mutations_keep_verified_bucket_identity() -> TestResult {
init_logging();
let (endpoint, mut rx, collector) = spawn_event_collector().await?;
let allowed_origin = endpoint_origin(&endpoint)?;
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[(ENV_OUTBOUND_ALLOW_ORIGINS, allowed_origin.as_str())])
.await?;
enable_notify_module(&env).await?;
let target = "metadata-events";
configure_webhook_target(&env, target, &endpoint).await?;
wait_for_target_registered(&env, target).await?;
let client = env.create_s3_client();
let bucket = "metadata-event-identity";
let key = "object";
client.create_bucket().bucket(bucket).send().await?;
client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from_static(b"metadata"))
.send()
.await?;
let queue = QueueConfiguration::builder()
.id("metadata-events")
.queue_arn(target_arn(target))
.events(Event::from("s3:ObjectTagging:*"))
.events(Event::from("s3:ObjectAcl:Put"))
.events(Event::from("s3:BucketRemoved:*"))
.build()?;
client
.put_bucket_notification_configuration()
.bucket(bucket)
.notification_configuration(NotificationConfiguration::builder().queue_configurations(queue).build())
.send()
.await?;
let tagging = aws_sdk_s3::types::Tagging::builder()
.tag_set(aws_sdk_s3::types::Tag::builder().key("kind").value("test").build()?)
.build()?;
client
.put_object_tagging()
.bucket(bucket)
.key(key)
.tagging(tagging)
.send()
.await?;
assert_eq!(
client
.get_object_tagging()
.bucket(bucket)
.key(key)
.send()
.await?
.tag_set()
.len(),
1
);
wait_for_event(&mut rx, key, "s3:ObjectTagging:Put", Duration::from_secs(20)).await?;
client.delete_object_tagging().bucket(bucket).key(key).send().await?;
assert!(
client
.get_object_tagging()
.bucket(bucket)
.key(key)
.send()
.await?
.tag_set()
.is_empty()
);
wait_for_event(&mut rx, key, "s3:ObjectTagging:Delete", Duration::from_secs(20)).await?;
client
.put_object_acl()
.bucket(bucket)
.key(key)
.acl(aws_sdk_s3::types::ObjectCannedAcl::Private)
.send()
.await?;
wait_for_event(&mut rx, key, "s3:ObjectAcl:Put", Duration::from_secs(20)).await?;
client.delete_object().bucket(bucket).key(key).send().await?;
client.delete_bucket().bucket(bucket).send().await?;
let removed = timeout(Duration::from_secs(20), async {
loop {
let event = rx.recv().await.expect("bucket-event collector remains open");
if event["EventName"]
.as_str()
.is_some_and(|name| name.starts_with("s3:BucketRemoved:"))
{
break event;
}
}
})
.await?;
assert_eq!(removed["Records"][0]["s3"]["bucket"]["name"].as_str(), Some(bucket));
env.stop_server();
collector.abort();
Ok(())
}
@@ -24,7 +24,7 @@
#[cfg(all(test, target_os = "linux"))]
mod tests {
use crate::chaos::{VersionShardCensus, census_object_version_on_disk};
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging, local_http_client};
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging};
use aws_sdk_s3::Client;
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, VersioningConfiguration};
@@ -412,7 +412,7 @@ mod tests {
.arg(test_binary)
.arg("--exact")
.arg(test_name)
.arg("--include-ignored")
.arg("--ignored")
.arg("--nocapture")
.env(NAMESPACE_ENV, "1")
.status()?;
@@ -1524,110 +1524,6 @@ mod tests {
assert!(assert_no_replacement_status_records_in_status(&definitive, target).is_ok());
}
/// Linux mount namespaces are per-thread; keep mount setup and process
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
#[tokio::test(flavor = "current_thread")]
async fn test_privileged_4x1_subdirectory_replacement_waits_for_write_quorum() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
if !privileged_run_enabled()? {
return Ok(());
}
if std::env::var_os(NAMESPACE_ENV).is_none() {
return run_current_test_in_mount_namespace(
"replacement_privileged_e2e_test::tests::test_privileged_4x1_subdirectory_replacement_waits_for_write_quorum",
);
}
let mut mounts = MountNamespaceGuard::new()?;
let mut cluster = RustFSTestClusterEnvironment::new(4).await?;
let filesystem: serde_json::Value = serde_json::from_str(&run_command_stdout(
"findmnt",
&["--json", "--target", &cluster.temp_dir, "--output", "TARGET,FSTYPE"],
)?)?;
let xfs_root = filesystem["filesystems"][0]["target"]
.as_str()
.filter(|root| *root != "/" && filesystem["filesystems"][0]["fstype"] == "xfs");
for (index, node) in cluster.nodes.iter_mut().enumerate() {
let mount = PathBuf::from(&node.data_dir);
if xfs_root.is_none() {
mounts.mount_tmpfs(&mount, &format!("rustfs-replacement-4x1-{index}"))?;
}
let data = mount.join("data");
fs::create_dir(&data)?;
node.data_dir = path_to_string(&data, "replacement subdirectory")?;
node.data_dirs[0] = node.data_dir.clone();
}
let target = PathBuf::from(&cluster.nodes[TARGET_NODE].data_dir);
let mount = xfs_root.unwrap_or(target.parent().and_then(Path::to_str).ok_or("missing target mount root")?);
eprintln!(
"4x1 replacement fixture filesystem = {}",
if xfs_root.is_some() { "xfs" } else { "tmpfs" }
);
cluster.set_node_env(TARGET_NODE, "RUSTFS_HEAL_REPLACEMENT_MOUNT_ROOTS", mount)?;
cluster.set_env("RUSTFS_STORAGE_CLASS_STANDARD", "EC:2");
cluster.set_env("RUSTFS_HEAL_ENABLED", "true");
cluster.set_env("RUSTFS_HEAL_INTERVAL_SECS", "1");
cluster.set_env("RUSTFS_SCANNER_START_DELAY_SECS", "0");
cluster.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false");
cluster.start().await?;
let clients = cluster.create_all_clients()?;
let versions = seed_baseline(&clients[0], &target, 0).await?;
cluster.stop_node_gracefully(TARGET_NODE).await?;
cluster.stop_node_gracefully(0).await?;
fs::remove_dir_all(&target)?;
fs::create_dir(&target)?;
let metadata = ["format.json", "pool.bin/xl.meta", "pool.bin.identity/xl.meta"];
let system_dir = Path::new(".rustfs.sys");
let survivor_files = cluster.nodes[2..]
.iter()
.flat_map(|node| metadata.map(|name| Path::new(&node.data_dir).join(system_dir).join(name)))
.map(|file| fs::read(&file).map(|bytes| (file, bytes)))
.collect::<std::io::Result<Vec<_>>>()?;
cluster.start_node_process(TARGET_NODE).await?;
let write_health = format!("{}/minio/health/cluster", cluster.nodes[2].url);
let http = local_http_client();
timeout(Duration::from_secs(30), async {
loop {
let status = http.get(&write_health).send().await?.status();
if status.as_u16() == 503 {
break;
}
sleep(Duration::from_millis(200)).await;
}
Ok::<_, reqwest::Error>(())
})
.await??;
verify_bodies(&clients[2], &versions).await?;
let version = &versions[0];
let failed_delete = clients[2]
.delete_object()
.bucket(&version.bucket)
.key(&version.key)
.send()
.await
.expect_err("two of four drives must not delete an existing object");
assert_eq!(failed_delete.raw_response().map(|response| response.status().as_u16()), Some(503));
for name in metadata {
assert!(!target.join(system_dir).join(name).try_exists()?, "unadmitted target published {name}");
}
for (file, before) in survivor_files {
assert_eq!(fs::read(&file)?, before, "surviving pool evidence changed below write quorum");
}
cluster.start_node(0).await?;
wait_for_completed_replacement_with_census(&cluster, &target, &versions, 90).await?;
for name in metadata {
assert!(fs::metadata(target.join(system_dir).join(name))?.is_file());
}
cluster.stop_node_gracefully(TARGET_NODE).await?;
cluster.start_node(TARGET_NODE).await?;
assert!(incomplete_versions(&target, &versions)?.is_empty());
verify_bodies(&clients[TARGET_NODE], &versions).await
}
/// Linux mount namespaces are per-thread; keep mount setup and process
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
#[tokio::test(flavor = "current_thread")]
+10 -331
View File
@@ -2075,18 +2075,12 @@ fn replication_response_hold() -> (ReplicationResponseHoldRuntime, ReplicationRe
)
}
#[derive(Clone)]
struct ReplicationProxyGate {
enabled: watch::Receiver<bool>,
blocked_admin_commit_path: Option<&'static str>,
}
async fn forward_replication_proxy_request(
request: Request<Incoming>,
backend_url: &str,
client: &reqwest::Client,
request_count: &AtomicU64,
mut gate: ReplicationProxyGate,
mut replication_enabled: watch::Receiver<bool>,
mut held_tagging: watch::Receiver<Option<String>>,
mut response_hold: ReplicationResponseHoldRuntime,
) -> Response<Full<bytes::Bytes>> {
@@ -2097,8 +2091,8 @@ async fn forward_replication_proxy_request(
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"REPLICA"));
if is_replication {
request_count.fetch_add(1, Ordering::Relaxed);
while !*gate.enabled.borrow() {
if gate.enabled.changed().await.is_err() {
while !*replication_enabled.borrow() {
if replication_enabled.changed().await.is_err() {
return proxy_error_response("replication gate closed");
}
}
@@ -2123,12 +2117,6 @@ async fn forward_replication_proxy_request(
Ok(body) => body.to_bytes(),
Err(error) => return proxy_error_response(error),
};
if gate.blocked_admin_commit_path == Some(parts.uri.path())
&& !*gate.enabled.borrow()
&& serde_json::from_slice::<serde_json::Value>(&body).is_ok_and(|payload| payload["phase"] == "commit")
{
return proxy_error_response("admin commit blocked by replication gate");
}
let mut forwarded = client.request(parts.method, format!("{backend_url}{path_and_query}"));
for (name, value) in &parts.headers {
forwarded = forwarded.header(name, value);
@@ -2165,7 +2153,7 @@ async fn start_replication_counting_proxy(
tasks: &mut JoinSet<()>,
) -> Result<(String, Arc<AtomicU64>, watch::Sender<bool>), Box<dyn Error + Send + Sync>> {
let (proxy_url, request_count, replication_enabled, _held_tagging, _response_hold) =
start_replication_counting_proxy_with_tag_hold(backend_url, tasks, None).await?;
start_replication_counting_proxy_with_tag_hold(backend_url, tasks).await?;
Ok((proxy_url, request_count, replication_enabled))
}
@@ -2173,11 +2161,9 @@ async fn start_replication_counting_proxy(
/// returned `watch::Sender<Option<String>>` holds `Some(tagging)`, replication
/// requests whose `x-amz-tagging` equals `tagging` are parked (and still
/// counted); all other traffic flows. Send `None` to release them.
/// An optional admin commit path rejects its commit phase while the replication gate is closed.
async fn start_replication_counting_proxy_with_tag_hold(
backend_url: &str,
tasks: &mut JoinSet<()>,
blocked_admin_commit_path: Option<&'static str>,
) -> Result<
(
String,
@@ -2194,10 +2180,6 @@ async fn start_replication_counting_proxy_with_tag_hold(
let request_count = Arc::new(AtomicU64::new(0));
let task_request_count = request_count.clone();
let (replication_enabled, task_replication_enabled) = watch::channel(true);
let gate = ReplicationProxyGate {
enabled: task_replication_enabled,
blocked_admin_commit_path,
};
let (held_tagging, task_held_tagging) = watch::channel(None);
let (response_hold_runtime, response_hold) = replication_response_hold();
tasks.spawn(async move {
@@ -2210,7 +2192,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
let backend_url = backend_url.clone();
let client = client.clone();
let request_count = task_request_count.clone();
let gate = gate.clone();
let replication_enabled = task_replication_enabled.clone();
let held_tagging = task_held_tagging.clone();
let response_hold = response_hold_runtime.clone();
connections.spawn(async move {
@@ -2218,7 +2200,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
let backend_url = backend_url.clone();
let client = client.clone();
let request_count = request_count.clone();
let gate = gate.clone();
let replication_enabled = replication_enabled.clone();
let held_tagging = held_tagging.clone();
let response_hold = response_hold.clone();
async move {
@@ -2228,7 +2210,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
&backend_url,
&client,
&request_count,
gate,
replication_enabled,
held_tagging,
response_hold,
)
@@ -2270,309 +2252,6 @@ async fn site_replication_remove(
Ok(serde_json::from_slice(&response.bytes().await?)?)
}
async fn decommission_site_v2(
env: &RustFSTestEnvironment,
request: &rustfs_madmin::SRRemoveV2Req,
) -> Result<rustfs_madmin::SRRemoveV2Status, Box<dyn Error + Send + Sync>> {
let response = signed_request(
http::Method::PUT,
&format!("{}/rustfs/admin/v3/site-replication/remove-v2", env.url),
&env.access_key,
&env.secret_key,
Some(serde_json::to_vec(request)?),
Some("application/json"),
)
.await?;
if response.status() != StatusCode::OK {
return Err(format!("decommission failed: {} {}", response.status(), response.text().await?).into());
}
Ok(response.json().await?)
}
#[tokio::test]
async fn test_site_decommission_dead_peer_recovers_pending_remove_and_bucket_delete() -> Result<(), Box<dyn Error + Send + Sync>>
{
init_logging();
let mut source = RustFSTestEnvironment::new().await?;
let mut target = RustFSTestEnvironment::new().await?;
let mut env = replication_fast_env();
env.extend_from_slice(FAST_SCANNER_ENV);
env.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
source.start_rustfs_server_with_env(vec![], &env).await?;
target.start_rustfs_server_without_cleanup_with_env(&env).await?;
let added = site_replication_add(
&source,
&[
PeerSite {
name: "survivor".to_string(),
endpoint: source.url.clone(),
access_key: source.access_key.clone(),
secret_key: source.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "retired".to_string(),
endpoint: target.url.clone(),
access_key: target.access_key.clone(),
secret_key: target.secret_key.clone(),
..Default::default()
},
],
)
.await?;
assert!(added.success, "{added:?}");
let source_client = source.create_s3_client();
let target_client = target.create_s3_client();
let bucket = "decommission-pending-delete";
source_client.create_bucket().bucket(bucket).send().await?;
wait_for_bucket_on_target(&target_client, bucket).await?;
let version = source_client
.put_object()
.bucket(bucket)
.key("data")
.body(ByteStream::from_static(b"decommission data survives until purge"))
.send()
.await?
.version_id
.ok_or("site bucket must be versioned")?;
wait_for_object_on_target(&target_client, bucket, "data").await?;
target.stop_server();
source_client
.delete_object()
.bucket(bucket)
.key("data")
.version_id(&version)
.send()
.await?;
let blocked = source_client
.delete_bucket()
.bucket(bucket)
.send()
.await
.expect_err("pending version must block delete");
assert_eq!(blocked.code(), Some("BucketNotEmpty"));
let legacy = site_replication_remove(
&source,
&SRRemoveReq {
site_names: vec!["retired".to_string()],
..Default::default()
},
)
.await?;
assert_eq!(legacy.status, "Partial");
assert!(site_replication_info(&source).await?.pending_operation.is_some());
let mut request = rustfs_madmin::SRRemoveV2Req {
mode: "dry-run".to_string(),
sites: vec!["retired".to_string()],
..Default::default()
};
let preview = decommission_site_v2(&source, &request).await?;
assert_eq!(preview.status, "planned");
request.mode = "execute".to_string();
request.operation_id = Some(preview.operation_id.clone());
request.preflight_token = Some(preview.preflight_token);
let removed = decommission_site_v2(&source, &request).await?;
assert_eq!(removed.status, "success", "{removed:?}");
assert_site_replication_bucket_detached(&source, bucket).await?;
assert!(site_replication_info(&source).await?.pending_operation.is_none());
source.restart_server_preserving_data(vec![], &env).await?;
let replay = decommission_site_v2(&source, &request).await?;
assert_eq!(replay.status, "success");
assert_eq!(replay.operation_id, removed.operation_id);
let deadline = tokio::time::Instant::now() + Duration::from_secs(120);
loop {
match source_client.delete_bucket().bucket(bucket).send().await {
Ok(_) => break,
Err(err) if err.code() == Some("BucketNotEmpty") && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(250)).await;
}
Err(err) => return Err(err.into()),
}
}
assert!(source_client.head_bucket().bucket(bucket).send().await.is_err());
Ok(())
}
#[tokio::test]
async fn test_site_decommission_preserves_two_live_sites_and_bidirectional_replication()
-> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut a = RustFSTestEnvironment::new().await?;
let mut b = RustFSTestEnvironment::new().await?;
let mut c = RustFSTestEnvironment::new().await?;
let mut env = replication_fast_env();
env.extend_from_slice(FAST_SCANNER_ENV);
env.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
a.start_rustfs_server_with_env(vec![], &env).await?;
b.start_rustfs_server_without_cleanup_with_env(&env).await?;
c.start_rustfs_server_without_cleanup_with_env(&env).await?;
let mut proxy_tasks = JoinSet::new();
let (c_proxy, _, allow_peer_removal, _, _) = start_replication_counting_proxy_with_tag_hold(
&c.url,
&mut proxy_tasks,
Some("/minio/admin/v3/site-replication/peer/remove-v2"),
)
.await?;
let added = site_replication_add(
&a,
&[
PeerSite {
name: "a".to_string(),
endpoint: a.url.clone(),
access_key: a.access_key.clone(),
secret_key: a.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "b".to_string(),
endpoint: b.url.clone(),
access_key: b.access_key.clone(),
secret_key: b.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "c".to_string(),
endpoint: c.url.clone(),
access_key: c.access_key.clone(),
secret_key: c.secret_key.clone(),
..Default::default()
},
],
)
.await?;
assert!(added.success, "{added:?}");
let info = wait_for_site_replication_enabled(&a, 3).await?;
let retired_id = info
.sites
.iter()
.find(|peer| peer.name == "b")
.ok_or("site b is missing")?
.deployment_id
.clone();
let mut survivor = info
.sites
.into_iter()
.find(|peer| peer.name == "c")
.ok_or("site c is missing")?;
let survivor_id = survivor.deployment_id.clone();
survivor.endpoint = c_proxy;
let edited = site_replication_edit(&a, "", &survivor).await?;
assert!(edited.success, "{edited:?}");
let ca = a.create_s3_client();
let cb = b.create_s3_client();
let cc = c.create_s3_client();
let bucket = "decommission-preserve-live-peers";
let operator_bucket = "decommission-operator-target";
cc.create_bucket().bucket(operator_bucket).send().await?;
enable_bucket_versioning(&c, operator_bucket).await?;
ca.create_bucket().bucket(bucket).send().await?;
wait_for_bucket_on_target(&cb, bucket).await?;
wait_for_bucket_on_target(&cc, bucket).await?;
let operator_arn = set_replication_target(&a, bucket, &c, operator_bucket).await?;
put_bucket_replication(&a, bucket, &operator_arn).await?;
ca.put_object()
.bucket(bucket)
.key("baseline")
.body(ByteStream::from_static(b"baseline"))
.send()
.await?;
wait_for_object_on_target(&cc, bucket, "baseline").await?;
wait_for_object_on_target(&cc, operator_bucket, "baseline").await?;
let retired_rule_id = format!("site-repl-{retired_id}");
let retired_arn = ca
.get_bucket_replication()
.bucket(bucket)
.send()
.await?
.replication_configuration
.ok_or("source bucket replication is missing")?
.rules
.into_iter()
.find(|rule| rule.id.as_deref() == Some(retired_rule_id.as_str()))
.and_then(|rule| rule.destination)
.ok_or("site b replication rule is missing")?
.bucket;
b.stop_server();
let preview_request = rustfs_madmin::SRRemoveV2Req {
mode: "dry-run".to_string(),
sites: vec!["b".to_string()],
..Default::default()
};
let preview = decommission_site_v2(&a, &preview_request).await?;
let request = rustfs_madmin::SRRemoveV2Req {
mode: "execute".to_string(),
operation_id: Some(preview.operation_id.clone()),
preflight_token: Some(preview.preflight_token),
..preview_request.clone()
};
allow_peer_removal.send(false)?;
let partial = decommission_site_v2(&a, &request).await?;
assert_eq!(partial.status, "Partial", "{partial:?}");
assert!(partial.local_cleanup_complete, "{partial:?}");
assert_eq!(partial.pending_peers, [survivor_id]);
assert!(partial.errors.iter().any(|error| error.contains("admin commit blocked")), "{partial:?}");
let prepared = site_replication_info(&c)
.await?
.pending_operation
.ok_or("site c must have prepared")?;
assert_eq!(prepared.id, preview.operation_id);
a.restart_server_preserving_data(vec![], &env).await?;
let restored = decommission_site_v2(&a, &preview_request).await?;
assert_eq!(restored.operation_id, preview.operation_id);
assert_eq!(restored.status, "Partial", "{restored:?}");
assert!(restored.local_cleanup_complete, "{restored:?}");
assert_eq!(restored.pending_peers, partial.pending_peers);
allow_peer_removal.send(true)?;
let result = decommission_site_v2(&a, &request).await?;
assert_eq!(result.status, "success", "{result:?}");
let ia = site_replication_info(&a).await?;
let ic = site_replication_info(&c).await?;
assert!(ia.enabled && ic.enabled);
assert!(ia.pending_operation.is_none() && ic.pending_operation.is_none());
assert_eq!(
ia.sites
.iter()
.map(|peer| peer.deployment_id.clone())
.collect::<std::collections::BTreeSet<_>>(),
ic.sites.iter().map(|peer| peer.deployment_id.clone()).collect()
);
assert!(!ia.sites.iter().any(|peer| peer.name == "b"));
let targets: Vec<serde_json::Value> = list_replication_targets_request(&a, Some(bucket))
.await?
.error_for_status()?
.json()
.await?;
assert!(
targets
.iter()
.any(|target| target["arn"] == operator_arn && target["targetbucket"] == operator_bucket),
"operator target {operator_arn} must survive decommission"
);
assert!(
!targets.iter().any(|target| target["arn"] == retired_arn),
"retired site target {retired_arn} must be removed"
);
ca.put_object()
.bucket(bucket)
.key("a-to-c")
.body(ByteStream::from_static(b"a to c survives"))
.send()
.await?;
assert_eq!(wait_for_object_on_target(&cc, bucket, "a-to-c").await?, b"a to c survives");
assert_eq!(wait_for_object_on_target(&cc, operator_bucket, "a-to-c").await?, b"a to c survives");
cc.put_object()
.bucket(bucket)
.key("c-to-a")
.body(ByteStream::from_static(b"c to a survives"))
.send()
.await?;
assert_eq!(wait_for_object_on_target(&ca, bucket, "c-to-a").await?, b"c to a survives");
c.restart_server_preserving_data(vec![], &env).await?;
assert!(site_replication_info(&c).await?.pending_operation.is_none());
assert_eq!(decommission_site_v2(&a, &request).await?.status, "success");
Ok(())
}
async fn site_replication_state_edit(
env: &RustFSTestEnvironment,
body: &rustfs_madmin::SRStateEditReq,
@@ -8543,7 +8222,7 @@ async fn test_site_replication_tagging_during_initial_pending_window_converges()
_site_b_replication_enabled,
_site_b_held_tagging,
mut site_b_response_hold,
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks).await?;
let add_status = site_replication_add(
&site_a_env,
@@ -8800,9 +8479,9 @@ async fn test_site_replication_tagging_lww_converges_active_active_real_dual_nod
let mut proxy_tasks = JoinSet::new();
let (site_a_proxy, site_a_replication_requests, _site_a_replication_enabled, site_a_held_tagging, _site_a_response_hold) =
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks, None).await?;
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks).await?;
let (site_b_proxy, site_b_replication_requests, _site_b_replication_enabled, site_b_held_tagging, _site_b_response_hold) =
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks).await?;
let site_a_client = site_a_env.create_s3_client();
let site_b_client = site_b_env.create_s3_client();
@@ -1,208 +0,0 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use std::collections::BTreeMap;
use std::path::Path;
use std::time::{Duration, SystemTime};
use aws_sdk_s3::{Client, primitives::ByteStream};
use futures::{StreamExt, TryStreamExt, stream};
use rustfs_data_usage::{BucketUsageValueState, DataUsageInfo};
use serde::{Deserialize, de::DeserializeOwned};
use tokio::time::{Instant, sleep, timeout};
use crate::common::{RustFSTestEnvironment, signed_request};
use crate::storage_api::scanner_peer_bucket::{BUCKET_META_PREFIX, RUSTFS_META_BUCKET};
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
const BUCKET: &str = "wide-directory-usage";
const WIDTH: usize = 512;
// The per-disk token bucket allows an initial burst of one second. Even the
// first pass can read at most (1 + 3) * 96 = 384 of these 512 root entries.
const SCAN_ENV: &[(&str, &str)] = &[
("RUST_LOG", "warn,rustfs::scanner::io=debug,rustfs::scanner::data_usage=debug"),
("RUSTFS_SCANNER_ENABLED", "true"),
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
("RUSTFS_SCANNER_CYCLE", "1"),
("RUSTFS_SCANNER_CYCLE_MAX_DURATION_SECS", "3"),
("RUSTFS_SCANNER_SPEED", "fastest"),
("RUSTFS_SCANNER_DISK_IO_BUDGET_IOPS", "96"),
("RUSTFS_SCANNER_DISK_IO_BUDGET_BYTES_PER_SEC", "off"),
];
#[derive(Debug, Deserialize)]
struct Status {
metrics: Metrics,
disk_io_budget: Vec<DiskBudget>,
}
#[derive(Debug, Deserialize)]
struct Metrics {
current_cycle_active: bool,
active_paths: Vec<String>,
cycle_max_duration_seconds: f64,
partial_cycles_runtime: u64,
}
#[derive(Debug, Deserialize)]
struct DiskBudget {
iops: Option<u64>,
}
async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str) -> TestResult<T> {
let url = format!("{}/rustfs/admin/v3/{resource}", env.url);
let response = signed_request(http::Method::GET, &url, &env.access_key, &env.secret_key, None, None).await?;
Ok(response.error_for_status()?.json().await?)
}
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();
while let Some(page) = pages.next().await {
for object in page?.contents() {
let key = object.key().ok_or("S3 inventory omitted object key")?;
let size = u64::try_from(object.size().ok_or("S3 inventory omitted object size")?)?;
assert!(sizes.insert(key.to_owned(), size).is_none(), "duplicate inventory key {key}");
}
}
Ok(sizes)
}
async fn scan_status(env: &RustFSTestEnvironment) -> TestResult<Status> {
let status: Status = admin(env, "scanner/status").await?;
assert_eq!(status.metrics.cycle_max_duration_seconds, 3.0, "effective cycle budget");
assert!(status.disk_io_budget.iter().all(|disk| disk.iops == Some(96)), "effective disk budget");
Ok(status)
}
#[tokio::test(flavor = "multi_thread")]
async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult {
let mut env = RustFSTestEnvironment::new().await?;
let temporary_log = tempfile::NamedTempFile::new()?;
let server_log = env
.capture_log_path
.get_or_insert_with(|| temporary_log.path().display().to_string())
.clone();
let bucket_metadata = Path::new(&env.temp_dir)
.join(RUSTFS_META_BUCKET)
.join(BUCKET_META_PREFIX)
.join(BUCKET);
// Seed a cold bucket without allowing any earlier, larger-budget sweep to count it.
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_SCANNER_ENABLED", "false")])
.await?;
let client = env.create_s3_client();
client.create_bucket().bucket(BUCKET).send().await?;
stream::iter(0..WIDTH)
.map(Ok)
.try_for_each_concurrent(12, |i| {
let client = &client;
async move {
client
.put_object()
.bucket(BUCKET)
.key(format!("object-{i:064x}"))
.body(ByteStream::from(vec![42; 1 + i % 67]))
.send()
.await
.map(|_| ())
}
})
.await?;
let expected = inventory(&client).await?;
assert_eq!(expected.len(), WIDTH);
env.restart_server_preserving_data(vec![], SCAN_ENV).await?;
let first_pid = env.process.as_ref().ok_or("missing scanner process")?.id();
timeout(Duration::from_secs(60), async {
loop {
let status = scan_status(&env).await?;
if status.metrics.partial_cycles_runtime >= 1
&& bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir()
&& status.metrics.current_cycle_active
&& status
.metrics
.active_paths
.iter()
.any(|path| path.split('/').any(|part| part == BUCKET))
{
let log = tokio::fs::read_to_string(&server_log).await?;
if !log
.lines()
.any(|line| line.contains("partial_saved_not_published") && line.contains(BUCKET))
{
sleep(Duration::from_millis(200)).await;
continue;
}
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
}
sleep(Duration::from_millis(200)).await;
}
})
.await
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
assert!(
partial
.buckets_usage
.get(BUCKET)
.is_none_or(|value| value.usage_certification.is_none()),
"the first process certified the bucket before the injected crash"
);
env.stop_server();
// The terminal save has returned and the old process can no longer write.
assert!(
bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir(),
"the interrupted process must have committed a paged checkpoint"
);
let restart_log_offset = usize::try_from(tokio::fs::metadata(&server_log).await?.len())?;
let restarted_at = SystemTime::now();
env.start_rustfs_server_without_cleanup_with_env(SCAN_ENV).await?;
let second_pid = env.process.as_ref().ok_or("missing restarted scanner process")?.id();
assert_ne!(first_pid, second_pid);
let deadline = Instant::now() + Duration::from_secs(180);
loop {
let usage: DataUsageInfo = admin(&env, "datausageinfo").await?;
let status = scan_status(&env).await?;
if let Some(bucket) = usage.buckets_usage.get(BUCKET)
&& bucket.usage_value_state == Some(BucketUsageValueState::Certified)
{
let log = tokio::fs::read_to_string(&server_log).await?;
let first_admission = log
.get(restart_log_offset..)
.ok_or("server log truncated across restart")?
.lines()
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
.find(|record| record["state"] == "bucket_checkpoint_prepared" && record["bucket"] == BUCKET)
.ok_or("no checkpoint admission in the restarted process")?;
assert_eq!(first_admission["resume_position"], true, "restarted scanner discarded the checkpoint");
assert!(usage.is_complete_bucket_usage_snapshot());
let certificate = bucket
.usage_certification
.ok_or("missing certificate for the measured bucket")?;
assert!(certificate.certified_at >= restarted_at, "stale pre-restart certificate");
assert!(status.metrics.partial_cycles_runtime > 0, "new process must cross a cycle deadline");
assert!(!status.disk_io_budget.is_empty(), "restarted scanner never admitted disk I/O");
assert_eq!(inventory(&client).await?, expected, "durable S3 inventory changed across restart");
let count = u64::try_from(expected.len())?;
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));
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
);
return Ok(());
}
assert!(
Instant::now() < deadline,
"no certified bucket after restart: {status:?}, value={:?}",
usage.buckets_usage.get(BUCKET)
);
sleep(Duration::from_millis(500)).await;
}
}
+9 -11
View File
@@ -28,7 +28,7 @@ pub mod diagnostic {
}
pub mod admin {
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info, get_server_info_with_inventory};
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info};
}
pub mod bitrot {
@@ -72,11 +72,10 @@ pub mod bucket {
ExpiryState, LifecycleOps, ManualTransitionCancelCheck, ManualTransitionProgressSink,
ManualTransitionQueueSnapshot, ManualTransitionRunExecution, ManualTransitionRunOptions,
ManualTransitionRunReport, RestoreRequestOps, TransitionState, TransitionedObject, apply_expiry_rule,
apply_transition_rule, apply_transition_rule_with_incarnation, enqueue_expiry_for_existing_objects,
enqueue_transition_for_existing_objects, enqueue_transition_for_existing_objects_scoped,
enqueue_transition_for_existing_objects_scoped_with_cancel, enqueue_transition_immediate,
expire_transitioned_object, get_global_expiry_state, get_global_transition_state, init_background_expiry,
lifecycle_version_delete_target, manual_transition_queue_snapshot, post_restore_opts,
apply_transition_rule, enqueue_expiry_for_existing_objects, enqueue_transition_for_existing_objects,
enqueue_transition_for_existing_objects_scoped, enqueue_transition_for_existing_objects_scoped_with_cancel,
enqueue_transition_immediate, expire_transitioned_object, get_global_expiry_state, get_global_transition_state,
init_background_expiry, lifecycle_version_delete_target, manual_transition_queue_snapshot, post_restore_opts,
run_stale_multipart_upload_cleanup_once, validate_transition_tier,
};
}
@@ -349,7 +348,7 @@ pub mod bucket {
pub mod utils {
pub use crate::bucket::utils::{
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args, check_object_args,
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args,
check_object_name_for_length_and_slash, check_valid_bucket_name_strict, deserialize, has_bad_path_component,
has_xml_invalid_control_characters, is_meta_bucketname, is_valid_object_prefix, serialize,
};
@@ -455,13 +454,13 @@ pub mod data_usage {
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, load_bucket_usage_from_backend_cached, load_compression_total_from_memory,
load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend,
load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
store_data_usage_in_backend, verified_account_bucket_usage,
store_data_usage_in_backend,
};
pub use crate::data_usage::{get_bucket_usage_memory, lookup_degraded_bucket_usage_baseline};
}
@@ -470,7 +469,6 @@ pub mod disk {
pub use crate::cluster::rpc::background_pipe::{BackgroundPipeReader, BackgroundPipeWriter, background_pipe};
pub use crate::cluster::rpc::background_reader_stream::BackgroundReaderStream;
pub use crate::disk::BOUNDED_DELETE_PREPARE_PROTOCOL_VERSION;
pub use crate::disk::ReplacementMount;
pub use crate::disk::background_memory::BackgroundEncodeBuffer;
pub use crate::disk::disk_store::get_object_disk_read_timeout;
#[cfg(feature = "test-util")]
@@ -51,20 +51,15 @@ impl LcAuditEvent {
}
}
pub(crate) fn emit_transition_failed_event(object: ObjectInfo, incarnation_id: Option<uuid::Uuid>) {
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT, incarnation_id);
pub(crate) fn emit_transition_failed_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT);
}
pub(crate) fn emit_transition_complete_event(object: ObjectInfo, incarnation_id: Option<uuid::Uuid>) {
emit_lifecycle_event(
EventName::ObjectTransitionComplete,
object,
LIFECYCLE_TRANSITION_USER_AGENT,
incarnation_id,
);
pub(crate) fn emit_transition_complete_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionComplete, object, LIFECYCLE_TRANSITION_USER_AGENT);
}
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo, incarnation_id: uuid::Uuid) {
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo) {
let event_name = transitioned_expiration_event_name(source.delete_marker, deleted.delete_marker);
let object = ObjectInfo {
bucket: source.bucket.clone(),
@@ -74,17 +69,12 @@ pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &
delete_marker: source.delete_marker,
..Default::default()
};
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
}
pub(crate) fn emit_non_transitioned_expiration_event(
action: IlmAction,
source: &ObjectInfo,
deleted: ObjectInfo,
incarnation_id: uuid::Uuid,
) {
pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source: &ObjectInfo, deleted: ObjectInfo) {
let event_name = non_transitioned_expiration_event_name(action, source.delete_marker, deleted.delete_marker);
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT);
}
/// Emit the lifecycle expiration event for one version removed by the batch
@@ -93,15 +83,9 @@ pub(crate) fn emit_non_transitioned_expiration_event(
/// That path never sent events, so a successful noncurrent-version expiry was
/// invisible to notification subscribers even though the equivalent
/// current-version path emits one (backlog#2202).
pub(crate) fn emit_noncurrent_expiration_event(
bucket: &str,
target: &ObjectToDelete,
deleted: &DeletedObject,
failed: bool,
incarnation_id: uuid::Uuid,
) {
pub(crate) fn emit_noncurrent_expiration_event(bucket: &str, target: &ObjectToDelete, deleted: &DeletedObject, failed: bool) {
if let Some((event_name, object)) = noncurrent_expiration_event(bucket, target, deleted, failed) {
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
}
}
@@ -147,10 +131,9 @@ fn noncurrent_expiration_event(
Some((event_name, object))
}
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str, incarnation_id: Option<uuid::Uuid>) {
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str) {
send_event(EventArgs {
event_name: event_name.to_string(),
bucket_incarnation_id: incarnation_id,
bucket_name: object.bucket.clone(),
object,
user_agent: user_agent.to_string(),
@@ -117,9 +117,9 @@ use tracing::{debug, error, warn};
use uuid::Uuid;
use xxhash_rust::xxh64;
pub(super) const LOG_COMPONENT_ECSTORE: &str = "ecstore";
pub(super) const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
pub(super) const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
const EVENT_LIFECYCLE_TRANSITION_COMPENSATION: &str = "lifecycle_transition_compensation";
const EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP: &str = "lifecycle_stale_multipart_cleanup";
const METRIC_STALE_MULTIPART_CLEANUP_BLOCKED_TOTAL: &str = "rustfs_stale_multipart_cleanup_blocked_total";
@@ -1566,12 +1566,7 @@ pub(super) async fn enqueue_recovered_free_version_with_cancel(
queued
}
type TransitionKey = (Option<Uuid>, String, String, String);
struct TransitionTask {
// Captured with the source object; recovery without this provenance must
// never bind notification authority from the bucket name at execution.
notification_bucket_incarnation: Option<Uuid>,
obj_info: ObjectInfo,
src: LcEventSrc,
event: lifecycle::Event,
@@ -1611,12 +1606,12 @@ pub struct TransitionState {
compensation_scheduled_tasks: AtomicI64,
compensation_running_tasks: AtomicI64,
compensation_buckets: Arc<Mutex<HashSet<String>>>,
// (incarnation, bucket, object, version) currently queued or being transitioned. A single
// (bucket, object, version) currently queued or being transitioned. A single
// PUT can enqueue the same object twice (immediate transition + startup
// compensation backfill); without this guard the duplicates run concurrently,
// and the loser races the winner's source cleanup — reading data the winner
// already removed and logging a spurious NotFound failure (rustfs/backlog#1268).
in_flight_transitions: Arc<Mutex<HashSet<TransitionKey>>>,
in_flight_transitions: Arc<Mutex<HashSet<(String, String, String)>>>,
last_day_stats: Arc<Mutex<HashMap<String, LastDayTierStats>>>,
}
@@ -1682,29 +1677,28 @@ impl TransitionState {
})
}
fn transition_key(oi: &ObjectInfo, incarnation: Option<Uuid>) -> TransitionKey {
fn transition_key(oi: &ObjectInfo) -> (String, String, String) {
(
incarnation,
oi.bucket.clone(),
oi.name.clone(),
oi.version_id.map(|v| v.to_string()).unwrap_or_default(),
)
}
/// Try to claim a transition for this exact (incarnation, bucket, object, version). Returns
/// Try to claim a transition for this exact (bucket, object, version). Returns
/// `false` when one is already queued or running, so the caller can skip the
/// duplicate enqueue (rustfs/backlog#1268). The claim is released in the
/// worker once the transition finishes, or here if the enqueue fails.
fn reserve_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) -> bool {
let key = Self::transition_key(oi, incarnation);
fn reserve_transition(&self, oi: &ObjectInfo) -> bool {
let key = Self::transition_key(oi);
match self.in_flight_transitions.lock() {
Ok(mut set) => set.insert(key),
Err(poisoned) => poisoned.into_inner().insert(key),
}
}
fn release_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) {
let key = Self::transition_key(oi, incarnation);
fn release_transition(&self, oi: &ObjectInfo) {
let key = Self::transition_key(oi);
match self.in_flight_transitions.lock() {
Ok(mut set) => set.remove(&key),
Err(poisoned) => poisoned.into_inner().remove(&key),
@@ -1908,7 +1902,6 @@ impl TransitionState {
event: &lifecycle::Event,
src: &LcEventSrc,
manual_job_id: Option<Uuid>,
notification_bucket_incarnation: Option<Uuid>,
) -> TransitionEnqueueOutcome {
if is_immediate_transition_source(src) && should_force_immediate_transition_enqueue_timeout() {
self.handle_immediate_enqueue_failure(oi, src, ImmediateEnqueueFailure::ForcedTimeout);
@@ -1921,7 +1914,7 @@ impl TransitionState {
// released by the worker after the transition finishes (rustfs/backlog#1268).
// This is a no-op, not a new enqueue, so it must not touch the enqueue
// counters (the first enqueue already counted this object).
if !self.reserve_transition(oi, notification_bucket_incarnation) {
if !self.reserve_transition(oi) {
self.record_scanner_transition_state();
return TransitionEnqueueOutcome::AlreadyInFlight;
}
@@ -1930,7 +1923,7 @@ impl TransitionState {
manual_job_id.map(|_| manual_transition_worker_result_task_key(&oi.bucket, &oi.name, oi.version_id));
if let (Some(job_id), Some(result_key)) = (manual_job_id, manual_result_key.as_deref()) {
let Some(api) = api else {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1955,7 +1948,7 @@ impl TransitionState {
)
.with_object_metadata(oi.etag.clone(), oi.mod_time, oi.size, oi.is_latest);
if let Err(err) = save_manual_transition_task_if_absent(api, &task_record).await {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1974,7 +1967,6 @@ impl TransitionState {
}
let task = TransitionTask {
notification_bucket_incarnation,
obj_info: oi.clone(),
src: src.clone(),
event: event.clone(),
@@ -2018,7 +2010,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2071,7 +2063,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2079,7 +2071,7 @@ impl TransitionState {
}
pub async fn queue_transition_task(self: &Arc<Self>, oi: &ObjectInfo, event: &lifecycle::Event, src: &LcEventSrc) -> bool {
self.queue_transition_task_outcome(None, oi, event, src, None, None)
self.queue_transition_task_outcome(None, oi, event, src, None)
.await
.is_handled()
}
@@ -2174,10 +2166,9 @@ impl TransitionState {
..Default::default()
};
let (incarnation_id, transition_result) =
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()), task.notification_bucket_incarnation)
.await;
if let Err(err) = transition_result
if let Err(err) =
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()))
.await
{
if let (Some(job_id), Some(result_key)) = (task.manual_job_id, task.manual_result_key.as_deref()) {
record_manual_transition_worker_result_for_task_with_reason(
@@ -2204,7 +2195,7 @@ impl TransitionState {
"Lifecycle tier operation failed"
);
}
emit_transition_failed_event(obj_info_for_event, incarnation_id);
emit_transition_failed_event(obj_info_for_event);
} else {
if let (Some(job_id), Some(result_key)) = (task.manual_job_id, task.manual_result_key.as_deref()) {
record_manual_transition_worker_result_for_task(
@@ -2226,11 +2217,11 @@ impl TransitionState {
}
transition_state.add_lastday_stats(&task.event.storage_class, ts);
emit_transition_complete_event(obj_info_for_event, incarnation_id);
emit_transition_complete_event(obj_info_for_event);
}
// Release the dedup claim so a later lifecycle pass can
// re-transition this object if needed (rustfs/backlog#1268).
transition_state.release_transition(&task.obj_info, task.notification_bucket_incarnation);
transition_state.release_transition(&task.obj_info);
TransitionState::add_counter(&transition_state.active_tasks, -1);
transition_state.record_scanner_transition_state();
}
@@ -2835,7 +2826,7 @@ async fn replay_manual_transition_pending_tasks(
};
match transition_state
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id))
.await
{
TransitionEnqueueOutcome::Queued | TransitionEnqueueOutcome::AlreadyInFlight => {
@@ -3093,7 +3084,6 @@ async fn recover_configured_tier_free_versions(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
});
}
@@ -3233,7 +3223,6 @@ async fn run_tier_free_version_recovery_loop<F, Fut>(
scanned = stats.scanned,
scanned_entries = stats.scanned_entries,
buckets_scanned = stats.buckets_scanned,
unreadable_objects = stats.unreadable_objects,
enqueued = stats.enqueued,
failed = stats.failed,
truncated = stats.truncated,
@@ -4070,11 +4059,9 @@ fn transitioned_cleanup_tuple(oi: &ObjectInfo) -> Result<(&str, &str, &str), std
Ok((&transitioned.name, &transitioned.version_id, &transitioned.tier))
}
/// Queue a committed object with its storage-validated bucket identity.
/// `None` permits the transition but withholds external notifications.
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc, notification_bucket_incarnation: Option<Uuid>) {
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc) {
if let Some(lc) = runtime_sources::bucket_lifecycle_config(&oi.bucket).await {
enqueue_transition_with_lifecycle(oi, &lc, &src, notification_bucket_incarnation).await;
enqueue_transition_with_lifecycle(oi, &lc, &src).await;
}
}
@@ -4547,20 +4534,10 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
let deadline = options.max_duration.map(|duration| tokio::time::Instant::now() + duration);
loop {
let (page, bucket_incarnation_id) = {
// Lock order: lifecycle read -> metadata transaction -> listing locks.
// Release the lifecycle fence before enqueue or progress persistence.
let guard = api.acquire_bucket_lifecycle_read_lock(bucket).await?;
let incarnation = api.bucket_incarnation_id_from_disk(bucket).await?;
let page = api
.clone()
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
.await?;
if guard.is_lock_lost() {
return Err(Error::other("bucket lifecycle lock was lost while listing transition candidates"));
}
(page, incarnation)
};
let page = api
.clone()
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
.await?;
for (index, object) in page.objects.iter().enumerate() {
if manual_transition_cancel_requested(&options).await {
@@ -4582,16 +4559,7 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
return Ok(report);
}
report.scanned = report.scanned.saturating_add(1);
enqueue_transition_with_lifecycle_report(
Some(api.clone()),
object,
&lc,
&src,
&options,
&mut report,
Some(bucket_incarnation_id),
)
.await;
enqueue_transition_with_lifecycle_report(Some(api.clone()), object, &lc, &src, &options, &mut report).await;
if report.has_enqueue_backpressure() {
report.next_marker.clone_from(&previous_marker);
report.next_version_idmarker.clone_from(&previous_version_marker);
@@ -4897,7 +4865,6 @@ async fn enqueue_transition_with_lifecycle_report(
src: &LcEventSrc,
options: &ManualTransitionRunOptions,
report: &mut ManualTransitionRunReport,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
if oi.transitioned_object.status == TRANSITION_COMPLETE {
if options
@@ -4950,7 +4917,7 @@ async fn enqueue_transition_with_lifecycle_report(
return true;
}
let outcome = runtime_sources::transition_state_handle()
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id, notification_bucket_incarnation)
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id)
.await;
report.record_enqueue_outcome(outcome);
return outcome.is_handled();
@@ -4960,12 +4927,7 @@ async fn enqueue_transition_with_lifecycle_report(
false
}
async fn enqueue_transition_with_lifecycle(
oi: &ObjectInfo,
lc: &PersistedLifecycleConfiguration,
src: &LcEventSrc,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecycleConfiguration, src: &LcEventSrc) -> bool {
let event = lc.eval(&oi.to_lifecycle_opts()).await;
match event.action {
IlmAction::TransitionAction | IlmAction::TransitionVersionAction => {
@@ -4976,9 +4938,8 @@ async fn enqueue_transition_with_lifecycle(
return false;
}
runtime_sources::transition_state_handle()
.queue_transition_task_outcome(None, oi, &event, src, None, notification_bucket_incarnation)
.queue_transition_task(oi, &event, src)
.await
.is_handled()
}
_ => false,
}
@@ -5160,7 +5121,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
}
};
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
// The transitioned version is gone; evict any cached body for this object
// so it does not linger until TTL (ODC-26).
@@ -5173,7 +5134,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
//audit_log_lifecycle(oi, ILMExpiry, tags);
emit_transitioned_expiration_event(oi, &dobj, bucket_incarnation_id);
emit_transitioned_expiration_event(oi, &dobj);
Ok(dobj)
}
@@ -5191,22 +5152,12 @@ pub fn gen_transition_objname(bucket: &str) -> Result<String, Error> {
Ok(obj)
}
async fn transition_object(
api: Arc<ECStore>,
oi: &ObjectInfo,
lae: LcAuditEvent,
notification_bucket_incarnation: Option<Uuid>,
) -> (Option<Uuid>, Result<(), Error>) {
pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditEvent) -> Result<(), Error> {
let time_ilm = Metrics::time_ilm(lae.event.action);
let Some((publication_guard, bucket_incarnation_id)) =
lifecycle_transition_publication_guard(&api, oi, notification_bucket_incarnation).await
else {
return (
notification_bucket_incarnation,
Err(Error::other("lifecycle transition is not allowed for this bucket")),
);
};
let (publication_guard, bucket_incarnation_id) = lifecycle_transition_publication_guard(&api, oi)
.await
.ok_or_else(|| Error::other("lifecycle transition is not allowed for this bucket"))?;
let etag = if let Some(etag) = &oi.etag { etag } else { "" };
let etag = etag.to_string();
@@ -5224,13 +5175,12 @@ async fn transition_object(
version_suspended: BucketVersioningSys::prefix_suspended(&oi.bucket, &oi.name).await,
mod_time: oi.mod_time,
expected_bucket_incarnation_id: Some(bucket_incarnation_id),
notification_bucket_incarnation_id: notification_bucket_incarnation,
..Default::default()
};
opts.add_namespace_lock_guard(&publication_guard);
let result = api.transition_object(&oi.bucket, &oi.name, &opts).await;
time_ilm(1)();
(notification_bucket_incarnation, result)
result
}
#[allow(
@@ -5841,22 +5791,12 @@ fn lifecycle_replication_blocks_action(oi: &ObjectInfo) -> bool {
}
pub async fn apply_transition_rule(event: &lifecycle::Event, src: &LcEventSrc, oi: &ObjectInfo) -> bool {
apply_transition_rule_with_incarnation(event, src, oi, None).await
}
pub async fn apply_transition_rule_with_incarnation(
event: &lifecycle::Event,
src: &LcEventSrc,
oi: &ObjectInfo,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
if oi.delete_marker || oi.is_dir {
return false;
}
runtime_sources::transition_state_handle()
.queue_transition_task_outcome(None, oi, event, src, None, notification_bucket_incarnation)
.queue_transition_task(oi, event, src)
.await
.is_handled()
}
async fn acquire_lifecycle_publication_guard(api: &ECStore, bucket: &str) -> Result<rustfs_lock::NamespaceLockGuard, Error> {
@@ -5905,14 +5845,10 @@ pub(crate) async fn lifecycle_expiry_publication_guard(
async fn lifecycle_transition_publication_guard(
api: &ECStore,
oi: &ObjectInfo,
expected_incarnation: Option<Uuid>,
) -> Option<(rustfs_lock::NamespaceLockGuard, Uuid)> {
let result: std::result::Result<(rustfs_lock::NamespaceLockGuard, Uuid), Error> = async {
let guard = acquire_lifecycle_publication_guard(api, &oi.bucket).await?;
let configs = metadata_boundary::get_expiry_configs(api, &oi.bucket).await?;
if expected_incarnation.is_some_and(|expected| expected != configs.bucket_incarnation_id) {
return Err(Error::PreconditionFailed);
}
Ok((guard, configs.bucket_incarnation_id))
}
.await;
@@ -6098,7 +6034,7 @@ async fn apply_expiry_on_non_transitioned_objects_with_lock_lost_signal(
{
accounting.commit(size).await;
}
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
// The object (or all its versions, for delete_all) was expired; evict any
// cached body so dead bytes do not sit resident until TTL (ODC-26). The
@@ -6114,7 +6050,7 @@ async fn apply_expiry_on_non_transitioned_objects_with_lock_lost_signal(
//let tags = LcAuditEvent::new(lc_event.clone(), src.clone()).tags();
//tags["version-id"] = dobj.version_id;
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj, bucket_incarnation_id);
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj);
if lc_event.action != IlmAction::NoneAction {
let mut num_versions = 1_u64;
@@ -6266,12 +6202,12 @@ fn lifecycle_deleted_object(oi: &ObjectInfo, dobj: &ObjectInfo) -> DeletedObject
}
}
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo, bucket_incarnation_id: Uuid) {
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo) {
let delete_object = lifecycle_deleted_object(oi, dobj);
if delete_object.replication_state.is_none() {
return;
}
replication_sink::schedule_delete(oi.bucket.clone(), delete_object, Some(bucket_incarnation_id)).await;
replication_sink::schedule_delete(oi.bucket.clone(), delete_object).await;
}
async fn lifecycle_delete_config_snapshot(api: &ECStore, oi: &ObjectInfo) -> Result<DeleteReplicationConfigSnapshot, Error> {
@@ -6661,7 +6597,6 @@ mod tests {
next_object_marker: truncated.then(|| "object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated,
}
}
@@ -9179,160 +9114,6 @@ mod tests {
assert!(recovery_notify.notified().now_or_never().is_some());
}
#[tokio::test]
async fn transition_dedup_keeps_recreated_bucket_admissions_independent() {
let state = TransitionState::new_with_capacity(2);
let object = ObjectInfo {
bucket: "bucket".to_string(),
name: "same-key".to_string(),
..Default::default()
};
let first = Uuid::new_v4();
let second = Uuid::new_v4();
let event = lifecycle::Event {
action: IlmAction::TransitionAction,
..Default::default()
};
for identity in [first, second] {
assert_eq!(
state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, Some(identity))
.await,
TransitionEnqueueOutcome::Queued
);
}
state.release_transition(&object, Some(first));
assert!(
!state.reserve_transition(&object, Some(second)),
"finishing the old incarnation must retain the new claim"
);
assert!(state.reserve_transition(&object, Some(first)), "only the old claim was released");
}
#[tokio::test]
#[serial]
async fn queued_transition_notifications_keep_the_admitted_bucket_incarnation() {
use super::metadata_boundary::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::services::event_notification::test_recorder;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "queued-transition-notification-origin";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original bucket");
let original = store.bucket_incarnation_id(bucket).await.expect("original identity");
let state = TransitionState::new_with_capacity(2);
let event = lifecycle::Event {
action: IlmAction::TransitionVersionAction,
storage_class: "missing-tier".to_string(),
..Default::default()
};
for (name, identity) in [("known-old", Some(original)), ("unknown-replay", None)] {
let object = ObjectInfo {
bucket: bucket.to_string(),
name: name.to_string(),
version_id: Some(Uuid::new_v4()),
..Default::default()
};
assert_eq!(
state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, identity)
.await,
TransitionEnqueueOutcome::Queued
);
}
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original bucket");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("recreate bucket");
let replacement = store.bucket_incarnation_id(bucket).await.expect("replacement identity");
assert_ne!(original, replacement);
test_recorder::install();
for expected in [Some(original), None] {
let task = state
.transition_rx
.recv()
.await
.expect("receive queued transition")
.expect("transition task");
assert_eq!(task.notification_bucket_incarnation, expected);
let (identity, result) = super::transition_object(
store.clone(),
&task.obj_info,
super::LcAuditEvent::new(task.event, task.src),
task.notification_bucket_incarnation,
)
.await;
assert!(result.is_err(), "the old version cannot transition in the replacement");
assert_eq!(identity, expected);
super::emit_transition_failed_event(task.obj_info, identity);
}
let events = test_recorder::recorded_for_bucket(bucket);
assert_eq!(events.len(), 2);
assert_eq!(events[0].bucket_incarnation_id, Some(original));
assert_eq!(events[1].bucket_incarnation_id, None);
assert!(events.iter().all(|event| event.bucket_incarnation_id != Some(replacement)));
}
#[tokio::test]
#[serial]
async fn successful_recovered_transition_keeps_unknown_notification_origin_unbound() {
use super::metadata_boundary::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::services::event_notification::test_recorder;
use crate::services::tier::test_util::register_mock_tier;
use rustfs_s3_types::EventName;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("recovered-notify-{}", &Uuid::new_v4().simple().to_string()[..12]);
let object = "object";
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create transition bucket");
let mut reader = PutObjReader::from_vec(b"transition payload".to_vec());
store
.put_object(&bucket, object, &mut reader, &ObjectOptions::default())
.await
.expect("seed transition object");
let object_info = store
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.expect("read transition object");
let tier = format!("COLDTIER{}", &Uuid::new_v4().simple().to_string()[..8]).to_uppercase();
register_mock_tier(&store.tier_config_mgr(), &tier).await;
test_recorder::install();
let (origin, result) = super::transition_object(
store,
&object_info,
super::LcAuditEvent::new(
lifecycle::Event {
action: IlmAction::TransitionAction,
storage_class: tier,
..Default::default()
},
LcEventSrc::Scanner,
),
None,
)
.await;
assert!(result.is_ok(), "recovered transition should complete: {result:?}");
assert_eq!(origin, None);
let events = test_recorder::recorded_for_bucket(&bucket);
let transition = events
.iter()
.find(|event| event.event_name == EventName::LifecycleTransition.as_str())
.expect("successful transition should emit its native lifecycle event");
assert_eq!(transition.bucket_incarnation_id, None);
}
#[tokio::test]
#[serial]
async fn scanner_transition_enqueue_reports_full_queue() {
@@ -9400,7 +9181,7 @@ mod tests {
.await
.expect("queue should remain open")
.expect("first queued transition task should be present");
state.release_transition(&first_task.obj_info, first_task.notification_bucket_incarnation);
state.release_transition(&first_task.obj_info);
assert!(
deferred.await,
@@ -10159,8 +9940,8 @@ mod tests {
..Default::default()
};
assert!(state.reserve_transition(&oi, None), "first claim must succeed");
assert!(!state.reserve_transition(&oi, None), "duplicate claim must be rejected");
assert!(state.reserve_transition(&oi), "first claim must succeed");
assert!(!state.reserve_transition(&oi), "duplicate claim must be rejected");
// A different object is independent.
let other = ObjectInfo {
@@ -10169,11 +9950,11 @@ mod tests {
version_id: None,
..Default::default()
};
assert!(state.reserve_transition(&other, None), "distinct object must claim independently");
assert!(state.reserve_transition(&other), "distinct object must claim independently");
// After release, the same object can be re-claimed (later lifecycle pass).
state.release_transition(&oi, None);
assert!(state.reserve_transition(&oi, None), "re-claim after release must succeed");
state.release_transition(&oi);
assert!(state.reserve_transition(&oi), "re-claim after release must succeed");
}
#[tokio::test]
@@ -10215,10 +9996,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.await;
let second = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10246,10 +10027,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None)
.await;
let second = state
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10282,7 +10063,7 @@ mod tests {
let task_key = manual_transition_worker_result_task_key(&object.bucket, &object.name, object.version_id);
let outcome = state
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id))
.await;
assert_eq!(outcome, TransitionEnqueueOutcome::Queued);
@@ -10319,14 +10100,14 @@ mod tests {
};
let failed = state
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()), None)
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()))
.await;
assert_eq!(failed, TransitionEnqueueOutcome::TaskJournalFailed);
assert_eq!(state.transition_rx.len(), 0);
let retried = state
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()), None)
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()))
.await;
assert_eq!(retried, TransitionEnqueueOutcome::Queued);
assert_eq!(state.transition_rx.len(), 1);
@@ -10827,7 +10608,7 @@ mod tests {
let lc = latest_transition_lifecycle();
let object = current_object(ReplicationStatusType::Pending);
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner, None).await;
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner).await;
assert!(!queued);
}
@@ -10843,7 +10624,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(handled);
assert_eq!(report.eligible, 1);
@@ -10865,7 +10646,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10884,7 +10665,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10899,7 +10680,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -11012,7 +10793,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -14357,7 +14138,7 @@ mod tests {
let admission_store = ecstore.clone();
let admission_object = object_info.clone();
let mut admission =
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object, None).await });
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object).await });
assert!(
tokio::time::timeout(StdDuration::from_millis(100), &mut admission)
.await
@@ -15176,37 +14957,6 @@ mod tests {
}
}
async fn seed_corrupt_free_version(disk_paths: &[PathBuf], bucket: &str, object: &str) -> Vec<u8> {
use rustfs_utils::http::metadata_compat::{SUFFIX_TRANSITIONED_VERSION_STATE, insert_bytes};
seed_recoverable_free_version(disk_paths, bucket, object, None, None).await;
let path = PathBuf::from(bucket).join(object).join(STORAGE_FORMAT_FILE);
let original = fs::read(disk_paths[0].join(&path))
.await
.expect("read the seeded free version");
let mut metadata = FileMeta::load(&original).expect("load the seeded metadata");
let mut version = metadata.versions[0].parse_version_meta().expect("decode the seeded version");
let marker = version.delete_marker.as_mut().expect("the free version is a delete marker");
insert_bytes(&mut marker.meta_sys, SUFFIX_TRANSITIONED_VERSION_STATE, b"invalid".to_vec());
metadata.versions[0] = version
.try_into()
.expect("encode the malformed marker with a consistent header");
let encoded = metadata.marshal_msg().expect("encode the metadata with a valid checksum");
let reloaded = FileMeta::load(&encoded).expect("the metadata envelope must remain readable");
assert_eq!(
reloaded
.get_file_info_versions(bucket, object, false)
.expect_err("decoding the marker must fail"),
rustfs_filemeta::Error::FileCorrupt
);
for disk in disk_paths {
fs::write(disk.join(&path), &encoded)
.await
.expect("persist the same malformed marker on every disk");
}
encoded
}
async fn remove_seeded_free_version(disk_paths: &[PathBuf], bucket: &str, object: &str) {
for disk_path in disk_paths {
fs::remove_dir_all(disk_path.join(bucket).join(object))
@@ -15279,7 +15029,6 @@ mod tests {
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
}
);
@@ -15476,14 +15225,12 @@ mod tests {
);
assert_eq!(check.reasons.len(), 1);
assert_eq!(check.reasons[0].kind, crate::services::tier::tier::TierDeletionReasonKind::CleanupPending);
seed_corrupt_free_version(&disks, &bucket, "corrupt").await;
let report = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("retry should enqueue durable cleanup");
assert_eq!(report.status, TierCleanupRetryStatus::Accepted);
assert_eq!(report.enqueued, 1);
assert_eq!(report.failed, 0);
assert_eq!(report.unreadable_objects, 1);
let rx = Arc::clone(&state.read().await.tasks_rx[0]);
let task = rx.lock().await.try_recv().expect("cleanup was queued").expect("queue item");
let task = task
@@ -15503,27 +15250,21 @@ mod tests {
let other = retry_tier_free_version_cleanup(api.clone(), "OTHER")
.await
.expect("other tier retry should be bounded");
assert_eq!(other.status, TierCleanupRetryStatus::Accepted);
assert_eq!(other.enqueued, 0, "retry must not enqueue a different tier's marker");
assert_eq!(other.failed, 0);
let json = serde_json::to_value(&other).expect("serialize the public retry report");
assert_eq!(json["unreadableObjects"], 1, "unreadable keys cannot be attributed to a tier");
assert!(rx.lock().await.try_recv().is_err());
reset_runtime_expiry_state(&api).await;
let failed = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("queue failure remains retryable");
assert_eq!(failed.failed, 1);
assert_eq!(failed.enqueued, 0);
assert_eq!(failed.unreadable_objects, 1);
assert_eq!(crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await, 1);
remove_seeded_free_version(&disks, &bucket, "corrupt").await;
api.tier_config_mgr()
.write()
.await
.remove("OTHER", true)
.await
.expect("remove other mock tier");
reset_runtime_expiry_state(&api).await;
let failed = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("queue failure remains retryable");
assert_eq!(failed.failed, 1);
assert_eq!(failed.enqueued, 0);
assert_eq!(crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await, 1);
remove_seeded_free_version(&disks, &bucket, "owned").await;
api.tier_config_mgr()
.write()
@@ -15743,121 +15484,6 @@ mod tests {
reset_runtime_expiry_state(&ecstore).await;
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_enqueues_past_a_corrupt_free_version() {
let (disk_paths, ecstore) = setup_test_env().await;
let prefix = format!("zzzz-recovery-corrupt-{}", Uuid::new_v4().simple());
let first_bucket = format!("{prefix}-a");
let second_bucket = format!("{prefix}-b");
for bucket in [&first_bucket, &second_bucket] {
create_test_bucket(&ecstore, bucket).await;
}
let healthy = [
(first_bucket.as_str(), "a"),
(first_bucket.as_str(), "c"),
(second_bucket.as_str(), "d"),
];
for (bucket, object) in healthy {
seed_recoverable_free_version(&disk_paths, bucket, object, None, None).await;
}
let corrupt = seed_corrupt_free_version(&disk_paths, &first_bucket, "b").await;
let state = install_unconsumed_runtime_expiry_worker(&ecstore, healthy.len()).await;
let stats = recover_tier_free_versions_with_cancel(
Arc::clone(&ecstore),
healthy.len() + 1,
Some(first_bucket.clone()),
None,
CancellationToken::new(),
)
.await
.expect("a corrupt free version must not discard other recovery candidates");
assert!(!stats.truncated);
assert_eq!(stats.enqueued, healthy.len());
let receiver = Arc::clone(&state.read().await.tasks_rx[0]);
let mut receiver = receiver.lock().await;
for (bucket, object) in healthy {
let task = receiver
.try_recv()
.expect("receive a healthy cleanup task")
.expect("the queue carries a task");
let task = task
.as_any()
.downcast_ref::<FreeVersionTask>()
.expect("a free-version cleanup task");
assert_eq!((task.0.bucket.as_str(), task.0.name.as_str()), (bucket, object));
}
drop(receiver);
reset_runtime_expiry_state(&ecstore).await;
for disk in &disk_paths {
let stored = fs::read(disk.join(&first_bucket).join("b").join(STORAGE_FORMAT_FILE))
.await
.expect("discovery must preserve the unreadable marker");
assert_eq!(stored, corrupt);
}
for (bucket, object) in healthy.into_iter().chain([(first_bucket.as_str(), "b")]) {
remove_seeded_free_version(&disk_paths, bucket, object).await;
}
for bucket in [&first_bucket, &second_bucket] {
ecstore
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete the empty test bucket");
}
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_counts_a_corrupt_boundary_once_per_sweep() {
let (disk_paths, ecstore) = setup_test_env().await;
let bucket = format!("zzzz-recovery-boundary-{}", Uuid::new_v4().simple());
create_test_bucket(&ecstore, &bucket).await;
seed_corrupt_free_version(&disk_paths, &bucket, "b").await;
seed_recoverable_free_version(&disk_paths, &bucket, "c", None, None).await;
let page_from = |marker| {
list_tier_free_versions_with_budget(
Arc::clone(&ecstore),
2,
Some(bucket.clone()),
marker,
CancellationToken::new(),
RecoveryWorkBudget {
max_objects: 1,
max_buckets: 1,
},
)
};
let first = page_from(None)
.await
.expect("the unreadable key should consume the first page");
assert!(first.items.is_empty());
assert_eq!(first.unreadable_objects, 1);
assert!(first.truncated);
assert_eq!(first.next_bucket_marker.as_deref(), Some(bucket.as_str()));
assert_eq!(first.next_object_marker.as_deref(), Some("b"));
let second = page_from(first.next_object_marker)
.await
.expect("resume past the unreadable boundary");
assert_eq!(second.unreadable_objects, 0);
assert_eq!(second.items.len(), 1);
assert_eq!(second.items[0].name, "c");
let next_sweep = page_from(None).await.expect("a later sweep must revisit the unreadable key");
assert_eq!(next_sweep.unreadable_objects, 1);
assert_eq!(next_sweep.next_object_marker.as_deref(), Some("b"));
for object in ["b", "c"] {
remove_seeded_free_version(&disk_paths, &bucket, object).await;
}
ecstore
.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("delete the empty test bucket");
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_real_enqueue_failure_retries_same_object() {
@@ -124,9 +124,6 @@ pub(crate) async fn get_lifecycle_config(bucket: &str) -> Result<(PersistedLifec
metadata_sys::get_lifecycle_config(bucket).await
}
#[cfg(test)]
pub(crate) use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support};
#[cfg(test)]
mod tests {
use super::*;
@@ -128,7 +128,7 @@ pub async fn delete_object_versions(
// order and admission; the event is derived from the committed
// result, and a send failure never rolls back a delete that
// already happened (backlog#2202).
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false, bucket_incarnation_id);
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false);
}
if !deleted_obj
.replication_state
@@ -137,7 +137,7 @@ pub async fn delete_object_versions(
{
continue;
}
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone(), Some(bucket_incarnation_id)).await;
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone()).await;
}
for (i, err) in errors.iter().enumerate() {
@@ -66,12 +66,8 @@ pub(crate) fn lifecycle_action_waits_for_replication(action: IlmAction) -> bool
)
}
pub(crate) async fn schedule_delete(
bucket: String,
delete_object: DeletedObject,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object, notification_bucket_incarnation).await;
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object).await;
}
#[cfg(test)]
@@ -20,9 +20,7 @@ use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::bucket::lifecycle::bucket_lifecycle_ops::{
EVENT_LIFECYCLE_WORKER_STATE, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_LIFECYCLE, enqueue_recovered_free_version_with_cancel,
};
use crate::bucket::lifecycle::bucket_lifecycle_ops::enqueue_recovered_free_version_with_cancel;
use crate::disk::RUSTFS_META_BUCKET;
use crate::error::Result;
use crate::object_api::ObjectInfo;
@@ -30,10 +28,9 @@ use crate::services::tier::tier::{ERR_TIER_INVALID_CONFIG, TierConfigMgr};
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use crate::storage_api_contracts::{
bucket::{BucketOperations, BucketOptions},
list::StorageWalkOptions,
list::{ListOperations as _, StorageObjectInfoOrErr, StorageWalkOptions},
};
use crate::store::ECStore;
use crate::store::list_objects::TierRecoveryEntry;
use rustfs_filemeta::FileInfo;
use rustfs_lock::error::LockError;
use rustfs_s3_client::admin_handler_utils::AdminError;
@@ -48,6 +45,7 @@ const BACKGROUND_WALK_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(test)]
const BACKGROUND_WALK_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
type ObjectInfoOrErr = StorageObjectInfoOrErr<ObjectInfo, crate::error::Error>;
type WalkOptions = StorageWalkOptions<fn(&FileInfo) -> bool>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -145,8 +143,6 @@ pub struct TierCleanupRetryReport {
pub scanned: usize,
pub enqueued: usize,
pub failed: usize,
/// Unreadable logical objects encountered in this pass, whose tier is unknown.
pub unreadable_objects: usize,
pub scan_truncated: bool,
}
@@ -165,7 +161,6 @@ impl TierCleanupRetryReport {
scanned: 0,
enqueued: 0,
failed: 0,
unreadable_objects: 0,
scan_truncated: false,
}
}
@@ -272,7 +267,6 @@ async fn retry_tier_free_version_cleanup_page(
.map_err(|_| tier_cleanup_retry_error())?;
let mut report = TierCleanupRetryReport::new(tier_name, TierCleanupRetryStatus::Accepted);
report.scanned = page.scanned_entries;
report.unreadable_objects = page.unreadable_objects;
report.scan_truncated = page.truncated;
for object in page.items {
if cancel.is_cancelled() {
@@ -296,7 +290,6 @@ pub struct FreeVersionRecoveryStats {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -307,7 +300,6 @@ pub struct FreeVersionRecoveryPage {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -351,7 +343,6 @@ pub(super) async fn recover_tier_free_versions_with_cancel(
next_object_marker: page.next_object_marker,
scanned_entries: page.scanned_entries,
buckets_scanned: page.buckets_scanned,
unreadable_objects: page.unreadable_objects,
truncated: page.truncated,
};
@@ -481,7 +472,6 @@ async fn list_tier_free_versions_for_tier(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
};
@@ -515,7 +505,6 @@ async fn list_tier_free_versions_for_tier(
let mut bucket_seen = bucket_marker.is_none();
let mut truncated_after: Option<RecoveryCursor> = None;
let mut remaining_scan_objects = work_budget.max_objects;
let mut first_unreadable = None;
for bucket in buckets {
if cancel_token.is_cancelled() {
@@ -546,7 +535,7 @@ async fn list_tier_free_versions_for_tier(
};
let bucket_walk_limit = remaining_scan_objects;
let (tx, mut rx) = mpsc::channel::<Result<TierRecoveryEntry>>(100);
let (tx, mut rx) = mpsc::channel::<ObjectInfoOrErr>(100);
let cancel = cancel_token.child_token();
let mut draining_after_truncation = false;
let mut drain_deadline = None;
@@ -570,7 +559,14 @@ async fn list_tier_free_versions_for_tier(
match action {
RecoveryWalkTestAction::SendItems(items) => {
for item in items {
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
return Ok(());
}
}
@@ -578,16 +574,35 @@ async fn list_tier_free_versions_for_tier(
}
RecoveryWalkTestAction::SendItemsThenError(items, err) => {
for item in items {
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
return Ok(());
}
}
let _ = tx.send(Err(err)).await;
let _ = tx
.send(ObjectInfoOrErr {
item: None,
err: Some(err),
})
.await;
return Ok(());
}
RecoveryWalkTestAction::SendItemsThenHang(items, started) => {
for item in items {
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
return Ok(());
}
}
@@ -599,11 +614,14 @@ async fn list_tier_free_versions_for_tier(
let mut index = 0usize;
loop {
if tx
.send(Ok(TierRecoveryEntry::Version(Box::new(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}))))
.send(ObjectInfoOrErr {
item: Some(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}),
err: None,
})
.await
.is_err()
{
@@ -621,7 +639,7 @@ async fn list_tier_free_versions_for_tier(
}
}
api.walk_for_tier_recovery(cancel, &bucket_name, tx, recovery_walk_options(bucket_walk_limit, object_marker))
api.walk(cancel, &bucket_name, "", tx, recovery_walk_options(bucket_walk_limit, object_marker))
.await
}
});
@@ -651,25 +669,21 @@ async fn list_tier_free_versions_for_tier(
},
};
page.scanned_entries += 1;
let entry = match item {
Ok(entry) => entry,
Err(err) => {
cancel.cancel();
receive_error = Some(err);
break;
}
};
if let Some(err) = item.err {
cancel.cancel();
receive_error = Some(err);
break;
}
if draining_after_truncation {
continue;
}
let name = match &entry {
TierRecoveryEntry::Version(oi) => oi.name.as_str(),
TierRecoveryEntry::Unreadable { object } => object.as_str(),
let Some(oi) = item.item else {
continue;
};
if last_seen_object.as_deref() != Some(name) && scanned_objects >= bucket_walk_limit {
if last_seen_object.as_deref() != Some(oi.name.as_str()) && scanned_objects >= bucket_walk_limit {
// The disk listing limit follows S3-visible counting rules and
// does not charge metadata containing only hidden/free versions.
// Charge the recovery budget by key, including unreadable metadata.
// Enforce the repair budget again at the decoded-object boundary.
page.truncated = true;
page.next_bucket_marker = Some(bucket.name.clone());
page.next_object_marker = last_seen_object.clone();
@@ -678,9 +692,9 @@ async fn list_tier_free_versions_for_tier(
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
continue;
}
record_scanned_object(&mut last_seen_object, &mut scanned_objects, name);
record_scanned_object(&mut last_seen_object, &mut scanned_objects, &oi.name);
if let Some(cursor) = &truncated_after
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != name)
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != oi.name.as_str())
{
page.truncated = true;
cancel.cancel();
@@ -688,14 +702,6 @@ async fn list_tier_free_versions_for_tier(
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
continue;
}
let oi = match entry {
TierRecoveryEntry::Version(oi) => *oi,
TierRecoveryEntry::Unreadable { object } => {
page.unreadable_objects += 1;
first_unreadable.get_or_insert_with(|| (bucket.name.clone(), object));
continue;
}
};
if is_recoverable_tier_free_version_for_tier(&oi, tier_name) {
let current_cursor = RecoveryCursor {
bucket: bucket.name.clone(),
@@ -750,18 +756,6 @@ async fn list_tier_free_versions_for_tier(
page.next_object_marker = None;
}
if let Some((bucket, object)) = first_unreadable {
tracing::warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LIFECYCLE,
state = "free_version_recovery_unreadable_metadata",
unreadable_objects = page.unreadable_objects,
sample_bucket = ?bucket,
sample_object = ?object,
"Retained unreadable objects during tier free-version recovery"
);
}
Ok(page)
}
@@ -829,7 +823,6 @@ mod tests {
next_object_marker: None,
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -850,7 +843,6 @@ mod tests {
next_object_marker: Some("object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -871,7 +863,6 @@ mod tests {
next_object_marker: Some("object-a".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
let mut cursor = RetryCursor::new(stats.next_bucket_marker.clone(), stats.next_object_marker.clone());
@@ -982,7 +973,6 @@ mod tests {
next_object_marker: None,
scanned_entries: DEFAULT_FREE_VERSION_RECOVERY_SCAN_LIMIT,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
+18 -320
View File
@@ -2090,74 +2090,6 @@ pub(crate) fn bump_local_meta_mutation_gen() {
LOCAL_META_MUTATION_GEN.fetch_add(1, std::sync::atomic::Ordering::Release);
}
/// Bumps `LOCAL_META_MUTATION_GEN` for mutations in `RUSTFS_META_BUCKET` except
/// known non-authority scanner, data-usage, and shutdown-marker paths.
///
/// The classifier is fail-closed: only exact 1-, 2-, or 3-segment paths naming
/// `unclean-shutdown`, root scanner summary/usage files under `buckets/`, or
/// per-bucket `.usage-cache.bin[.bkp]` files (with at most one optional trailing
/// `/<uuid>` data-dir/transaction cleanup segment) skip the generation bump.
/// All bucket authority files (`.metadata.bin`, `.bucket-incarnation`), bucket
/// metadata directories (including names ending in `.usage-cache.bin`), and any
/// other `.rustfs.sys` paths bump `LOCAL_META_MUTATION_GEN`.
pub(crate) fn maybe_bump_local_meta_mutation_gen_for_path(volume: &str, path: &str) {
if volume != crate::disk::RUSTFS_META_BUCKET {
return;
}
if !is_non_authority_meta_bucket_path(path) {
bump_local_meta_mutation_gen();
}
}
fn is_non_authority_meta_bucket_path(path: &str) -> bool {
let trimmed = path.trim_matches('/');
if trimmed.is_empty() {
return false;
}
let normalized = match trimmed.rsplit_once('/') {
Some((prefix, tail)) if !prefix.is_empty() && Uuid::parse_str(tail).is_ok() => prefix,
_ => trimmed,
};
if normalized == crate::disk::UNCLEAN_SHUTDOWN_MARKER_PATH {
return true;
}
let Some(rest) = normalized
.strip_prefix(crate::disk::BUCKET_META_PREFIX)
.and_then(|rest| rest.strip_prefix('/'))
else {
return false;
};
if rest.is_empty() {
return false;
}
match rest.split_once('/') {
None => {
let base = rest.strip_suffix(".bkp").unwrap_or(rest);
base == crate::data_usage::DATA_USAGE_CACHE_NAME
|| matches!(
rest,
".usage.v2.json"
| ".usage.v2.json.bkp"
| ".usage.v2.json.recovery-pending.json"
| ".usage.observed.json"
| ".usage.json"
| ".usage.json.bkp"
| ".bloomcycle.bin"
| ".compression.json"
| ".background-heal.json"
)
}
Some((bucket, name)) => {
!bucket.is_empty()
&& !bucket.contains('/')
&& bucket != "."
&& bucket != ".."
&& !name.contains('/')
&& name.strip_suffix(".bkp").unwrap_or(name) == crate::data_usage::DATA_USAGE_CACHE_NAME
}
}
}
pub(crate) fn current_local_meta_mutation_gen() -> u64 {
LOCAL_META_MUTATION_GEN.load(std::sync::atomic::Ordering::Acquire)
}
@@ -2203,20 +2135,6 @@ pub struct BucketMetadataSys {
/// then the metadata map. It is only ever taken as the first of those, so
/// it cannot invert against a path that already holds one of the others.
lazy_load_locks: Arc<MetadataPublishLockRegistry>,
/// Deduplicates concurrent cold-cache loads in
/// [`Self::read_authoritative_metadata_from_disk_under_guard`] when
/// `can_use_local_authority_cache` is true.
///
/// Lock order: caller's bucket lifecycle / metadata-transaction guard ->
/// `authority_load_locks` -> disk reads. Separate from `lazy_load_locks`
/// (which is acquired before the bucket namespace lock); holders of
/// `authority_load_locks` never acquire `lazy_load_locks`,
/// `metadata_publish_locks`, or `metadata_map`. If the leader errors or the
/// generation moves during the load, queued followers serialize and retry
/// under their own held guard.
authority_load_locks: Arc<MetadataPublishLockRegistry>,
#[cfg(test)]
authority_disk_loads: Arc<std::sync::atomic::AtomicUsize>,
#[cfg(test)]
lazy_load_lock_probe: Arc<std::sync::atomic::AtomicBool>,
/// Counts disk loads taken by the lazy `get_config` path, so a test can
@@ -2251,11 +2169,6 @@ impl BucketMetadataSys {
lazy_load_locks: Arc::new(MetadataPublishLockRegistry {
locks: StdMutex::new(HashMap::new()),
}),
authority_load_locks: Arc::new(MetadataPublishLockRegistry {
locks: StdMutex::new(HashMap::new()),
}),
#[cfg(test)]
authority_disk_loads: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
#[cfg(test)]
lazy_load_lock_probe: Arc::new(std::sync::atomic::AtomicBool::new(false)),
#[cfg(test)]
@@ -2340,7 +2253,6 @@ impl BucketMetadataSys {
.await?;
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, persisted, &guard)
.await
.map(|_| ())
}
#[cfg(test)]
@@ -2379,12 +2291,6 @@ impl BucketMetadataSys {
Self::bucket_lock_in(&self.lazy_load_locks, bucket)
}
/// Per-bucket gate for cold `local_authority_cache` loads. See
/// [`Self::authority_load_locks`].
fn authority_load_lock(&self, bucket: &str) -> Arc<Mutex<MetadataPublishLockState>> {
Self::bucket_lock_in(&self.authority_load_locks, bucket)
}
fn bucket_lock_in(registry: &Arc<MetadataPublishLockRegistry>, bucket: &str) -> Arc<Mutex<MetadataPublishLockState>> {
let mut locks = registry.locks.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
locks.get(bucket).and_then(Weak::upgrade).unwrap_or_else(|| {
@@ -2644,7 +2550,7 @@ impl BucketMetadataSys {
metadata: BucketMetadata,
persisted: bool,
namespace_guard: &rustfs_lock::NamespaceLockGuard,
) -> Result<bool> {
) -> Result<()> {
self.revoke_pending_bucket_creation(bucket).await;
if !persisted {
let _publish_guard = self
@@ -2657,7 +2563,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(false);
return Ok(());
}
let removed = map.remove(bucket).is_some();
drop(map);
@@ -2668,7 +2574,7 @@ impl BucketMetadataSys {
clear_bucket_overrides(bucket);
clear_on_demand_migration(bucket);
}
return Ok(true);
return Ok(());
}
let _publish_guard = self
.lock_metadata_publish(bucket, namespace_guard, "refreshed bucket metadata publish")
@@ -2681,7 +2587,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(false);
return Ok(());
}
map.insert(bucket.to_string(), Arc::clone(&metadata));
drop(map);
@@ -2690,7 +2596,7 @@ impl BucketMetadataSys {
sync_bucket_target_sys(bucket, &metadata).await;
sync_bucket_overrides(bucket, &metadata);
sync_on_demand_migration(bucket, &metadata);
Ok(true)
Ok(())
}
pub async fn get(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
@@ -2974,35 +2880,25 @@ impl BucketMetadataSys {
namespace_guard: &rustfs_lock::NamespaceLockGuard,
) -> Result<()> {
self.revoke_pending_bucket_creation(bucket).await;
let expected = self.metadata_map.read().await.get(bucket).cloned();
if !self
.bucket_exists(bucket, namespace_guard, "peer bucket metadata existence check")
.await?
{
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
// A concurrent publication can reject the snapshot we read. Re-read
// from storage so a newer committed config does not lose its reload to
// an older one that happened to publish first.
for _ in 0..3 {
let expected = self.metadata_map.read().await.get(bucket).cloned();
let (metadata, persisted) = await_bucket_namespace_operation(
Some(namespace_guard),
bucket,
"peer bucket metadata load",
load_bucket_metadata_parse_with_presence(self.object_store(), bucket, true),
)
.await?;
if !persisted {
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
if self
.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
.await?
{
return Ok(());
}
let (metadata, persisted) = await_bucket_namespace_operation(
Some(namespace_guard),
bucket,
"peer bucket metadata load",
load_bucket_metadata_parse_with_presence(self.object_store(), bucket, true),
)
.await?;
if !persisted {
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
Err(Error::other("bucket metadata changed repeatedly during peer reload"))
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
.await
}
pub async fn get_config(&self, bucket: &str) -> Result<(Arc<BucketMetadata>, bool)> {
@@ -3579,7 +3475,7 @@ impl BucketMetadataSys {
let store = self.object_store();
let can_use_local_authority_cache = !store.ctx.lock_manager().is_disabled() && store.all_disks_local_and_online();
let mut gen_before = current_local_meta_mutation_gen();
let gen_before = current_local_meta_mutation_gen();
let cached_authority = can_use_local_authority_cache
.then(|| {
self.local_authority_cache
@@ -3603,43 +3499,6 @@ impl BucketMetadataSys {
}
}
let _load_guard = if can_use_local_authority_cache {
let load_lock = self.authority_load_lock(bucket);
let acquired = Box::pin(await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata authoritative snapshot",
async { Ok(load_lock.lock_owned().await) },
))
.await?;
gen_before = current_local_meta_mutation_gen();
let cached_after_lock = self
.local_authority_cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(bucket)
.filter(|(cached_gen, _)| *cached_gen == gen_before)
.map(|(_, bm)| Arc::clone(bm));
if let Some(cached) = cached_after_lock {
await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata authoritative snapshot",
std::future::ready(Ok::<_, Error>(())),
)
.await?;
if current_local_meta_mutation_gen() == gen_before && store.all_disks_local_and_online() {
return Ok(BucketMetadataAuthority::Authoritative(cached));
}
}
Some(acquired)
} else {
None
};
#[cfg(test)]
self.authority_disk_loads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (bucket_info_res, metadata_res) = tokio::join!(
Box::pin(await_bucket_namespace_operation(
Some(guard),
@@ -7122,165 +6981,4 @@ mod tests {
assert!(!should_refresh);
}
#[tokio::test]
#[serial]
async fn concurrent_authoritative_metadata_loads_singleflight_and_survive_usage_cache_writes() {
use std::sync::atomic::Ordering;
const CHILD: &str = "RUSTFS_TEST_AUTHORITY_SINGLEFLIGHT_CHILD";
const TEST: &str =
"bucket::metadata_sys::tests::concurrent_authoritative_metadata_loads_singleflight_and_survive_usage_cache_writes";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
.args(["--exact", TEST, "--nocapture", "--test-threads=1"])
.env(CHILD, "1")
.output()
.expect("authority singleflight subprocess");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "authority singleflight child failed: {stdout}{stderr}");
assert!(
stdout.contains("AUTHORITY_SINGLEFLIGHT_OK"),
"authority singleflight child must execute all assertions: {stdout}"
);
return;
}
let (dirs, ecstore) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(ecstore.clone(), Vec::new()).await;
let sys_lock = bucket_metadata_sys_of(&ecstore.ctx).expect("initialized bucket_metadata_sys");
let sys = Arc::new(sys_lock.read().await.clone());
let bucket = "authority-singleflight-bucket";
for dir in &dirs {
std::fs::create_dir_all(dir.path().join(bucket)).expect("bucket volume should exist");
}
sys.persist_new_and_set(BucketMetadata::new(bucket))
.await
.expect("persist committed bucket metadata and incarnation sidecar");
sys.local_authority_cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
sys.authority_disk_loads.store(0, Ordering::Relaxed);
// Hold one leader lock so all 16 waiters queue behind authority_load_lock after missing the cold cache.
let held_load_lock = sys.authority_load_lock(bucket);
let held_load_guard = held_load_lock.lock_owned().await;
let gen_before_burst = current_local_meta_mutation_gen();
let waiters = 16;
let mut handles = Vec::with_capacity(waiters);
for _ in 0..waiters {
let sys = Arc::clone(&sys);
let store = Arc::clone(&ecstore);
handles.push(tokio::spawn(async move {
let guard = acquire_bucket_metadata_transaction_read_lock_in(&store.ctx, bucket)
.await
.expect("transaction read lock");
match sys
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
.await
.expect("authoritative read")
{
BucketMetadataAuthority::Authoritative(bm) => bm,
_ => panic!("expected Authoritative metadata"),
}
}));
}
tokio::time::sleep(Duration::from_millis(30)).await;
drop(held_load_guard);
let mut results = Vec::with_capacity(waiters);
for h in handles {
results.push(h.await.expect("waiter task joins"));
}
assert_eq!(
current_local_meta_mutation_gen(),
gen_before_burst,
"generation must stay stable across cold singleflight burst"
);
assert_eq!(
sys.authority_disk_loads.load(Ordering::Relaxed),
1,
"16 concurrent cold authority reads must collapse into 1 disk load"
);
for bm in &results[1..] {
assert!(Arc::ptr_eq(&results[0], bm), "followers must share the leader's Arc<BucketMetadata>");
}
// Verify real store config writes to non-authority .rustfs.sys paths do NOT bump LOCAL_META_MUTATION_GEN.
let gen_before = current_local_meta_mutation_gen();
crate::config::com::save_config(ecstore.clone(), "buckets/.usage-cache.bin", b"usage-snapshot".to_vec())
.await
.expect("save root usage cache");
crate::config::com::save_config(ecstore.clone(), "buckets/.usage-cache.bin.bkp", b"usage-snapshot-bkp".to_vec())
.await
.expect("save root usage cache bkp");
assert_eq!(
current_local_meta_mutation_gen(),
gen_before,
"real usage-cache writes must not bump LOCAL_META_MUTATION_GEN"
);
let tx_uuid = Uuid::new_v4();
for inert_path in [
"unclean-shutdown".to_string(),
"buckets/.usage-cache.bin".to_string(),
"buckets/.usage-cache.bin.bkp".to_string(),
format!("buckets/.usage-cache.bin/{tx_uuid}"),
format!("buckets/{bucket}/.usage-cache.bin"),
format!("buckets/{bucket}/.usage-cache.bin.bkp"),
format!("buckets/{bucket}/.usage-cache.bin.bkp/{tx_uuid}"),
"buckets/.usage.v2.json".to_string(),
"buckets/.usage.v2.json.bkp".to_string(),
"buckets/.usage.v2.json.recovery-pending.json".to_string(),
"buckets/.usage.observed.json".to_string(),
"buckets/.usage.json".to_string(),
"buckets/.usage.json.bkp".to_string(),
"buckets/.bloomcycle.bin".to_string(),
"buckets/.compression.json".to_string(),
"buckets/.background-heal.json".to_string(),
] {
maybe_bump_local_meta_mutation_gen_for_path(crate::disk::RUSTFS_META_BUCKET, &inert_path);
assert_eq!(
current_local_meta_mutation_gen(),
gen_before,
"inert path {inert_path} must not invalidate local_authority_cache"
);
}
// Warm hit after inert writes still performs 0 additional disk loads.
let guard = acquire_bucket_metadata_transaction_read_lock_in(&ecstore.ctx, bucket)
.await
.expect("transaction read lock");
let _ = sys
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
.await
.expect("warm cached read");
assert_eq!(sys.authority_disk_loads.load(Ordering::Relaxed), 1);
// Negative controls: authority paths and suffix-bearing bucket names MUST bump LOCAL_META_MUTATION_GEN.
for authority_path in [
format!("buckets/{bucket}/.metadata.bin"),
format!("buckets/{bucket}/.bucket-incarnation"),
format!("buckets/{bucket}/.metadata.bin/{tx_uuid}"),
"buckets/tenant.usage-cache.bin".to_string(),
format!("buckets/tenant.usage-cache.bin/{tx_uuid}"),
format!("buckets/{bucket}"),
"buckets".to_string(),
"format.json".to_string(),
] {
let before = current_local_meta_mutation_gen();
maybe_bump_local_meta_mutation_gen_for_path(crate::disk::RUSTFS_META_BUCKET, &authority_path);
assert_eq!(
current_local_meta_mutation_gen(),
before + 1,
"authority path {authority_path} must bump LOCAL_META_MUTATION_GEN"
);
}
println!("AUTHORITY_SINGLEFLIGHT_OK");
}
}
@@ -13,8 +13,6 @@
// limitations under the License.
pub(crate) use crate::services::event_notification::EventArgs;
#[cfg(test)]
pub(crate) use crate::services::event_notification::test_recorder;
use super::runtime_boundary;
@@ -89,11 +89,7 @@ impl ReplicationLifecycleBridge {
}
}
pub(crate) async fn schedule_delete(
bucket: String,
delete_object: DeletedObject,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
#[cfg(test)]
{
SCHEDULED_DELETE_OBJECTS
@@ -102,7 +98,6 @@ impl ReplicationLifecycleBridge {
.push(delete_object.clone());
}
super::replication_pool::schedule_replication_delete(DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket,
event_type: REPLICATE_INCOMING_DELETE.to_string(),
@@ -22,10 +22,6 @@ use rustfs_utils::path::path_join_buf;
use time::OffsetDateTime;
use super::replication_error_boundary::{Error, Result};
#[cfg(test)]
pub(crate) use crate::bucket::metadata_sys::{
bucket_metadata_sys_of, init_bucket_metadata_sys, set_bucket_metadata_in, test_support,
};
pub(crate) type ReplicationInstanceContext = InstanceContext;
@@ -110,16 +110,13 @@ impl ReplicationObjectBridge {
check_replicate_delete_with_snapshot(object, source, opts, source_error, snapshot)
}
/// Admits replication with the bucket identity verified by the originating mutation.
/// An absent identity suppresses external notifications; workers never infer one by name.
pub async fn schedule_object<S: ReplicationStorage>(
object: ObjectInfo,
storage: Arc<S>,
decision: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
schedule_replication(object, storage, decision, op_type, notification_bucket_incarnation).await;
schedule_replication(object, storage, decision, op_type).await;
}
pub async fn schedule_delete(delete_object: DeletedObjectReplicationInfo) {
@@ -151,16 +148,8 @@ impl ReplicationObjectBridge {
}
}
/// Schedules a committed delete with its originating bucket identity for notifications.
/// An absent identity leaves external notifications unbound.
pub async fn schedule_storage_delete(
delete_object: DeletedObject,
bucket: String,
event_type: String,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
pub async fn schedule_storage_delete(delete_object: DeletedObject, bucket: String, event_type: String) {
Self::schedule_delete(DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket,
event_type,
@@ -169,18 +158,10 @@ impl ReplicationObjectBridge {
.await;
}
/// Schedules committed deletes from one bucket instance, retaining that notification identity.
/// An absent identity leaves external notifications unbound.
pub async fn schedule_storage_deletes(
delete_objects: Vec<DeletedObject>,
bucket: String,
event_type: String,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
pub async fn schedule_storage_deletes(delete_objects: Vec<DeletedObject>, bucket: String, event_type: String) {
let delete_objects = delete_objects
.into_iter()
.map(|delete_object| DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket: bucket.clone(),
event_type: event_type.clone(),
@@ -1016,9 +1016,7 @@ async fn replay_mrf_metadata_entry<S: ReplicationStorage>(
/// admitted targets, carrying over the entry's retry count.
fn admitted_mrf_replicate_object(oi: ObjectInfo, entry: &MrfReplicateEntry, op_type: ReplicationType) -> ReplicateObjectInfo {
let dsc = replicate_decision_for_admitted_targets(&entry.target_arns);
// The journal does not bind this task to a bucket instance. Keep external
// notifications unbound instead of attaching an old task to a reused name.
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type, None);
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type);
roi.retry_count = entry.retry_count.max(0) as u32;
roi
}
@@ -3173,13 +3171,12 @@ pub(crate) async fn schedule_replication<S: ReplicationStorage>(
o: Arc<S>,
dsc: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
let (synchronous, asynchronous) = dsc.partition_by_sync();
let mut async_oi = oi;
if synchronous.replicate_any() {
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type, notification_bucket_incarnation);
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type);
let state = replicate_object(ri, o.clone()).await;
async_oi.replication_status_internal = state.replication_status_internal;
async_oi.version_purge_status_internal = state.version_purge_status_internal;
@@ -3188,7 +3185,7 @@ pub(crate) async fn schedule_replication<S: ReplicationStorage>(
if asynchronous.replicate_any()
&& let Some(pool) = runtime_sources::replication_pool()
{
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type, notification_bucket_incarnation);
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type);
let _ = pool.queue_replica_task(ri).await;
}
}
@@ -3197,7 +3194,6 @@ fn replicate_object_info_from_object_info(
oi: ObjectInfo,
dsc: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) -> ReplicateObjectInfo {
let tgt_statuses = replication_statuses_map(&oi.replication_status_internal.clone().unwrap_or_default());
let purge_statuses = version_purge_statuses_map(&oi.version_purge_status_internal.clone().unwrap_or_default());
@@ -3213,7 +3209,6 @@ fn replicate_object_info_from_object_info(
let checksum = if ssec { oi.checksum.clone() } else { None };
ReplicateObjectInfo {
notification_bucket_incarnation,
name: oi.name,
size: oi.size,
actual_size: asz,
@@ -3355,7 +3350,7 @@ pub async fn queue_replication_metadata(bucket: &str, oi: ObjectInfo, retry_coun
return ReplicationQueueAdmission::Skipped;
}
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata, None);
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata);
roi.retry_count = retry_count;
if let Some(pool) = runtime_sources::replication_pool() {
pool.queue_replica_task(roi).await
@@ -5210,117 +5205,6 @@ mod tests {
}
}
#[test]
fn replication_admission_keeps_original_incarnation_and_mrf_replay_does_not_guess() {
let incarnation = Uuid::new_v4();
let target = "arn:rustfs:replication:target-a";
for op_type in [ReplicationType::Object, ReplicationType::Metadata] {
let object = ObjectInfo {
bucket: "source".to_string(),
name: "object".to_string(),
version_id: Some(Uuid::new_v4()),
..Default::default()
};
let admitted = replicate_object_info_from_object_info(
object.clone(),
test_replicate_decision(&[target]),
op_type,
Some(incarnation),
);
assert_eq!(admitted.notification_bucket_incarnation, Some(incarnation));
let encoded = encode_mrf_file(&[admitted.to_mrf_entry()]).expect("encode queued replication");
let entries = decode_mrf_file(&encoded).expect("decode queued replication");
let replayed = admitted_mrf_replicate_object(object, &entries[0], op_type);
assert_eq!(
replayed.notification_bucket_incarnation, None,
"MRF replay must not infer a bucket instance from a reused name"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial_test::serial]
async fn queued_delete_notifications_keep_origin_across_bucket_recreation() {
use super::super::replication_event_sink::test_recorder;
use super::super::replication_metadata_boundary::{
bucket_metadata_sys_of, init_bucket_metadata_sys, set_bucket_metadata_in,
test_support::isolated_store_over_temp_disks,
};
use super::super::replication_storage_boundary::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
runtime_sources::set_test_object_layer(store.clone()).await;
test_recorder::install();
let bucket = "queued-delete-notification-origin";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original bucket");
let original = store.bucket_incarnation_id(bucket).await.expect("original incarnation");
let queued = DeletedObjectReplicationInfo {
notification_bucket_incarnation: Some(original),
bucket: bucket.to_string(),
target_arn: "arn:rustfs:replication:target-a".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "original-object".to_string(),
version_id: Some(Uuid::new_v4()),
replication_state: Some(ReplicationState {
replicate_decision_str: "malformed-decision".to_string(),
..Default::default()
}),
..Default::default()
},
..Default::default()
};
let encoded = encode_mrf_file(&[queued.to_mrf_entry()]).expect("persist old delete task");
let entries = decode_mrf_file(&encoded).expect("recover old delete task");
let mut replayed = reconstructed_heal_delete_info(
&entries[0],
&ObjectInfo::default(),
&replicate_decision_for_admitted_targets(&entries[0].target_arns),
);
replayed
.delete_object
.replication_state
.as_mut()
.expect("reconstructed replication state")
.replicate_decision_str = "malformed-decision".to_string();
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original bucket");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create replacement bucket");
let replacement = store.bucket_incarnation_id(bucket).await.expect("replacement incarnation");
assert_ne!(original, replacement);
let sys = bucket_metadata_sys_of(&store.ctx).expect("metadata owner");
let mut metadata = (*sys.read().await.get(bucket).await.expect("replacement metadata")).clone();
metadata.notification_config_xml = br#"<NotificationConfiguration><QueueConfiguration><Id>replacement</Id><Queue>arn:rustfs:sqs:us-east-1:replacement:webhook</Queue><Event>s3:Replication:*</Event></QueueConfiguration></NotificationConfiguration>"#.to_vec();
set_bucket_metadata_in(&store.ctx, metadata)
.await
.expect("install replacement notification configuration");
assert!(!replicate_delete_with_outcome(queued, store.clone()).await);
assert!(!replicate_delete_with_outcome(replayed, store).await);
let events = test_recorder::recorded_for_bucket(bucket);
assert_eq!(events.len(), 2, "both worker failures must emit an observable local event");
assert!(
events
.iter()
.all(|event| event.object == "original-object" && event.event_name == "s3:Replication:OperationNotTracked")
);
assert_eq!(events[0].bucket_incarnation_id, Some(original));
assert_eq!(
events[1].bucket_incarnation_id, None,
"a replay without provenance must not acquire the replacement bucket's identity"
);
assert!(events.iter().all(|event| event.bucket_incarnation_id != Some(replacement)));
}
#[test]
fn replicate_object_info_from_object_info_preserves_ssec_checksum() {
let checksum = bytes::Bytes::from_static(b"ssec-checksum");
@@ -5335,7 +5219,7 @@ mod tests {
..Default::default()
};
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object, None);
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object);
assert!(ri.ssec);
assert_eq!(ri.checksum, Some(checksum));
@@ -5351,12 +5235,8 @@ mod tests {
user_tags: Arc::new("owner=a3".to_string()),
..Default::default()
};
let live = replicate_object_info_from_object_info(
object.clone(),
test_replicate_decision(&[target]),
ReplicationType::Metadata,
None,
);
let live =
replicate_object_info_from_object_info(object.clone(), test_replicate_decision(&[target]), ReplicationType::Metadata);
let persisted = live.to_mrf_entry();
let encoded = encode_mrf_file(std::slice::from_ref(&persisted)).expect("metadata MRF entry should encode");
let decoded = decode_mrf_file(&encoded).expect("metadata MRF entry should decode");
@@ -2274,7 +2274,6 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
let replication_generation = oi.replication_generation_snapshot();
Ok(ReplicateObjectInfo {
notification_bucket_incarnation: None,
name: oi.name.clone(),
size: oi.size,
actual_size,
@@ -2449,7 +2448,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Failed to parse replicate decision"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2531,7 +2529,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Failed to verify source delete-marker state before replication"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2566,7 +2563,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Skipping replication delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2597,7 +2593,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Skipping replication delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2697,7 +2692,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Replication resync task failed"
);
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2806,7 +2800,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(object) => {
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object,
@@ -2832,7 +2825,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
);
}
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3164,7 +3156,6 @@ async fn purge_stale_delete_marker_targets(bucket: &str, dobj: &DeletedObjectRep
}
async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &DeletedObjectReplicationInfo, storage: Arc<S>) -> bool {
let incarnation_id = dobj.notification_bucket_incarnation;
let bucket = &dobj.bucket;
let object_name = &dobj.delete_object.object_name;
let admitted_target_arns = dobj.admitted_target_arns();
@@ -3185,7 +3176,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because replication config is missing"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3209,7 +3199,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because replication config lookup failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3244,7 +3233,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3273,7 +3261,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3321,7 +3308,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because target client is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3352,7 +3338,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationFailed.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3389,7 +3374,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationFailed.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -4253,7 +4237,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Skipping replication object"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4277,7 +4260,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Skipping replication object"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4344,7 +4326,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Replication resync task failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4489,7 +4470,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
if publication.emit_event {
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object: object_info,
@@ -4632,7 +4612,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4648,7 +4627,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
else {
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4692,7 +4670,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4724,7 +4701,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4750,7 +4726,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4882,7 +4857,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4911,7 +4885,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -5009,7 +4982,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
else {
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -5043,7 +5015,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let size = match object_info.get_actual_size() {
Ok(size) => size,
Err(e) => {
note_replicate_all_size_unavailable(&bucket, &tgt_client, object_info, &e, self.notification_bucket_incarnation);
note_replicate_all_size_unavailable(&bucket, &tgt_client, object_info, &e);
return rinfo;
}
};
@@ -5052,7 +5024,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let transfer_size = if self.ssec { object_info.size } else { size };
if tgt_client.bucket.is_empty() {
note_replicate_all_target_bucket_empty(&bucket, &tgt_client, object_info, self.notification_bucket_incarnation);
note_replicate_all_target_bucket_empty(&bucket, &tgt_client, object_info);
return rinfo;
}
@@ -5098,15 +5070,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let (put_opts, is_multipart) = match replication_put_object_options_for_target(&tgt_client, &object_info) {
Ok((put_opts, is_mp)) => (put_opts, is_mp),
Err(e) => {
fail_replicate_all_put_options(
&mut rinfo,
&tgt_client,
&bucket,
object_info,
&e,
start_time,
self.notification_bucket_incarnation,
);
fail_replicate_all_put_options(&mut rinfo, &tgt_client, &bucket, object_info, &e, start_time);
return rinfo;
}
};
@@ -5210,7 +5174,6 @@ fn note_replicate_all_target_offline(roi: &ReplicateObjectInfo, bucket: &str, tg
"Skipped replication because target is offline"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: roi.to_object_info(),
@@ -5249,7 +5212,6 @@ fn note_replicate_all_reader_unavailable(roi: &ReplicateObjectInfo, bucket: &str
"Skipped replication because object reader is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: roi.to_object_info(),
@@ -5261,13 +5223,7 @@ fn note_replicate_all_reader_unavailable(roi: &ReplicateObjectInfo, bucket: &str
/// Log and notify that replication was skipped because the actual object size
/// is unavailable.
fn note_replicate_all_size_unavailable(
bucket: &str,
tgt_client: &TargetClient,
object_info: ObjectInfo,
e: &std::io::Error,
incarnation_id: Option<uuid::Uuid>,
) {
fn note_replicate_all_size_unavailable(bucket: &str, tgt_client: &TargetClient, object_info: ObjectInfo, e: &std::io::Error) {
debug!(
event = EVENT_RESYNC_RUNTIME_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
@@ -5280,7 +5236,6 @@ fn note_replicate_all_size_unavailable(
"Skipped replication because actual object size is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5291,12 +5246,7 @@ fn note_replicate_all_size_unavailable(
/// Log and notify that replication was skipped because the target bucket is
/// empty.
fn note_replicate_all_target_bucket_empty(
bucket: &str,
tgt_client: &TargetClient,
object_info: ObjectInfo,
incarnation_id: Option<uuid::Uuid>,
) {
fn note_replicate_all_target_bucket_empty(bucket: &str, tgt_client: &TargetClient, object_info: ObjectInfo) {
debug!(
event = EVENT_RESYNC_RUNTIME_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
@@ -5308,7 +5258,6 @@ fn note_replicate_all_target_bucket_empty(
"Skipped replication because target bucket is empty"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5422,7 +5371,6 @@ async fn resolve_replicate_all_action(
"Skipping replication because newer target version exists"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info.clone(),
@@ -5546,7 +5494,6 @@ async fn resolve_replicate_all_action(
"Failed replication head-object fallback"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5579,7 +5526,6 @@ async fn resolve_replicate_all_action(
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5608,7 +5554,6 @@ fn fail_replicate_all_put_options(
object_info: ObjectInfo,
e: &Error,
start_time: OffsetDateTime,
incarnation_id: Option<uuid::Uuid>,
) {
rinfo.replication_status = ReplicationStatusType::Failed;
rinfo.error = Some(e.to_string());
@@ -5624,7 +5569,6 @@ fn fail_replicate_all_put_options(
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -24,8 +24,6 @@ pub(crate) use crate::object_api::{
};
#[cfg(test)]
pub(crate) use crate::object_api::{NamespaceLockFence, NamespaceLockSignalTestFence};
#[cfg(test)]
pub(crate) use crate::storage_api_contracts::bucket::{BucketOperations, DeleteBucketOptions, MakeBucketOptions};
pub(crate) use crate::storage_api_contracts::list::{
ListOperations, StorageListObjectVersionsInfo, StorageListObjectsV2Info, StorageObjectInfoOrErr, StorageWalkOptions,
};
@@ -18,8 +18,6 @@ use super::replication_bandwidth_boundary::ReplicationBucketMonitor;
use super::replication_pool::DynReplicationPool;
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::ReplicationObjectStore;
#[cfg(test)]
pub(crate) use crate::runtime::global::set_object_layer as set_test_object_layer;
use crate::runtime::sources;
pub use crate::runtime::sources::{
ScannerDirtyUsageMutationObserver, ScannerDirtyUsageMutationSource, set_scanner_dirty_usage_mutation_observer,
+19 -551
View File
@@ -1102,22 +1102,6 @@ struct RenameAdmissionGrant {
batch: bool,
}
struct QuarantinedRenamePermit {
permit: Option<OwnedSemaphorePermit>,
batch: bool,
items: usize,
}
impl Drop for QuarantinedRenamePermit {
fn drop(&mut self) {
let Some(permit) = self.permit.take() else {
return;
};
drop(permit);
rustfs_io_metrics::record_ecstore_rename_quarantine_released(self.batch, self.items);
}
}
impl RenameAdmissionGrant {
fn release_one(&mut self) -> bool {
self.permit.as_mut().is_some_and(|permit| permit.split(1).is_some())
@@ -1127,7 +1111,7 @@ impl RenameAdmissionGrant {
drop(self.permit.take());
}
fn quarantine_after_ambiguity(mut self) {
fn quarantine_until(mut self, deadline: tokio::time::Instant) {
let Some(permit) = self.permit.take() else {
return;
};
@@ -1135,26 +1119,19 @@ impl RenameAdmissionGrant {
if items == 0 {
return;
}
// The RPC deadline has already expired when timeout ambiguity is
// detected. Hold admission for another operation timeout so detached
// server-side disk work cannot immediately be replaced by new work.
let hold = get_max_timeout_duration();
let release_at = tokio::time::Instant::now() + hold;
let hold = deadline.saturating_duration_since(tokio::time::Instant::now());
rustfs_io_metrics::record_ecstore_rename_quarantine(self.batch, items, hold);
let permit = QuarantinedRenamePermit {
permit: Some(permit),
batch: self.batch,
items,
};
let batch = self.batch;
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
tokio::time::sleep_until(release_at).await;
tokio::time::sleep_until(deadline).await;
drop(permit);
rustfs_io_metrics::record_ecstore_rename_quarantine_released(batch, items);
});
} else {
// Without a runtime there is no safe deadline task. Leaking until
// process exit is safer than admitting work over a still-running mutation.
rustfs_io_metrics::record_ecstore_rename_quarantine_no_runtime(self.batch, items);
rustfs_io_metrics::record_ecstore_rename_quarantine_no_runtime(batch, items);
std::mem::forget(permit);
}
}
@@ -1210,7 +1187,7 @@ impl Drop for RenameBatchCallGuard {
if self.dispatch_state == RenameAdmissionDispatchState::MayHavePublished
&& let Some(admission) = self.admission.take()
{
admission.quarantine_after_ambiguity();
admission.quarantine_until(self.deadline);
}
}
}
@@ -1251,7 +1228,7 @@ impl RemoteRenameBatchStream {
}
self.terminal = true;
if let Some(admission) = self.admission.take() {
admission.quarantine_after_ambiguity();
admission.quarantine_until(self.deadline);
}
error
}
@@ -1325,7 +1302,7 @@ impl Drop for RemoteRenameBatchStream {
rustfs_io_metrics::record_ecstore_rename_batch_terminal_missing(missing);
}
if let Some(admission) = self.admission.take() {
admission.quarantine_after_ambiguity();
admission.quarantine_until(self.deadline);
}
}
}
@@ -2839,12 +2816,7 @@ impl RemoteDisk {
{
Ok(Ok(permit)) => (Ok(permit), false),
Ok(Err(_)) => (Err(Error::RemoteClientUnavailable("internode rename admission closed".to_owned())), false),
Err(_) => {
if started.is_none() {
rustfs_io_metrics::record_ecstore_rename_admission(item_count > 1, item_count, Duration::ZERO, true);
}
(Err(DiskError::DiskOngoingReq), true)
}
Err(_) => (Err(DiskError::DiskOngoingReq), true),
};
if let Some(started) = started {
rustfs_io_metrics::record_ecstore_rename_admission(item_count > 1, item_count, started.elapsed(), timed_out);
@@ -2911,11 +2883,7 @@ fn encode_delete_options_msgpack(value: &DeleteOptions) -> Result<Vec<u8>> {
}
fn encode_file_info_msgpack(value: &FileInfo) -> Result<Vec<u8>> {
// Inline shards dominate the encoded payload. Reserving their known size
// avoids repeated growth while retaining the bounded base hint for metadata.
let inline_bytes = value.data.as_ref().map_or(0, Bytes::len);
let capacity = FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT.saturating_add(inline_bytes);
encode_msgpack_with_capacity(value, capacity)
encode_msgpack_with_capacity(value, FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT)
}
fn encode_file_info_versions_msgpack(value: &FileInfoVersions) -> Result<Vec<u8>> {
@@ -6446,145 +6414,6 @@ mod tests {
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_batch_unimplemented_releases_real_tonic_admission() {
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("rename batch peer must bind");
temp_env::async_with_vars([(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true"))], async {
let remote = remote_disk_for_addr(&peer.addr).await;
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let file_infos = vec![sample_rename_data_file_info(), sample_rename_data_file_info()];
let result = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.await;
assert!(matches!(result, Err(RenameBatchStartError::UnsupportedBeforeStream)));
assert_eq!(peer.peer.rename_batch_calls(), 1, "the real peer must observe one batch attempt");
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT,
"call-level UNIMPLEMENTED must release every batch permit without quarantine"
);
remote.cancel_token.cancel();
rustfs_protos::evict_failed_connection(&peer.addr).await;
})
.await;
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_batch_real_tonic_stream_decodes_out_of_order_items_and_releases_permits() {
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("rename batch peer must bind");
peer.peer.serve_rename_batch_results(usize::MAX);
temp_env::async_with_vars([(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true"))], async {
let remote = remote_disk_for_addr(&peer.addr).await;
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
for width in [2_usize, 4] {
let file_infos = (0..width).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.await
.unwrap_or_else(|_| panic!("{width}-item real batch must start"));
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - width,
"the batch owns one permit per pending item"
);
for completed in 1..=width {
let expected_slot = width - completed;
let outcome = stream
.next_outcome()
.await
.expect("real batch stream item must decode")
.expect("real batch stream must contain every item");
assert_eq!(outcome.slot, expected_slot, "the test peer returns items in reverse order");
let response = outcome.result.expect("real batch result payload must decode");
assert_eq!(response.sign, Some(u32::try_from(expected_slot).unwrap().to_be_bytes().to_vec()));
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - width + completed,
"each decoded item releases exactly one permit"
);
}
assert!(stream.next_outcome().await.expect("complete real stream EOF").is_none());
drop(stream);
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
assert_eq!(peer.peer.rename_batch_calls(), 2);
remote.cancel_token.cancel();
rustfs_protos::evict_failed_connection(&peer.addr).await;
})
.await;
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_batch_real_partial_eof_quarantines_only_missing_items() {
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("rename batch peer must bind");
peer.peer.serve_rename_batch_results(1);
temp_env::async_with_vars(
[
(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true")),
(rustfs_config::ENV_DRIVE_MAX_TIMEOUT_DURATION, Some("1")),
],
async {
let remote = remote_disk_for_addr(&peer.addr).await;
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let file_infos = (0..4).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.await
.unwrap_or_else(|_| panic!("real partial batch must start"));
let outcome = stream
.next_outcome()
.await
.expect("the first real response must decode")
.expect("the partial stream must return one response");
assert_eq!(outcome.slot, 3);
assert!(outcome.result.is_ok());
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3,
"the completed item releases one permit before EOF"
);
let error = match stream.next_outcome().await {
Err(error) => error,
Ok(_) => panic!("real partial EOF must be commit-ambiguous"),
};
assert!(matches!(error, DiskError::Unexpected));
assert_eq!(peer.peer.rename_batch_calls(), 1);
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3,
"only missing item permits enter the fresh ambiguity quarantine"
);
drop(stream);
remote.cancel_token.cancel();
rustfs_protos::evict_failed_connection(&peer.addr).await;
},
)
.await;
peer.stop().await;
}
#[tokio::test]
async fn quota_fence_old_peer_rejects_without_legacy_fallback() {
runtime_sources::ensure_test_rpc_secret();
@@ -6770,9 +6599,7 @@ mod tests {
);
assert_eq!(
remote
.pool_meta_native_recovery(PoolMetaNativeRecoveryRequest::Inspect {
object: crate::disk::PoolMetaNativeObject::PoolBin,
})
.pool_meta_native_recovery(PoolMetaNativeRecoveryRequest::Probe {})
.await,
Err(DiskError::UnsupportedDisk),
);
@@ -6783,7 +6610,7 @@ mod tests {
"/node_service.NodeService/UndoPoolMetaWrite",
"/node_service.NodeService/PoolMetaNativeRecovery"
],
"protected mutations and native inspection must never fall back to legacy RPCs",
"protected mutations and capability probes must never fall back to legacy RPCs",
);
peer.stop().await;
}
@@ -7393,8 +7220,6 @@ mod tests {
audience: String,
disk_info_calls: Arc<AtomicU32>,
read_all_calls: Arc<AtomicU32>,
rename_batch_calls: Arc<AtomicU32>,
rename_batch_result_limit: Arc<StdMutex<Option<usize>>>,
object_read_all_disks: Arc<StdMutex<Vec<String>>>,
format_data: Bytes,
read_all_data: Bytes,
@@ -7422,8 +7247,6 @@ mod tests {
audience,
disk_info_calls: Arc::new(AtomicU32::new(0)),
read_all_calls: Arc::new(AtomicU32::new(0)),
rename_batch_calls: Arc::new(AtomicU32::new(0)),
rename_batch_result_limit: Arc::default(),
object_read_all_disks: Arc::default(),
format_data,
read_all_data,
@@ -7448,17 +7271,6 @@ mod tests {
self.read_all_calls.load(Ordering::Acquire)
}
fn serve_rename_batch_results(&self, limit: usize) {
*self
.rename_batch_result_limit
.lock()
.expect("rename batch result limit lock poisoned") = Some(limit);
}
fn rename_batch_calls(&self) -> u32 {
self.rename_batch_calls.load(Ordering::Acquire)
}
fn object_read_all_disks(&self) -> Vec<String> {
self.object_read_all_disks
.lock()
@@ -7497,70 +7309,6 @@ mod tests {
fn call(&mut self, request: http::Request<B>) -> Self::Future {
match request.uri().path() {
"/node_service.NodeService/RenameDataBatch" => {
type RenameBatchStream = Pin<
Box<dyn futures_util::Stream<Item = std::result::Result<RenameDataBatchResult, Status>> + Send + 'static>,
>;
#[derive(Clone)]
struct RenameDataBatchSvc(AuthenticatedReadPeer);
impl tonic::server::ServerStreamingService<RenameDataBatchRequest> for RenameDataBatchSvc {
type Response = RenameDataBatchResult;
type ResponseStream = RenameBatchStream;
type Future =
Pin<Box<dyn Future<Output = std::result::Result<Response<Self::ResponseStream>, Status>> + Send>>;
fn call(&mut self, request: Request<RenameDataBatchRequest>) -> Self::Future {
let peer = self.0.clone();
Box::pin(async move {
peer.rename_batch_calls.fetch_add(1, Ordering::AcqRel);
let Some(limit) = *peer
.rename_batch_result_limit
.lock()
.expect("rename batch result limit lock poisoned")
else {
return Err(Status::unimplemented("test peer does not support rename batch"));
};
peer.verify_auth(&request, "/node_service.NodeService/RenameDataBatch")?;
let canonical_body = rustfs_protos::canonical_rename_data_batch_request_body(request.get_ref())
.map_err(|_| Status::invalid_argument("rename batch body length"))?;
crate::cluster::rpc::verify_tonic_canonical_body_digest(&request, &canonical_body)
.map_err(|_| Status::permission_denied("rename batch body digest"))?;
let responses = request
.into_inner()
.items
.into_iter()
.rev()
.take(limit)
.map(|item| {
let response = RenameDataResp {
sign: Some(item.item_index.to_be_bytes().to_vec()),
..Default::default()
};
let payload = rmp_serde::to_vec_named(&response)
.map_err(|error| Status::internal(error.to_string()))?;
Ok(RenameDataBatchResult {
item_index: item.item_index,
success: true,
error: None,
rename_data_resp_msgpack: payload.into(),
})
})
.collect::<Vec<_>>();
Ok(Response::new(Box::pin(tokio_stream::iter(responses)) as RenameBatchStream))
})
}
}
let peer = self.peer.clone();
Box::pin(async move {
let method = RenameDataBatchSvc(peer);
let codec = tonic_prost::ProstCodec::default();
let mut grpc = tonic::server::Grpc::new(codec);
Ok(grpc.server_streaming(method, request).await)
})
}
"/node_service.NodeService/DiskInfo" => {
#[derive(Clone)]
struct DiskInfoSvc(AuthenticatedReadPeer);
@@ -7924,18 +7672,6 @@ mod tests {
}
}
fn rename_batch_client_items(file_infos: &[FileInfo]) -> Vec<RenameBatchClientItem<'_>> {
file_infos
.iter()
.enumerate()
.map(|(slot, file_info)| RenameBatchClientItem {
slot,
disk: format!("disk-{slot}"),
file_info,
})
.collect()
}
fn sample_read_multiple_resp(file: &str, data: &[u8]) -> ReadMultipleResp {
ReadMultipleResp {
bucket: "bucket".to_string(),
@@ -8417,38 +8153,6 @@ mod tests {
);
}
#[test]
fn rename_data_inline_file_info_msgpack_reserves_known_payloads() {
for (object_size, inline_len) in [(32 * 1024, 2_763), (100 * 1024, 8_566), (12 * (32 * 1024 - 32), 32 * 1024)] {
let mut file_info = sample_rename_data_file_info();
file_info.size = object_size;
file_info.erasure.data_blocks = 12;
file_info.erasure.parity_blocks = 4;
file_info.erasure.distribution = (1..=16).collect();
file_info.data = Some(Bytes::from(vec![0x5a; inline_len]));
let fixed_hint = encode_msgpack_with_capacity(&file_info, FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT)
.expect("fixed-hint inline file info should encode");
assert!(
fixed_hint.capacity() > Vec::<u8>::with_capacity(FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT).capacity(),
"the fixed hint must grow for the representative inline shard"
);
let encoded = encode_file_info_msgpack(&file_info).expect("inline file info should encode");
let reserved = FILE_INFO_MSGPACK_ENCODE_CAPACITY_HINT + inline_len;
assert!(
encoded.len() <= reserved,
"the payload-aware capacity must cover a representative inline shard"
);
assert_eq!(
encoded.capacity(),
Vec::<u8>::with_capacity(reserved).capacity(),
"encoding the inline shard must not grow the initial buffer"
);
let decoded: FileInfo = rmp_serde::from_slice(&encoded).expect("inline file info should decode");
assert_eq!(decoded, file_info);
}
}
#[test]
fn rename_data_resp_named_msgpack_is_smaller_than_json() {
let response = RenameDataResp {
@@ -13770,147 +13474,28 @@ mod tests {
}
#[tokio::test(start_paused = true)]
#[serial_test::serial(rename_admission_metrics)]
async fn rename_admission_timeout_is_visible_without_stage_metrics() {
temp_env::async_with_vars([(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true"))], async {
rustfs_io_metrics::set_put_stage_metrics_enabled(false);
let disk = remote_disk_for_addr("http://127.0.0.1:59989").await;
let gate = Arc::clone(disk.rename_admission.as_ref().expect("configured rename admission"));
let recorder = crate::test_metrics::CapturingRecorder::default();
let _recorder_guard = metrics::set_default_local_recorder(&recorder);
let admission = disk
.acquire_rename_admission_until(1, tokio::time::Instant::now() + Duration::from_secs(1))
.await
.expect("available admission succeeds")
.expect("rename admission is enabled");
drop(admission);
assert_eq!(
recorder.counter_value("rustfs_ecstore_rename_admission_timeouts_total", &[("mode", "unary")]),
0
);
let held = Arc::clone(&gate)
.acquire_many_owned(
u32::try_from(rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT)
.expect("rename admission limit fits u32"),
)
.await
.expect("hold every rename admission permit");
let error = match disk
.acquire_rename_admission_until(1, tokio::time::Instant::now() + Duration::from_secs(1))
.await
{
Ok(_) => panic!("exhausted admission must time out"),
Err(error) => error,
};
assert!(matches!(error, DiskError::DiskOngoingReq));
assert_eq!(
recorder.counter_value("rustfs_ecstore_rename_admission_timeouts_total", &[("mode", "unary")]),
1
);
drop(held);
gate.close();
let error = match disk
.acquire_rename_admission_until(1, tokio::time::Instant::now() + Duration::from_secs(1))
.await
{
Ok(_) => panic!("closed admission must fail without a timeout"),
Err(error) => error,
};
assert!(matches!(error, DiskError::RemoteClientUnavailable(_)));
assert_eq!(
recorder.counter_value("rustfs_ecstore_rename_admission_timeouts_total", &[("mode", "unary")]),
1
);
disk.cancel_token.cancel();
})
.await;
}
#[tokio::test(start_paused = true)]
async fn rename_admission_quarantine_holds_after_ambiguity() {
async fn rename_admission_quarantine_holds_until_absolute_deadline() {
let gate = peer_rename_admission("http://rename-quarantine-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate)
.acquire_many_owned(4)
.await
.expect("weighted batch admission");
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
RenameAdmissionGrant {
permit: Some(permit),
batch: true,
}
.quarantine_after_ambiguity();
.quarantine_until(deadline);
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
let hold = get_max_timeout_duration();
assert!(!hold.is_zero(), "the test requires a bounded positive ambiguity hold");
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::time::advance(Duration::from_millis(999)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::time::advance(Duration::from_millis(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[test]
fn rename_admission_quarantine_metrics_release_when_runtime_stops() {
use metrics_util::MetricKind;
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let gate = peer_rename_admission("http://rename-quarantine-runtime-stop-peer", true).expect("enabled rename gate");
metrics::with_local_recorder(&recorder, || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.expect("quarantine runtime");
runtime.block_on(async {
let permit = Arc::clone(&gate)
.acquire_many_owned(4)
.await
.expect("weighted batch admission");
RenameAdmissionGrant {
permit: Some(permit),
batch: true,
}
.quarantine_after_ambiguity();
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
});
drop(runtime);
});
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
let rows = snapshotter.snapshot().into_vec();
let metric_value = |name: &str, kind: MetricKind| {
&rows
.iter()
.find(|(composite, _, _, _)| {
composite.kind() == kind
&& composite.key().name() == name
&& composite
.key()
.labels()
.any(|label| label.key() == "mode" && label.value() == "batch")
})
.unwrap_or_else(|| panic!("missing batch quarantine metric {name}"))
.3
};
assert!(matches!(
metric_value("rustfs_ecstore_rename_quarantine_events_total", MetricKind::Counter),
DebugValue::Counter(1)
));
assert!(matches!(
metric_value("rustfs_ecstore_rename_quarantine_released_items_total", MetricKind::Counter),
DebugValue::Counter(4)
));
assert!(matches!(
metric_value("rustfs_ecstore_rename_quarantine_active_items", MetricKind::Gauge),
DebugValue::Gauge(value) if value.into_inner() == 0.0
));
}
#[tokio::test(start_paused = true)]
async fn rename_call_guard_quarantines_only_after_dispatch() {
let gate = peer_rename_admission("http://rename-call-guard-peer", true).expect("enabled rename gate");
@@ -13938,7 +13523,7 @@ mod tests {
guard.mark_dispatched();
drop(guard);
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
tokio::time::advance(get_max_timeout_duration()).await;
tokio::time::advance(Duration::from_secs(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
@@ -13959,123 +13544,6 @@ mod tests {
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test(start_paused = true)]
async fn rename_call_guard_timeout_starts_a_fresh_ambiguity_hold() {
let gate = peer_rename_admission("http://rename-expired-call-guard-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("dispatched permits");
let mut guard = RenameBatchCallGuard {
admission: Some(RenameAdmissionGrant {
permit: Some(permit),
batch: true,
}),
deadline: tokio::time::Instant::now(),
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
guard.mark_dispatched();
drop(guard);
tokio::task::yield_now().await;
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4,
"an RPC timeout must not immediately readmit work over detached mutations"
);
let hold = get_max_timeout_duration();
assert!(!hold.is_zero(), "the test requires a bounded positive ambiguity hold");
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test(start_paused = true)]
async fn rename_batch_stream_incomplete_eof_quarantines_only_missing_items() {
use tonic::codec::Codec;
let gate = peer_rename_admission("http://rename-incomplete-stream-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("batch permits");
let mut admission = RenameAdmissionGrant {
permit: Some(permit),
batch: true,
};
assert!(admission.release_one(), "the completed first item releases its permit");
let mut codec = tonic_prost::ProstCodec::<RenameDataBatchResult, RenameDataBatchResult>::default();
let inner = Streaming::new_empty(codec.decoder(), http_body_util::Empty::<Bytes>::new());
let mut stream = RemoteRenameBatchStream {
inner,
expected_mask: 0b1111,
seen_mask: 0b0001,
admission: Some(admission),
deadline: tokio::time::Instant::now(),
terminal: false,
stream_started_at: None,
first_item_at: None,
};
let error = match stream.next_outcome().await {
Err(error) => error,
Ok(_) => panic!("incomplete EOF must be commit-ambiguous"),
};
assert!(matches!(error, DiskError::Unexpected));
tokio::task::yield_now().await;
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3,
"only the three missing item permits remain quarantined"
);
let hold = get_max_timeout_duration();
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3);
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test(start_paused = true)]
async fn rename_batch_stream_drop_quarantines_only_missing_items() {
use tonic::codec::Codec;
let gate = peer_rename_admission("http://rename-dropped-stream-peer", true).expect("enabled rename gate");
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("batch permits");
let mut admission = RenameAdmissionGrant {
permit: Some(permit),
batch: true,
};
assert!(admission.release_one(), "the completed first item releases its permit");
let mut codec = tonic_prost::ProstCodec::<RenameDataBatchResult, RenameDataBatchResult>::default();
let inner = Streaming::new_empty(codec.decoder(), http_body_util::Empty::<Bytes>::new());
let stream = RemoteRenameBatchStream {
inner,
expected_mask: 0b1111,
seen_mask: 0b0001,
admission: Some(admission),
deadline: tokio::time::Instant::now(),
terminal: false,
stream_started_at: None,
first_item_at: None,
};
drop(stream);
tokio::task::yield_now().await;
assert_eq!(
gate.available_permits(),
rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3,
"dropping an active stream quarantines only the three missing item permits"
);
let hold = get_max_timeout_duration();
tokio::time::advance(hold - Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3);
tokio::time::advance(Duration::from_nanos(1)).await;
tokio::task::yield_now().await;
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
}
#[tokio::test]
async fn remote_disk_builds_optional_complete_body_gate_from_configuration() {
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, Some("3"))], async {
@@ -207,10 +207,10 @@ async fn pool_meta_native_physical_split_without_ordinary_commit_performs_no_mut
let before = snapshots(&fixture.store).await;
let mut state = clean_state(&fixture);
let fence = PoolMetaPersistenceFence::Owned(owner(&fixture.store).await);
let error = repair(&fixture.store, &mut state, &fence)
.await
.expect_err("reconstruction alone must never authorize a COMMIT");
assert!(error.to_string().contains("(no_ordinary_v3_authority)"), "{error}");
assert!(
repair(&fixture.store, &mut state, &fence).await.is_err(),
"reconstruction alone must never authorize a COMMIT"
);
assert_eq!(
snapshots(&fixture.store).await,
before,
@@ -222,24 +222,6 @@ async fn pool_meta_native_physical_split_without_ordinary_commit_performs_no_mut
.expect("missing ordinary authority alone must not install a permanent corruption latch");
}
#[tokio::test]
#[serial_test::serial(pool_meta_version_env)]
async fn pool_meta_native_inspection_rejects_an_absent_slot_without_changing_evidence() {
let fixture = fixture(1).await;
let before = snapshots(&fixture.store).await;
let fence = PoolMetaPersistenceFence::Owned(owner(&fixture.store).await);
let last_pool = fixture.store.pools.last().expect("fixture has a last pool");
let set = last_pool.get_disks_by_key(POOL_META_NAME);
let missing = set.disks.write().await[0].take().expect("fixture has a disk in slot zero");
let result = inspect(&fixture.store.pools, &fence).await;
set.disks.write().await[0] = Some(missing);
let error = result.err().expect("an absent slot cannot provide native evidence");
assert!(error.to_string().contains("(missing_pool_metadata_slot)"), "{error}");
assert_eq!(snapshots(&fixture.store).await, before);
}
async fn interrupted_first_commit_fixture() -> (PhysicalFixture, PoolMetaCommittedCandidate) {
let fixture = fixture(3).await;
let PoolMetaReplica::Valid {
@@ -19,7 +19,6 @@ use crate::disk::{
PoolMetaNativeRecoveryResponse as Response,
};
use bytes::Bytes;
use futures::TryStreamExt as _;
#[cfg(test)]
#[derive(Default)]
@@ -39,16 +38,8 @@ struct InspectedPool {
snapshots: Vec<PoolMetaNativeInspection>,
}
#[derive(Debug, thiserror::Error)]
#[error("native pool metadata recovery requires one proven V3 transaction and complete matching disk evidence ({0})")]
struct MissingEvidence(&'static str);
fn missing_evidence(reason: &'static str) -> Error {
Error::other(MissingEvidence(reason))
}
fn invalid() -> Error {
missing_evidence("inconsistent_evidence")
Error::other("native pool metadata recovery requires one proven V3 transaction and complete matching disk evidence")
}
fn known_validation(source: Error, phase: &'static str) -> Error {
@@ -80,19 +71,13 @@ fn latch_validation(state: &mut PoolMetaWriteState, error: Error) -> Error {
fn current(pool: &InspectedPool) -> Result<Vec<Bytes>> {
pool.snapshots
.iter()
.map(|snapshot| {
snapshot
.current
.clone()
.ok_or_else(|| missing_evidence("missing_pool_metadata_head"))
})
.map(|snapshot| snapshot.current.clone().ok_or_else(invalid))
.collect()
}
async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> Result<Vec<InspectedPool>> {
let mut inspected = Vec::with_capacity(pools.len());
// Check every slot before starting I/O. The authenticated, read-only
// Inspect RPC proves both protocol support and the disk's evidence.
// Pool -> disk order is stable; all capability probes precede every mutation.
for pool in pools {
fence.ensure_held()?;
let set = pool.get_disks_by_key(POOL_META_NAME);
@@ -102,8 +87,20 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
.await
.iter()
.cloned()
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_metadata_slot")))
.map(|disk| disk.ok_or_else(invalid))
.collect::<Result<Vec<_>>>()?;
let probes = futures::stream::iter(disks.iter().cloned().map(|disk| async move {
match disk.pool_meta_native_recovery(Request::Probe {}).await? {
Response::Probed => Ok(()),
_ => Err(invalid()),
}
}))
.buffered(4)
.collect::<Vec<Result<()>>>()
.await;
for result in probes {
result?;
}
inspected.push(InspectedPool {
disks,
snapshots: Vec::new(),
@@ -111,7 +108,7 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
}
for pool in &mut inspected {
fence.ensure_held()?;
pool.snapshots = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
let results = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
match disk
.pool_meta_native_recovery(Request::Inspect {
object: PoolMetaNativeObject::PoolBin,
@@ -119,12 +116,15 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
.await?
{
Response::Inspected(snapshot) if !snapshot.disk_id.is_nil() => Ok(snapshot),
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
_ => Err(invalid()),
}
}))
.buffered(4)
.try_collect()
.await?;
.collect::<Vec<Result<PoolMetaNativeInspection>>>()
.await;
for result in results {
pool.snapshots.push(result?);
}
}
fence.ensure_held()?;
Ok(inspected)
@@ -142,7 +142,7 @@ async fn validate_identities(pools: &[Arc<Sets>], canonical: &[u8], fence: &Pool
.await
.iter()
.cloned()
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_identity_slot")))
.map(|disk| disk.ok_or_else(invalid))
.collect::<Result<Vec<_>>>()?;
let results = futures::stream::iter(disks.into_iter().enumerate().map(|(index, disk)| async move {
match disk.pool_meta_native_recovery(Request::InspectIdentity {}).await? {
@@ -151,7 +151,7 @@ async fn validate_identities(pools: &[Arc<Sets>], canonical: &[u8], fence: &Pool
.await
.map_err(|error| codec_validation(error, "native_identity_validation"))
}
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
_ => Err(invalid()),
}
}))
.buffered(4)
@@ -479,7 +479,7 @@ pub(super) async fn repair(
})
.collect::<Vec<_>>();
if ordinary_commits.is_empty() && ordinary_prepares.is_empty() {
return Err(missing_evidence("no_ordinary_v3_authority"));
return Err(invalid());
}
let selection = select_pool_meta_replica_reads(reads)
.map_err(|error| latch_validation(state, known_validation(error, "native_metadata_validation")))?;
@@ -535,7 +535,7 @@ pub(super) async fn repair(
.iter()
.any(|read| !matches!(read.replica, PoolMetaIdentityReplica::Valid(_)))
{
return Err(missing_evidence("pool_identity_unavailable"));
return Err(invalid());
}
let identity = select_pool_meta_identity(identities, cluster_id)
.map_err(|error| latch_validation(state, known_validation(error, "native_identity_validation")))?;
@@ -847,10 +847,7 @@ mod tests {
async fn pool_meta_native_plan_rejects_missing_or_corrupt_evidence() {
let mut f = fixture().await;
let before = f.pools[1].snapshots[2].current.take();
let error = plan(&f.pools, &f.commit, f.revision, &f.identity, None)
.await
.expect_err("missing current shard must block the repair plan");
assert!(error.to_string().contains("(missing_pool_metadata_head)"), "{error}");
assert!(plan(&f.pools, &f.commit, f.revision, &f.identity, None).await.is_err());
f.pools[1].snapshots[2].current = before;
f.pools[1].snapshots[2].backups[0].data = Bytes::from_static(b"invalid metadata");
assert!(plan(&f.pools, &f.commit, f.revision, &f.identity, None).await.is_err());
@@ -1,94 +0,0 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::{ADMIN_USAGE_INCARNATION_CONCURRENCY, ADMIN_USAGE_INCARNATION_TIMEOUT, BucketUsageInfo, ECStore};
use futures::StreamExt;
use std::{collections::HashMap, sync::Arc};
use tokio::time::{Instant, timeout_at};
/// Read only the caller-selected bucket identities. One deadline bounds the
/// entire batch, including concurrent reads waiting for metadata locks.
pub(crate) async fn current_admin_bucket_incarnations(
store: Arc<ECStore>,
buckets: Vec<String>,
deadline: Instant,
) -> HashMap<String, String> {
let mut current = HashMap::new();
let mut reads = futures::stream::iter(buckets)
.map(move |name| {
let store = store.clone();
async move {
let id = store.bucket_incarnation_id_from_disk(&name).await;
(name, id)
}
})
.buffer_unordered(ADMIN_USAGE_INCARNATION_CONCURRENCY);
while Instant::now() < deadline {
let Ok(Some((name, id))) = timeout_at(deadline, reads.next()).await else {
break;
};
if let Ok(id) = id
&& !id.is_nil()
{
current.insert(name, id.to_string());
}
}
current
}
/// Verify both persisted scanner and single-node overlay values at the time of
/// an account-info read. Only names already selected by the IAM policy enter
/// metadata I/O; missing legacy identities and metadata timeouts remain unknown.
pub async fn verified_account_bucket_usage(
store: Arc<ECStore>,
mut measured: HashMap<String, BucketUsageInfo>,
allowed_names: Vec<String>,
) -> HashMap<String, BucketUsageInfo> {
let names = allowed_names
.into_iter()
.filter(|name| measured.get(name).is_some_and(|value| value.bucket_incarnation.is_some()))
.collect();
let current = current_admin_bucket_incarnations(store, names, Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT).await;
measured.retain(|name, value| {
current
.get(name)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
});
measured
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::storage_api_contracts::bucket::{BucketOperations as _, MakeBucketOptions};
#[tokio::test]
#[serial_test::serial]
async fn account_inventory_preserves_only_permitted_current_incarnations_including_measured_zero() {
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let mut usage = HashMap::new();
for (name, objects) in [("permitted", 0), ("private", 300), ("recreated", 900), ("legacy", 90)] {
store.make_bucket(name, &MakeBucketOptions::default()).await.unwrap();
let current = store.bucket_incarnation_id_from_disk(name).await.unwrap();
let incarnation = match name {
"recreated" => Some("11111111-1111-4111-8111-111111111111".to_string()),
"legacy" => None,
_ => Some(current.to_string()),
};
usage.insert(
name.to_owned(),
BucketUsageInfo {
objects_count: objects,
bucket_incarnation: incarnation,
..Default::default()
},
);
}
let allowed = ["permitted", "recreated", "legacy"].map(String::from).to_vec();
let values = verified_account_bucket_usage(store, usage, allowed).await;
assert_eq!(values.len(), 1);
assert_eq!(values["permitted"].objects_count, 0);
}
}
+46 -119
View File
@@ -14,9 +14,6 @@
// #730: scanner/data-usage state is partially migrated and still owns staged cache helpers.
mod admin_bucket_identity;
pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
pub use admin_bucket_identity::verified_account_bucket_usage;
pub mod local_snapshot;
use crate::storage_api_contracts::{
@@ -60,7 +57,7 @@ const DATA_COMPRESSION_TOTAL_NAME: &str = ".compression.json";
pub const DATA_USAGE_CACHE_NAME: &str = ".usage-cache.bin";
const DATA_USAGE_CACHE_TTL_SECS: u64 = 30;
const ADMIN_USAGE_INCARNATION_CONCURRENCY: usize = 4;
pub(crate) const ADMIN_USAGE_INCARNATION_TIMEOUT: Duration = Duration::from_secs(2);
const ADMIN_USAGE_INCARNATION_TIMEOUT: Duration = Duration::from_secs(2);
// A scanner save invalidates only the saving process's snapshot cache; every
// other node sees it only after reloading. A fail-closed usage lookup for a
// bucket the cached snapshot does not mention at all may reload a copy this
@@ -1466,43 +1463,45 @@ async fn load_admin_data_usage_from_backend(store: Arc<ECStore>) -> Result<DataU
let observed = load_observed_data_usage_snapshot(store.clone()).await.ok().flatten();
let (selected, selected_is_current_format) =
select_admin_data_usage_snapshot(authoritative, source.is_authoritative(), observed);
Ok(normalize_loaded_data_usage(selected, selected_is_current_format).await.0)
}
async fn project_admin_data_usage_for_current_buckets(
store: Arc<ECStore>,
mut response: DataUsageInfo,
with_memory_overlay: bool,
) -> DataUsageInfo {
if !(response.is_complete_bucket_usage_snapshot() || response.is_valid_partial_snapshot()) {
return DataUsageInfo::default();
}
let overlay_authoritative = with_memory_overlay && !runtime_sources::setup_is_dist_erasure().await;
let mut response = normalize_loaded_data_usage(selected, selected_is_current_format).await.0;
use futures::StreamExt as _;
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let mut buckets = response
.buckets_usage
.keys()
.chain(response.usage_snapshot_bucket_observations.keys())
.cloned()
.collect::<HashSet<_>>();
if overlay_authoritative {
// Copy names under the memory lock, then release it before storage I/O.
buckets.extend(memory_cache().read().await.keys().cloned());
let mut incarnations = HashMap::new();
{
// Display-only identity reads must not serialize every bucket behind a
// slow metadata lock while holding the shared admin refresh permit.
// The common deadline bounds their total added latency; dropping this
// stream cancels all unfinished reads without spawning detached work.
// Own the names and store across awaits so this future remains Send
// when composed into spawned metrics collectors.
let buckets = response
.usage_snapshot_bucket_observations
.keys()
.cloned()
.collect::<Vec<_>>();
let mut identities = futures::stream::iter(buckets)
.map(move |bucket| {
let store = store.clone();
async move {
let identity = store.bucket_incarnation_id_from_disk(&bucket).await;
(bucket, identity)
}
})
.buffer_unordered(ADMIN_USAGE_INCARNATION_CONCURRENCY);
while tokio::time::Instant::now() < deadline {
let Ok(Some((bucket, identity))) = tokio::time::timeout_at(deadline, identities.next()).await else {
break;
};
// Unavailable, timed-out or recreated buckets retain canonical values.
if let Ok(incarnation) = identity
&& !incarnation.is_nil()
{
incarnations.insert(bucket, incarnation.to_string());
}
}
}
let incarnations = current_admin_bucket_incarnations(store, buckets.into_iter().collect(), deadline).await;
response.project_bucket_observations_for_admin(&incarnations);
if apply_bucket_usage_memory_overlay_if_authoritative(&mut response, overlay_authoritative).await {
response.usage_snapshot_complete = false;
response.usage_snapshot_partial = true;
response.usage_snapshot_converged = Some(false);
response.usage_snapshot_admin_projection = true;
response.replication_info.clear();
response.tier_stats = None;
response.unknown_tier_stats = None;
}
response.retain_current_bucket_usage_for_admin(&incarnations);
response
Ok(response)
}
fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) {
@@ -1691,7 +1690,11 @@ async fn project_data_usage_from_backend_cached<T>(
}
}
async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
/// Load the freshest structurally complete snapshot for authenticated admin
/// observability. A scan raced by namespace activity may be selected here, but
/// never by [`load_data_usage_from_backend_cached`], which remains the
/// converged source for quota admission.
pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let ttl = Duration::from_secs(DATA_USAGE_CACHE_TTL_SECS);
loop {
@@ -1740,38 +1743,6 @@ async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<Da
}
}
/// Load cached scanner statistics for authenticated admin observability.
///
/// Each response verifies bucket identities against current storage metadata,
/// including cache hits. Missing, failed, or timed-out identity reads leave that
/// bucket's usage absent (unknown). Legacy values without an incarnation stay
/// unknown until a scanner snapshot certifies their identity. Per-bucket reads
/// linearize independently; this is not an atomic namespace snapshot.
/// Identity reads have a shared deadline and do not outlive cancellation. The
/// unchanged cached baseline remains independent of quota and persistence.
///
/// # Errors
/// Returns the cached snapshot loading error when no baseline can be loaded.
pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let response = load_admin_data_usage_snapshot_cached(store.clone()).await?;
Ok(project_admin_data_usage_for_current_buckets(store, response, false).await)
}
/// Load the admin view with the existing authoritative single-process overlay.
///
/// Only a complete or valid partial scanner snapshot can receive memory values.
/// The final identity check excludes statistics from retired or unverified buckets.
/// Distributed nodes continue to use scanner statistics without local totals.
/// Cancellation, unknown values, and per-bucket read semantics are the same as
/// [`load_admin_data_usage_from_backend_cached`]. No overlay is persisted.
///
/// # Errors
/// Returns the cached snapshot loading error when no baseline can be loaded.
pub async fn load_admin_data_usage_with_memory_overlay(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let response = load_admin_data_usage_snapshot_cached(store.clone()).await?;
Ok(project_admin_data_usage_for_current_buckets(store, response, true).await)
}
/// Invalidate the process-local persisted usage snapshot cache after a durable
/// scanner write.
pub async fn invalidate_data_usage_snapshot_cache() {
@@ -2834,17 +2805,16 @@ async fn replace_bucket_usage_memory_from_info_if_generation(data_usage_info: &D
*cache = next_cache;
}
async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mut DataUsageInfo, authoritative: bool) -> bool {
async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mut DataUsageInfo, authoritative: bool) {
if !authoritative {
return false;
return;
}
let cache = memory_cache().read().await;
if cache.is_empty() {
return false;
return;
}
let was_complete = data_usage_info.usage_snapshot_complete;
let persisted_update = data_usage_info.last_update;
let mut changed = false;
let mut added_bucket = false;
@@ -2881,7 +2851,6 @@ async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mu
data_usage_info.buckets_count = data_usage_info.buckets_usage.len() as u64;
data_usage_info.calculate_totals();
}
changed || was_complete != data_usage_info.usage_snapshot_complete
}
pub async fn apply_bucket_usage_memory_overlay(data_usage_info: &mut DataUsageInfo) {
@@ -3775,23 +3744,6 @@ mod tests {
*cache_updating().write().await = false;
}
async fn bind_admin_usage_test_identities(store: &Arc<ECStore>, snapshot: &mut DataUsageInfo) {
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
for (bucket, usage) in &mut snapshot.buckets_usage {
store
.make_bucket(bucket, &crate::storage_api_contracts::bucket::MakeBucketOptions::default())
.await
.expect("create a real bucket for current admin identity validation");
usage.bucket_incarnation = Some(
store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("read the storage-owned fixture identity")
.to_string(),
);
}
}
fn data_usage_info_for_test(bucket: &str, objects_count: u64, size: u64, last_update: SystemTime) -> DataUsageInfo {
let mut info = DataUsageInfo {
last_update: Some(last_update),
@@ -4327,11 +4279,7 @@ mod tests {
use crate::config::com::save_config;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let (mut authoritative, mut observed) = usage_snapshots_with_missing_observed_set();
bind_admin_usage_test_identities(&store, &mut authoritative).await;
for (bucket, usage) in &mut observed.buckets_usage {
usage.bucket_incarnation = authoritative.buckets_usage[bucket].bucket_incarnation.clone();
}
let (authoritative, observed) = usage_snapshots_with_missing_observed_set();
let primary_bytes = serde_json::to_vec(&authoritative).expect("encode complete usage");
let observed_bytes = serde_json::to_vec(&observed).expect("encode partial observation");
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), primary_bytes.clone())
@@ -4380,11 +4328,6 @@ mod tests {
reconciled.scanner_epoch = Some(4);
reconciled.scanner_cycle = Some(12);
reconciled.usage_snapshot_converged = Some(true);
reconciled
.buckets_usage
.get_mut("large-bucket")
.expect("reconciled bucket")
.bucket_incarnation = authoritative.buckets_usage["large-bucket"].bucket_incarnation.clone();
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -4906,12 +4849,6 @@ mod tests {
backup.scanner_epoch = Some(4);
backup.scanner_cycle = Some(10);
backup.usage_snapshot_converged = Some(true);
bind_admin_usage_test_identities(&store, &mut current).await;
backup
.buckets_usage
.get_mut("existing")
.expect("backup bucket")
.bucket_incarnation = current.buckets_usage["existing"].bucket_incarnation.clone();
for (path, info) in [
(DATA_USAGE_OBJ_NAME_PATH.as_str(), &current),
(DATA_USAGE_OBJ_BACKUP_PATH.as_str(), &backup),
@@ -4934,11 +4871,6 @@ mod tests {
after_delete.scanner_epoch = current.scanner_epoch;
after_delete.scanner_cycle = current.scanner_cycle;
after_delete.usage_snapshot_converged = Some(true);
after_delete
.buckets_usage
.get_mut("existing")
.expect("post-delete bucket")
.bucket_incarnation = current.buckets_usage["existing"].bucket_incarnation.clone();
let mut stale_observation =
data_usage_info_for_test("retired-incarnation", 99, 999, SystemTime::UNIX_EPOCH + Duration::from_secs(4));
stale_observation.scanner_epoch = Some(4);
@@ -5000,7 +4932,6 @@ mod tests {
authoritative.scanner_epoch = Some(7);
authoritative.scanner_cycle = Some(10);
authoritative.usage_snapshot_converged = Some(true);
bind_admin_usage_test_identities(&store, &mut authoritative).await;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -5015,10 +4946,6 @@ mod tests {
info.scanner_cycle = Some(cycle);
info.usage_snapshot_converged = Some(false);
info.usage_snapshot_authoritative_baseline = Some(authoritative.snapshot_identity());
info.buckets_usage
.get_mut("bucket")
.expect("observed bucket")
.bucket_incarnation = authoritative.buckets_usage["bucket"].bucket_incarnation.clone();
info
};
let first = observation(7, 11, 200, 11, 1_100);
@@ -221,7 +221,7 @@ async fn companion_admin_cache_isolated_from_quota_memory_and_persistence() {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_buckets() {
async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buckets() {
use crate::bucket::metadata_sys::{
acquire_metadata_transaction_guard, init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks,
};
@@ -280,11 +280,8 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
.await
.expect("optional projection must return before the blocked metadata lock's long timeout")
.expect("canonical admin response stays available");
assert!(
!response.buckets_usage.contains_key(blocked),
"an unavailable current identity cannot bind the canonical value"
);
assert!(!response.bucket_sizes.contains_key(blocked));
assert_eq!(response.buckets_usage[blocked].size, 100);
assert_eq!(response.buckets_usage[blocked].usage_value_state, Some(BucketUsageValueState::Carried));
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);
@@ -296,12 +293,13 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
.is_ok()
);
drop(blocked_guard);
invalidate_data_usage_snapshot_cache().await;
let recovered = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("refresh after lock recovery");
assert_eq!(
recovered.buckets_usage[blocked].size, 250,
"unavailable identity can recover on a cache hit"
"unavailable identity can recover on the next refresh"
);
assert_eq!(recovered.buckets_usage[healthy].size, 250);
let quota = load_data_usage_from_backend_cached(store)
@@ -310,331 +308,3 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
assert_eq!(quota.buckets_usage[blocked].size, 100);
assert_eq!(quota.buckets_usage[healthy].size, 100);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_invalidation() {
use crate::bucket::metadata::{load_bucket_incarnation, save_bucket_incarnation};
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "usage-recreated-cache";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create identity fixture");
let old_identity = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("original identity");
let mut canonical = companion_snapshot(bucket, old_identity);
canonical.usage_snapshot_bucket_observations.clear();
canonical.usage_snapshot_converged = Some(true);
canonical.usage_snapshot_pending_buckets.clear();
canonical.usage_snapshot_pending_bucket_count = 0;
canonical
.buckets_usage
.get_mut(bucket)
.expect("canonical bucket")
.objects_count = 107;
canonical.calculate_totals();
let original_bytes = serde_json::to_vec(&canonical).expect("encode canonical old bucket");
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), original_bytes.clone())
.await
.expect("persist canonical root");
invalidate_data_usage_snapshot_cache().await;
let first = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("prime raw admin cache");
assert_eq!(first.buckets_usage[bucket].objects_count, 107);
assert!(first.is_complete_bucket_usage_snapshot());
let cache_generation = admin_data_usage_snapshot_generation();
let new_identity = uuid::Uuid::new_v4();
// Simulate the storage-owned identity changing on another node while this
// process has not received its invalidation notice. Do not clear the cache.
save_bucket_incarnation(store.clone(), bucket, new_identity)
.await
.expect("publish changed disk identity");
assert_eq!(
load_bucket_incarnation(store.clone(), bucket)
.await
.expect("read new sidecar"),
Some(new_identity)
);
let second = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("read raw cache with fresh identity");
assert_eq!(admin_data_usage_snapshot_generation(), cache_generation);
assert!(
!second.buckets_usage.contains_key(bucket),
"same name cannot retain the predecessor's 107"
);
assert!(!second.bucket_sizes.contains_key(bucket));
assert_eq!(second.usage_snapshot_converged, Some(false));
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(certified_bucket_usage(&second, bucket, new_identity).is_none());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
let quota = load_data_usage_from_backend_cached(store.clone())
.await
.expect("independent quota baseline");
assert_eq!(quota.buckets_usage[bucket].objects_count, 107);
assert_eq!(
read_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("unchanged persisted root"),
original_bytes
);
// Rebinding a cached raw baseline is transient: recovery does not need to
// reload or permanently blank a healthy bucket's statistics.
save_bucket_incarnation(store.clone(), bucket, old_identity)
.await
.expect("restore fixture identity");
let recovered = load_admin_data_usage_from_backend_cached(store)
.await
.expect("recover on another cache hit");
assert_eq!(recovered.buckets_usage[bucket].objects_count, 107);
assert!(recovered.is_complete_bucket_usage_snapshot());
assert_eq!(admin_data_usage_snapshot_generation(), cache_generation);
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_memory_overlay_requires_a_measured_scanner_baseline() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
assert!(!runtime_sources::setup_is_dist_erasure().await);
let bucket = "usage-unmeasured-overlay";
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
let incarnation = store.bucket_incarnation_id_from_disk(bucket).await.unwrap();
let mut baseline = data_usage_info_for_test(bucket, 1, 100, SystemTime::UNIX_EPOCH);
let usage = baseline.buckets_usage.get_mut(bucket).unwrap();
usage.bucket_incarnation = Some(incarnation.to_string());
let memory_usage = BucketUsageInfo {
size: 150,
..usage.clone()
};
clear_usage_memory_cache_for_test().await;
replace_bucket_usage_memory_from_authoritative(bucket, memory_usage, SystemTime::now()).await;
// A missing snapshot and a mismatched bucket count both leave usage unknown.
for (buckets_count, expected_size) in [(None, None), (Some(2), None), (Some(1), Some(150))] {
if let Some(count) = buckets_count {
baseline.buckets_count = count;
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&baseline).unwrap())
.await
.unwrap();
}
invalidate_data_usage_snapshot_cache().await;
let response = load_admin_data_usage_with_memory_overlay(store.clone()).await.unwrap();
assert_eq!(
response.buckets_usage.get(bucket).map(|usage| usage.size),
expected_size,
"baseline count {buckets_count:?}"
);
assert_eq!(response.bucket_sizes.get(bucket).copied(), expected_size);
assert_eq!(response.objects_total_size, expected_size.unwrap_or_default());
assert_eq!(response.usage_snapshot_admin_projection, expected_size.is_some());
assert!(!response.is_complete_bucket_usage_snapshot());
assert!(!response.is_valid_partial_snapshot());
}
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_identity_filter_does_not_validate_an_unmeasured_partial_snapshot() {
use crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
use crate::config::com::save_config;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let current = "usage-partial-current";
let stale = "usage-partial-stale";
let mut baseline = data_usage_info_for_test(current, 5, 100, SystemTime::UNIX_EPOCH);
baseline.buckets_usage.insert(
stale.to_owned(),
BucketUsageInfo {
size: 200,
objects_count: 10,
..Default::default()
},
);
baseline.bucket_sizes.insert(stale.to_owned(), 200);
baseline.buckets_count = 2;
baseline.calculate_totals();
baseline.usage_snapshot_complete = false;
baseline.usage_snapshot_partial = true;
baseline.usage_snapshot_converged = Some(false);
baseline.scanner_epoch = Some(2);
baseline.scanner_cycle = Some(9);
baseline.usage_snapshot_set_states = vec![DataUsageSnapshotSetState {
scanner_epoch: baseline.scanner_epoch,
scanner_cycle: baseline.scanner_cycle,
scan_plan_digest: Some([1; 32]),
..Default::default()
}];
bind_admin_usage_test_identities(&store, &mut baseline).await;
let current_incarnation = baseline.buckets_usage[current].bucket_incarnation.clone();
assert_ne!(current_incarnation, baseline.buckets_usage[stale].bucket_incarnation);
baseline
.buckets_usage
.get_mut(stale)
.expect("stale bucket fixture")
.bucket_incarnation = current_incarnation;
for (case, snapshot, expected_size) in [
(
"missing set provenance",
DataUsageInfo {
usage_snapshot_set_states: Vec::new(),
..baseline.clone()
},
None,
),
(
"mismatched bucket count",
DataUsageInfo {
buckets_count: 3,
..baseline.clone()
},
None,
),
("valid partial snapshot", baseline, Some(100)),
] {
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&snapshot).expect("encode partial snapshot"),
)
.await
.expect("persist partial snapshot");
invalidate_admin_data_usage_snapshot_cache().await;
let response = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("load admin usage through the identity filter");
assert_eq!(response.buckets_usage.get(current).map(|usage| usage.size), expected_size, "{case}");
assert_eq!(response.bucket_sizes.get(current).copied(), expected_size, "{case}");
assert!(!response.buckets_usage.contains_key(stale), "{case}");
assert!(!response.bucket_sizes.contains_key(stale), "{case}");
assert_eq!(response.objects_total_size, expected_size.unwrap_or_default(), "{case}");
assert_eq!(response.usage_snapshot_admin_projection, expected_size.is_some(), "{case}");
}
invalidate_admin_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_memory_overlay_cannot_reintroduce_a_predecessor_identity() {
use crate::bucket::metadata::save_bucket_incarnation;
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "usage-recreated-overlay";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create overlay identity fixture");
let old_identity = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("original identity");
let mut canonical = companion_snapshot(bucket, old_identity);
canonical.usage_snapshot_bucket_observations.clear();
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&canonical).expect("encode canonical root"),
)
.await
.expect("persist overlay fixture");
invalidate_data_usage_snapshot_cache().await;
let cached_usage = canonical.buckets_usage[bucket].clone();
replace_bucket_usage_memory_from_authoritative(bucket, cached_usage, SystemTime::now()).await;
let new_identity = uuid::Uuid::new_v4();
save_bucket_incarnation(store.clone(), bucket, new_identity)
.await
.expect("publish a replacement identity");
let response = load_admin_data_usage_with_memory_overlay(store.clone())
.await
.expect("project after memory overlay");
assert!(!response.buckets_usage.contains_key(bucket));
assert_eq!(response.usage_snapshot_converged, Some(false));
assert!(response.usage_snapshot_admin_projection);
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_overlay_flags_only_change_keeps_identity_bound_cold_usage() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
assert!(
!runtime_sources::setup_is_dist_erasure().await,
"exercise the production single-process overlay"
);
let cold = "usage-overlay-cold";
let unverified = "usage-overlay-unverified";
for bucket in [cold, unverified] {
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create overlay fixture bucket");
}
let identity = store
.bucket_incarnation_id_from_disk(cold)
.await
.expect("cold bucket identity");
let mut canonical = companion_snapshot(cold, identity);
canonical.usage_snapshot_bucket_observations.clear();
canonical.usage_snapshot_converged = Some(true);
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&canonical).expect("encode cold canonical value"),
)
.await
.expect("persist cold baseline");
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
memory_cache().write().await.insert(
unverified.to_string(),
cached_bucket_usage_from_backend(BucketUsageInfo::default(), SystemTime::UNIX_EPOCH, false),
);
record_bucket_object_write_memory(unverified, None, 42).await;
{
let cache = memory_cache().read().await;
assert!(cache[unverified].dirty);
assert!(!cache[unverified].authoritative);
}
let response = load_admin_data_usage_with_memory_overlay(store)
.await
.expect("identity-filtered flags-only overlay");
assert_eq!(response.buckets_usage[cold].size, 100);
assert_eq!(response.objects_total_size, 100);
assert_eq!(response.bucket_sizes[cold], 100);
assert!(!response.buckets_usage.contains_key(unverified));
assert!(response.usage_snapshot_admin_projection);
assert_eq!(response.usage_snapshot_converged, Some(false));
assert!(!response.is_complete_bucket_usage_snapshot());
assert!(!response.is_valid_partial_snapshot());
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
@@ -50,8 +50,6 @@ const EVENT_SERVER_INFO: &str = "server_info";
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_DIAGNOSTICS: &str = "diagnostics";
mod inventory;
use shadow_rs::shadow;
shadow!(build);
@@ -278,14 +276,6 @@ fn collect_runtime_server_stats() -> (MemStats, u64, u64) {
}
pub async fn get_server_info(get_pools: bool) -> InfoMessage {
get_server_info_with_inventory(get_pools, false).await.0
}
pub async fn get_server_info_with_inventory(
get_pools: bool,
include_inventory: bool,
) -> (InfoMessage, Option<rustfs_madmin::ClusterInventory>) {
let mut inventory = include_inventory.then(rustfs_madmin::ClusterInventory::default);
let started = tracing::enabled!(tracing::Level::TRACE).then(Instant::now);
let local = get_local_server_property().await;
@@ -311,24 +301,25 @@ pub async fn get_server_info_with_inventory(
if let Some(store) = runtime_sources::object_store_handle() {
mode = ITEM_ONLINE;
let namespace_options = BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
};
let load_snapshot = load_server_info_usage_snapshot(store.clone());
let (snapshot, namespace) = if include_inventory {
let (snapshot, namespace, measured) =
inventory::collect(&store, load_snapshot, store.list_bucket_for_scanner(&namespace_options)).await;
inventory = Some(measured);
(snapshot, Some(namespace))
} else {
(load_snapshot.await, None)
};
apply_data_usage_result(snapshot, &mut buckets, &mut objects, &mut versions, &mut delete_markers, &mut usage);
apply_data_usage_result(
load_server_info_usage_snapshot(store.clone()).await,
&mut buckets,
&mut objects,
&mut versions,
&mut delete_markers,
&mut usage,
);
if buckets.error.is_some() {
let listing = inventory::namespace_or_fallback(namespace, store.list_bucket_for_scanner(&namespace_options)).await;
apply_bucket_namespace_count(listing, &mut buckets);
apply_bucket_namespace_count(
store
.list_bucket_for_scanner(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
.await,
&mut buckets,
);
}
let backend_info = StorageAdminApi::backend_info(store.as_ref()).await;
@@ -384,7 +375,7 @@ pub async fn get_server_info_with_inventory(
);
}
let info = InfoMessage {
InfoMessage {
mode: Some(mode.to_string()),
domain: None,
region: None,
@@ -399,8 +390,7 @@ pub async fn get_server_info_with_inventory(
services: Some(services),
servers: Some(servers),
pools: Some(pools),
};
(info, inventory)
}
}
fn is_online_drive_state(state: &str) -> bool {
@@ -1043,26 +1033,16 @@ mod tests {
#[tokio::test]
#[serial]
async fn server_info_reads_complete_observation_without_promoting_authority() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
use crate::config::com::{read_config, save_config};
use crate::data_usage::{
DATA_USAGE_OBJ_NAME_PATH, DATA_USAGE_OBSERVED_OBJ_NAME_PATH, invalidate_data_usage_snapshot_cache,
load_data_usage_from_backend_cached,
};
use crate::storage_api_contracts::bucket::{BucketOperations as _, MakeBucketOptions};
use rustfs_data_usage::{BucketUsageInfo, DataUsageInfo};
use std::time::{Duration, SystemTime};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
store
.make_bucket("bucket", &MakeBucketOptions::default())
.await
.expect("create a real observed bucket");
let incarnation = store
.bucket_incarnation_id_from_disk("bucket")
.await
.expect("read current storage-owned incarnation");
let primary = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
scanner_epoch: Some(1),
@@ -1086,7 +1066,6 @@ mod tests {
versions_count: 4,
delete_markers_count: 1,
size: 6,
bucket_incarnation: Some(incarnation.to_string()),
..Default::default()
},
)]
@@ -1138,46 +1117,6 @@ mod tests {
invalidate_data_usage_snapshot_cache().await;
}
#[test]
fn identity_filtered_usage_remains_unknown_in_server_info() {
let mut info = rustfs_data_usage::DataUsageInfo {
last_update: Some(std::time::SystemTime::UNIX_EPOCH),
buckets_count: 1,
objects_total_count: 107,
objects_total_size: 1024,
buckets_usage: [(
"bucket".to_string(),
rustfs_data_usage::BucketUsageInfo {
objects_count: 107,
size: 1024,
bucket_incarnation: Some("11111111-1111-4111-8111-111111111111".to_string()),
..Default::default()
},
)]
.into_iter()
.collect(),
usage_snapshot_complete: true,
..Default::default()
};
let current =
std::collections::HashMap::from([("bucket".to_string(), "22222222-2222-4222-8222-222222222222".to_string())]);
assert_eq!(info.retain_current_bucket_usage_for_admin(&current), 1);
assert!(info.buckets_usage.is_empty());
assert!(info.usage_snapshot_admin_projection);
assert_eq!(info.usage_snapshot_converged, Some(false));
let mut buckets = rustfs_madmin::Buckets::default();
let mut objects = rustfs_madmin::Objects::default();
let mut versions = rustfs_madmin::Versions::default();
let mut delete_markers = rustfs_madmin::DeleteMarkers::default();
let mut usage = rustfs_madmin::Usage::default();
apply_data_usage_result(Ok(info), &mut buckets, &mut objects, &mut versions, &mut delete_markers, &mut usage);
assert_eq!(buckets.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(objects.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(versions.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(delete_markers.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(usage.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
}
#[test]
fn incomplete_data_usage_is_unavailable_in_server_info() {
let mut buckets = rustfs_madmin::Buckets::default();
@@ -1,345 +0,0 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::ScannerBucketListing;
use rustfs_data_usage::DataUsageInfo;
use rustfs_madmin::ClusterInventory;
use std::collections::HashSet;
use crate::data_usage::{ADMIN_USAGE_INCARNATION_TIMEOUT, current_admin_bucket_incarnations};
use crate::error::Result;
use crate::store::ECStore;
use std::collections::HashMap;
use std::sync::Arc;
pub(super) async fn collect(
store: &Arc<ECStore>,
load_snapshot: impl Future<Output = Result<DataUsageInfo>>,
list_namespace: impl Future<Output = Result<ScannerBucketListing>>,
) -> (Result<DataUsageInfo>, Result<ScannerBucketListing>, ClusterInventory) {
let snapshot = load_snapshot.await;
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let namespace = bounded_namespace(deadline, list_namespace).await;
let mut current_ids = HashMap::new();
if let (Ok(namespace), Ok(snapshot)) = (&namespace, &snapshot)
&& namespace.topology_complete
{
let names = namespace
.buckets
.iter()
.filter(|bucket| {
!bucket.name.starts_with('.')
&& snapshot
.buckets_usage
.get(&bucket.name)
.is_some_and(|usage| usage.bucket_incarnation.is_some())
})
.map(|bucket| bucket.name.clone())
.collect();
current_ids = current_admin_bucket_incarnations(store.clone(), names, deadline).await;
}
let measured = summarize(namespace.as_ref().ok(), snapshot.as_ref().ok(), &current_ids);
(snapshot, namespace, measured)
}
pub(super) async fn bounded_namespace(
deadline: tokio::time::Instant,
read: impl Future<Output = crate::error::Result<ScannerBucketListing>>,
) -> crate::error::Result<ScannerBucketListing> {
tokio::time::timeout_at(deadline, read)
.await
.map_err(|_| crate::error::Error::other("inventory namespace read timed out"))?
}
pub(super) async fn namespace_or_fallback(
previous: Option<crate::error::Result<ScannerBucketListing>>,
read: impl Future<Output = crate::error::Result<ScannerBucketListing>>,
) -> crate::error::Result<ScannerBucketListing> {
// A failed or timed-out optional listing is already an observation.
// Retrying it without the deadline would stall the independent health response.
match previous {
Some(result) => result,
None => read.await,
}
}
pub(super) fn summarize(
namespace: Option<&ScannerBucketListing>,
snapshot: Option<&DataUsageInfo>,
current_ids: &HashMap<String, String>,
) -> ClusterInventory {
// An admin projection is a validated display-only view produced by the loader.
let snapshot = snapshot.filter(|info| {
info.usage_snapshot_admin_projection || info.is_complete_bucket_usage_snapshot() || info.is_valid_partial_snapshot()
});
let mut inventory = ClusterInventory {
snapshot_at: snapshot
.and_then(|info| info.last_update)
.and_then(|time| time.try_into().ok()),
..Default::default()
};
let Some(namespace) = namespace.filter(|listing| listing.topology_complete) else {
return inventory;
};
let names: HashSet<_> = namespace
.buckets
.iter()
.map(|bucket| bucket.name.as_str())
.filter(|name| !name.starts_with('.'))
.collect();
inventory.current_buckets = u64::try_from(names.len()).ok();
let Some(snapshot) = snapshot else {
return inventory;
};
let mut measured = 0_u64;
let mut objects = Some(0_u64);
let mut bytes = Some(0_u64);
for &name in &names {
let Some(usage) = snapshot.buckets_usage.get(name) else { continue };
if usage
.bucket_incarnation
.as_ref()
.is_none_or(|id| current_ids.get(name) != Some(id))
{
continue;
}
measured += 1;
objects = objects.and_then(|total| total.checked_add(usage.objects_count));
bytes = bytes.and_then(|total| total.checked_add(usage.size));
}
inventory.measured_buckets = Some(measured);
if measured != 0 || names.is_empty() {
inventory.measured_objects = objects;
inventory.measured_bytes = bytes;
}
inventory.converged = if objects.is_none() || bytes.is_none() {
None
} else if inventory.current_buckets != Some(measured)
|| snapshot.buckets_usage.len() != names.len()
|| snapshot.usage_snapshot_pending_bucket_count > 0
|| !snapshot.usage_snapshot_pending_buckets.is_empty()
|| !snapshot.is_complete_bucket_usage_snapshot()
{
Some(false)
} else {
snapshot.usage_snapshot_converged
};
inventory
}
#[cfg(test)]
mod tests {
use super::*;
use rustfs_data_usage::BucketUsageInfo;
use std::time::{Duration, SystemTime};
fn namespace(names: &[&str]) -> ScannerBucketListing {
ScannerBucketListing {
buckets: names
.iter()
.map(|name| crate::storage_api_contracts::bucket::BucketInfo {
name: name.to_string(),
..Default::default()
})
.collect(),
set_buckets: vec![],
topology_complete: true,
}
}
fn snapshot(names: &[(&str, u64)]) -> DataUsageInfo {
DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
usage_snapshot_complete: true,
usage_snapshot_converged: Some(true),
buckets_count: u64::try_from(names.len()).unwrap(),
buckets_usage: names
.iter()
.map(|&(name, count)| {
(
name.to_owned(),
BucketUsageInfo {
objects_count: count,
size: count,
bucket_incarnation: Some("11111111-1111-4111-8111-111111111111".into()),
..Default::default()
},
)
})
.collect(),
..Default::default()
}
}
fn view(namespace: Option<&ScannerBucketListing>, snapshot: Option<&DataUsageInfo>) -> ClusterInventory {
let ids = namespace
.into_iter()
.flat_map(|ns| &ns.buckets)
.map(|bucket| (bucket.name.clone(), "11111111-1111-4111-8111-111111111111".to_string()))
.collect();
summarize(namespace, snapshot, &ids)
}
#[tokio::test(start_paused = true)]
async fn inventory_namespace_timeout_is_reused_by_the_legacy_fallback() {
use tokio::time::{Duration, Instant};
let deadline = Instant::now() + Duration::from_secs(2);
let result = bounded_namespace(deadline, std::future::pending()).await;
assert!(result.is_err());
assert_eq!(Instant::now(), deadline);
let result = namespace_or_fallback(Some(result), async { panic!("must not retry a failed namespace read") }).await;
assert!(result.is_err());
let inventory = view(result.as_ref().ok(), None);
assert_eq!(inventory.current_buckets, None);
assert_eq!(inventory.measured_objects, None);
}
#[tokio::test]
#[serial_test::serial]
async fn inventory_excludes_stale_bucket_incarnations_after_a_slow_cold_snapshot_refresh() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::data_usage::{DATA_USAGE_OBJ_NAME_PATH, invalidate_data_usage_snapshot_cache};
use crate::storage_api_contracts::bucket::{BucketOperations as _, BucketOptions, MakeBucketOptions};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
for bucket in ["unchanged", "recreated", "new"] {
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
}
let mut scanned = snapshot(&[("unchanged", 4), ("recreated", 99), ("deleted", 6)]);
let current = store.bucket_incarnation_id_from_disk("unchanged").await.unwrap();
scanned.buckets_usage.get_mut("unchanged").unwrap().bucket_incarnation = Some(current.to_string());
scanned.usage_snapshot_converged = None;
scanned.calculate_totals();
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&scanned).unwrap())
.await
.unwrap();
invalidate_data_usage_snapshot_cache().await;
let options = BucketOptions {
no_metadata: true,
..Default::default()
};
let cold_refresh = async {
// Model a refresh that outlasts the inventory budget; keep disk I/O
// on the real clock so its independent timeouts behave normally.
tokio::time::pause();
tokio::time::advance(ADMIN_USAGE_INCARNATION_TIMEOUT + Duration::from_secs(1)).await;
tokio::time::resume();
super::super::load_server_info_usage_snapshot(store.clone()).await
};
let (loaded, listing, result) = collect(&store, cold_refresh, store.list_bucket_for_scanner(&options)).await;
assert_eq!(loaded.unwrap().usage_snapshot_converged, Some(true));
assert!(listing.unwrap().topology_complete);
assert_eq!(result.current_buckets, Some(3));
assert_eq!(result.measured_buckets, Some(1));
assert_eq!(result.measured_objects, Some(4));
assert_eq!(result.converged, Some(false));
// A complete canonical snapshot from before the convergence field was
// added inherits the admin loader's existing convergence interpretation.
let mut legacy = snapshot(&[("unchanged", 4), ("recreated", 0), ("new", 0)]);
legacy.usage_snapshot_converged = None;
for (name, usage) in &mut legacy.buckets_usage {
usage.bucket_incarnation = Some(store.bucket_incarnation_id_from_disk(name).await.unwrap().to_string());
}
legacy.calculate_totals();
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&legacy).unwrap())
.await
.unwrap();
invalidate_data_usage_snapshot_cache().await;
let (_, _, result) = collect(
&store,
super::super::load_server_info_usage_snapshot(store.clone()),
store.list_bucket_for_scanner(&options),
)
.await;
assert_eq!(result.measured_objects, Some(4));
assert_eq!(result.converged, Some(true));
invalidate_data_usage_snapshot_cache().await;
}
#[test]
fn inventory_reports_only_the_intersection_of_current_and_measured_buckets() {
let scope = namespace(&["existing", "new", ".rustfs.sys"]);
let before = snapshot(&[("existing", 300_000), ("deleted", 7)]);
let result = view(Some(&scope), Some(&before));
assert_eq!(result.current_buckets, Some(2));
assert_eq!(result.measured_buckets, Some(1));
assert_eq!(result.measured_objects, Some(300_000));
assert_eq!(result.measured_bytes, Some(300_000));
assert_eq!(result.converged, Some(false));
assert_eq!(result.snapshot_at.unwrap().as_second(), 1);
}
#[test]
fn inventory_distinguishes_unavailable_and_confirmed_empty_measurements() {
let empty = namespace(&[]);
let missing = view(Some(&empty), Some(&DataUsageInfo::default()));
assert_eq!(missing.current_buckets, Some(0));
assert_eq!(missing.measured_objects, None);
assert_eq!(missing.measured_buckets, None);
let available = view(Some(&empty), Some(&snapshot(&[])));
assert_eq!(available.measured_objects, Some(0));
assert_eq!(available.converged, Some(true));
let scope = namespace(&["new"]);
let no_overlap = view(Some(&scope), Some(&snapshot(&[("deleted", 7)])));
assert_eq!(no_overlap.measured_buckets, Some(0));
assert_eq!(no_overlap.measured_objects, None);
let known_empty = view(Some(&scope), Some(&snapshot(&[("new", 0)])));
assert_eq!(known_empty.measured_objects, Some(0));
assert_eq!(known_empty.measured_buckets, Some(1));
}
#[test]
fn inventory_keeps_the_recorded_snapshot_convergence_and_age() {
let scope = namespace(&["a"]);
let mut scanned = snapshot(&[("a", 12)]);
scanned.usage_snapshot_converged = None;
assert_eq!(view(Some(&scope), Some(&scanned)).converged, None);
scanned.usage_snapshot_converged = Some(true);
scanned.usage_snapshot_pending_buckets = vec!["a".into()];
assert_eq!(view(Some(&scope), Some(&scanned)).converged, Some(false));
scanned.usage_snapshot_pending_buckets.clear();
scanned.usage_snapshot_converged = Some(false);
scanned.usage_snapshot_complete = false;
scanned.usage_snapshot_admin_projection = true;
let result = view(Some(&scope), Some(&scanned));
assert_eq!(result.measured_objects, Some(12));
assert_eq!(result.converged, Some(false));
assert_eq!(result.snapshot_at.unwrap().as_second(), 1);
}
#[test]
fn inventory_requires_complete_namespace_and_checks_each_sum() {
let mut scope = namespace(&["a", "b"]);
let mut scanned = snapshot(&[("a", u64::MAX), ("b", 1)]);
scanned.buckets_usage.get_mut("a").unwrap().size = 1;
scope.topology_complete = false;
let missing = view(Some(&scope), Some(&scanned));
assert_eq!(missing.current_buckets, None);
assert_eq!(missing.measured_buckets, None);
assert_eq!(missing.converged, None);
scope.topology_complete = true;
let overflow = view(Some(&scope), Some(&scanned));
assert_eq!(overflow.measured_buckets, Some(2));
assert_eq!(overflow.measured_objects, None);
assert_eq!(overflow.measured_bytes, Some(2));
assert_eq!(overflow.converged, None);
}
#[test]
fn inventory_checks_even_cached_canonical_incarnations_on_main() {
let scope = namespace(&["recreated", "unreadable", "legacy"]);
let mut scanned = snapshot(&[("recreated", 5), ("unreadable", 6), ("legacy", 7)]);
scanned.buckets_usage.get_mut("legacy").unwrap().bucket_incarnation = None;
let ids = HashMap::from([
("recreated".to_string(), "22222222-2222-4222-8222-222222222222".to_string()),
("legacy".to_string(), "33333333-3333-4333-8333-333333333333".to_string()),
]);
let result = summarize(Some(&scope), Some(&scanned), &ids);
assert_eq!(result.current_buckets, Some(3));
assert_eq!(result.measured_buckets, Some(0));
assert_eq!(result.measured_objects, None);
}
}
+23 -23
View File
@@ -1631,8 +1631,6 @@ pub struct LocalDiskWrapper {
health_check: bool,
/// Cancellation token for monitoring tasks
cancel_token: CancellationToken,
/// Retirement belongs to this wrapper instance, not its monitoring policy.
retired: CancellationToken,
/// Disk ID for stale checking
disk_id: Arc<RwLock<Option<Uuid>>>,
/// Timeout policy for scanner-sensitive operations, loaded once on wrapper initialization.
@@ -1786,7 +1784,6 @@ impl LocalDiskWrapper {
physical_admission: Arc::new(crate::disk::io_admission::PhysicalDiskBinding::default()),
health_check: health_check && env_health_check,
cancel_token: CancellationToken::new(),
retired: CancellationToken::new(),
disk_id: Arc::new(RwLock::new(None)),
timeout_health_policy: get_drive_timeout_health_policy(),
};
@@ -1876,9 +1873,28 @@ impl LocalDiskWrapper {
}
async fn acquire_disk_io_permit(&self) -> Result<Option<crate::disk::io_admission::DiskIoPermit>> {
crate::disk::io_admission::acquire_wrapper_disk_io_permit(&self.io_admission)
.await
.map_err(DiskError::Io)
if let Some(context) = current_disk_io_context() {
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(&self.io_admission)
{
return Ok(Some(permit.clone()));
}
if context
.admission
.as_ref()
.is_some_and(|admission| Arc::ptr_eq(admission, &self.io_admission))
{
return Ok(None);
}
if context.class == DiskIoClass::Background {
return context
.background_permit(&self.io_admission)
.await
.map(Some)
.map_err(DiskError::Io);
}
}
Ok(Some(self.io_admission.foreground()))
}
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
@@ -1975,11 +1991,6 @@ impl LocalDiskWrapper {
self.cancel_token.cancel();
}
/// Observe retirement without granting callers authority to retire this wrapper.
pub fn retirement_token(&self) -> CancellationToken {
self.retired.child_token()
}
fn spawn_recovery_monitor_if_needed(&self) {
if !self.health_check {
return;
@@ -2455,14 +2466,7 @@ impl LocalDiskWrapper {
transaction: uuid::Uuid,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
) -> Result<
Option<(
crate::disk::DeleteRecoveryJournal,
bool,
bool,
Option<super::local::delete_recovery::LocalPublishedDeleteState>,
)>,
> {
) -> Result<Option<(crate::disk::DeleteRecoveryJournal, bool, bool)>> {
self.track_disk_health_mutation(
"settle_delete_transaction",
DiskMetricMutation::Delete,
@@ -2478,7 +2482,6 @@ impl LocalDiskWrapper {
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
&self,
volume: &str,
@@ -2487,7 +2490,6 @@ impl LocalDiskWrapper {
journal: &crate::disk::DeleteRecoveryJournal,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
published_state: Option<super::local::delete_recovery::LocalPublishedDeleteState>,
) -> Result<bool> {
self.track_disk_health_mutation(
"settle_delete_transaction",
@@ -2502,7 +2504,6 @@ impl LocalDiskWrapper {
journal,
namespace_owner,
work_budget,
published_state,
)
.await
})
@@ -2987,7 +2988,6 @@ impl DiskAPI for LocalDiskWrapper {
}
async fn close(&self) -> Result<()> {
self.retired.cancel();
self.stop_monitoring().await;
self.disk.close().await
}
+1 -11
View File
@@ -139,17 +139,7 @@ pub fn create_dir_all_std(path: &Path) -> io::Result<()> {
match std::fs::create_dir(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent)?;
return match std::fs::create_dir(path) {
Ok(()) => Ok(()),
Err(_) if path.is_dir() => Ok(()),
Err(e) => Err(e),
};
}
std::fs::create_dir_all(path)
}
Err(e) if e.kind() == io::ErrorKind::NotFound => std::fs::create_dir_all(path),
Err(e) => Err(e),
}
}
+35 -214
View File
@@ -294,21 +294,6 @@ pub(crate) fn with_optional_disk_io_context<F: Future>(
}
}
#[cfg(test)]
tokio::task_local! {
static TEST_CONTEXT_CLONES: std::sync::atomic::AtomicUsize;
}
fn clone_context_with_current_resource_unit(context: &DiskIoContext) -> DiskIoContext {
#[cfg(test)]
let _ = TEST_CONTEXT_CLONES.try_with(|c| c.fetch_add(1, Ordering::Relaxed));
let mut cloned = context.clone();
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
cloned.resource_unit = Some(unit);
}
cloned
}
/// An owned commit outlives its waiter. Retain an outer I/O class and physical
/// ownership, but give admission its own cancellation lifetime. Leave per-disk
/// scopes to the caller's existing ownership handoff: inheriting their class
@@ -316,23 +301,19 @@ fn clone_context_with_current_resource_unit(context: &DiskIoContext) -> DiskIoCo
/// The drive timeout bounds only queued admission; an admitted mutation still
/// drains to completion. Nested owners retain the original admission deadline.
pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future<Output = F::Output> {
let context = DISK_IO_CONTEXT
.try_with(|context| {
(context.admission.is_none() && context.permit.is_none()).then(|| {
let mut context = clone_context_with_current_resource_unit(context);
context.cancellation = CancellationToken::new();
let timeout = super::disk_store::get_max_timeout_duration();
if context.class == DiskIoClass::Background
&& !timeout.is_zero()
&& let Some(deadline) = Instant::now().checked_add(timeout)
{
context.admission_deadline = Some(context.admission_deadline.map_or(deadline, |old| old.min(deadline)));
}
context
})
})
.ok()
.flatten();
let context = current_disk_io_context()
.filter(|context| context.admission.is_none() && context.permit.is_none())
.map(|mut context| {
context.cancellation = CancellationToken::new();
let timeout = super::disk_store::get_max_timeout_duration();
if context.class == DiskIoClass::Background
&& !timeout.is_zero()
&& let Some(deadline) = Instant::now().checked_add(timeout)
{
context.admission_deadline = Some(context.admission_deadline.map_or(deadline, |old| old.min(deadline)));
}
context
});
async move {
match context {
Some(context) => with_disk_io_context(context, future).await,
@@ -342,74 +323,34 @@ pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future
}
pub(crate) fn current_disk_io_context() -> Option<DiskIoContext> {
DISK_IO_CONTEXT.try_with(clone_context_with_current_resource_unit).ok()
}
pub(crate) async fn acquire_wrapper_disk_io_permit(admission: &Arc<DiskIoAdmission>) -> io::Result<Option<DiskIoPermit>> {
enum WrapperPermitAction {
Immediate(Option<DiskIoPermit>),
Background(DiskIoContext),
}
let action = match DISK_IO_CONTEXT.try_with(|context| {
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return WrapperPermitAction::Immediate(Some(permit.clone()));
}
if context
.admission
.as_ref()
.is_some_and(|ctx_admission| Arc::ptr_eq(ctx_admission, admission))
{
return WrapperPermitAction::Immediate(None);
}
match context.class {
DiskIoClass::Foreground => WrapperPermitAction::Immediate(Some(admission.foreground())),
DiskIoClass::Background => WrapperPermitAction::Background(clone_context_with_current_resource_unit(context)),
}
}) {
Ok(action) => action,
Err(_) => return Ok(Some(admission.foreground())),
};
match action {
WrapperPermitAction::Immediate(permit) => Ok(permit),
WrapperPermitAction::Background(context) => context.background_permit(admission).await.map(Some),
}
DISK_IO_CONTEXT
.try_with(|context| {
let mut context = context.clone();
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
context.resource_unit = Some(unit);
}
context
})
.ok()
}
/// Acquire one low-level permit only when the current walker explicitly owns a gate.
/// Ordinary wrapper calls use their outer operation permit instead.
pub(crate) async fn acquire_context_disk_io_permit() -> io::Result<Option<DiskIoPermit>> {
enum ContextPermitAction {
Immediate(Option<DiskIoPermit>),
Background(Arc<DiskIoAdmission>, DiskIoContext),
}
let action = match DISK_IO_CONTEXT.try_with(|context| {
let Some(admission) = context.admission.as_ref() else {
return ContextPermitAction::Immediate(None);
};
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return ContextPermitAction::Immediate(Some(permit.clone()));
}
match context.class {
DiskIoClass::Foreground => ContextPermitAction::Immediate(Some(admission.foreground())),
DiskIoClass::Background => {
ContextPermitAction::Background(Arc::clone(admission), clone_context_with_current_resource_unit(context))
}
}
}) {
Ok(action) => action,
Err(_) => return Ok(None),
let Some(context) = current_disk_io_context() else {
return Ok(None);
};
match action {
ContextPermitAction::Immediate(permit) => Ok(permit),
ContextPermitAction::Background(admission, context) => context.background_permit(&admission).await.map(Some),
let Some(admission) = context.admission.as_ref() else {
return Ok(None);
};
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return Ok(Some(permit.clone()));
}
match context.class {
DiskIoClass::Foreground => Ok(Some(admission.foreground())),
DiskIoClass::Background => Ok(Some(context.background_permit(admission).await?)),
}
}
@@ -1332,124 +1273,4 @@ mod tests {
assert!(tokio::time::timeout(Duration::from_millis(10), worker.0).await.is_err());
wait_for_foreground_active(&admission, 0).await;
}
#[tokio::test]
async fn wrapper_and_context_permit_fast_paths_avoid_context_clones_and_preserve_resource_projection() {
use rustfs_concurrency::adaptive::AdaptiveAdmission;
use std::num::NonZeroU16;
use std::sync::atomic::AtomicUsize;
TEST_CONTEXT_CLONES
.scope(AtomicUsize::new(0), async {
let take_clones = || TEST_CONTEXT_CLONES.with(|c| c.swap(0, Ordering::Relaxed));
let admission = DiskIoAdmission::new("disk-fast");
let other_admission = DiskIoAdmission::new("disk-other");
// 1. No ambient context: wrapper returns Foreground permit, walker context returns None, 0 clones.
let wrapper_p = acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper permit")
.expect("foreground permit");
drop(wrapper_p);
assert!(acquire_context_disk_io_permit().await.expect("walker permit").is_none());
assert_eq!(take_clones(), 0);
// 2. Foreground context with admission=Some(admission), permit=None:
// - wrapper sees matching admission and returns Ok(None) (walker owns per-step permits)
// - walker acquires a Foreground permit from context.admission
// - 0 context clones.
let fg_ctx = DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: None,
resource_unit: None,
};
with_disk_io_context(fg_ctx, async {
assert!(
acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper under walker")
.is_none()
);
let step_p = acquire_context_disk_io_permit()
.await
.expect("walker step")
.expect("walker foreground permit");
assert!(step_p.is_for(&admission));
let other_p = acquire_wrapper_disk_io_permit(&other_admission)
.await
.expect("other disk wrapper")
.expect("other disk foreground permit");
assert!(other_p.is_for(&other_admission));
})
.await;
assert_eq!(take_clones(), 0);
// 3. Permit-match fast path on both helpers: 0 context clones.
let held_permit = admission.foreground();
let permit_ctx = DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: Some(held_permit),
resource_unit: None,
};
with_disk_io_context(permit_ctx, async {
let wp = acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper permit match")
.expect("matched permit");
assert!(wp.is_for(&admission));
let cp = acquire_context_disk_io_permit()
.await
.expect("context permit match")
.expect("matched context permit");
assert!(cp.is_for(&admission));
})
.await;
assert_eq!(take_clones(), 0);
// 4. Background context with inner RESOURCE_IO_UNIT override preserved across with_detached_disk_io_context.
let adaptive = AdaptiveAdmission::new(NonZeroU16::new(2).expect("two units"), 2);
let outer_unit = adaptive.acquire().await;
let inner_unit = adaptive.acquire().await;
with_background_disk_io(
CancellationToken::new(),
with_background_resource_unit(outer_unit, async {
with_background_resource_unit(inner_unit, async {
let bg_ctx = DiskIoContext {
class: DiskIoClass::Background,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: None,
resource_unit: None,
};
with_disk_io_context(bg_ctx, async {
let bg_step = acquire_context_disk_io_permit()
.await
.expect("background walker step")
.expect("background walker permit");
assert!(bg_step.is_for(&admission));
})
.await;
assert!(take_clones() >= 1, "background path must clone context with resource unit");
let spawned = tokio::spawn(with_detached_disk_io_context(async {
let ctx = current_disk_io_context().expect("detached background context");
assert_eq!(ctx.class, DiskIoClass::Background);
assert!(ctx.resource_unit.is_some(), "inner resource unit must be merged");
}));
spawned.await.expect("detached task joins");
})
.await;
}),
)
.await;
})
.await;
}
}
File diff suppressed because it is too large Load Diff
+3 -11
View File
@@ -744,7 +744,7 @@ impl LocalDisk {
}
}
if dst_volume == crate::disk::RUSTFS_META_BUCKET {
crate::bucket::metadata_sys::maybe_bump_local_meta_mutation_gen_for_path(dst_volume, dst_path);
crate::bucket::metadata_sys::bump_local_meta_mutation_gen();
}
if fi.is_legacy_indexed_delete_marker() {
fi.erasure.index = 0;
@@ -975,26 +975,18 @@ impl LocalDisk {
Box::new(fi_moved),
));
}
let version_id = fi_moved.version_id.unwrap_or_default();
let mut xlmeta = FileMeta::new();
let mut dst_meta_unparsable = false;
if let Some(ref old_file) = old_destination_file {
if FileMeta::is_xl2_v1_format(&old_file.bytes)
&& let Ok((mut nmeta, old_inline_buf)) = FileMeta::load_with_borrowed_inline_data(&old_file.bytes)
&& let Ok(nmeta) = FileMeta::load(&old_file.bytes)
{
if !old_inline_buf.is_empty()
&& nmeta
.versions
.iter()
.any(|v| v.header.version_id.unwrap_or_default() != version_id)
{
nmeta.data.update(old_inline_buf);
}
xlmeta = nmeta;
} else {
dst_meta_unparsable = true;
}
}
let version_id = fi_moved.version_id.unwrap_or_default();
let has_old_data_dir = xlmeta.find_unshared_data_dir_for_version(Some(version_id));
let rollback_data_dir = has_old_data_dir.or_else(|| {
if old_destination_file.is_some() && xlmeta.find_version(Some(version_id)).is_ok() {
File diff suppressed because it is too large Load Diff
+1 -38
View File
@@ -121,7 +121,6 @@ use sha2::Digest as _;
use std::{fmt::Debug, path::PathBuf, sync::Arc, time::Duration};
use time::OffsetDateTime;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
/// Independent admission and physical ownership for one disk rename.
@@ -242,14 +241,6 @@ pub enum PoolMetaNativeRecoveryResponse {
pub type DiskStore = Arc<Disk>;
/// Filesystem evidence for a replacement data directory on its expected mount.
#[derive(Debug)]
pub struct ReplacementMount {
pub canonical_path: PathBuf,
pub physical_device_ids: Vec<String>,
pub filesystem_identity: String,
}
pub trait DiskFileWriter: AsyncWrite + Send + Sync + Unpin + std::any::Any {}
impl<T: AsyncWrite + Send + Sync + Unpin + 'static> DiskFileWriter for T {}
@@ -460,14 +451,7 @@ impl Disk {
transaction: Uuid,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
) -> Result<
Option<(
DeleteRecoveryJournal,
bool,
bool,
Option<local::delete_recovery::LocalPublishedDeleteState>,
)>,
> {
) -> Result<Option<(DeleteRecoveryJournal, bool, bool)>> {
match self {
Self::Local(disk) => {
disk.try_publish_prepared_delete_local(volume, object, transaction, namespace_owner, work_budget)
@@ -477,7 +461,6 @@ impl Disk {
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
&self,
volume: &str,
@@ -486,7 +469,6 @@ impl Disk {
journal: &DeleteRecoveryJournal,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
published_state: Option<local::delete_recovery::LocalPublishedDeleteState>,
) -> Result<bool> {
match self {
Self::Local(disk) => {
@@ -497,7 +479,6 @@ impl Disk {
journal,
namespace_owner,
work_budget,
published_state,
)
.await
}
@@ -1481,15 +1462,6 @@ impl Disk {
}
}
/// Observe a local wrapper's retirement. Remote handles have their own RPC lifecycle.
/// Cancelling the returned child token does not retire the underlying wrapper.
pub fn local_retirement_token(&self) -> Option<CancellationToken> {
match self {
Disk::Local(local_disk) => Some(local_disk.retirement_token()),
Disk::Remote(_) => None,
}
}
pub fn offline_duration_secs(&self) -> Option<u64> {
match self {
Disk::Local(local_disk) => local_disk.offline_duration_secs(),
@@ -1613,15 +1585,6 @@ impl Disk {
}
}
/// Observe the expected mount through the same local disk handle that will
/// execute recovery. Call from a blocking context.
pub fn replacement_mount(&self, mount_roots: &[PathBuf]) -> Option<ReplacementMount> {
match self {
Self::Local(disk) => disk.get_disk().replacement_mount(mount_roots),
Self::Remote(_) => None,
}
}
pub async fn acquire_replacement_execution_lease(&self) -> Result<std::sync::Arc<local::ReplacementExecutionLease>> {
match self {
Self::Local(disk) => disk.get_disk().acquire_replacement_execution_lease().await,
+23 -110
View File
@@ -428,24 +428,6 @@ pub(crate) mod prepared_publication_test_hooks {
}
}
#[cfg(target_os = "linux")]
pub(crate) fn has_rename_hooks(source: &Path, destination: &Path) -> bool {
let before_publication = {
let guard = BEFORE_PUBLICATION.lock();
!guard.is_empty()
&& (guard.contains_key(&(Stage::Rename, source.to_path_buf()))
|| guard.contains_key(&(Stage::Rename, destination.to_path_buf())))
};
#[cfg(test)]
{
before_publication || RENAME_DESTINATIONS.lock().contains_key(source)
}
#[cfg(not(test))]
{
before_publication
}
}
#[cfg(test)]
type RenameDestinationHook = Box<dyn FnOnce(&Path) + Send>;
#[cfg(test)]
@@ -2689,7 +2671,6 @@ pub(crate) const MAX_FSYNC_WORKERS_PER_DISK: usize = 8;
// Return busy workers to the shared pool so other disks can acquire a slot.
const MAX_BLOCKING_JOBS_PER_WORKER: usize = 64;
const WORKER_IDLE_SPIN_ITERS: usize = 256;
const FSYNC_IDLE_YIELD_ITERS: usize = 2;
const DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 256;
const MAX_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 1024;
const FALLBACK_NAMESPACE_QUEUE_SHARDS: usize = 8;
@@ -2888,11 +2869,6 @@ impl DiskBlockingQueue {
self.lanes.iter().map(|lane| lane.state.lock().submitted_jobs).sum()
}
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn submitted_fsync_jobs_for_test(&self) -> usize {
self.lane(DiskBlockingLane::Fsync).state.lock().submitted_jobs
}
#[inline]
fn foreground_lane() -> DiskBlockingLane {
if is_isolated_io_thread() {
@@ -2995,18 +2971,6 @@ impl DiskBlockingQueue {
std::hint::spin_loop();
spun += 1;
}
if lane == DiskBlockingLane::Fsync
&& spin_iters > 0
&& spun == spin_iters
&& !queue.lane(lane).ready.load(std::sync::atomic::Ordering::Relaxed)
{
for _ in 0..FSYNC_IDLE_YIELD_ITERS {
std::thread::yield_now();
if queue.lane(lane).ready.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
}
}
if let Some(metrics) = spin_metrics {
metrics.finish(spun);
}
@@ -3307,37 +3271,6 @@ fn disk_namespace_mutation_lock_by_key(key: &[u8]) -> Arc<NamespaceMutationLock>
static DISK_METADATA_MUTATION_LOCKS: LazyLock<ShardedPathLockRegistry<NamespaceMutationLock>> =
LazyLock::new(ShardedPathLockRegistry::new);
/// Distinct handle for the per-object metadata mutation lock domain so callers
/// cannot accidentally swap metadata and namespace lock handles across stages.
#[derive(Clone)]
pub(crate) struct MetadataMutationLockHandle(Arc<NamespaceMutationLock>);
impl MetadataMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
/// Distinct handle for the per-path namespace mutation lock domain.
#[derive(Clone)]
pub(in crate::disk) struct NamespaceMutationLockHandle(Arc<NamespaceMutationLock>);
impl NamespaceMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
pub(crate) fn lookup_metadata_mutation_lock(object: &Path) -> MetadataMutationLockHandle {
MetadataMutationLockHandle(DISK_METADATA_MUTATION_LOCKS.get_or_create(object, || AsyncMutex::new(())))
}
pub(in crate::disk) fn lookup_namespace_mutation_lock(path: &Path) -> NamespaceMutationLockHandle {
NamespaceMutationLockHandle(disk_namespace_mutation_lock(path))
}
/// Serializes the complete xl.meta read/modify/commit transaction. This domain
/// precedes namespace/volume publication locks, whose narrower syscall leases
/// may retain it after cancellation of the async caller.
@@ -3350,16 +3283,9 @@ pub(crate) async fn acquire_metadata_mutation_lease(
object: &Path,
owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<MetadataMutationLease> {
let lock = lookup_metadata_mutation_lock(object);
acquire_metadata_mutation_lease_with_lock(&lock, owner).await
}
pub(crate) async fn acquire_metadata_mutation_lease_with_lock(
lock: &MetadataMutationLockHandle,
owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<MetadataMutationLease> {
let lock = DISK_METADATA_MUTATION_LOCKS.get_or_create(object, || AsyncMutex::new(()));
Arc::new(MetadataMutationLease {
_guard: lock.0.clone().lock_owned().await,
_guard: lock.lock_owned().await,
_owner: owner,
})
}
@@ -3396,25 +3322,8 @@ pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_owner(
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
let blocking_queue = disk_blocking_queue_for_path(path);
acquire_namespace_mutation_lease_with_queue(path, blocking_queue, namespace_owner).await
}
pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_queue(
path: &Path,
blocking_queue: Arc<DiskBlockingQueue>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
let lock = lookup_namespace_mutation_lock(path);
acquire_namespace_mutation_lease_with_lock_and_queue(&lock, blocking_queue, namespace_owner).await
}
pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_lock_and_queue(
lock: &NamespaceMutationLockHandle,
blocking_queue: Arc<DiskBlockingQueue>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
Arc::new(NamespaceMutationLease {
_namespace_guard: lock.0.clone().lock_owned().await,
_namespace_guard: disk_namespace_mutation_lock(path).lock_owned().await,
_staging_guard: None,
_volume_guard: None,
external_guard: Mutex::new(None),
@@ -5399,11 +5308,11 @@ pub(crate) async fn rename_all_with_prepared_source(
#[cfg(target_os = "linux")]
pub(crate) fn rename_all_with_commit_guard_on_thread(source: &Path, destination: &Path, guard: &RenameCommitGuard) -> Result<()> {
guard.directories.prepare_destination().map_err(to_file_error)?;
#[cfg(test)]
prepared_publication_test_hooks::run_rename_destination(source, destination);
#[cfg(any(test, feature = "test-util"))]
if prepared_publication_test_hooks::has_rename_hooks(source, destination) {
guard.directories.prepare_destination().map_err(to_file_error)?;
#[cfg(test)]
prepared_publication_test_hooks::run_rename_destination(source, destination);
{
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, source);
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, destination);
}
@@ -5761,13 +5670,12 @@ pub(crate) async fn acquire_file_sync_admission(disk_permits: Arc<Semaphore>) ->
/// Keep the disk admission and namespace lease with the blocking syscall if
/// the async waiter is cancelled. The process-wide admission remains with the
/// waiter so cancellation cannot starve healthy disks.
#[cfg(any(unix, test))]
pub(crate) async fn run_blocking_namespace_file_sync_operation<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
operation: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
run_cancellable_blocking_namespace_file_sync_operation(lease, admission, move |_| operation()).await
run_blocking_namespace_file_sync_operation_with_global(lease, admission, &FILE_SYNC_PERMITS, operation).await
}
pub(crate) async fn run_cancellable_blocking_namespace_file_sync_operation<T: Send + 'static>(
@@ -5778,6 +5686,16 @@ pub(crate) async fn run_cancellable_blocking_namespace_file_sync_operation<T: Se
run_cancellable_blocking_namespace_file_sync_operation_with_global(lease, admission, &FILE_SYNC_PERMITS, operation).await
}
async fn run_blocking_namespace_file_sync_operation_with_global<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
global_permits: &Semaphore,
operation: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
run_cancellable_blocking_namespace_file_sync_operation_with_global(lease, admission, global_permits, move |_| operation())
.await
}
async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
@@ -12665,16 +12583,11 @@ mod tests {
let (release_tx, release_rx) = mpsc::channel();
let waiter_global_permits = global_permits.clone();
let waiter = tokio::spawn(async move {
run_cancellable_blocking_namespace_file_sync_operation_with_global(
lease,
&admission,
waiter_global_permits.as_ref(),
move |_| {
entered_tx.send(()).expect("signal blocking work");
release_rx.recv().expect("wait for blocking work release");
Ok(())
},
)
run_blocking_namespace_file_sync_operation_with_global(lease, &admission, waiter_global_permits.as_ref(), move || {
entered_tx.send(()).expect("signal blocking work");
release_rx.recv().expect("wait for blocking work release");
Ok(())
})
.await
});
@@ -49,7 +49,6 @@ pub(crate) fn test_single_inflight_construction_count() -> u64 {
}
type FillTask = oneshot::Receiver<FillResult>;
type FillBatch = (Vec<u8>, VecDeque<Vec<u8>>);
struct FillWorker {
tx: mpsc::Sender<FillRequest>,
@@ -294,7 +293,7 @@ where
Self::new_with_fill_policy_inner(source, engine, total_length, metrics_path, fill_policy)
}
fn poll_fill_result(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<Option<FillBatch>>> {
fn poll_fill_result(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<Option<Vec<u8>>>> {
if self.fill.is_none() {
let fill_worker_tx = match self.fill_worker_tx() {
Ok(tx) => tx,
@@ -346,6 +345,15 @@ where
if let Some(deferred_error) = deferred_error {
self.prefetch_error = Some(deferred_error);
}
// Queued stripes are delivered to the client via `prefetched_bufs.pop_front()`
// in `poll_read` without touching `self.remaining`, so their bytes must be
// accounted for here. Otherwise, under multi-in-flight fill policies (e.g. the
// default `DualInFlight`), `remaining` never reaches 0 and a fully delivered
// multi-block object still terminates the GET with `LessData`. Buffers in
// `queued_buffers` come only from `Ok(true)` decodes, so they are non-empty and
// their total is bounded by `remaining - main_buf.len()`, ruling out underflow.
self.remaining -= queued_buffers.iter().map(Vec::len).sum::<usize>();
self.prefetched_bufs.extend(queued_buffers);
match result {
Ok(Some(buf)) => {
@@ -354,14 +362,8 @@ where
}
rustfs_io_metrics::record_get_object_reader_stripe(self.metrics_path);
rustfs_io_metrics::record_get_object_reader_bytes(self.metrics_path, buf.len());
// Queued stripes are delivered to the client via `prefetched_bufs.pop_front()`
// in `poll_read` without touching `self.remaining`, so their bytes must be
// accounted for here alongside the primary stripe. Buffers in `queued_buffers`
// come only from `Ok(true)` decodes, so they are non-empty and their total is
// bounded by `remaining - buf.len()`, ruling out underflow.
self.remaining -= buf.len();
self.remaining -= queued_buffers.iter().map(Vec::len).sum::<usize>();
Poll::Ready(Ok(Some((buf, queued_buffers))))
Poll::Ready(Ok(Some(buf)))
}
Ok(None) => {
if self.remaining == 0 {
@@ -399,8 +401,8 @@ where
};
match fill {
Ok(Some((buf, queued_buffers))) => {
let output_has_remaining = self.output_pos < self.output_buf.len() || !self.prefetched_bufs.is_empty();
Ok(Some(buf)) => {
let output_has_remaining = self.output_pos < self.output_buf.len();
let mut queued_count = 0usize;
let mut queued_bytes = 0usize;
@@ -418,7 +420,6 @@ where
self.output_buf = buf;
self.output_pos = 0;
}
self.prefetched_bufs.extend(queued_buffers);
if !self.prefetched_bufs.is_empty() {
let total_prefetched_bytes = self.prefetched_bufs.iter().map(Vec::len).sum::<usize>();
@@ -450,7 +451,7 @@ where
Poll::Ready(Ok(()))
}
Err(err) => {
if self.output_pos < self.output_buf.len() || !self.prefetched_bufs.is_empty() {
if self.output_pos < self.output_buf.len() {
rustfs_io_metrics::record_get_object_reader_prefetch(self.metrics_path, GET_READER_PREFETCH_ERROR_DEFERRED);
self.prefetch_error = Some(err);
Poll::Ready(Ok(()))
@@ -1859,42 +1860,6 @@ mod tests {
.expect("dual inflight policy should prefetch two future stripes before current output drains");
}
#[tokio::test]
async fn erasure_decode_reader_dual_inflight_preserves_stripe_order_when_prefetch_completes_before_output_drains() {
let erasure = Erasure::new(4, 2, 16);
let data = (0..96u8).collect::<Vec<_>>();
let read_count = Arc::new(AtomicUsize::new(0));
let mut source = source_from_data(&erasure, &data, &[]);
source.read_count = Some(Arc::clone(&read_count));
let engine = LegacyEcDecodeEngine::new(erasure);
let mut reader = ErasureDecodeReader::new_with_fill_policy(
source,
engine,
data.len(),
GET_OBJECT_PATH_CODEC_STREAMING,
FillPolicy::DualInFlight,
)
.expect("reader should be constructed");
let mut decoded = Vec::with_capacity(data.len());
let mut chunk = [0u8; 5];
loop {
let n = reader.read(&mut chunk).await.expect("chunk read should succeed");
if n == 0 {
break;
}
decoded.extend_from_slice(&chunk[..n]);
// Yield between partial reads so the DualInFlight worker completes
// a 2-stripe fill (primary + queued_buffers) while output_buf still
// has unconsumed bytes.
for _ in 0..4 {
yield_now().await;
}
}
assert_eq!(decoded, data);
}
#[tokio::test]
async fn erasure_decode_reader_dual_inflight_reads_multi_block_object_to_end() {
// Regression for the byte-accounting bug: under DualInFlight each fill
+2 -17
View File
@@ -103,11 +103,8 @@ fn use_bytesmut_ingest() -> bool {
}
fn small_ingest_capacity(erasure: &Erasure, size_hint: usize) -> usize {
if size_hint <= erasure.block_size {
erasure.encoded_capacity_for_data_len(size_hint)
} else {
erasure.block_size
}
let data_len = size_hint.min(erasure.block_size);
erasure.encoded_capacity_for_data_len(data_len).min(erasure.block_size)
}
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
@@ -3525,24 +3522,12 @@ mod tests {
assert_eq!(small_ingest_capacity(&erasure, 0), 0);
assert_eq!(small_ingest_capacity(&erasure, 4 * 1024), 6 * 1024);
assert_eq!(small_ingest_capacity(&erasure, 16 * 1024), 24 * 1024);
assert_eq!(
small_ingest_capacity(&erasure, 1024 * 1024),
erasure.encoded_capacity_for_data_len(1024 * 1024)
);
assert_eq!(small_ingest_capacity(&erasure, usize::MAX), 1024 * 1024);
let legacy = Erasure::new_with_options(4, 2, 1024 * 1024, true);
assert_eq!(small_ingest_capacity(&legacy, 4 * 1024), 6 * 1024);
assert_eq!(
small_ingest_capacity(&legacy, 1024 * 1024),
legacy.encoded_capacity_for_data_len(1024 * 1024)
);
let high_parity = Erasure::new(4, 12, 1024 * 1024);
assert_eq!(
small_ingest_capacity(&high_parity, 1024 * 1024),
high_parity.encoded_capacity_for_data_len(1024 * 1024)
);
assert_eq!(small_ingest_capacity(&high_parity, usize::MAX), 1024 * 1024);
}
+6 -23
View File
@@ -974,18 +974,12 @@ impl ReadPlan {
let _ = sequence_number;
let decrypted_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if is_multipart {
match material.mode {
ReadEncryptionMode::Object => {
// The rio-v2 reader fails a stream that ends before a
// listed part, so it must not hear about empty ones.
#[cfg(feature = "rio-v2")]
let part_numbers = without_empty_parts(part_numbers, &oi.parts);
crate::io_support::rio::decrypt_multipart_reader_with_object_key(
reader,
material.key_bytes,
part_numbers,
sequence_number,
)
}
ReadEncryptionMode::Object => crate::io_support::rio::decrypt_multipart_reader_with_object_key(
reader,
material.key_bytes,
part_numbers,
sequence_number,
),
ReadEncryptionMode::Direct { base_nonce } => crate::io_support::rio::decrypt_multipart_reader(
reader,
material.key_bytes,
@@ -1440,17 +1434,6 @@ fn multipart_part_numbers(parts: &[ObjectPartInfo]) -> Vec<usize> {
parts.iter().map(|part| part.number).collect()
}
/// Drops from `part_numbers` the parts that stored no bytes: a DARE writer
/// emits no package for an empty part, so none follows on disk.
#[cfg(feature = "rio-v2")]
fn without_empty_parts(mut part_numbers: Vec<usize>, parts: &[ObjectPartInfo]) -> Vec<usize> {
let empty_parts: Vec<usize> = parts.iter().filter(|part| part.size == 0).map(|part| part.number).collect();
if !empty_parts.is_empty() {
part_numbers.retain(|number| !empty_parts.contains(number));
}
part_numbers
}
#[cfg(test)]
mod tests {
use super::*;
-5
View File
@@ -1259,11 +1259,6 @@ pub struct ObjectOptions {
pub expected_current_version_id: Option<String>,
/// Persisted bucket incarnation observed before authorization.
pub expected_bucket_incarnation_id: Option<Uuid>,
/// Bucket incarnation that was admitted for an externally visible event.
/// This is kept separate from the storage fence because recovered work may
/// be allowed to commit while its notification provenance remains unknown.
#[doc(hidden)]
pub notification_bucket_incarnation_id: Option<Uuid>,
pub no_lock: bool,
/// Require complete participant observations for internal multipart size decisions.
/// This transient flag is never derived from client input or stored on disk.
@@ -82,8 +82,6 @@ impl EventNotifier {
#[derive(Debug, Default)]
pub struct EventArgs {
/// Bucket instance verified by storage when producing this event.
pub bucket_incarnation_id: Option<uuid::Uuid>,
pub event_name: String,
pub bucket_name: String,
pub object: ObjectInfo,
@@ -137,7 +135,6 @@ pub(crate) mod test_recorder {
#[derive(Clone, Debug)]
pub(crate) struct RecordedEvent {
pub(crate) event_name: String,
pub(crate) bucket_incarnation_id: Option<Uuid>,
pub(crate) bucket: String,
pub(crate) object: String,
pub(crate) version_id: Option<Uuid>,
@@ -157,7 +154,6 @@ pub(crate) mod test_recorder {
register_event_dispatch_hook(|args| {
recorded().lock().unwrap_or_else(|err| err.into_inner()).push(RecordedEvent {
event_name: args.event_name,
bucket_incarnation_id: args.bucket_incarnation_id,
bucket: args.bucket_name,
object: args.object.name,
version_id: args.object.version_id,
@@ -62,10 +62,6 @@ impl MetricType {
pub const RPC: MetricType = MetricType(1 << 8);
pub const HTTP: MetricType = MetricType(1 << 9);
/// Internal GetMetrics selector for a compact, generation-bound node sample.
/// Excluded from ALL so existing HTTP and rolling-upgrade peers keep their wire shape.
pub const SCANNER_SUMMARY: MetricType = MetricType(1 << 10);
// MetricsAll must be last.
pub const ALL: MetricType = MetricType((1 << 10) - 1);
@@ -162,7 +158,6 @@ fn to_madmin_scanner_metrics(metrics: rustfs_scanner_metrics::metrics::ScannerMe
last_cycle_lifecycle_transition_actions: metrics.last_cycle_lifecycle_transition_actions,
last_cycle_partial_source: metrics.last_cycle_partial_source,
last_cycle_partial_source_code: metrics.last_cycle_partial_source_code,
last_cycle_partial_stage: metrics.last_cycle_partial_stage,
last_cycle_duration_seconds: metrics.last_cycle_duration_seconds,
last_cycle_objects_scanned: metrics.last_cycle_objects_scanned,
last_cycle_directories_scanned: metrics.last_cycle_directories_scanned,
@@ -410,27 +405,6 @@ impl MetricType {
pub async fn collect_local_metrics(types: MetricType, opts: &CollectMetricsOpts) -> RealtimeMetrics {
debug!("collect_local_metrics");
let mut real_time_metrics = RealtimeMetrics::default();
if types.0 == MetricType::SCANNER_SUMMARY.0 {
let sample = global_metrics().scanner_node_observation().await;
real_time_metrics.scanner_node = Some(rustfs_madmin::metrics::ScannerNodeSample {
active: sample.active,
leader: sample.leader,
cycle: sample.cycle,
epoch: sample.epoch,
started_at: sample.started_at,
objects_scanned: sample.objects_scanned,
last_attempt: sample
.last_attempt
.map(|attempt| rustfs_madmin::metrics::ScannerAttemptSample {
epoch: attempt.epoch,
cycle: attempt.cycle,
result: attempt.result.to_string(),
partial_reason: attempt.partial_reason.map(str::to_string),
duration_seconds: attempt.duration.as_secs_f64(),
}),
});
return real_time_metrics;
}
if types.0 == MetricType::NONE.0 {
info!("types is None, return");
return real_time_metrics;
@@ -711,7 +685,6 @@ mod test {
current_started,
last_cycle_partial_source: "usage".to_string(),
last_cycle_partial_source_code: 1,
last_cycle_partial_stage: Some("object_budget".into()),
cycle_timeout_total: 3,
cycle_recovery_required_total: 2,
cycle_last_progress_age: 17,
@@ -727,7 +700,6 @@ mod test {
assert_eq!(scanner.current_started, current_started);
assert_eq!(scanner.last_cycle_partial_source, "usage");
assert_eq!(scanner.last_cycle_partial_source_code, 1);
assert_eq!(scanner.last_cycle_partial_stage.as_deref(), Some("object_budget"));
assert_eq!(scanner.cycle_timeout_total, 3);
assert_eq!(scanner.cycle_recovery_required_total, 2);
assert_eq!(scanner.cycle_last_progress_age, 17);
@@ -17,8 +17,8 @@
use crate::disk::error::{DiskError, Result, RpcStatusError};
use crate::disk::{
DELETE_RECOVERY_PROTOCOL_VERSION, DeleteRecoveryAction, DeleteRecoveryInspection, DeleteRecoveryJournal, DeleteRecoveryState,
DeleteRecoveryVersionIdentity, DeleteTransactionId, DiskAPI, DiskStore,
DELETE_RECOVERY_PROTOCOL_VERSION, DeleteRecoveryAction, DeleteRecoveryInspection, DeleteRecoveryState, DeleteTransactionId,
DiskAPI, DiskStore,
};
use crate::error::StorageError;
use crate::set_disk::SetDisks;
@@ -204,39 +204,16 @@ pub(in crate::set_disk) fn unsupported_recovery(error: &DiskError) -> bool {
.is_some_and(|status| status.status().code() == tonic::Code::Unimplemented))
}
/// Set authority needs generation identities, not the potentially large
/// per-version apply requests carried by returning-drive adoption.
struct DecisionEvidence {
transaction: Uuid,
deleted_versions: HashSet<Uuid>,
original_null_versions: HashSet<DeleteRecoveryVersionIdentity>,
original_versions: HashSet<crate::disk::DeleteRecoveryVersionIdentity>,
predecessors: HashSet<Uuid>,
target_absent: bool,
}
impl From<&DeleteRecoveryJournal> for DecisionEvidence {
fn from(journal: &DeleteRecoveryJournal) -> Self {
let deleted_versions: HashSet<_> = journal.deleted_versions.iter().copied().collect();
// Only the null version can be reused for a different generation.
// Adjacent transactions deleting unique version IDs need no identity index.
let original_null_versions = if deleted_versions.contains(&Uuid::nil()) {
journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.cloned()
.collect()
} else {
HashSet::new()
};
Self {
transaction: journal.transaction,
deleted_versions,
original_null_versions,
predecessors: journal.predecessors.iter().copied().collect(),
target_absent: journal.target_digest.is_none(),
}
}
}
fn receipt(state: DeleteRecoveryState) -> bool {
matches!(state, DeleteRecoveryState::QuorumCommitted | DeleteRecoveryState::CommitFinished)
}
@@ -557,7 +534,7 @@ impl SetDisks {
};
let mut fast_receipt_quorum = false;
if can_try_local_fast_path && can_commit() {
let mut fast_published = join_all(disks.iter().map(|disk| async {
let fast_published = join_all(disks.iter().map(|disk| async {
if !can_commit() {
return Err(DiskError::other("delete recovery namespace fence was lost"));
}
@@ -581,17 +558,13 @@ impl SetDisks {
return Ok(());
}
let all_fast_published = fast_published.len() == self.set_drive_count
&& fast_published.iter().all(|res| matches!(res, Ok(Some((_, true, true, _)))));
&& fast_published.iter().all(|res| matches!(res, Ok(Some((_, true, true)))));
if all_fast_published && can_commit() {
#[cfg(test)]
test_hooks::record_cleanup_attempt(bucket, object);
let finalized = join_all(disks.iter().zip(fast_published.iter_mut()).map(|(disk, pub_res)| {
let finalized = join_all(disks.iter().zip(fast_published.iter()).map(|(disk, pub_res)| {
let ns_owner = context.namespace_owner.clone();
let work_budget = context.work_budget.clone();
let published_input = match pub_res {
Ok(Some((journal, _, _, state))) => Some((&*journal, state.take())),
_ => None,
};
async move {
if !can_commit() {
return Ok(false);
@@ -599,7 +572,7 @@ impl SetDisks {
let Some(disk) = disk.as_ref() else {
return Ok(false);
};
let Some((journal, state)) = published_input else {
let Ok(Some((journal, _, _))) = pub_res else {
return Ok(false);
};
disk.try_finish_and_finalize_prepared_delete_local(
@@ -609,7 +582,6 @@ impl SetDisks {
journal,
ns_owner,
work_budget,
state,
)
.await
}
@@ -628,9 +600,6 @@ impl SetDisks {
return Ok(());
}
}
// Flush any unconsumed Stage 2 receipt entries into `PUBLISHED_DELETE_RECEIPTS`
// (via `LocalPublishedDeleteState::drop`) before falling back to `inspect`.
drop(fast_published);
}
let states = inspect(disks, bucket, object, transaction, context.work_budget.as_deref()).await;
if states
@@ -1069,7 +1038,13 @@ impl SetDisks {
.flatten()
.filter(|state| receipt(state.state))
.filter_map(|state| state.journal.as_ref())
.map(DecisionEvidence::from)
.map(|journal| DecisionEvidence {
transaction: journal.transaction,
deleted_versions: journal.deleted_versions.iter().copied().collect(),
original_versions: journal.original_versions.iter().cloned().collect(),
predecessors: journal.predecessors.iter().copied().collect(),
target_absent: journal.target_digest.is_none(),
})
.collect::<Vec<_>>();
let mut unresolved = false;
let mut mutated = false;
@@ -1125,43 +1100,49 @@ impl SetDisks {
.iter()
.filter(|state| receipt(state.state))
.filter_map(|state| state.journal.as_ref())
.max_by_key(|journal| !journal.requests.is_empty());
let finished =
|copy: &DeleteRecoveryInspection| copy.state == DeleteRecoveryState::CommitFinished && copy.commit_data_safe;
if authority.is_some() && copies.iter().all(finished) {
// Neither settlement phase writes. The sibling inspections
// remain valid under the same key fence.
summary.committed += 1;
continue;
}
.max_by_key(|journal| !journal.requests.is_empty())
.cloned();
let prepared = copies.iter().find_map(|state| state.journal.as_ref());
let can_finish = authority.is_some()
|| fresh_absence_decision
|| prepared
.filter(|journal| !journal.deleted_versions.is_empty())
.is_some_and(|journal| {
authorities.iter().any(|authority| {
journal.deleted_versions.iter().all(|version| {
authority.deleted_versions.contains(version)
&& (!version.is_nil()
|| journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.all(|source| authority.original_null_versions.contains(source))
|| (authority.predecessors.contains(&journal.transaction)
&& journal.target_digest.is_none()
&& authority.target_absent
&& copies.iter().all(|copy| {
copy.current_digest.is_none()
|| copy.current_versions == journal.original_versions
})))
})
let covered = prepared
.filter(|journal| !journal.deleted_versions.is_empty())
.is_some_and(|journal| {
authorities.iter().any(|authority| {
journal.deleted_versions.iter().all(|version| {
authority.deleted_versions.contains(version)
&& (!version.is_nil()
|| journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.all(|source| authority.original_versions.contains(source))
|| (authority.predecessors.contains(&journal.transaction)
&& journal.target_digest.is_none()
&& authority.target_absent
&& copies.iter().all(|copy| {
copy.current_digest.is_none() || copy.current_versions == journal.original_versions
})))
})
});
if can_finish {
})
});
let original_quorum = prepared.is_some_and(|journal| {
copies
.iter()
.filter(|copy| copy.current_versions == journal.original_versions)
.count()
> self.set_drive_count / 2
});
let all_decisions_precede = !authorities.is_empty()
&& authorities.iter().all(|authority| {
copies
.iter()
.filter_map(|copy| copy.journal.as_ref())
.any(|journal| journal.predecessors.contains(&authority.transaction))
});
if authority.is_some() || covered || fresh_absence_decision {
let certified_same_transaction = authority.is_some();
let reference = authority.or(prepared).ok_or(DiskError::FileCorrupt)?;
let reference = authority
.or_else(|| copies.iter().find_map(|state| state.journal.clone()))
.ok_or(DiskError::FileCorrupt)?;
if dry_run {
if copies.iter().any(|copy| {
if certified_same_transaction
@@ -1171,7 +1152,7 @@ impl SetDisks {
{
copy.journal
.as_ref()
.is_none_or(|local| !local.matches_prepared_authority(reference))
.is_none_or(|local| !local.matches_prepared_authority(&reference))
} else if copy.state == DeleteRecoveryState::Absent {
copy.current_digest.is_some() && !reference.matches_adoption_source(&copy.current_versions)
} else {
@@ -1184,14 +1165,6 @@ impl SetDisks {
}
continue;
}
let needs_adoption = |copy: &DeleteRecoveryInspection| {
copy.state == DeleteRecoveryState::Absent
|| (certified_same_transaction
&& copy.state == DeleteRecoveryState::NewPrepared
&& copy.current_digest.is_none()
&& !copy.commit_data_safe)
};
let adoption_source = copies.iter().any(needs_adoption).then(|| reference.clone());
mutated = true;
let mut pending = settle_group(
&disks,
@@ -1201,12 +1174,20 @@ impl SetDisks {
if receipt(copy.state) && copy.commit_data_safe {
return None;
}
Some(match adoption_source.as_ref().filter(|_| needs_adoption(copy)) {
Some(authority) => DeleteRecoveryAction::AdoptCommit {
authority: Box::new(authority.clone()),
Some(
if copy.state == DeleteRecoveryState::Absent
|| (certified_same_transaction
&& copy.state == DeleteRecoveryState::NewPrepared
&& copy.current_digest.is_none()
&& !copy.commit_data_safe)
{
DeleteRecoveryAction::AdoptCommit {
authority: Box::new(reference.clone()),
}
} else {
DeleteRecoveryAction::PublishCommit
},
None => DeleteRecoveryAction::PublishCommit,
})
)
},
can_commit,
RecoveryWorkScope {
@@ -1221,7 +1202,10 @@ impl SetDisks {
&disks,
bucket,
copies,
|copy| (!finished(copy)).then_some(DeleteRecoveryAction::FinishCommit),
|copy| {
(copy.state != DeleteRecoveryState::CommitFinished || !copy.commit_data_safe)
.then_some(DeleteRecoveryAction::FinishCommit)
},
can_commit,
RecoveryWorkScope {
namespace_owner: namespace_owner.as_ref(),
@@ -1240,21 +1224,7 @@ impl SetDisks {
} else {
// A sibling decision or foreign generation can supersede this
// snapshot. Never guess by restoring the whole old backup.
let conflicts_with_decision = !authorities.is_empty()
&& !prepared.is_some_and(|journal| {
copies
.iter()
.filter(|copy| copy.current_versions == journal.original_versions)
.count()
> self.set_drive_count / 2
})
&& !authorities.iter().all(|authority| {
copies
.iter()
.filter_map(|copy| copy.journal.as_ref())
.any(|journal| journal.predecessors.contains(&authority.transaction))
});
if conflicts_with_decision
if (!authorities.is_empty() && !original_quorum && !all_decisions_precede)
|| copies
.iter()
.any(|state| state.state != DeleteRecoveryState::Absent && !state.rollback_data_complete)
@@ -3768,128 +3738,6 @@ mod tests {
}
}
#[test]
fn delete_recovery_decision_indexes_only_null_generation_evidence() {
let mut current = DeleteRecoveryVersionIdentity {
version_id: None,
mod_time: None,
data_dir: Some(Uuid::from_u128(1)),
deleted: false,
metadata_digest: [0; 32],
};
let null_without_id = current.clone();
current.version_id = Some(Uuid::nil());
current.data_dir = Some(Uuid::from_u128(2));
let mut original_versions: Vec<_> = (1..=8_192)
.map(|id| DeleteRecoveryVersionIdentity {
version_id: Some(Uuid::from_u128(id)),
..current.clone()
})
.collect();
original_versions.extend([null_without_id.clone(), current.clone()]);
let mut journal = DeleteRecoveryJournal {
protocol_version: DELETE_RECOVERY_PROTOCOL_VERSION,
volume: "bucket".to_owned(),
object: "object".to_owned(),
transaction: Uuid::from_u128(20_000),
bucket_incarnation: None,
original_digest: None,
target_digest: None,
data_dirs: Vec::new(),
deleted_versions: vec![Uuid::from_u128(1)],
requests: Vec::new(),
original_versions,
predecessors: Vec::new(),
};
let versioned = DecisionEvidence::from(&journal);
assert!(versioned.original_null_versions.is_empty());
assert!(versioned.deleted_versions.contains(&Uuid::from_u128(1)));
journal.deleted_versions.push(Uuid::nil());
let mixed = DecisionEvidence::from(&journal);
assert_eq!(mixed.original_null_versions, HashSet::from([null_without_id, current.clone()]));
current.metadata_digest = [1; 32];
assert!(
!mixed.original_null_versions.contains(&current),
"reusing the null version ID cannot authorize a different generation"
);
}
#[tokio::test]
async fn delete_recovery_finished_receipts_do_not_rescan_blocked_siblings() {
let bucket = "recover-finished-before-legacy";
let (dirs, store, disks) = fixture(bucket).await;
let first = put(&store, bucket, &[11; 4096], true).await.expect("first version");
let second = put(&store, bucket, &[12; 4096], true).await.expect("second version");
let survivor = put(&store, bucket, &[13; 4096], true).await.expect("surviving version");
for (id, version) in [(10, first), (20, second)] {
let transaction = applied_at(&store, &disks, bucket, Some(version), disks.len(), Uuid::from_u128(id)).await;
for disk in &disks {
publish(disk, bucket, transaction).await;
let state = disk
.inspect_delete_transaction(bucket, "object", transaction)
.await
.expect("certified transaction");
let finished = disk
.settle_delete_transaction(
bucket,
"object",
transaction,
state.fingerprint,
DeleteRecoveryAction::FinishCommit,
)
.await
.expect("finish certified transaction before coordinator retry");
assert_eq!(finished.state, DeleteRecoveryState::CommitFinished);
}
}
let legacy = Uuid::from_u128(30);
for dir in &dirs {
let data = dir.path().join(bucket).join("object").join(Uuid::from_u128(40).to_string());
tokio::fs::create_dir(&data).await.expect("legacy data directory");
tokio::fs::write(data.join(format!("reserve-delete-data.{legacy}")), [])
.await
.expect("legacy reservation without a decision");
}
// Admit enough work for complete discovery and exactly one inspection
// per transaction and drive. No-op settlement must fit this budget.
let mut entries = 0;
for disk in &disks {
let page = disk
.discover_delete_transactions_bounded(bucket, "object", 4096)
.await
.expect("inspect bounded discovery cost");
assert!(page.complete);
assert_eq!(page.transactions.len(), 3);
entries += page.visited;
for id in page.transactions {
let cost = disk
.inspect_delete_transaction_bounded(bucket, "object", id.transaction, 4096)
.await
.expect("inspect bounded evidence cost");
entries += cost.visited;
}
}
let incarnation = store.bucket_incarnation_id_from_disk(bucket).await.expect("bucket identity");
let mut context = DeleteRecoveryContext::new(Some(incarnation), &|| true);
context.work_budget = Some(Arc::new(crate::object_api::DeleteRecoveryWorkBudget::new(entries)));
let report = store.pools[0].disk_set[0]
.recover_delete_object(bucket, "object", context)
.await
.expect("finished receipts must not invalidate sibling inspections");
assert_eq!(report.committed, 2);
assert_eq!(report.legacy_ambiguous, 1);
for disk in &disks {
let page = disk
.discover_delete_transactions(bucket, Some("object"), None, 128)
.await
.expect("unresolved key still retains its evidence");
assert_eq!(page.transactions.len(), 3, "the key-wide GC barrier keeps certified receipts");
}
assert_eq!(body(&store, bucket, Some(survivor)).await, vec![13; 4096]);
}
#[tokio::test]
async fn delete_recovery_partial_receipt_converges_after_later_version_absence() {
let bucket = "recover-partial-chained-versions";
+17 -343
View File
@@ -4103,27 +4103,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
checksum_type = rustfs_rio::ChecksumType::from_string_with_obj_type(cs, ct);
if let Some(want) = opts.want_checksum.as_ref()
&& (want.checksum_type.base() != checksum_type.base()
|| (want.checksum_type.is(rustfs_rio::ChecksumType::FULL_OBJECT) && !checksum_type.full_object_requested()))
&& !want.checksum_type.is(checksum_type)
{
debug!(
target: "rustfs_ecstore::set_disk",
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "checksum_type_mismatch",
op = "complete_multipart_upload",
bucket = %bucket,
object = %object,
upload_id = %upload_id,
want = %want.checksum_type,
got = %checksum_type,
"Set disk multipart completion checksum algorithm mismatch"
);
return Err(Error::other(rustfs_rio::ChecksumMismatch {
want: want.checksum_type.to_string(),
got: checksum_type.to_string(),
}));
return Err(Error::other(format!("checksum type mismatch, got {:?}, want {:?}", want, checksum_type)));
}
}
@@ -4346,52 +4328,25 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
if let Some(wtcs) = opts.want_checksum.as_ref() {
if checksum_type.full_object_requested() {
// A wire `-N` suffix (including `-0`) sets MULTIPART without INCLUDES_MULTIPART;
// stored multipart records carry both flags and are not suffixed claims.
let has_part_suffix = wtcs.want_parts != 0
|| (wtcs.checksum_type.is(rustfs_rio::ChecksumType::MULTIPART)
&& !wtcs.checksum_type.is(rustfs_rio::ChecksumType::INCLUDES_MULTIPART));
if (!wtcs.encoded.is_empty() && wtcs.encoded != checksum.encoded) || has_part_suffix {
let want = if has_part_suffix {
format!("{}-{}", wtcs.encoded, wtcs.want_parts)
} else {
wtcs.encoded.clone()
};
debug!(
target: "rustfs_ecstore::set_disk",
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "checksum_mismatch",
op = "complete_multipart_upload",
bucket = %bucket,
object = %object,
upload_id = %upload_id,
want = %want,
got = %checksum.encoded,
"Set disk multipart full-object checksum mismatch"
if wtcs.encoded != checksum.encoded {
error!(
"complete_multipart_upload checksum mismatch want={}, got={}",
wtcs.encoded, checksum.encoded
);
return Err(Error::other(rustfs_rio::ChecksumMismatch {
want,
got: checksum.encoded,
}));
return Err(Error::other(format!(
"complete_multipart_upload checksum mismatch want={}, got={}",
wtcs.encoded, checksum.encoded
)));
}
} else if let Err(err) = wtcs.matches(&checksum_combined, uploaded_parts.len() as i32) {
debug!(
target: "rustfs_ecstore::set_disk",
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "checksum_mismatch",
op = "complete_multipart_upload",
bucket = %bucket,
object = %object,
upload_id = %upload_id,
want = %err.want,
got = %err.got,
"Set disk multipart composite checksum mismatch"
error!(
"complete_multipart_upload checksum matches failed want={}, got={}, err={}",
wtcs.encoded, checksum.encoded, err
);
return Err(Error::other(err));
return Err(Error::other(format!(
"complete_multipart_upload checksum matches failed want={}, got={}",
wtcs.encoded, checksum.encoded
)));
}
}
@@ -18015,285 +17970,4 @@ mod tests {
"legacy records must keep returning their stored checksum value"
);
}
fn unwrap_checksum_mismatch(err: Error) -> rustfs_rio::ChecksumMismatch {
match err {
Error::Io(io_err) => io_err
.get_ref()
.and_then(|source| source.downcast_ref::<rustfs_rio::ChecksumMismatch>())
.cloned()
.unwrap_or_else(|| panic!("expected ChecksumMismatch, got Io({io_err:?})")),
other => panic!("expected ChecksumMismatch Io error, got {other:?}"),
}
}
async fn stage_checksummed_multipart_upload(
set_disks: &Arc<SetDisks>,
bucket: &str,
object: &str,
create_checksum_type: Option<rustfs_rio::ChecksumType>,
parts: &[&[u8]],
) -> (String, Vec<CompletePart>, Vec<rustfs_rio::Checksum>) {
let create_opts = ObjectOptions {
want_checksum: create_checksum_type.map(|checksum_type| rustfs_rio::Checksum {
checksum_type,
..Default::default()
}),
..Default::default()
};
let upload = set_disks
.new_multipart_upload(bucket, object, &create_opts)
.await
.expect("multipart upload should be created");
let mut complete_parts = Vec::with_capacity(parts.len());
let mut part_checksums = Vec::with_capacity(parts.len());
for (index, bytes) in parts.iter().enumerate() {
let len = i64::try_from(bytes.len()).expect("test payload length fits i64");
let mut hash_reader = HashReader::from_stream(Cursor::new(bytes.to_vec()), len, len, None, None, false)
.expect("hash reader should be constructed");
let part_checksum = create_checksum_type.map(|ty| {
let checksum = rustfs_rio::Checksum::new_from_data(ty.base(), bytes).expect("part checksum");
hash_reader
.add_non_trailing_checksum(Some(checksum.clone()), false)
.expect("attach part checksum");
checksum
});
let mut reader = PutObjReader::new(hash_reader);
let part = set_disks
.put_object_part(bucket, object, &upload.upload_id, index + 1, &mut reader, &create_opts)
.await
.expect("uploading part should succeed");
let mut complete_part = CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
};
if let (Some(ty), Some(cs)) = (create_checksum_type, part_checksum) {
match ty.base() {
rustfs_rio::ChecksumType::SHA256 => complete_part.checksum_sha256 = Some(cs.encoded.clone()),
rustfs_rio::ChecksumType::CRC32 => complete_part.checksum_crc32 = Some(cs.encoded.clone()),
other => panic!("unsupported test checksum type {other:?}"),
}
part_checksums.push(cs);
}
complete_parts.push(complete_part);
}
(upload.upload_id, complete_parts, part_checksums)
}
#[tokio::test]
async fn complete_multipart_upload_returns_checksum_mismatch_for_invalid_composite_and_preserves_upload_issue_9272() {
let (_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "complete-checksum-composite-9272";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let part1 = vec![0x61_u8; 5 * 1024 * 1024];
let part2 = b"part-two-payload";
let (upload_id, parts, part_checksums) =
stage_checksummed_multipart_upload(&set, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &[&part1, part2])
.await;
let whole_payload: Vec<u8> = part1.iter().chain(part2.iter()).copied().collect();
let whole_sha256 =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::SHA256, &whole_payload).expect("whole object sha256");
let mut combined = Vec::new();
for cs in &part_checksums {
combined.extend_from_slice(&cs.raw);
}
let composite_base =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::SHA256, &combined).expect("composite sha256");
let wrong_part_count =
rustfs_rio::Checksum::new_with_type(rustfs_rio::ChecksumType::SHA256, &format!("{}-3", composite_base.encoded))
.expect("wrong part count checksum");
let wrong_algorithm =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, b"part").expect("crc32 checksum");
for (label, bad_checksum) in [
("whole-object sha256", whole_sha256),
("wrong composite part count", wrong_part_count),
("mismatched algorithm", wrong_algorithm),
] {
let err = set
.clone()
.complete_multipart_upload(
bucket,
object,
&upload_id,
parts.clone(),
&ObjectOptions {
want_checksum: Some(bad_checksum),
..Default::default()
},
)
.await
.expect_err(label);
let _mismatch = unwrap_checksum_mismatch(err);
let info_err = set
.get_object_info(bucket, object, &ObjectOptions::default())
.await
.expect_err("failed completion must not publish object");
assert!(is_err_object_not_found(&info_err), "{label}: got {info_err:?}");
assert!(
set.get_multipart_info(bucket, object, &upload_id, &ObjectOptions::default())
.await
.is_ok(),
"{label}: upload must remain active after rejected completion"
);
}
let matching_composite =
rustfs_rio::Checksum::new_with_type(rustfs_rio::ChecksumType::SHA256, &format!("{}-2", composite_base.encoded))
.expect("matching composite checksum");
let completed = set
.clone()
.complete_multipart_upload(
bucket,
object,
&upload_id,
parts,
&ObjectOptions {
want_checksum: Some(matching_composite),
..Default::default()
},
)
.await
.expect("matching composite checksum should complete");
assert_eq!(completed.size, i64::try_from(whole_payload.len()).expect("test payload length fits i64"));
}
#[tokio::test]
async fn complete_multipart_upload_returns_checksum_mismatch_for_full_object_and_unconfigured_uploads_issue_9272() {
let (_dirs, disks, set) = hermetic_set_disks(4).await;
let bucket = "complete-checksum-full-object-9272";
make_bucket_on_all(&disks, bucket).await;
let full_object_type = rustfs_rio::ChecksumType::from_string_with_obj_type("CRC32", "FULL_OBJECT");
let payload = b"full-object-part-payload";
let (full_upload_id, full_parts, _) =
stage_checksummed_multipart_upload(&set, bucket, "full-obj", Some(full_object_type), &[payload]).await;
let right_crc32 = rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, payload).expect("right crc32");
let wrong_crc32 =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, b"different-payload").expect("wrong crc32");
let suffixed_crc32 = |parts| {
rustfs_rio::Checksum::new_with_type(full_object_type, &format!("{}-{parts}", right_crc32.encoded))
.expect("suffixed crc32")
};
for (label, bad_checksum) in [
("wrong value", wrong_crc32),
("composite suffix on FULL_OBJECT", suffixed_crc32(1)),
("zero-part suffix on FULL_OBJECT", suffixed_crc32(0)),
] {
let err = set
.clone()
.complete_multipart_upload(
bucket,
"full-obj",
&full_upload_id,
full_parts.clone(),
&ObjectOptions {
want_checksum: Some(bad_checksum),
..Default::default()
},
)
.await
.expect_err(label);
let _mismatch = unwrap_checksum_mismatch(err);
}
// Omitting the optional x-amz-checksum-type header passes a bare CRC32 checksum_type.
let bare_right_crc32 =
rustfs_rio::Checksum::new_with_type(rustfs_rio::ChecksumType::CRC32, &right_crc32.encoded).expect("bare crc32");
let completed_full = set
.clone()
.complete_multipart_upload(
bucket,
"full-obj",
&full_upload_id,
full_parts,
&ObjectOptions {
want_checksum: Some(bare_right_crc32),
..Default::default()
},
)
.await
.expect("matching full-object CRC32 without optional checksum-type flag should succeed");
assert_eq!(completed_full.size, i64::try_from(payload.len()).expect("test payload length fits i64"));
// A stored multipart record carries MULTIPART | INCLUDES_MULTIPART with no wire suffix;
// a matching value in that shape must still complete a FULL_OBJECT upload.
let (internal_upload_id, internal_parts, _) =
stage_checksummed_multipart_upload(&set, bucket, "full-obj-internal", Some(full_object_type), &[payload]).await;
let mut internal_type = full_object_type;
internal_type
.merge(rustfs_rio::ChecksumType::MULTIPART)
.merge(rustfs_rio::ChecksumType::INCLUDES_MULTIPART);
let stored_record_crc32 = rustfs_rio::Checksum {
checksum_type: internal_type,
encoded: right_crc32.encoded.clone(),
raw: right_crc32.raw.clone(),
want_parts: 0,
};
let completed_internal = set
.clone()
.complete_multipart_upload(
bucket,
"full-obj-internal",
&internal_upload_id,
internal_parts,
&ObjectOptions {
want_checksum: Some(stored_record_crc32),
..Default::default()
},
)
.await
.expect("matching stored-record FULL_OBJECT checksum should complete");
assert_eq!(
completed_internal.size,
i64::try_from(payload.len()).expect("test payload length fits i64")
);
let (plain_upload_id, plain_parts, _) =
stage_checksummed_multipart_upload(&set, bucket, "plain-obj", None, &[payload]).await;
let payload_sha256 =
rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::SHA256, payload).expect("payload sha256");
let unconfigured_err = set
.clone()
.complete_multipart_upload(
bucket,
"plain-obj",
&plain_upload_id,
plain_parts.clone(),
&ObjectOptions {
want_checksum: Some(payload_sha256),
..Default::default()
},
)
.await
.expect_err("unconfigured upload with mismatched digest must fail with ChecksumMismatch");
let _mismatch = unwrap_checksum_mismatch(unconfigured_err);
// Legacy stack compatibility (pinned by embedded_gateway_stack_test): an unconfigured
// upload compares want_checksum against the empty combined part-digest buffer.
let empty_crc32 = rustfs_rio::Checksum::new_from_data(rustfs_rio::ChecksumType::CRC32, b"").expect("empty crc32");
let completed_plain = set
.clone()
.complete_multipart_upload(
bucket,
"plain-obj",
&plain_upload_id,
plain_parts,
&ObjectOptions {
want_checksum: Some(empty_crc32),
..Default::default()
},
)
.await
.expect("unconfigured upload with empty-buffer CRC32 should preserve legacy compatibility");
assert_eq!(completed_plain.size, i64::try_from(payload.len()).expect("test payload length fits i64"));
}
}
+2 -233
View File
@@ -7194,224 +7194,6 @@ mod legacy_duplex_producer_reader_tests {
}
}
#[cfg(feature = "rio-v2")]
struct ObjectKeyResolver {
object_key: [u8; 32],
}
#[cfg(feature = "rio-v2")]
#[async_trait::async_trait]
impl ObjectEncryptionResolver for ObjectKeyResolver {
async fn resolve_read_material(
&self,
_request: crate::object_api::ReadEncryptionRequest<'_>,
) -> std::result::Result<Option<ReadEncryptionMaterial>, EncryptionResolutionError> {
Ok(Some(ReadEncryptionMaterial {
key_bytes: self.object_key,
mode: ReadEncryptionMode::Object,
}))
}
}
#[cfg(feature = "rio-v2")]
const RIO_V2_FIXTURE_OBJECT_KEY: [u8; 32] = [0x67; 32];
#[cfg(feature = "rio-v2")]
fn rio_v2_fixture_plaintext(len: usize, seed: usize) -> Vec<u8> {
(0..len)
.map(|index| u8::try_from((index + seed) % 251).expect("a remainder below 251 fits in u8"))
.collect()
}
/// Reads a rio-v2 encrypted object the way the legacy GET path does: a
/// producer task feeds the stored bytes into a pipe sized by
/// `adaptive_duplex_buffer_size`, so the decrypt reader sees `Pending`
/// wherever a DARE package outruns the pipe. `parts` lists each part's
/// `(plaintext, stored)` length as the object metadata records it, and
/// `stored` is what the drives actually hold, which a test may cut short.
#[cfg(feature = "rio-v2")]
async fn read_rio_v2_object_through_get_pipe(
stored: Vec<u8>,
parts: &[(usize, usize)],
range: Option<HTTPRangeSpec>,
) -> std::io::Result<Vec<u8>> {
let plaintext_size: usize = parts.iter().map(|(plaintext_len, _)| plaintext_len).sum();
let multipart = parts.len() > 1;
let object_info = ObjectInfo {
bucket: "bucket".to_string(),
name: "rio-v2-encrypted-object".to_string(),
size: i64::try_from(parts.iter().map(|(_, stored_len)| stored_len).sum::<usize>())
.expect("stored fixture length should fit in i64"),
etag: multipart.then(|| format!("{}-{}", "0".repeat(32), parts.len())),
parts: Arc::new(if multipart {
parts
.iter()
.enumerate()
.map(|(index, (plaintext_len, stored_len))| rustfs_filemeta::ObjectPartInfo {
number: index + 1,
size: *stored_len,
actual_size: i64::try_from(*plaintext_len).expect("part plaintext length should fit in i64"),
..Default::default()
})
.collect()
} else {
Vec::new()
}),
user_defined: Arc::new(HashMap::from([
("x-amz-server-side-encryption-customer-algorithm".to_string(), "AES256".to_string()),
(
"x-amz-server-side-encryption-customer-original-size".to_string(),
plaintext_size.to_string(),
),
])),
..Default::default()
};
let ctx = InstanceContext::new();
assert!(
ctx.set_object_encryption_resolver(Arc::new(ObjectKeyResolver {
object_key: RIO_V2_FIXTURE_OBJECT_KEY
}))
.is_ok(),
"fresh context should accept resolver"
);
let (mut writer, reader) = tokio::io::duplex(adaptive_duplex_buffer_size(object_info.size));
let (terminal_tx, terminal_rx) = tokio::sync::oneshot::channel();
let (mut reader, storage_offset, storage_length) = get_legacy_object_reader_with_context(
&ctx,
reader,
terminal_rx,
range,
&object_info,
&ObjectOptions::default(),
&HeaderMap::new(),
)
.await
.expect("encrypted read plan should build");
let storage_length = usize::try_from(storage_length).expect("storage length should not be negative");
let producer = tokio::spawn(async move {
let window_end = stored.len().min(storage_offset + storage_length);
let window_start = storage_offset.min(window_end);
let written = writer.write_all(&stored[window_start..window_end]).await;
drop(writer);
// The reader may already have failed and dropped the receiver.
let _ = terminal_tx.send(Ok(()));
written
});
let mut out = Vec::new();
let read = reader.read_to_end(&mut out).await;
drop(reader);
// A failed read drops the pipe early, so the producer's own result only
// matters once the read itself succeeded.
let written = producer.await.expect("producer task should not panic");
read?;
written?;
Ok(out)
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_get_survives_pipe_refills_mid_package() {
const MIB: usize = 1024 * 1024;
// Stored sizes up to 128 KiB get a 64 KiB pipe, smaller than one DARE
// package; 3 MiB objects get a 1 MiB pipe that packages straddle.
let mut failures = Vec::new();
for plaintext_len in [65_535, 65_536, 65_537, 71_680, 3 * MIB, 3 * MIB + 1] {
let plaintext = rio_v2_fixture_plaintext(plaintext_len, 0);
let mut stored = Vec::new();
crate::io_support::rio::EncryptReader::new_with_object_key(
std::io::Cursor::new(plaintext.clone()),
RIO_V2_FIXTURE_OBJECT_KEY,
)
.read_to_end(&mut stored)
.await
.expect("encrypt singlepart fixture");
let stored_len = stored.len();
match read_rio_v2_object_through_get_pipe(stored, &[(plaintext_len, stored_len)], None).await {
Ok(out) if out == plaintext => {}
Ok(_) => failures.push(format!("{plaintext_len}-byte object: plaintext mismatch")),
Err(err) => failures.push(format!("{plaintext_len}-byte object: {err}")),
}
}
assert!(failures.is_empty(), "rio-v2 encrypted GET failed for: {failures:#?}");
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_multipart_get_survives_pipe_refills_mid_package() {
const MIB: usize = 1024 * 1024;
let part_plaintexts = [rio_v2_fixture_plaintext(5 * MIB, 1), rio_v2_fixture_plaintext(MIB + 17, 2)];
let (stored, parts) = rio_v2_multipart_fixture(&part_plaintexts).await;
let out = read_rio_v2_object_through_get_pipe(stored, &parts, None)
.await
.expect("read multipart object through the GET pipe");
assert!(out == part_plaintexts.concat(), "multipart plaintext mismatch");
}
/// Encrypts each part with its own part key and returns the concatenated
/// stored stream with every part's `(plaintext, stored)` length.
#[cfg(feature = "rio-v2")]
async fn rio_v2_multipart_fixture(part_plaintexts: &[Vec<u8>]) -> (Vec<u8>, Vec<(usize, usize)>) {
let mut stored = Vec::new();
let mut parts = Vec::new();
for (part_number, part_plaintext) in (1u32..).zip(part_plaintexts) {
let stored_before = stored.len();
crate::io_support::rio::EncryptReader::new_multipart_with_object_key(
std::io::Cursor::new(part_plaintext.clone()),
RIO_V2_FIXTURE_OBJECT_KEY,
part_number,
)
.read_to_end(&mut stored)
.await
.expect("encrypt multipart fixture part");
parts.push((part_plaintext.len(), stored.len() - stored_before));
}
(stored, parts)
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_multipart_range_get_rejects_a_missing_trailing_part() {
let part_plaintexts = [rio_v2_fixture_plaintext(70_000, 1), rio_v2_fixture_plaintext(140_000, 2)];
let (mut stored, parts) = rio_v2_multipart_fixture(&part_plaintexts).await;
// The drives hold part 1 only, although the metadata still lists part 2.
stored.truncate(parts[0].1);
// The range starts in part 1 and ends inside the missing part 2.
let range = HTTPRangeSpec {
is_suffix_length: false,
start: 69_900,
end: 70_099,
};
let outcome = read_rio_v2_object_through_get_pipe(stored, &parts, Some(range)).await;
match outcome {
Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof, "{err}"),
Ok(out) => panic!("a 200-byte range over a missing part read {} bytes as a clean EOF", out.len()),
}
}
#[cfg(feature = "rio-v2")]
#[tokio::test]
async fn rio_v2_encrypted_multipart_get_accepts_an_empty_trailing_part() {
let part_plaintexts = [rio_v2_fixture_plaintext(70_000, 1), Vec::new()];
let (stored, parts) = rio_v2_multipart_fixture(&part_plaintexts).await;
assert_eq!(parts[1], (0, 0), "an empty part stores no DARE package");
let out = read_rio_v2_object_through_get_pipe(stored, &parts, None)
.await
.expect("an empty trailing part is not a truncated stream");
assert!(out == part_plaintexts[0], "plaintext mismatch for an object with an empty trailing part");
}
#[tokio::test]
async fn legacy_duplex_reader_fails_closed_when_terminal_channel_closes() {
let (mut writer, reader) = tokio::io::duplex(64);
@@ -9538,12 +9320,7 @@ impl SetDisks {
)
.await?;
if let Some((_, deleted_object)) = replication_delete {
ReplicationLifecycleBridge::schedule_delete(
bucket.to_string(),
deleted_object,
opts.expected_bucket_incarnation_id,
)
.await;
ReplicationLifecycleBridge::schedule_delete(bucket.to_string(), deleted_object).await;
}
deleted += 1;
}
@@ -11821,12 +11598,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
)
.await?;
if let Some((_, deleted_object)) = replication_delete {
ReplicationLifecycleBridge::schedule_delete(
bucket.to_string(),
deleted_object,
opts.expected_bucket_incarnation_id,
)
.await;
ReplicationLifecycleBridge::schedule_delete(bucket.to_string(), deleted_object).await;
}
}
} else {
@@ -12995,7 +12767,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let obj_info = ObjectInfo::from_file_info(&fi, bucket, object, opts.versioned || opts.version_suspended);
send_event(EventArgs {
event_name: event_name.to_string(),
bucket_incarnation_id: opts.notification_bucket_incarnation_id,
bucket_name: bucket.to_string(),
object: obj_info,
user_agent: "Internal: [ILM-Transition]".to_string(),
@@ -13142,7 +12913,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let restored_info = self_.finalize_restore_metadata(bucket, object, &restored_info, &opts).await?;
send_event(EventArgs {
event_name: EventName::ObjectRestoreCompleted.as_str().to_string(),
bucket_incarnation_id: opts.expected_bucket_incarnation_id,
bucket_name: bucket.to_string(),
object: restored_info,
user_agent: "Internal: [Restore-Completed]".to_string(),
@@ -13279,7 +13049,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
let restored_info = self_.finalize_restore_metadata(bucket, object, &restored_info, opts).await?;
send_event(EventArgs {
event_name: EventName::ObjectRestoreCompleted.as_str().to_string(),
bucket_incarnation_id: opts.expected_bucket_incarnation_id,
bucket_name: bucket.to_string(),
object: restored_info,
user_agent: "Internal: [Restore-Completed]".to_string(),
+1 -134
View File
@@ -1407,11 +1407,7 @@ impl SetDisks {
object: &str,
opts: &ObjectOptions,
) -> (ObjectInfo, FileInfo, usize, Option<StorageError>) {
// Unversioned/latest-version deletes discard `parts_metadata` and
// `op_online_disks`, and `latest_early_stop_decision` requires write
// quorum agreement with zero conflicts, NotFound, or hard errors.
let allow_early_stop = opts.version_id.as_deref().is_none_or(str::is_empty);
let snapshot = match self.get_object_fileinfo(bucket, object, opts, false, allow_early_stop).await {
let snapshot = match self.get_object_fileinfo(bucket, object, opts, false, false).await {
Ok(snapshot) => snapshot,
Err(e) => return (ObjectInfo::default(), FileInfo::default(), 0, Some(e)),
};
@@ -6640,135 +6636,6 @@ mod metadata_cache_tests {
"freshly inserted entry should be retrievable"
);
}
#[tokio::test]
#[serial(metadata_cache_publish_barrier, body_cache_hook)]
async fn get_object_info_fileinfo_and_quorum_early_stops_at_write_quorum_and_preserves_explicit_version_fanout() {
use crate::object_api::WriteCompletion;
use crate::set_disk::core::io_primitives::disk_call_counters;
use crate::storage_api_contracts::bucket::{BucketOperations, MakeBucketOptions};
temp_env::async_with_vars(
[
("RUSTFS_GET_METADATA_EARLY_STOP_ENABLE", Some("true")),
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
("RUSTFS_GET_METADATA_VERSION_EARLY_STOP_ENABLE", Some("true")),
],
async {
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
ctx.update_erasure_type(crate::layout::endpoints::SetupType::Erasure).await;
let (dirs, set) = crate::ecstore_validation_blackbox::make_local_set_disks_with_ctx(8, 4, ctx).await;
let bucket = "delete-preflight-early-stop";
let object = "delete-preflight.bin";
set.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let committed = set
.put_object(
bucket,
object,
&mut PutObjReader::from_vec(vec![0x42; 4096]),
&ObjectOptions {
write_completion: WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("commit 8 shards");
set.invalidate_get_object_metadata_cache(bucket, object).await;
for version_id in [None, Some(String::new())] {
let calls = disk_call_counters::observe(object);
let opts = ObjectOptions {
version_id,
..Default::default()
};
let (oi, fi, write_quorum, err) = set.get_object_info_fileinfo_and_quorum(bucket, object, &opts).await;
assert!(err.is_none(), "healthy preflight read must succeed: {err:?}");
assert_eq!(write_quorum, 5);
assert_eq!(oi.etag, committed.etag);
assert_eq!(fi.size, 4096);
assert_eq!(
calls.total(disk_call_counters::KIND_READ_VERSION),
5,
"healthy unversioned/latest delete preflight must early-stop at write quorum (5/8)"
);
assert!(
set.cached_get_object_fileinfo(bucket, object).await.is_none(),
"delete preflight read_data=false early-stop must not populate metadata cache"
);
}
// Remove xl.meta on 3 drives so any 5-drive initial subset sees FileNotFound and expands fanout,
// while the remaining 5 drives still satisfy write quorum.
for dir in &dirs[..3] {
std::fs::remove_file(dir.path().join(bucket).join(object).join("xl.meta")).expect("remove drive xl.meta");
}
let calls = disk_call_counters::observe(object);
let (oi_degraded, fi_degraded, quorum_degraded, err_degraded) = set
.get_object_info_fileinfo_and_quorum(bucket, object, &ObjectOptions::default())
.await;
assert!(err_degraded.is_none(), "5/8 surviving drives must still succeed: {err_degraded:?}");
assert_eq!(quorum_degraded, 5);
assert_eq!(oi_degraded.etag, committed.etag);
assert_eq!(fi_degraded.size, 4096);
assert!(
calls.total(disk_call_counters::KIND_READ_VERSION) > 5,
"missing shard in initial subset must expand fanout beyond write quorum"
);
// Explicit versionId on a 6+2 set with RUSTFS_GET_METADATA_VERSION_EARLY_STOP_ENABLE=true
// must keep full 8-drive fanout rather than stopping at 4/8.
let ctx62 = Arc::new(crate::runtime::instance::InstanceContext::new());
ctx62.update_erasure_type(crate::layout::endpoints::SetupType::Erasure).await;
let (_dirs62, set62) = crate::ecstore_validation_blackbox::make_local_set_disks_with_ctx(8, 2, ctx62).await;
let v_bucket = "delete-preflight-62";
let v_object = "delete-preflight-versioned.bin";
set62
.make_bucket(
v_bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
)
.await
.expect("create versioned 6+2 bucket");
let v_vid = Uuid::new_v4().to_string();
let v_committed = set62
.put_object(
v_bucket,
v_object,
&mut PutObjReader::from_vec(vec![0x24; 4096]),
&ObjectOptions {
versioned: true,
version_id: Some(v_vid.clone()),
write_completion: WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("commit versioned 6+2 object");
set62.invalidate_get_object_metadata_cache(v_bucket, v_object).await;
let v_calls = disk_call_counters::observe(v_object);
let v_opts = ObjectOptions {
versioned: true,
version_id: Some(v_vid),
..Default::default()
};
let (v_oi, _v_fi, v_quorum, v_err) = set62.get_object_info_fileinfo_and_quorum(v_bucket, v_object, &v_opts).await;
assert!(v_err.is_none(), "explicit-version preflight on 6+2 must succeed: {v_err:?}");
assert_eq!(v_quorum, 6);
assert_eq!(v_oi.etag, v_committed.etag);
assert_eq!(
v_calls.total(disk_call_counters::KIND_READ_VERSION),
8,
"explicit-version delete preflight must keep full fanout even when version early-stop is enabled"
);
},
)
.await;
}
}
#[cfg(test)]
+11 -149
View File
@@ -1935,46 +1935,6 @@ impl ECStore {
opts: &DeleteBucketOptions,
diagnostic_budget: BucketDeleteDiagnosticBudget,
) -> Result<()> {
self.delete_bucket_capturing_notification(bucket, opts, diagnostic_budget, false)
.await
.map(|_| ())
}
/// Deletes a bucket and captures its final notification metadata under the
/// lifecycle, metadata-transaction and namespace fences. No cached rules are used.
/// Missing or unreadable metadata yields no notification authority.
///
/// # Errors
/// Returns the same deletion failures as `delete_bucket`; capture is returned
/// only after deletion succeeds, with the same cancellation/partial-delete contract.
pub fn delete_bucket_with_notification<'a>(
&'a self,
bucket: &'a str,
force: bool,
) -> futures::future::BoxFuture<'a, Result<Option<Arc<crate::bucket::metadata::BucketMetadata>>>> {
// Preserve the boxed native-operation boundary instead of propagating the
// deletion state machine through request and gateway futures.
Box::pin(async move {
self.delete_bucket_capturing_notification(
bucket,
&DeleteBucketOptions {
force,
..Default::default()
},
BucketDeleteDiagnosticBudget::new(),
true,
)
.await
})
}
async fn delete_bucket_capturing_notification(
&self,
bucket: &str,
opts: &DeleteBucketOptions,
diagnostic_budget: BucketDeleteDiagnosticBudget,
capture_notification: bool,
) -> Result<Option<Arc<crate::bucket::metadata::BucketMetadata>>> {
if is_meta_bucketname(bucket) {
return Err(StorageError::BucketNameInvalid(bucket.to_string()));
}
@@ -1999,7 +1959,7 @@ impl ECStore {
publication_guard.as_ref(),
bucket,
"table-bucket publication fence during bucket deletion",
self.handle_delete_bucket_under_publication_lock(bucket, opts, diagnostic_budget, capture_notification),
self.handle_delete_bucket_under_publication_lock(bucket, opts, diagnostic_budget),
)
.await
}
@@ -2009,8 +1969,7 @@ impl ECStore {
bucket: &str,
opts: &DeleteBucketOptions,
mut diagnostic_budget: BucketDeleteDiagnosticBudget,
capture_notification: bool,
) -> Result<Option<Arc<crate::bucket::metadata::BucketMetadata>>> {
) -> Result<()> {
let bucket_lifecycle_guard = if !opts.no_lock {
Some(self.acquire_bucket_lifecycle_write_lock(bucket).await?)
} else {
@@ -2020,7 +1979,7 @@ impl ECStore {
// bucket namespace. Holding the transaction while waiting for the
// namespace prevents a migration writer and force delete from
// acquiring these two locks in opposite orders.
let metadata_transaction = if (opts.force || capture_notification) && !is_meta_bucketname(bucket) {
let object_lock_metadata_transaction = if opts.force && !is_meta_bucketname(bucket) {
Some(
await_bucket_namespace_operation(
bucket_lifecycle_guard.as_ref(),
@@ -2091,19 +2050,16 @@ impl ECStore {
// Keep configuration changes fenced until data deletion finishes;
// a force delete cannot bypass any Object Lock protection.
let object_lock_incarnation = if bucket_exists
&& opts.force
&& let Some(guard) = metadata_transaction.as_ref()
{
let object_lock_metadata_guard = if bucket_exists && let Some(guard) = object_lock_metadata_transaction {
let (state, incarnation, _) =
crate::bucket::metadata_sys::get_object_lock_config_and_incarnation_from_disk_with_guard_in(
&self.ctx,
bucket,
Some(ns_guard.as_deref().unwrap_or(guard)),
Some(ns_guard.as_deref().unwrap_or(&guard)),
)
.await?;
match state {
crate::bucket::metadata_sys::ObjectLockConfigState::ConfirmedAbsent => Some(incarnation),
crate::bucket::metadata_sys::ObjectLockConfigState::ConfirmedAbsent => Some((guard, incarnation)),
crate::bucket::metadata_sys::ObjectLockConfigState::Configured { .. } => {
return Err(StorageError::PrefixAccessDenied(bucket.to_owned(), String::new()));
}
@@ -2129,7 +2085,7 @@ impl ECStore {
bucket,
"bucket delete marker creation",
await_bucket_namespace_operation(
metadata_transaction.as_ref(),
object_lock_metadata_guard.as_ref().map(|(guard, _)| guard),
bucket,
"Object Lock configuration fence during bucket retirement",
self.mark_bucket_deleted(bucket),
@@ -2142,7 +2098,7 @@ impl ECStore {
// Legacy buckets without a stamp cannot produce retirement authority.
let retirement = if bucket_exists && bucket_lifecycle_guard.is_some() && !is_meta_bucketname(bucket) {
if let Some(store) = metadata_sys::object_store_if_initialized_in(&self.ctx).await {
if let Some(incarnation) = object_lock_incarnation.as_ref() {
if let Some((_, incarnation)) = object_lock_metadata_guard.as_ref() {
Some((store, *incarnation))
} else {
crate::bucket::metadata::load_bucket_incarnation(store.clone(), bucket)
@@ -2156,26 +2112,12 @@ impl ECStore {
None
};
let notification = if capture_notification && bucket_exists {
if let Some(store) = metadata_sys::object_store_if_initialized_in(&self.ctx).await {
crate::bucket::metadata::load_bucket_metadata_parse_with_presence(store, bucket, true)
.await
.ok()
.filter(|(metadata, persisted)| *persisted && !metadata.bucket_incarnation_id.is_nil())
.map(|(metadata, _)| Arc::new(metadata))
} else {
None
}
} else {
None
};
let delete_result = await_bucket_namespace_operation(
bucket_lifecycle_guard.as_ref(),
bucket,
"physical bucket deletion",
await_bucket_namespace_operation(
metadata_transaction.as_ref(),
object_lock_metadata_guard.as_ref().map(|(guard, _)| guard),
bucket,
"Object Lock configuration fence during bucket deletion",
run_physical_bucket_deletion(ns_guard.as_deref(), bucket, async {
@@ -2186,7 +2128,7 @@ impl ECStore {
),
)
.await;
drop(metadata_transaction);
drop(object_lock_metadata_guard);
if let Err(err) = delete_result
&& (!sr_delete || !is_err_strict_volume_not_found(&err))
{
@@ -2245,7 +2187,7 @@ impl ECStore {
// A scanner may have sampled the first fence before the physical
// namespace disappeared. The completion fence invalidates that scan.
crate::store::list_objects::observe_scanner_namespace_mutations(bucket, 1);
Ok(notification)
Ok(())
}
}
@@ -2516,86 +2458,6 @@ mod tests {
);
}
#[tokio::test]
async fn deleted_notification_snapshot_ignores_a_previous_incarnation_cache() {
let (_dirs, store) = metadata_sys::test_support::isolated_store_over_temp_disks().await;
metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "deleted-notification-stale-cache";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original");
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG,
b"<NotificationConfiguration><QueueConfiguration><Id>old</Id><Queue>arn:rustfs:sqs:us-east-1:old:webhook</Queue><Event>s3:BucketRemoved:*</Event></QueueConfiguration></NotificationConfiguration>".to_vec()).await.expect("commit the original removal subscription");
let sys = metadata_sys::bucket_metadata_sys_of(&store.ctx).expect("metadata owner");
let stale = sys.read().await.get(bucket).await.expect("original metadata");
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create replacement");
let replacement = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("replacement identity");
let xml = b"<NotificationConfiguration/>".to_vec();
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG, xml.clone())
.await
.expect("commit replacement configuration");
sys.read().await.set(bucket.to_string(), stale.clone()).await;
let removed = store
.delete_bucket_with_notification(bucket, false)
.await
.expect("delete replacement")
.expect("authoritative snapshot");
assert_ne!(replacement, stale.bucket_incarnation_id);
assert_eq!(removed.bucket_incarnation_id, replacement);
assert_eq!(removed.notification_config_xml, xml);
}
#[tokio::test]
async fn deleted_notification_snapshot_observes_the_last_fenced_configuration() {
let (_dirs, store) = metadata_sys::test_support::isolated_store_over_temp_disks().await;
metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "deleted-notification-last-commit";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG,
b"<NotificationConfiguration><QueueConfiguration><Id>old</Id><Queue>arn:rustfs:sqs:us-east-1:old:webhook</Queue><Event>s3:BucketRemoved:*</Event></QueueConfiguration></NotificationConfiguration>".to_vec()).await.expect("commit the original removal subscription");
let lock = store
.new_ns_lock(bucket, rustfs_common::table_catalog::TABLE_BUCKET_PUBLICATION_LOCK_PATH)
.await
.expect("publication lock");
let guard = lock
.get_read_lock(get_lock_acquire_timeout())
.await
.expect("hold configuration publication");
let other = store.clone();
let mut deletion = tokio::spawn(async move { other.delete_bucket_with_notification(bucket, false).await });
assert!(
tokio::time::timeout(std::time::Duration::from_millis(100), &mut deletion)
.await
.is_err(),
"deletion must wait for the publication fence"
);
let xml = b"<NotificationConfiguration/>".to_vec();
metadata_sys::update_in(&store.ctx, bucket, crate::bucket::metadata::BUCKET_NOTIFICATION_CONFIG, xml.clone())
.await
.expect("withdraw subscription before deletion acquires its fence");
drop(guard);
let removed = deletion
.await
.expect("join delete")
.expect("delete bucket")
.expect("metadata snapshot");
assert_eq!(removed.notification_config_xml, xml);
}
async fn setup_bucket_delete_test_env() -> (Vec<PathBuf>, Arc<ECStore>) {
BUCKET_DELETE_TEST_ENV
.get_or_init(|| async {
@@ -19,7 +19,6 @@
use super::ECStore;
use crate::bucket::utils::is_meta_bucketname;
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
use crate::error::StorageError;
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
use rustfs_heal_contracts::heal_channel::HealOpts;
use std::collections::{HashMap, HashSet, VecDeque};
@@ -42,8 +41,6 @@ const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status";
const KEYS_PER_PASS: usize = 16;
const RECOVERY_CONCURRENCY: usize = 4;
const INTERVAL: Duration = Duration::from_secs(1);
const INITIAL_RETRY_DELAY: Duration = Duration::from_secs(5);
const MAX_RETRY_DELAY: Duration = Duration::from_secs(5 * 60);
const INVENTORY_INTERVAL: Duration = Duration::from_secs(30);
const DISCOVERY_BUDGET: Duration = Duration::from_secs(5);
const ANTI_ENTROPY_INTERVAL: Duration = Duration::from_secs(60 * 60);
@@ -63,7 +60,6 @@ pub(crate) struct DeleteRecoveryTicket {
key: Arc<DeleteRecoveryKey>,
generation: Uuid,
admission: Option<Arc<AdmissionGuard>>,
retry: Option<RetrySchedule>,
}
#[derive(Debug)]
@@ -86,40 +82,10 @@ impl Drop for AdmissionGuard {
}
}
#[derive(Clone, Copy, Debug)]
struct RetrySchedule {
ready_at: Instant,
delay: Duration,
}
impl RetrySchedule {
fn after_failure(previous: Option<Self>, now: Instant) -> Self {
let delay = previous.map_or(INITIAL_RETRY_DELAY, |retry| (retry.delay * 2).clamp(INITIAL_RETRY_DELAY, MAX_RETRY_DELAY));
Self {
ready_at: now + delay,
delay,
}
}
}
#[derive(Debug)]
struct PendingHint {
generation: Uuid,
queue_generation: Uuid,
kind: PendingHintKind,
}
#[derive(Clone, Copy, Debug)]
enum PendingHintKind {
Foreground,
Discovered,
Retry(RetrySchedule),
}
#[derive(Debug)]
struct HintState {
pending: HashMap<Arc<DeleteRecoveryKey>, PendingHint>,
order: VecDeque<(Arc<DeleteRecoveryKey>, Uuid)>,
pending: HashMap<Arc<DeleteRecoveryKey>, (Uuid, Uuid, bool)>,
order: VecDeque<DeleteRecoveryTicket>,
rescan: Option<Uuid>,
started: HashSet<Uuid>,
#[cfg(test)]
@@ -127,18 +93,6 @@ struct HintState {
}
impl HintState {
fn enqueue(&mut self, key: Arc<DeleteRecoveryKey>, generation: Uuid, kind: PendingHintKind) {
self.pending.insert(
key.clone(),
PendingHint {
generation,
queue_generation: generation,
kind,
},
);
self.order.push_back((key, generation));
}
fn compact_order(&mut self, capacity: usize) {
// Twice the pending capacity guarantees at least capacity completed
// entries between compactions, even with a full retry backlog. This
@@ -152,7 +106,7 @@ impl HintState {
self.compaction_visits += self.order.len();
}
let Self { pending, order, .. } = self;
order.retain(|(key, generation)| pending.get(key).is_some_and(|entry| entry.queue_generation == *generation));
order.retain(|ticket| pending.get(&ticket.key).is_some_and(|entry| entry.1 == ticket.generation));
}
}
@@ -188,28 +142,32 @@ impl DeleteRecoveryHints {
let key = Arc::new(key);
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let generation = Uuid::new_v4();
if let Some(entry) = state.pending.get_mut(&key) {
entry.generation = generation;
entry.kind = PendingHintKind::Foreground;
if let Some((current, _, _)) = state.pending.get_mut(&key) {
*current = generation;
} else {
if state.pending.len() >= self.capacity {
// Durable evidence remains the authority. Rotate the oldest
// hint so permanently blocked keys cannot exclude later raw
// discoveries forever; the next scan revisits evicted keys.
while let Some((oldest, generation)) = state.order.pop_front() {
while let Some(oldest) = state.order.pop_front() {
if state
.pending
.get(&oldest)
.is_some_and(|entry| entry.queue_generation == generation)
.get(&oldest.key)
.is_some_and(|entry| entry.1 == oldest.generation)
{
state.pending.remove(&oldest);
state.pending.remove(&oldest.key);
break;
}
}
state.rescan = Some(Uuid::new_v4());
}
state.compact_order(self.capacity);
state.enqueue(key.clone(), generation, PendingHintKind::Foreground);
state.pending.insert(key.clone(), (generation, generation, false));
state.order.push_back(DeleteRecoveryTicket {
key: key.clone(),
generation,
admission: None,
});
}
Some(DeleteRecoveryTicket {
admission: Some(Arc::new(AdmissionGuard {
@@ -219,7 +177,6 @@ impl DeleteRecoveryHints {
})),
key,
generation,
retry: None,
})
}
@@ -231,21 +188,28 @@ impl DeleteRecoveryHints {
if state.pending.len() >= self.capacity {
// Only previously attempted work may yield its slot. Unattempted
// keys apply backpressure so a fast scan cannot overwrite them.
let retried = state.order.iter().position(|(queued, generation)| {
let retried = state.order.iter().position(|ticket| {
state
.pending
.get(queued)
.is_some_and(|entry| entry.queue_generation == *generation && matches!(entry.kind, PendingHintKind::Retry(_)))
.get(&ticket.key)
.is_some_and(|entry| entry.1 == ticket.generation && entry.2)
});
let Some(index) = retried else { return false };
if let Some((oldest, _)) = state.order.remove(index) {
state.pending.remove(&oldest);
if let Some(oldest) = state.order.remove(index) {
state.pending.remove(&oldest.key);
}
// This durable key has already been attempted. The hourly sweep
// revisits it; immediate rescans would loop on permanent failures.
}
state.compact_order(self.capacity);
state.enqueue(Arc::new(key), Uuid::new_v4(), PendingHintKind::Discovered);
let key = Arc::new(key);
let generation = Uuid::new_v4();
state.pending.insert(key.clone(), (generation, generation, false));
state.order.push_back(DeleteRecoveryTicket {
key,
generation,
admission: None,
});
true
}
@@ -257,36 +221,33 @@ impl DeleteRecoveryHints {
if state
.pending
.get(&ticket.key)
.is_some_and(|entry| entry.generation == ticket.generation)
.is_some_and(|entry| entry.0 == ticket.generation)
{
state.pending.remove(&ticket.key);
}
}
fn take_available(&self, active: &HashSet<Arc<DeleteRecoveryKey>>, now: Instant) -> Option<DeleteRecoveryTicket> {
fn take_available(&self, active: &HashSet<Arc<DeleteRecoveryKey>>) -> Option<DeleteRecoveryTicket> {
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let queued = state.order.len();
for _ in 0..queued {
let (key, slot) = state.order.pop_front()?;
let Some(entry) = state.pending.get(&key).filter(|entry| entry.queue_generation == slot) else {
continue;
};
let retry = match entry.kind {
PendingHintKind::Retry(retry) => Some(retry),
PendingHintKind::Discovered | PendingHintKind::Foreground => None,
};
if retry.is_some_and(|retry| retry.ready_at > now) || active.contains(&key) {
state.order.push_back((key, slot));
continue;
let ticket = state.order.pop_front()?;
if let Some(&(generation, slot, _)) = state.pending.get(&ticket.key)
&& slot == ticket.generation
{
if active.contains(&ticket.key) {
// Preserve a newer hint while this key still owns a slot.
// Other keys can proceed without waiting on its lock.
state.order.push_back(ticket);
continue;
}
state.pending.remove(&ticket.key);
return Some(DeleteRecoveryTicket {
key: ticket.key,
generation,
admission: None,
});
}
let ticket = DeleteRecoveryTicket {
generation: entry.generation,
admission: None,
retry,
key,
};
state.pending.remove(&ticket.key);
return Some(ticket);
}
None
}
@@ -294,38 +255,24 @@ impl DeleteRecoveryHints {
#[cfg(test)]
fn take(&self, limit: usize) -> Vec<DeleteRecoveryTicket> {
let active = HashSet::new();
std::iter::from_fn(|| self.take_available(&active, Instant::now()))
.take(limit)
.collect()
std::iter::from_fn(|| self.take_available(&active)).take(limit).collect()
}
fn retry(&self, ticket: DeleteRecoveryTicket, retry: RetrySchedule) {
fn retry(&self, ticket: DeleteRecoveryTicket) {
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(entry) = state.pending.get_mut(&ticket.key) {
// Discovery can see the same journal while replay is in flight.
// Keep its queue slot, but only new foreground work resets backoff.
if matches!(entry.kind, PendingHintKind::Discovered) {
entry.kind = PendingHintKind::Retry(retry);
}
return;
}
if state.pending.len() >= self.capacity {
// Attempted work yields to new admissions and the periodic durable sweep.
if state.pending.contains_key(&ticket.key) {
return;
}
state.compact_order(self.capacity);
state.enqueue(ticket.key, ticket.generation, PendingHintKind::Retry(retry));
}
#[cfg(test)]
fn retry_now(&self, ticket: DeleteRecoveryTicket) {
self.retry(
ticket,
RetrySchedule {
ready_at: Instant::now(),
delay: Duration::ZERO,
},
);
if state.pending.len() >= self.capacity {
// Previously attempted work yields to admitted keys until the
// periodic sweep. Foreground admission retains its own rescan guard.
return;
}
state
.pending
.insert(ticket.key.clone(), (ticket.generation, ticket.generation, true));
state.order.push_back(ticket);
}
#[cfg(test)]
@@ -695,12 +642,7 @@ impl<'a> RecoveryWork<'a> {
&& Instant::now() < self.deadline
&& !self.cancel.is_cancelled()
{
let Some(ticket) = self
.store
.ctx
.delete_recovery_hints()
.take_available(&self.active, Instant::now())
else {
let Some(ticket) = self.store.ctx.delete_recovery_hints().take_available(&self.active) else {
break;
};
self.active.insert(ticket.key.clone());
@@ -746,32 +688,15 @@ async fn recover_hint(
) => Some(result),
};
let mut failures = RecoveryFailures::default();
let now = Instant::now();
let retry = match outcome {
Some(Ok(_)) => None,
Some(Err(StorageError::ErasureReadQuorum)) => {
failures.pending = 1;
// Check returning participants on the normal maintenance cadence.
Some(RetrySchedule {
ready_at: now + INTERVAL,
delay: INTERVAL,
})
if !matches!(outcome, Some(Ok(_))) {
match outcome {
Some(Err(crate::error::StorageError::ErasureReadQuorum)) => failures.pending = 1,
Some(Err(crate::error::StorageError::SlowDown)) => failures.blocked = 1,
Some(Err(crate::error::StorageError::FileCorrupt)) => failures.corrupt = 1,
Some(Err(_)) => failures.failed = 1,
_ => {}
}
Some(Err(error)) => {
match error {
StorageError::SlowDown => failures.blocked = 1,
StorageError::FileCorrupt => failures.corrupt = 1,
_ => failures.failed = 1,
}
Some(RetrySchedule::after_failure(ticket.retry, now))
}
None => Some(ticket.retry.unwrap_or(RetrySchedule {
ready_at: now,
delay: Duration::ZERO,
})),
};
if let Some(retry) = retry {
store.ctx.delete_recovery_hints().retry(ticket, retry);
store.ctx.delete_recovery_hints().retry(ticket);
}
(key, failures)
}
@@ -901,7 +826,7 @@ mod tests {
assert_eq!(taken[0].generation, newer.generation);
let latest = hints.register(key("a")).expect("hint during recovery");
hints.ack(&taken[0]);
hints.retry_now(taken.into_iter().next().expect("selected ticket"));
hints.retry(taken.into_iter().next().expect("selected ticket"));
let pending = hints.take(2);
assert_eq!(pending[0].key.object, "b");
assert_eq!(pending[1].generation, latest.generation, "old recovery cannot replace a newer hint");
@@ -940,7 +865,7 @@ mod tests {
assert!(hints.state.lock().expect("hint state").order.len() <= 2);
let mut tickets = hints.take(2);
assert_eq!(tickets.len(), 2);
hints.retry_now(tickets.remove(0));
hints.retry(tickets.remove(0));
assert_eq!(hints.take(2).len(), 1, "failed work survives an empty queue");
}
@@ -952,48 +877,18 @@ mod tests {
let active = HashSet::from([admitted.key.clone()]);
let newer = hints.register(key("active")).expect("new foreground generation");
hints.register(key("later")).expect("independent key");
let later = hints.take_available(&active, Instant::now()).expect("skip the active key");
let later = hints.take_available(&active).expect("skip the active key");
assert_eq!(later.key.object, "later");
assert!(
hints.take_available(&active, Instant::now()).is_none(),
"a newer generation cannot occupy a second slot"
);
assert!(hints.take_available(&active).is_none(), "a newer generation cannot occupy a second slot");
hints.ack(&original);
hints.retry_now(admitted);
hints.retry(admitted);
assert!(hints.is_pending(&key("active")), "old success or cancellation cannot clear newer work");
let next = hints
.take_available(&HashSet::new(), Instant::now())
.take_available(&HashSet::new())
.expect("active key becomes eligible after completion");
assert_eq!(next.generation, newer.generation, "retry cannot overwrite the foreground generation");
}
#[test]
fn delete_recovery_backoff_survives_rediscovery_and_resets_for_foreground_work() {
let hints = DeleteRecoveryHints::with_capacity(2);
let active = HashSet::new();
let key = key("blocked");
let mut now = Instant::now();
assert!(hints.register_discovered(key.clone()));
let mut ticket = hints.take_available(&active, now).expect("discovery is immediately eligible");
for seconds in [5, 10, 20, 40, 80, 160, 300, 300] {
assert!(hints.register_discovered(key.clone()), "discovery arrives during replay");
let retry = RetrySchedule::after_failure(ticket.retry, now);
hints.retry(ticket, retry);
assert!(hints.register_discovered(key.clone()), "discovery also sees the queued retry");
now += Duration::from_secs(seconds);
assert!(hints.take_available(&active, now - Duration::from_nanos(1)).is_none());
ticket = hints.take_available(&active, now).expect("admit at the retry deadline");
}
let retry = RetrySchedule::after_failure(ticket.retry, now);
hints.retry(ticket, retry);
let foreground = hints.register(key).expect("foreground request during backoff");
let ticket = hints
.take_available(&active, now)
.expect("admit new foreground work promptly");
assert_eq!(ticket.generation, foreground.generation);
assert!(ticket.retry.is_none());
}
#[test]
fn delete_recovery_hint_compaction_stays_amortized_near_capacity() {
let capacity = HINT_CAPACITY;
@@ -1030,7 +925,7 @@ mod tests {
hints.register(key("blocked-a")).expect("first blocked key");
hints.register(key("blocked-b")).expect("second blocked key");
for ticket in hints.take(2) {
hints.retry_now(ticket);
hints.retry(ticket);
}
hints
.register(key("healthy-later"))
@@ -1223,8 +1118,7 @@ mod tests {
publish_one(&disks[0], bucket, transaction).await;
let set = &store.pools[0].disk_set[0];
let offline = set.disks.write().await[3].take();
let cancel = CancellationToken::new();
assert_eq!(recover_hints(&store, &cancel).await.pending, 1, "the participant is required");
pass.run(&store, &CancellationToken::new()).await;
assert_eq!(
store
.ctx
@@ -1237,10 +1131,7 @@ mod tests {
1
);
set.disks.write().await[3] = offline;
tokio::time::pause();
tokio::time::advance(INTERVAL).await;
tokio::time::resume();
pass.run(&store, &cancel).await;
pass.run(&store, &CancellationToken::new()).await;
assert!(
store.ctx.delete_recovery_hints().take(1).is_empty(),
"returning participant releases retained work"
@@ -1293,7 +1184,7 @@ mod tests {
assert!(hints.register_discovered(key(&format!("blocked-{index}"))));
}
for ticket in hints.take(KEYS_PER_PASS) {
hints.retry_now(ticket);
hints.retry(ticket);
}
for index in 0..KEYS_PER_PASS {
assert!(
@@ -1303,7 +1194,7 @@ mod tests {
}
let in_flight = hints.take(1).pop().expect("one admitted recovery attempt");
assert!(hints.register_discovered(key("arrived-during-recovery")));
hints.retry_now(in_flight);
hints.retry(in_flight);
let mut pass = RecoveryPass {
next_inventory: Some(Instant::now() + ANTI_ENTROPY_INTERVAL),
scan_generation: Some(scanning),
@@ -1330,65 +1221,6 @@ mod tests {
assert_eq!(hints.rescan(), Some(foreground), "an older scan cannot clear a foreground obligation");
}
#[tokio::test]
async fn delete_recovery_blocked_legacy_key_backs_off_without_delaying_other_keys() {
let bucket = "runtime-legacy-backoff";
let (dirs, store, disks) = fixture(bucket).await;
let transaction = Uuid::new_v4();
for disk in &disks {
disk.delete_version(
bucket,
"object",
FileInfo {
name: "object".to_owned(),
..Default::default()
},
false,
DeleteOptions {
old_data_dir: Some(transaction),
..Default::default()
},
)
.await
.expect("leave an undecided historical delete");
}
let backups: Vec<_> = dirs
.iter()
.map(|dir| {
dir.path()
.join(bucket)
.join("object")
.join(transaction.to_string())
.join("xl.meta.bkp")
})
.collect();
let before: Vec<_> = backups
.iter()
.map(|path| std::fs::read(path).expect("read original evidence"))
.collect();
register(&store, bucket).await;
let cancel = CancellationToken::new();
assert_eq!(recover_hints(&store, &cancel).await.blocked, 1);
let hints = store.ctx.delete_recovery_hints();
let healthy = DeleteRecoveryKey {
object: "absent-key".to_owned(),
bucket: bucket.to_owned(),
incarnation: Some(store.bucket_incarnation_id_from_disk(bucket).await.expect("bucket identity")),
..key("absent-key")
};
assert!(hints.register_discovered(healthy.clone()));
assert_eq!(
recover_hints(&store, &cancel).await.blocked,
0,
"do not re-inspect a blocked key on the next pass"
);
assert!(!hints.is_pending(&healthy), "the independent key still settles promptly");
assert_eq!(hints.pending_len(), 1, "the blocked key remains eligible for a later retry");
for (path, bytes) in backups.iter().zip(before) {
assert_eq!(std::fs::read(path).expect("retained historical evidence"), bytes);
}
}
#[tokio::test]
async fn delete_recovery_admission_stays_within_each_tick_budget() {
let bucket = "runtime-admission-budget";
@@ -1581,10 +1413,7 @@ mod tests {
.find(|(key, _)| key.object == format!("waiting-{index}"))
.expect("unattempted key remains queued")
.1;
assert!(
matches!(queued.kind, PendingHintKind::Foreground),
"budget exhaustion must not grant discovery permission to evict untouched work"
);
assert!(!queued.2, "budget exhaustion must not grant discovery permission to evict untouched work");
}
}
@@ -1605,7 +1434,7 @@ mod tests {
for ticket in hints.take(KEYS_PER_PASS) {
let index: usize = ticket.key.object.parse().expect("numeric test key");
if index % 1_024 < KEYS_PER_PASS {
hints.retry_now(ticket);
hints.retry(ticket);
} else {
recovered.insert(index);
}
-19
View File
@@ -29,7 +29,6 @@ const LOG_SUBSYSTEM_HEAL: &str = "heal";
const EVENT_HEAL_ABANDONED_PARTS: &str = "heal_abandoned_parts";
const EVENT_HEAL_FORMAT_COMPLETED: &str = "heal_format_completed";
const EVENT_HEAL_OBJECT_STARTED: &str = "heal_object_started";
const EVENT_HEAL_DELETE_RECOVERY_BLOCKED: &str = "heal_delete_recovery_blocked";
/// An explicit bucket-heal admission owns one lifecycle generation through its write tail.
pub(crate) struct BucketHealScope {
@@ -424,24 +423,6 @@ impl ECStore {
}
}
}
if let Some(object) = &object
&& !opts.dry_run
&& summary.blocked > 0
{
tracing::debug!(
event = EVENT_HEAL_DELETE_RECOVERY_BLOCKED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_HEAL,
state = "insufficient_evidence",
bucket = ?bucket,
object = ?decode_dir_object(object),
pool = opts.pool,
set = opts.set,
legacy_ambiguous = summary.legacy_ambiguous,
other_blocked = summary.blocked - summary.legacy_ambiguous,
"Exact-key delete recovery is blocked"
);
}
if object.is_some() && summary.pending > 0 {
return Err(StorageError::ErasureReadQuorum);
}
+48 -359
View File
@@ -47,7 +47,6 @@ use rand::seq::SliceRandom;
use rustfs_filemeta::{
FileMeta, FileMetaShallowVersion, MetaCacheEntries, MetaCacheEntriesSorted, MetaCacheEntry, MetadataResolutionParams,
};
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration;
use rustfs_io_metrics::{
LIST_OBJECTS_GATHER_OUTCOME_INPUT_CLOSED, LIST_OBJECTS_GATHER_OUTCOME_LIMIT_REACHED, LIST_OBJECTS_SOURCE_WALKER,
ListObjectsGatherCaller, ListObjectsGatherObservation,
@@ -79,113 +78,6 @@ type ListObjectVersionsInfo = StorageListObjectVersionsInfo<ObjectInfo>;
type ObjectInfoOrErr = StorageObjectInfoOrErr<ObjectInfo, Error>;
type WalkOptions = StorageWalkOptions<fn(&rustfs_filemeta::FileInfo) -> bool>;
/// Evidence from a single named object during free-version recovery.
#[derive(Debug)]
pub(crate) enum TierRecoveryEntry {
Version(Box<ObjectInfo>),
Unreadable { object: String },
}
enum ListingMergeOutput {
Entries(Sender<MetaCacheEntry>),
TierRecovery {
sender: Sender<Result<TierRecoveryEntry>>,
bucket: String,
versioning: Option<PersistedVersioningConfiguration>,
marker: Option<String>,
},
}
impl From<Sender<MetaCacheEntry>> for ListingMergeOutput {
fn from(sender: Sender<MetaCacheEntry>) -> Self {
Self::Entries(sender)
}
}
impl ListingMergeOutput {
fn accepts_key(&self, key: &str) -> Result<bool> {
if let Self::TierRecovery { marker, .. } = self {
if key.is_empty() {
return Err(Error::FileCorrupt);
}
// The drive may repeat the last key. A recovery cursor covers every
// version (or the unreadable metadata) at that key.
return Ok(marker.as_deref().is_none_or(|marker| key > marker));
}
Ok(true)
}
async fn send_group(
&self,
cancel: &CancellationToken,
mut entry: MetaCacheEntry,
others: std::vec::Drain<'_, MetaCacheEntry>,
last_emitted: &mut String,
) -> Result<bool> {
if !self.accepts_key(&entry.name)? {
return Ok(true);
}
let merge = if others.as_slice().is_empty() {
Ok(())
} else {
merge_object_entry_versions(
&mut entry,
others,
match self {
Self::Entries(_) => log_listing_merge_corruption,
// Recovery reports unreadable keys once per page.
Self::TierRecovery { .. } => |_, _, _| {},
},
)
};
let is_new = entry.name != *last_emitted;
if is_new {
last_emitted.clone_from(&entry.name);
}
match (self, merge) {
(Self::TierRecovery { sender, .. }, Err(Error::FileCorrupt)) if is_new => {
send_or_cancel(cancel, sender, Ok(TierRecoveryEntry::Unreadable { object: entry.name })).await
}
(Self::TierRecovery { .. }, Err(Error::FileCorrupt)) => Ok(true),
(_, Err(err)) => Err(err),
(_, Ok(())) if is_new => self.send(cancel, entry).await,
(_, Ok(())) => Ok(true),
}
}
async fn send(&self, cancel: &CancellationToken, entry: MetaCacheEntry) -> Result<bool> {
match self {
Self::Entries(sender) => send_or_cancel(cancel, sender, entry).await,
Self::TierRecovery {
sender,
bucket,
versioning,
..
} => {
if entry.is_dir() {
return Ok(true);
}
// This operation decodes an already enumerated buffer. Even
// parser errors wrapping UnexpectedEof are local to this key.
let versions = match entry.file_info_versions_with_free_versions(bucket) {
Ok(versions) => versions,
Err(_) => {
return send_or_cancel(cancel, sender, Ok(TierRecoveryEntry::Unreadable { object: entry.name })).await;
}
};
let versioned = versioning.as_ref().is_some_and(|v| v.versioned(&entry.name));
for fi in versions.versions.into_iter().chain(versions.free_versions) {
let info = ObjectInfo::from_owned_file_info(fi, bucket, &entry.name, versioned);
if !send_or_cancel(cancel, sender, Ok(TierRecoveryEntry::Version(Box::new(info)))).await? {
return Ok(false);
}
}
Ok(true)
}
}
}
}
fn unversioned_authoritative_page(bucket: &str, page: ListPage) -> Result<ListObjectVersionsInfo> {
let mut objects = Vec::new();
for entry in page.entries.entries() {
@@ -1466,7 +1358,7 @@ impl ECStore {
return Ok(Vec::new());
};
if entries.len() > 0 {
merge_object_entry_versions(&mut entry, entries, log_listing_merge_corruption)?;
merge_object_entry_versions(&mut entry, entries)?;
}
// This projection excludes tier free-version bookkeeping but retains
// pending version purges for the evaluator's replication safeguards.
@@ -1822,63 +1714,12 @@ impl ECStore {
check_list_objs_args(bucket, prefix, &None)?;
let rx = rx.child_token();
let (sender, receiver) = mpsc::channel(100);
// Some strict consumers drain the result only after walk returns.
let _forwarder = spawn_walk_entry_forwarder(rx.clone(), receiver, result, opts.clone(), bucket.to_owned());
self.walk_merged_entries(rx, bucket, prefix, opts, sender.into()).await
}
pub(crate) async fn walk_for_tier_recovery(
self: Arc<Self>,
cancel: CancellationToken,
bucket: &str,
sender: Sender<Result<TierRecoveryEntry>>,
mut opts: WalkOptions,
) -> Result<()> {
check_list_objs_args(bucket, "", &None)?;
let cancel = cancel.child_token();
let _cancel_on_drop = cancel.clone().drop_guard();
let versioning = tokio::select! {
_ = cancel.cancelled() => return Ok(()),
_ = sender.closed() => return Ok(()),
result = get_versioning_config(bucket) => result.ok().map(|(config, _)| config),
};
if opts.marker.is_some() && opts.limit > 0 {
// Drives include forward_to in their limit; the consumer counts
// only distinct keys strictly beyond the recovery marker.
opts.limit = opts.limit.saturating_add(1);
}
let output = ListingMergeOutput::TierRecovery {
sender,
bucket: bucket.to_owned(),
versioning,
marker: opts.marker.clone(),
};
self.walk_merged_entries(cancel, bucket, "", opts, output).await
}
async fn walk_merged_entries(
self: Arc<Self>,
rx: CancellationToken,
bucket: &str,
prefix: &str,
opts: WalkOptions,
output: ListingMergeOutput,
) -> Result<()> {
let mut futures = Vec::new();
let mut inputs = Vec::new();
for eset in self.pools.iter() {
for set in eset.disk_set.iter() {
let online_disks = set.get_online_disks_with_healing_and_info(true);
let (mut disks, infos, _) = match &output {
ListingMergeOutput::Entries(_) => online_disks.await,
ListingMergeOutput::TierRecovery { sender, .. } => tokio::select! {
_ = rx.cancelled() => return Ok(()),
_ = sender.closed() => return Ok(()),
disks = online_disks => disks,
},
};
let (mut disks, infos, _) = set.get_online_disks_with_healing_and_info(true).await;
let opts = opts.clone();
let (sender, list_out_rx) = mpsc::channel::<MetaCacheEntry>(1);
@@ -1991,7 +1832,13 @@ impl ECStore {
}
}
let merge_task = spawn_listing_merge(rx, inputs, output);
let (merge_tx, merge_rx) = mpsc::channel::<MetaCacheEntry>(100);
let bucket = bucket.to_owned();
// Not awaited: callers may drain `result` only after this returns, so
// waiting on the forwarder here could stall them on the channel bound.
let _forwarder = spawn_walk_entry_forwarder(rx.clone(), merge_rx, result, opts, bucket.clone());
let merge_task = spawn_listing_merge(rx, inputs, merge_tx);
let walk_started = std::time::Instant::now();
let walk_results = join_all(futures).await;
@@ -2074,23 +1921,6 @@ impl ECStore {
}
}
/// Stop the producers if recovery drops its receiver, retaining terminal
/// producer errors that may already be in flight.
async fn run_tier_walk_with_consumer(
cancel: &CancellationToken,
consumer: &Sender<Result<TierRecoveryEntry>>,
walk: impl Future<Output = Result<()>>,
) -> Result<()> {
tokio::pin!(walk);
tokio::select! {
result = &mut walk => result,
_ = consumer.closed() => {
cancel.cancel();
walk.await
}
}
}
/// Forwards merged raw entries to a walk consumer as `ObjectInfoOrErr`,
/// applying the walk's version projection, sort order and filter. The first
/// entry that fails to decode ends the stream with that error; a consumer that
@@ -2646,7 +2476,7 @@ async fn send_or_cancel<T: Send>(rx: &CancellationToken, out_channel: &Sender<T>
}
}
fn log_listing_merge_corruption(object: &str, version_id: Option<Uuid>, validation: &'static str) {
fn listing_merge_corruption(object: &str, version_id: Option<Uuid>, validation: &'static str) -> Error {
error!(
event = EVENT_LISTING_MERGE_REJECTED,
component = LOG_COMPONENT_ECSTORE,
@@ -2657,39 +2487,30 @@ fn log_listing_merge_corruption(object: &str, version_id: Option<Uuid>, validati
validation,
"Listing version merge rejected metadata"
);
Error::FileCorrupt
}
/// Each input has already been resolved inside its own erasure set. This is a
/// union of version histories, never a quorum vote between unrelated pools.
fn merge_object_entry_versions(
first: &mut MetaCacheEntry,
others: impl Iterator<Item = MetaCacheEntry>,
report_corruption: fn(&str, Option<Uuid>, &'static str),
) -> Result<()> {
let name = first.name.as_str();
let corrupt = |version_id, validation| {
report_corruption(name, version_id, validation);
Error::FileCorrupt
};
fn merge_object_entry_versions(first: &mut MetaCacheEntry, others: impl Iterator<Item = MetaCacheEntry>) -> Result<()> {
let name = first.name.clone();
let mut versions: HashMap<(Option<Uuid>, bool), (FileMetaShallowVersion, ObjectInfo)> = HashMap::new();
let inputs = std::iter::once((first.cached.take(), std::mem::take(&mut first.metadata)))
.chain(others.map(|entry| (entry.cached, entry.metadata)));
for (cached, metadata) in inputs {
let meta = match cached {
for mut entry in std::iter::once(std::mem::take(first)).chain(others) {
let meta = match entry.cached.take() {
Some(meta) => meta,
None => FileMeta::load(&metadata).map_err(|_| corrupt(None, "metadata_decode"))?,
None => FileMeta::load(&entry.metadata).map_err(|_| listing_merge_corruption(&name, None, "metadata_decode"))?,
};
if meta.versions.is_empty() {
return Err(corrupt(None, "empty_version_stack"));
return Err(listing_merge_corruption(&name, None, "empty_version_stack"));
}
for version in meta.versions {
let corrupt = |validation| corrupt(version.header.version_id, validation);
let corrupt = |validation| listing_merge_corruption(&name, version.header.version_id, validation);
let parsed = version.parse_version_meta().map_err(|_| corrupt("version_decode"))?;
if !parsed.valid() || parsed.version_type != version.header.version_type {
return Err(corrupt("version_type_or_validity"));
}
let fi = parsed
.into_fileinfo("", name, true)
.into_fileinfo("", &name, true)
.map_err(|_| corrupt("file_info_decode"))?;
let version_id = fi.version_id.filter(|id| !id.is_nil());
if version_id != version.header.version_id.filter(|id| !id.is_nil())
@@ -2698,7 +2519,7 @@ fn merge_object_entry_versions(
{
return Err(corrupt("version_header_mismatch"));
}
let info = ObjectInfo::from_file_info(&fi, "", name, true);
let info = ObjectInfo::from_file_info(&fi, "", &name, true);
let identity = (version_id, version.header.free_version());
match versions.entry(identity) {
std::collections::hash_map::Entry::Vacant(slot) => {
@@ -2767,9 +2588,13 @@ fn merge_object_entry_versions(
std::cmp::Ordering::Equal
}
});
first.metadata = merged.marshal_msg()?;
first.cached = Some(merged);
first.reusable = true;
let metadata = merged.marshal_msg()?;
*first = MetaCacheEntry {
name,
metadata,
cached: Some(merged),
reusable: true,
};
Ok(())
}
@@ -2778,25 +2603,11 @@ fn merge_object_entry_versions(
fn spawn_listing_merge(
rx: CancellationToken,
inputs: Vec<Receiver<MetaCacheEntry>>,
sender: impl Into<ListingMergeOutput>,
sender: Sender<MetaCacheEntry>,
) -> AbortOnDropHandle<Result<()>> {
let sender = sender.into();
AbortOnDropHandle::new(tokio::spawn(
async move {
let consumer = match &sender {
ListingMergeOutput::TierRecovery { sender, .. } => Some(sender.clone()),
ListingMergeOutput::Entries(_) => None,
};
let merge = merge_entry_channels(rx.clone(), inputs, sender, 1);
let result = match consumer {
Some(consumer) => {
// End the event stream as soon as merge finishes, even if a
// drive is still winding down. Recovery bounds that join.
let _stop_producers = rx.clone().drop_guard();
run_tier_walk_with_consumer(&rx, &consumer, merge).await
}
None => merge.await,
};
let result = merge_entry_channels(rx.clone(), inputs, sender, 1).await;
if result.is_err() {
rx.cancel();
}
@@ -2809,7 +2620,7 @@ fn spawn_listing_merge(
async fn merge_entry_channels(
rx: CancellationToken,
in_channels: Vec<Receiver<MetaCacheEntry>>,
out_channel: impl Into<ListingMergeOutput>,
out_channel: Sender<MetaCacheEntry>,
read_quorum: usize,
) -> Result<()> {
let completions = (0..in_channels.len()).map(|_| None).collect();
@@ -2822,10 +2633,9 @@ async fn merge_entry_channels_with_cuts(
rx: CancellationToken,
in_channels: Vec<Receiver<MetaCacheEntry>>,
mut completions: Vec<Option<MergeCompletion>>,
out_channel: impl Into<ListingMergeOutput>,
out_channel: Sender<MetaCacheEntry>,
read_quorum: usize,
) -> Result<Option<String>> {
let out_channel = out_channel.into();
if in_channels.is_empty() {
return Ok(None);
}
@@ -2838,7 +2648,8 @@ async fn merge_entry_channels_with_cuts(
tokio::select! {
has_entry = in_channels[0].recv()=>{
if let Some(entry) = has_entry{
if out_channel.accepts_key(&entry.name)? && !out_channel.send(&rx, entry).await? {
// warn!("merge_entry_channels entry {}", &entry.name);
if !send_or_cancel(&rx, &out_channel, entry).await? {
return Ok(None);
}
} else {
@@ -2944,12 +2755,21 @@ async fn merge_entry_channels_with_cuts(
}
}
if let Some(head) = object_winner.or(dir_winner)
&& !out_channel
.send_group(&rx, head.entry, object_entries.drain(..), &mut last_emitted)
.await?
if !object_entries.is_empty()
&& let Some(winner) = object_winner.as_mut()
{
return Ok(None);
merge_object_entry_versions(&mut winner.entry, object_entries.drain(..))?;
}
if let Some(head) = object_winner.or(dir_winner)
&& head.entry.name != last_emitted
{
last_emitted.clear();
last_emitted.push_str(&head.entry.name);
let MergeHead { entry, .. } = *head;
if !send_or_cancel(&rx, &out_channel, entry).await? {
return Ok(None);
}
}
for &idx in &refill {
@@ -3788,137 +3608,6 @@ mod test {
assert!(!parent.is_cancelled());
}
#[tokio::test]
async fn tier_recovery_walk_isolates_named_decode_and_cross_pool_merge_failures() {
use super::{ListingMergeOutput, TierRecoveryEntry};
let logs = CapturedLogs::default();
let subscriber = tracing_subscriber::fmt().with_writer(logs.clone()).finish();
let _guard = tracing::subscriber::set_default(subscriber);
let corrupt = |name: &str| MetaCacheEntry {
name: name.to_owned(),
metadata: vec![0xff],
..Default::default()
};
let time = time::OffsetDateTime::from_unix_timestamp(1_705_312_300).expect("valid version timestamp");
let mut inputs = Vec::new();
for entries in [
vec![
corrupt("a-marker"),
test_object_meta_entry("b-healthy"),
corrupt("c-bad-buffer"),
test_object_meta_entry_with_erasure_versions("d-conflict", &[(time, "first-etag", 2, 2)]),
],
vec![
test_object_meta_entry_with_erasure_versions("d-conflict", &[(time, "different-etag", 2, 2)]),
test_object_meta_entry("e-later"),
],
] {
let (tx, rx) = mpsc::channel(entries.len());
for entry in entries {
tx.try_send(entry).expect("buffer each sorted set stream");
}
inputs.push(rx);
}
let (sender, mut events) = mpsc::channel(8);
let output = ListingMergeOutput::TierRecovery {
sender,
bucket: "bucket".to_owned(),
versioning: None,
marker: Some("a-marker".to_owned()),
};
merge_entry_channels(CancellationToken::new(), inputs, output, 1)
.await
.expect("isolated metadata failures should allow the walk to finish");
assert!(
!logs.contents().contains("Listing version merge rejected metadata"),
"recovery reports its unreadable keys in one page summary"
);
let mut actual = Vec::new();
while let Some(event) = events.recv().await {
actual.push(match event.expect("each event belongs to an enumerated key") {
TierRecoveryEntry::Version(info) => (info.name, false),
TierRecoveryEntry::Unreadable { object } => (object, true),
});
}
assert_eq!(
actual,
[
("b-healthy".to_owned(), false),
("c-bad-buffer".to_owned(), true),
("d-conflict".to_owned(), true),
("e-later".to_owned(), false),
]
);
}
#[tokio::test]
async fn tier_recovery_walk_closes_event_stream_before_joining_drives() {
let (source, input) = mpsc::channel(1);
let (sender, mut events) = mpsc::channel(1);
let output = super::ListingMergeOutput::TierRecovery {
sender,
bucket: "bucket".to_owned(),
versioning: None,
marker: None,
};
let cancel = CancellationToken::new();
let merge = super::spawn_listing_merge(cancel.clone(), vec![input], output);
// A later drive join may still be pending. Recovery must be able to
// observe EOF and apply its shutdown timeout as soon as the merge ends.
drop(source);
timeout(Duration::from_secs(5), async {
assert!(events.recv().await.is_none());
cancel.cancelled().await;
merge.await.expect("merge worker must not panic").expect("clean stream");
})
.await
.expect("end of stream must release producers before their final join");
}
#[tokio::test]
async fn tier_recovery_walk_dropped_receiver_cancels_producers_and_preserves_error() {
let (sender, receiver) = mpsc::channel(1);
let cancel = CancellationToken::new();
let (started_tx, started) = oneshot::channel();
let producer = async {
started_tx.send(()).expect("notify that the producer is running");
cancel.cancelled().await;
Err(StorageError::FaultyDisk)
};
let close_receiver = async {
started.await.expect("wait for the active producer");
drop(receiver);
};
let (result, ()) = timeout(Duration::from_secs(5), async {
tokio::join!(super::run_tier_walk_with_consumer(&cancel, &sender, producer), close_receiver)
})
.await
.expect("receiver loss must cancel the active walk");
assert_eq!(result.expect_err("terminal disk errors must still propagate"), StorageError::FaultyDisk);
}
#[tokio::test]
async fn tier_recovery_walk_propagates_unattributed_failures() {
let (source, input) = mpsc::channel(1);
let (complete, completion) = oneshot::channel();
drop(source);
complete
.send(Err(StorageError::FileCorrupt))
.expect("set should report its terminal error");
let (sender, mut events) = mpsc::channel(1);
let output = super::ListingMergeOutput::TierRecovery {
sender,
bucket: "bucket".to_owned(),
versioning: None,
marker: None,
};
let error = merge_entry_channels_with_cuts(CancellationToken::new(), vec![input], vec![Some(completion)], output, 1)
.await
.expect_err("corruption without a trusted object key must abort recovery");
assert_eq!(error, StorageError::FileCorrupt);
assert!(events.recv().await.is_none());
}
#[tokio::test]
async fn walk_forwarder_abort_before_poll_cancels_producers() {
let (entry_tx, entry_rx) = mpsc::channel(1);
@@ -9060,7 +8749,7 @@ mod test {
.insert("x-amz-meta-private".to_string(), "sensitive-value-must-not-be-logged".to_string());
});
assert_eq!(
super::merge_object_entry_versions(&mut original, std::iter::once(conflicting), super::log_listing_merge_corruption)
super::merge_object_entry_versions(&mut original, std::iter::once(conflicting))
.expect_err("conflicting user metadata must still fail closed"),
StorageError::FileCorrupt
);
+1 -1
View File
@@ -410,7 +410,7 @@ async fn enqueue_transition_after_write(
// transition/expiry already ran for the original commit; the scanner
// still sees the object if that commit never reached this hook.
if !oi.multipart_completion_replayed && should_enqueue_transition_immediately(&oi) {
enqueue_transition_immediate(&oi, src.clone(), opts.expected_bucket_incarnation_id).await;
enqueue_transition_immediate(&oi, src.clone()).await;
// Immediate expiry needs the bucket incarnation under the
// metadata-transaction lock; a lockless cache PUT leaves expiry
// to the scanner.
@@ -1,35 +0,0 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
mod storage_api;
use storage_api::local_drive_retirement::{Disk, DiskAPI, DiskOption, Endpoint, new_disk};
#[tokio::test]
async fn local_wrapper_retirement_is_shared_and_independent_of_monitoring() {
let dir = tempfile::tempdir().expect("retirement fixture directory");
let endpoint = Endpoint::try_from(dir.path().to_str().expect("UTF-8 fixture path")).expect("local endpoint");
let disk = new_disk(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.expect("local disk");
let Disk::Local(wrapper) = disk.as_ref() else { panic!("fixture must use a local disk") };
let cloned = wrapper.clone();
let observer = disk.local_retirement_token().expect("local retirement observer");
let cancelled_observer = disk.local_retirement_token().expect("another observer");
cancelled_observer.cancel();
assert!(!observer.is_cancelled(), "observers cannot retire the wrapper");
wrapper.stop_monitoring().await;
assert!(!observer.is_cancelled(), "monitoring policy is not retirement");
cloned.close().await.expect("close shared wrapper");
assert!(observer.is_cancelled(), "clones share retirement");
assert!(
disk.local_retirement_token().expect("late observer").is_cancelled(),
"late observers see retirement"
);
disk.close().await.expect("retirement is idempotent");
}
-5
View File
@@ -98,8 +98,3 @@ pub(crate) mod pinned_erasure_fixtures {
pub(crate) mod bucket_config_codec {
pub(crate) use rustfs_ecstore::api::bucket::utils::{BucketConfigXml, deserialize, serialize};
}
pub(crate) mod local_drive_retirement {
pub(crate) use super::{DiskAPI, DiskOption, Endpoint, new_disk};
pub(crate) use rustfs_ecstore::api::disk::Disk;
}
+4
View File
@@ -366,6 +366,10 @@ impl FileMeta {
Ok(Self::find_inline_data_slice(inline_data, version_id)?.map(<[u8]>::to_vec))
}
fn find_inline_data_for_version(&self, version_id: Option<Uuid>) -> Result<Option<Vec<u8>>> {
Self::find_inline_data_in_slice(self.data.as_slice(), version_id)
}
// Find version
pub fn find_version(&self, vid: Option<Uuid>) -> Result<(usize, FileMetaVersion)> {
let vid = vid.unwrap_or_default();
+21 -25
View File
@@ -26,28 +26,6 @@ impl FileMeta {
Ok(xl)
}
/// Parses and validates the `xl.meta` envelope (including `InlineData::validate_slice`),
/// returning the decoded version headers/metadata and the borrowed `inline_buf` slice
/// without eagerly copying `inline_buf` into `self.data`.
pub fn load_with_borrowed_inline_data(buf: &[u8]) -> Result<(FileMeta, &[u8])> {
let mut xl = FileMeta::default();
let (meta, inline_buf) = Self::parse_validated_xl_envelope(buf)?;
if !meta.is_empty() {
let (versions_len, header_ver, meta_ver, meta) = Self::decode_validated_xl_headers(meta)?;
xl.meta_ver = meta_ver;
xl.versions = Vec::with_capacity(versions_len);
let mut cur: Cursor<&[u8]> = Cursor::new(meta);
for _ in 0..versions_len {
let (header, ver_meta) = Self::read_next_shallow_slice(meta, &mut cur, header_ver)?;
xl.versions.push(FileMetaShallowVersion {
header,
meta: ver_meta.to_vec(),
});
}
}
Ok((xl, inline_buf))
}
/// Read (major, minor, header_ver, meta_ver) from xl.meta without full parse.
/// Returns Err if format is not feat (e.g. legacy uses rmp_serde in meta block).
pub fn read_format_versions(buf: &[u8]) -> Result<(u16, u16, u8, u8)> {
@@ -278,11 +256,29 @@ impl FileMeta {
#[hotpath::measure(impl_type = "FileMeta")]
pub fn unmarshal_msg(&mut self, buf: &[u8]) -> Result<u64> {
let i = buf.len() as u64;
let (mut loaded, inline_buf) = Self::load_with_borrowed_inline_data(buf)?;
let (meta, inline_buf) = Self::parse_validated_xl_envelope(buf)?;
if !inline_buf.is_empty() {
loaded.data.update(inline_buf);
self.data.update(inline_buf);
}
*self = loaded;
// Parse meta
if !meta.is_empty() {
let (versions_len, header_ver, meta_ver, meta) = Self::decode_validated_xl_headers(meta)?;
self.meta_ver = meta_ver;
self.versions = Vec::with_capacity(versions_len);
let mut cur: Cursor<&[u8]> = Cursor::new(meta);
for _ in 0..versions_len {
let (header, ver_meta) = Self::read_next_shallow_slice(meta, &mut cur, header_ver)?;
self.versions.push(FileMetaShallowVersion {
header,
meta: ver_meta.to_vec(),
});
}
}
Ok(i)
}
+2 -12
View File
@@ -120,19 +120,9 @@ impl FileMeta {
return 0;
};
if !self
.versions
.iter()
.any(|v| v.header.version_type == VersionType::Object && v.header.version_id != Some(vid))
{
return 0;
}
if has_inline_data.unwrap_or_else(|| {
Self::find_inline_data_slice(self.data.as_slice(), version_id)
.ok()
.flatten()
.is_some()
self.data.entries().unwrap_or_default() > 0
&& self.find_inline_data_for_version(version_id).unwrap_or_default().is_some()
}) {
return 0;
}
+22 -13
View File
@@ -14,9 +14,12 @@
use super::{
DiskError, DiskStore, HEALING_MARKER_PATH, RUSTFS_META_BUCKET,
replacement_readiness::{ReplacementTargets, local_replacement_disks, probe_replacement_mounts},
replacement_readiness::{auto_replacement_target_identities, replacement_target_disk},
resume::ReplacementTargetIdentity,
storage_api::{EcstoreConditionalFileUpdate, EcstoreDiskAPI, EcstoreDiskBytes, EcstoreReplacementExecutionLease},
storage_api::{
EcstoreConditionalFileUpdate, EcstoreDiskAPI, EcstoreDiskBytes, EcstoreReplacementExecutionLease,
ecstore_local_disk_map_read,
},
};
use crate::{Error, Result};
use std::{future::Future, sync::Arc};
@@ -32,27 +35,33 @@ pub struct ReplacementExecution {
impl ReplacementExecution {
pub(crate) async fn acquire(targets: &[String]) -> Result<Arc<Self>> {
let targets = ReplacementTargets::open(targets)
.await
.ok_or_else(|| Error::ReplacementTargetNotReady("replacement target is unavailable".to_string()))?;
let identities = targets
.identities()
let identities = auto_replacement_target_identities(targets)
.await
.ok_or_else(|| Error::ReplacementTargetNotReady("target mount admission failed".to_string()))?;
let local_disks = ecstore_local_disk_map_read()
.await
.values()
.flatten()
.filter(|disk| EcstoreDiskAPI::is_local(disk.as_ref()))
.cloned()
.collect::<Vec<_>>();
let mut disks = Vec::with_capacity(identities.len());
let mut leases = Vec::with_capacity(identities.len());
// Take leases in endpoint order. Revalidate those same handles against
// the current inventory so a reopened disk cannot supply their proof.
for disk in &targets.disks {
// Identities are sorted by endpoint, the same order on every opener.
for identity in &identities {
let disk = replacement_target_disk(&identity.endpoint, &local_disks)
.await
.ok_or_else(|| Error::ReplacementTargetNotReady("replacement target is unavailable".to_string()))?;
leases.push(disk.acquire_replacement_execution_lease().await?);
disks.push(disk);
}
let local_disks = local_replacement_disks().await;
if probe_replacement_mounts(&targets.disks, &local_disks).await.as_ref() != Some(&identities) {
if auto_replacement_target_identities(targets).await.as_ref() != Some(&identities) {
return Err(Error::ReplacementTargetNotReady(
"target changed while acquiring execution leases".to_string(),
));
}
Ok(Arc::new(Self {
disks: targets.disks,
disks,
identities,
_leases: leases,
}))
+126 -203
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use std::{fs, path::Path};
use super::{
DiskOption, DiskStore, Endpoint, HealDiskExt as _, local_disk_map_read, new_disk, resume::ReplacementTargetIdentity,
@@ -24,15 +24,12 @@ use super::{
/// Directory-backed deployments already declare, through
/// `RUSTFS_UNSAFE_BYPASS_DISK_CHECK`, that their endpoints are plain
/// directories sharing a device with the host root. Those endpoints can never
/// pass the independent-mount check, so without this fallback a
/// satisfy [`auto_replacement_target_identity`], so without this fallback a
/// runtime-wiped or replaced directory disk would stay deferred forever. The
/// admission check itself is never bypassed; the fallback only routes the heal
/// through the ordinary format path that formats every unformatted disk in the
/// set, which is exactly what the pre-admission `heal_disk` path did.
pub(crate) fn directory_backed_replacement_fallback_enabled() -> bool {
if cfg!(target_os = "linux") && std::env::var_os(rustfs_config::ENV_HEAL_REPLACEMENT_MOUNT_ROOTS).is_some() {
return false;
}
rustfs_utils::get_env_bool_with_aliases(
rustfs_config::ENV_UNSAFE_BYPASS_DISK_CHECK,
&[rustfs_config::ENV_MINIO_CI],
@@ -41,66 +38,53 @@ pub(crate) fn directory_backed_replacement_fallback_enabled() -> bool {
}
pub(crate) async fn auto_replacement_target_ready(disk: &DiskStore, local_disks: &[DiskStore]) -> bool {
probe_replacement_mounts(std::slice::from_ref(disk), local_disks)
.await
.is_some()
auto_replacement_target_identity(disk, local_disks).await.is_some()
}
pub(super) async fn probe_replacement_mounts(
disks: &[DiskStore],
pub(crate) async fn auto_replacement_target_identity(
disk: &DiskStore,
local_disks: &[DiskStore],
) -> Option<Vec<ReplacementTargetIdentity>> {
if disks.is_empty() {
return Some(Vec::new());
}
let disks = disks.to_vec();
let local_disks = local_disks.to_vec();
) -> Option<ReplacementTargetIdentity> {
let lease_root = disk.replacement_mount_lease_root()?;
let endpoint = disk.endpoint().to_string();
let sibling_lease_roots = local_disks
.iter()
.filter(|sibling| sibling.endpoint().is_local && sibling.endpoint().to_string() != endpoint)
.map(|sibling| sibling.replacement_mount_lease_root())
.collect::<Option<Vec<_>>>()?;
tokio::task::spawn_blocking(move || {
let mount_roots = std::env::var_os(rustfs_config::ENV_HEAL_REPLACEMENT_MOUNT_ROOTS)
.as_ref()
.into_iter()
.flat_map(std::env::split_paths)
.collect::<Vec<_>>();
let mut identities = Vec::with_capacity(disks.len());
for disk in &disks {
let mount = disk.replacement_mount(&mount_roots)?;
if mount.physical_device_ids.is_empty() {
return None;
}
identities.push(ReplacementTargetIdentity {
endpoint: disk.endpoint().to_string(),
canonical_path: mount.canonical_path.into_os_string().into_string().ok()?,
physical_device_ids: mount.physical_device_ids,
filesystem_identity: mount.filesystem_identity,
});
}
let mut target_devices = HashSet::new();
for target in &identities {
if target
.physical_device_ids
.iter()
.any(|device| !target_devices.insert(device.as_str()))
{
return None;
}
}
let root_devices = rustfs_utils::os::get_physical_device_ids("/").ok()?;
if root_devices.is_empty() || root_devices.iter().any(|device| target_devices.contains(device.as_str())) {
let canonical_path = fs::canonicalize(&lease_root).ok()?;
let metadata = fs::metadata(&lease_root).ok()?;
let Ok(target_device_ids) = rustfs_utils::os::get_physical_device_ids(lease_root.to_string_lossy().as_ref()) else {
return None;
};
let Ok(root_device_ids) = rustfs_utils::os::get_physical_device_ids("/") else {
return None;
};
if target_device_ids.is_empty()
|| root_device_ids.is_empty()
|| target_device_ids.iter().any(|target| root_device_ids.contains(target))
|| !rustfs_utils::os::is_mount_point(&canonical_path).unwrap_or(false)
{
return None;
}
let targets: HashSet<_> = identities.iter().map(|identity| identity.endpoint.as_str()).collect();
for sibling in &local_disks {
let endpoint = sibling.endpoint();
if endpoint.is_local && !targets.contains(endpoint.to_string().as_str()) {
let root = sibling.replacement_mount_lease_root()?;
let devices = rustfs_utils::os::get_physical_device_ids(root.to_str()?).ok()?;
if devices.iter().any(|device| target_devices.contains(device.as_str())) {
return None;
}
}
if sibling_lease_roots.iter().any(|sibling_lease_root| {
rustfs_utils::os::get_physical_device_ids(sibling_lease_root.to_string_lossy().as_ref())
.map(|ids| ids.iter().any(|id| target_device_ids.contains(id)))
.unwrap_or(true)
}) {
return None;
}
Some(identities)
let filesystem_identity = filesystem_identity(&metadata, &canonical_path)?;
Some(ReplacementTargetIdentity {
endpoint,
canonical_path: canonical_path.to_string_lossy().into_owned(),
physical_device_ids: target_device_ids,
filesystem_identity,
})
})
.await
.ok()
@@ -122,76 +106,72 @@ fn local_replacement_endpoint(target: &str, local_grid_hosts: &[String]) -> Opti
Some(endpoint)
}
pub(super) async fn local_replacement_disks() -> Vec<DiskStore> {
local_disk_map_read()
.await
pub(super) async fn replacement_target_disk(target: &str, local_disks: &[DiskStore]) -> Option<DiskStore> {
if let Some(disk) = local_disks.iter().find(|disk| disk.endpoint().to_string() == target) {
return Some(disk.clone());
}
let local_grid_hosts = local_disks.iter().map(|disk| disk.endpoint().grid_host()).collect::<Vec<_>>();
let endpoint = local_replacement_endpoint(target, &local_grid_hosts)?;
new_disk(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.ok()
}
pub(crate) async fn auto_replacement_target_identities(targets: &[String]) -> Option<Vec<ReplacementTargetIdentity>> {
let local_disk_map = local_disk_map_read().await;
let local_disks = local_disk_map
.values()
.flatten()
.filter(|disk| disk.endpoint().is_local)
.cloned()
.collect()
.collect::<Vec<_>>();
drop(local_disk_map);
let mut identities = Vec::with_capacity(targets.len());
for target in targets {
let disk = replacement_target_disk(target, &local_disks).await?;
identities.push(auto_replacement_target_identity(&disk, &local_disks).await?);
}
identities.sort_by(|left, right| left.endpoint.cmp(&right.endpoint));
identities.dedup_by(|left, right| left.endpoint == right.endpoint);
(identities.len() == targets.len()).then_some(identities)
}
pub(super) struct ReplacementTargets {
pub(super) disks: Vec<DiskStore>,
local_disks: Vec<DiskStore>,
#[cfg(target_os = "linux")]
fn filesystem_identity(metadata: &fs::Metadata, canonical_path: &Path) -> Option<String> {
use std::os::unix::fs::MetadataExt as _;
let escaped_path = canonical_path.to_string_lossy().replace(' ', "\\040");
let mountinfo = fs::read_to_string("/proc/self/mountinfo").ok()?;
let mount_id = mountinfo.lines().find_map(|line| {
let mut fields = line.split_whitespace();
let mount_id = fields.next()?;
fields.next()?;
fields.next()?;
fields.next()?;
(fields.next()? == escaped_path).then_some(mount_id)
})?;
Some(format!("{mount_id}:{}:{}", metadata.dev(), metadata.ino()))
}
impl ReplacementTargets {
pub(super) async fn open(targets: &[String]) -> Option<Self> {
let mut ordered: Vec<_> = targets.iter().map(String::as_str).collect();
ordered.sort_unstable();
if ordered.windows(2).any(|pair| pair[0] == pair[1]) {
return None;
}
#[cfg(all(unix, not(target_os = "linux")))]
fn filesystem_identity(metadata: &fs::Metadata, _canonical_path: &Path) -> Option<String> {
use std::os::unix::fs::MetadataExt as _;
let registry = local_disk_map_read().await;
let requested: Vec<_> = ordered
.into_iter()
.map(|target| {
let disk = registry
.get(target)
.and_then(Option::as_ref)
.filter(|disk| disk.endpoint().is_local)
.cloned();
(target, disk)
})
.collect();
let local_disks = registry
.values()
.flatten()
.filter(|disk| disk.endpoint().is_local)
.cloned()
.collect::<Vec<_>>();
drop(registry);
let mut disks = Vec::with_capacity(requested.len());
let mut hosts = None;
for (target, disk) in requested {
let disk = match disk {
Some(disk) => disk,
None => {
let local_hosts = hosts
.get_or_insert_with(|| local_disks.iter().map(|disk| disk.endpoint().grid_host()).collect::<Vec<_>>());
let endpoint = local_replacement_endpoint(target, local_hosts)?;
new_disk(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.ok()?
}
};
disks.push(disk);
}
Some(Self { disks, local_disks })
}
Some(format!("{}:{}", metadata.dev(), metadata.ino()))
}
pub(super) async fn identities(&self) -> Option<Vec<ReplacementTargetIdentity>> {
probe_replacement_mounts(&self.disks, &self.local_disks).await
}
#[cfg(not(unix))]
fn filesystem_identity(_metadata: &fs::Metadata, _canonical_path: &Path) -> Option<String> {
None
}
#[cfg(test)]
@@ -289,8 +269,8 @@ mod tests {
mod linux_privileged_tests {
use super::*;
use std::error::Error;
use std::path::Path;
use std::process::Command;
use std::{fs, path::Path};
const ENABLE_ENV: &str = "RUSTFS_PRIVILEGED_MOUNT_READINESS_TESTS";
const NAMESPACE_ENV: &str = "RUSTFS_PRIVILEGED_MOUNT_READINESS_TESTS_IN_NAMESPACE";
@@ -416,86 +396,39 @@ mod tests {
#[ignore = "requires Linux root/CAP_SYS_ADMIN and RUSTFS_PRIVILEGED_MOUNT_READINESS_TESTS=1"]
fn auto_replacement_readiness_accepts_an_independent_mount() -> Result<(), Box<dyn Error + Send + Sync>> {
run_privileged_mount_test(|mut mounts| async move {
let temp = TempDir::new()?;
let parent = temp.path().join("parent");
let target = parent.join("replacement disk");
let data = target.join("data");
let temp = TempDir::new().expect("temporary replacement roots should be created");
let target = temp.path().join("target");
let sibling = temp.path().join("sibling");
fs::create_dir(&parent)?;
mounts.mount_tmpfs(&parent, "rustfs-readiness-parent")?;
// Leave a directory at the same path below the target mount.
fs::create_dir_all(&data)?;
std::fs::create_dir(&target).expect("target mountpoint should be created");
std::fs::create_dir(&sibling).expect("sibling mountpoint should be created");
mounts.mount_tmpfs(&target, "rustfs-readiness-target")?;
fs::create_dir(&data)?;
fs::create_dir(&sibling)?;
mounts.mount_tmpfs(&sibling, "rustfs-readiness-sibling")?;
let target_endpoint = Endpoint::try_from(target.to_string_lossy().as_ref())?;
let sibling_endpoint = Endpoint::try_from(sibling.to_string_lossy().as_ref())?;
let options = DiskOption {
cleanup: false,
health_check: false,
};
let target_disk = new_disk(&target_endpoint, &options).await?;
let sibling_disk = new_disk(&sibling_endpoint, &options).await?;
assert!(
auto_replacement_target_ready(&target_disk, &[target_disk.clone(), sibling_disk.clone()]).await,
"a separately mounted replacement target with no sibling device overlap must be admitted"
);
let disks = [target_disk, sibling_disk];
let mut identities = probe_replacement_mounts(&disks, &disks)
.await
.expect("independently mounted replacement targets should be admitted together");
assert_eq!(identities[0].endpoint, disks[0].endpoint().to_string());
assert_eq!(identities[1].endpoint, disks[1].endpoint().to_string());
identities.sort_unstable_by(|left, right| left.endpoint.cmp(&right.endpoint));
let endpoints = [identities[1].endpoint.clone(), identities[0].endpoint.clone()];
let execution = crate::heal::replacement_execution::ReplacementExecution::acquire(&endpoints).await?;
assert_eq!(execution.identities(), identities);
assert!(
crate::heal::replacement_execution::ReplacementExecution::acquire(&endpoints)
.await
.is_err(),
"a second executor must not take leases on the same targets"
);
drop(execution);
let endpoint = Endpoint::try_from(path_to_string(&data, "data directory")?.as_str())?;
let disk = new_disk(&endpoint, &options).await?;
let key = rustfs_config::ENV_HEAL_REPLACEMENT_MOUNT_ROOTS;
temp_env::async_with_vars([(key, None::<&str>)], async {
assert!(!auto_replacement_target_ready(&disk, &[]).await);
})
.await;
let roots = std::env::join_paths([&parent, &target])?;
temp_env::async_with_vars(
[
(key, Some(roots.to_str().ok_or("mount roots are not UTF-8")?)),
(rustfs_config::ENV_UNSAFE_BYPASS_DISK_CHECK, Some("true")),
],
async {
assert!(!directory_backed_replacement_fallback_enabled());
let identities = probe_replacement_mounts(std::slice::from_ref(&disk), &[])
.await
.expect("data directory on its configured independent mount should be admitted");
assert_eq!(Path::new(&identities[0].canonical_path), data.canonicalize()?);
let reopened = new_disk(&endpoint, &options).await?;
assert_eq!(probe_replacement_mounts(&[reopened], &[]).await, Some(identities));
run_command("umount", &["-l", &path_to_string(&target, "replacement mount")?])?;
assert!(!auto_replacement_target_ready(&disk, &[]).await);
let exposed_disk = new_disk(&endpoint, &options).await?;
assert!(
!auto_replacement_target_ready(&exposed_disk, &[]).await,
"a new handle on the exposed parent filesystem must also be rejected"
);
Ok(())
let target_disk = new_disk(
&target_endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.await?;
let sibling_disk = new_disk(
&sibling_endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
)
.await?;
let identity = auto_replacement_target_identity(&target_disk, &[target_disk.clone(), sibling_disk.clone()]).await;
assert!(
identity.is_some(),
"a separately mounted replacement target with no sibling device overlap must be admitted"
);
Ok(())
})
}
@@ -534,20 +467,10 @@ mod tests {
.await?;
assert!(
!auto_replacement_target_ready(&target_disk, &[target_disk.clone(), sibling_disk.clone()]).await,
"replacement readiness must reject a target sharing its physical device with a sibling endpoint"
);
assert!(
probe_replacement_mounts(&[target_disk.clone(), sibling_disk], &[])
auto_replacement_target_identity(&target_disk, &[target_disk.clone(), sibling_disk.clone()])
.await
.is_none(),
"a batch must reject overlapping targets even before they are registered"
);
assert!(auto_replacement_target_ready(&target_disk, &[]).await);
mounts.mount_bind(&source, &target)?;
assert!(
!auto_replacement_target_ready(&target_disk, &[]).await,
"rebinding the same inode must invalidate the held mount identity"
"replacement readiness must reject a target sharing its physical device with a sibling endpoint"
);
Ok(())
})
+2 -8
View File
@@ -519,14 +519,8 @@ pub(crate) fn replacement_target_identities_match(
expected: &[ReplacementTargetIdentity],
actual: &[ReplacementTargetIdentity],
) -> bool {
if expected == actual {
return true;
}
if expected.len() != actual.len() {
return false;
}
let mut expected: Vec<_> = expected.iter().collect();
let mut actual: Vec<_> = actual.iter().collect();
let mut expected = expected.to_vec();
let mut actual = actual.to_vec();
expected.sort_by(|left, right| left.endpoint.cmp(&right.endpoint));
actual.sort_by(|left, right| left.endpoint.cmp(&right.endpoint));
expected == actual
+18 -11
View File
@@ -38,7 +38,7 @@ use super::storage_api::storage::{
ObjectIO as _, ObjectOperations as _, StorageAdminApi,
};
use super::{
DiskError, DiskStore, ECStore, HealDiskExt as _, StorageError,
DiskError, DiskStore, ECStore, HealDiskExt as _, StorageError, local_disk_map_read,
resume::{ReplacementRecoveryCandidate, ReplacementTargetIdentity, merge_replacement_recovery_candidate},
};
pub use super::{HealObjectInfo, HealObjectOptions, HealPutObjReader};
@@ -2457,13 +2457,9 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn replacement_target_identities(&self, targets: &[String]) -> Result<Vec<ReplacementTargetIdentity>> {
let error = || Error::ReplacementTargetNotReady("replacement target is not a stable mounted disk".to_string());
super::replacement_readiness::ReplacementTargets::open(targets)
super::replacement_readiness::auto_replacement_target_identities(targets)
.await
.ok_or_else(error)?
.identities()
.await
.ok_or_else(error)
.ok_or_else(|| Error::ReplacementTargetNotReady("replacement target is not a stable mounted disk".to_string()))
}
async fn replacement_targets_ready_for_retry(
@@ -2472,14 +2468,25 @@ impl HealStorageAPI for ECStoreHealStorage {
targets: &[String],
expected_identities: &[ReplacementTargetIdentity],
) -> Result<bool> {
let Some(targets) = super::replacement_readiness::ReplacementTargets::open(targets).await else {
return Ok(false);
let identities = match self.replacement_target_identities(targets).await {
Ok(identities) => identities,
Err(_) => return Ok(false),
};
if targets.identities().await.as_deref() != Some(expected_identities) {
if identities != expected_identities {
return Ok(false);
}
for disk in targets.disks {
let local_disks = local_disk_map_read()
.await
.values()
.flatten()
.filter(|disk| disk.endpoint().is_local)
.cloned()
.collect::<Vec<_>>();
for target in targets {
let Some(disk) = local_disks.iter().find(|disk| disk.endpoint().to_string() == *target) else {
return Ok(false);
};
let endpoint = disk.endpoint();
if crate::heal::utils::format_set_disk_id_from_i32(endpoint.pool_idx, endpoint.set_idx).as_deref()
!= Some(set_disk_id)
@@ -228,10 +228,10 @@ impl HealTask {
// first target format write. A task retry keeps this id; a newly
// admitted blank replacement gets a fresh id and cannot reuse cursor
// progress from an older disk at the same endpoint.
let replacement_resume = if let Some(execution) = &replacement_execution {
self.check_control_flags().await?;
// Bind durable intent to the mounts whose execution leases we hold.
let identities = execution.identities().to_vec();
let replacement_resume = if is_auto_replacement {
let identities = self
.await_with_control(self.storage.replacement_target_identities(&self.heal_endpoints))
.await?;
let disk = replacement_resume_disk.clone().ok_or_else(|| Error::TaskExecutionFailed {
message: format!("Replacement resume disk is missing for automatic heal {set_disk_id}"),
})?;
+5 -35
View File
@@ -1258,40 +1258,6 @@ async fn recovered_replacement_never_uses_a_fresh_resume_disk() {
assert!(!*storage.listed.lock().unwrap(), "an unavailable durable anchor must not list buckets");
}
#[tokio::test]
async fn automatic_replacement_does_not_format_a_mount_outside_its_execution_lease() {
let temp = TempDir::new().expect("resume disk directory");
let disk = make_resume_disk(&temp).await;
let leased = replacement_identity("replacement-a", "device-a", "mount-a");
let remounted = replacement_identity("replacement-a", "device-a", "mount-b");
let storage = Arc::new(MockStorage {
bucket_incarnation_id: Mutex::new(Some(Uuid::from_u128(1))),
replacement_target_identities_ready: Mutex::new(true),
replacement_target_identity_sequences: Mutex::new(VecDeque::from([vec![remounted.clone()], vec![remounted]])),
replacement_execution_fixture: Mutex::new(Some(crate::heal::storage::ReplacementExecution::for_test(
Vec::new(),
vec![leased.clone()],
))),
resume_disk: Mutex::new(Some(disk.clone())),
..Default::default()
});
let mut request = directory_backed_replacement_request();
request.heal_endpoints = vec!["replacement-a".to_string()];
let task = HealTask::from_request(request, storage.clone());
let error = task.execute().await.expect_err("a remount must be rejected before format");
assert!(error.to_string().contains("changed during format"), "{error}");
assert!(storage.replacement_format_calls.lock().unwrap().is_empty());
let state = ResumeManager::load_replacement_intent(disk, &task.id)
.await
.expect("durable intent should identify the leased target")
.get_state()
.await;
assert_eq!(state.replacement_phase, ReplacementPhase::Intent);
assert_eq!(state.replacement_target_identities, vec![leased]);
}
#[tokio::test]
async fn automatic_replacement_rejects_a_new_identity_after_format() {
let temp = TempDir::new().expect("temporary resume disk directory should be created");
@@ -1301,7 +1267,11 @@ async fn automatic_replacement_rejects_a_new_identity_after_format() {
let storage = Arc::new(MockStorage {
bucket_incarnation_id: Mutex::new(Some(Uuid::from_u128(1))),
replacement_target_identities_ready: Mutex::new(true),
replacement_target_identity_sequences: Mutex::new(VecDeque::from([vec![first_identity.clone()], vec![second_identity]])),
replacement_target_identity_sequences: Mutex::new(VecDeque::from([
vec![first_identity.clone()],
vec![first_identity.clone()],
vec![second_identity],
])),
resume_disk: Mutex::new(Some(disk.clone())),
..Default::default()
});
+1 -47
View File
@@ -1786,7 +1786,7 @@ where
}
pub async fn update_user_secret_key(&self, access_key: &str, secret_key: &str) -> Result<(OffsetDateTime, AccountStatus)> {
self.update_user_secret_key_with_guard(access_key, secret_key, None, None)
self.update_user_secret_key_with_guard(access_key, secret_key, None)
.await
.map(|(updated_at, status, _guard)| (updated_at, status))
}
@@ -1796,7 +1796,6 @@ where
access_key: &str,
secret_key: &str,
expected_secret: Option<&str>,
session: Option<&Credentials>,
) -> Result<(
OffsetDateTime,
AccountStatus,
@@ -1825,51 +1824,6 @@ where
}
}
// Lock order is parent, then the presenting STS credential. Deletion and
// session refresh use the same STS lock. Release it before the revocation sweep.
let _session_guard = match session {
Some(session) => {
let guard = self.cache.sts_account_mutation_lock(&session.access_key).lock_owned().await;
let current = self
.api
.load_user_identity(&session.access_key, UserType::Sts)
.await
.map_err(|error| {
if is_err_no_such_user(&error) {
Error::IAMActionNotAllowed
} else {
error
}
})?;
let parent = if current.credentials.parent_user.is_empty() {
current.credentials.claims_or_empty().get("parent").and_then(Value::as_str)
} else {
Some(current.credentials.parent_user.as_str())
};
use subtle::ConstantTimeEq as _;
if !session.is_valid()
|| !current.credentials.is_valid()
|| !current.credentials.is_temp()
|| current.credentials.is_service_account()
|| current.credentials.access_key != session.access_key
|| parent != Some(access_key)
|| !bool::from(current.credentials.secret_key.as_bytes().ct_eq(session.secret_key.as_bytes()))
|| !bool::from(
current
.credentials
.session_token
.as_bytes()
.ct_eq(session.session_token.as_bytes()),
)
|| current.sts_generation != u.sts_generation
{
return Err(Error::IAMActionNotAllowed);
}
Some(guard)
}
None => None,
};
let mut cred = u.credentials.clone();
cred.secret_key = secret_key.to_string();
+7 -184
View File
@@ -593,7 +593,7 @@ impl<T: Store> IamSys<T> {
pub async fn info_policy(&self, name: &str) -> Result<rustfs_madmin::PolicyInfo> {
let d = self.store.get_policy_doc(name).await?;
let pdata = d.policy.to_export_value()?;
let pdata = serde_json::to_value(&d.policy)?;
Ok(rustfs_madmin::PolicyInfo {
policy_name: name.to_string(),
@@ -1421,11 +1421,11 @@ impl<T: Store> IamSys<T> {
access_key: &str,
secret_key: &str,
) -> Result<(OffsetDateTime, rustfs_madmin::AccountStatus, usize)> {
self.rotate_user_secret_key_checked(access_key, secret_key, None, None).await
self.rotate_user_secret_key_checked(access_key, secret_key, None).await
}
/// Change an enabled regular user's secret only if the supplied current
/// secret still matches under the parent mutation lock. Status and policies are kept.
/// Change an enabled regular caller's secret only if its signing secret is
/// still current under the parent mutation lock. Status and policies are kept.
/// Persistence and revocation continue after caller cancellation.
pub async fn change_own_secret_key(
&self,
@@ -1433,27 +1433,7 @@ impl<T: Store> IamSys<T> {
expected_secret: &str,
secret_key: &str,
) -> Result<(OffsetDateTime, rustfs_madmin::AccountStatus, usize)> {
self.rotate_user_secret_key_checked(access_key, secret_key, Some(expected_secret), None)
.await
}
/// Change a local IAM password using an authenticated STS session and its parent password.
///
/// The parent and session mutation locks protect revalidation through the secret write.
/// Persistence and session revocation continue after request cancellation.
/// A revocation failure is returned after the new secret has been persisted.
///
/// # Errors
/// Returns `IAMActionNotAllowed` for inactive sessions, parent mismatches, or an
/// incorrect current password. Storage and revocation errors are propagated.
pub async fn change_own_secret_key_from_session(
&self,
access_key: &str,
expected_secret: &str,
secret_key: &str,
session: &Credentials,
) -> Result<(OffsetDateTime, rustfs_madmin::AccountStatus, usize)> {
self.rotate_user_secret_key_checked(access_key, secret_key, Some(expected_secret), Some(session))
self.rotate_user_secret_key_checked(access_key, secret_key, Some(expected_secret))
.await
}
@@ -1462,18 +1442,16 @@ impl<T: Store> IamSys<T> {
access_key: &str,
secret_key: &str,
expected_secret: Option<&str>,
session: Option<&Credentials>,
) -> Result<(OffsetDateTime, rustfs_madmin::AccountStatus, usize)> {
let runtime = tokio::runtime::Handle::try_current().map_err(Error::other)?;
let iam = self.clone();
let access_key = access_key.to_string();
let secret_key = secret_key.to_string();
let expected_secret = expected_secret.map(str::to_string);
let session = session.cloned();
#[cfg(test)]
let notification_probe = crate::LOAD_USER_NOTIFICATION_PROBE.try_with(Arc::clone).ok();
let operation = async move {
iam.rotate_user_secret_key_inner(&access_key, &secret_key, expected_secret.as_deref(), session.as_ref())
iam.rotate_user_secret_key_inner(&access_key, &secret_key, expected_secret.as_deref())
.await
};
#[cfg(test)]
@@ -1493,7 +1471,6 @@ impl<T: Store> IamSys<T> {
access_key: &str,
secret_key: &str,
expected_secret: Option<&str>,
session: Option<&Credentials>,
) -> Result<(OffsetDateTime, rustfs_madmin::AccountStatus, usize)> {
if !is_access_key_valid(access_key) {
return Err(IamError::InvalidAccessKeyLength);
@@ -1505,7 +1482,7 @@ impl<T: Store> IamSys<T> {
let (updated_at, status, parent_guard) = self
.store
.update_user_secret_key_with_guard(access_key, secret_key, expected_secret, session)
.update_user_secret_key_with_guard(access_key, secret_key, expected_secret)
.await?;
let revoked = self.revoke_sts_sessions_for_parent(access_key).await?;
drop(parent_guard);
@@ -4838,160 +4815,6 @@ mod tests {
assert!(matches!(issuer.check_key(&legacy.access_key).await, Ok((None, false))));
}
#[tokio::test]
async fn own_secret_change_revalidates_the_presenting_session_under_the_parent_lock() {
ensure_test_global_credentials();
for mutation in ["revoke", "expire", "disable", "parent", "secret", "token", "generation"] {
let store = StsTestMockStore::new(false);
let iam = Arc::new(IamSys::new(IamCache::new(store.clone()).await.expect("IAM")));
let parent = "session-change-parent";
let password = "currentParentSecret123";
iam.create_user(
parent,
&AddOrUpdateUserReq {
secret_key: password.to_string(),
policy: None,
status: rustfs_madmin::AccountStatus::Enabled,
},
)
.await
.expect("create parent");
let session = rotation_test_session(parent, "password-session");
let owner = iam.get_user(parent).await.expect("parent").credentials;
iam.set_temp_user_from_parent(&session, &owner)
.await
.expect("publish session");
let guard = iam.store.cache.parent_mutation_lock(parent).lock_owned().await;
let pending = {
let iam = Arc::clone(&iam);
let session = session.clone();
tokio::spawn(async move {
iam.change_own_secret_key_from_session(parent, password, "replacementParentSecret123", &session)
.await
})
};
if mutation == "revoke" {
iam.delete_temp_account(&session.access_key, false)
.await
.expect("revoke presenting session");
} else {
let mut saved = store.saved_sts_users.lock().expect("saved identities");
let current = saved.get_mut(&session.access_key).expect("durable session");
match mutation {
"expire" => current.credentials.expiration = Some(OffsetDateTime::UNIX_EPOCH),
"disable" => current.credentials.status = "off".to_string(),
"parent" => current.credentials.parent_user = "another-parent".to_string(),
"secret" => current.credentials.secret_key = "replacementSessionSecret123".to_string(),
"token" => current.credentials.session_token = "replacement-token".to_string(),
"generation" => {
assert!(current.sts_generation.take().is_some());
}
_ => unreachable!("known fixture mutation"),
}
}
drop(guard);
let error = tokio::time::timeout(std::time::Duration::from_secs(5), pending)
.await
.expect("queued rotation finishes")
.expect("rotation task")
.expect_err("stale session must fail");
assert_eq!(error, Error::IAMActionNotAllowed, "{mutation}");
let saved = store.saved_sts_users.lock().expect("saved identities");
assert_eq!(saved.get(parent).expect("parent survives").credentials.secret_key, password, "{mutation}");
}
}
#[tokio::test]
async fn session_secret_change_uses_the_durable_parent_password_with_a_stale_cache() {
let iam = test_iam_sys().await;
let parent = "stale-password-parent";
iam.create_user(
parent,
&AddOrUpdateUserReq {
secret_key: "cachedParentSecret123".to_string(),
policy: None,
status: rustfs_madmin::AccountStatus::Enabled,
},
)
.await
.expect("create parent");
let session = rotation_test_session(parent, "fresh-password-session");
let owner = iam.get_user(parent).await.expect("cached parent").credentials;
iam.set_temp_user_from_parent(&session, &owner)
.await
.expect("publish session");
iam.store
.api
.saved_sts_users
.lock()
.expect("saved identities")
.get_mut(parent)
.expect("durable parent")
.credentials
.secret_key = "durableParentSecret123".to_string();
assert_eq!(
iam.store
.get_user(parent)
.await
.expect("stale cached parent")
.credentials
.secret_key,
"cachedParentSecret123"
);
let probe = IamSys::<StsTestMockStore>::load_user_notification_probe(0, false, false);
crate::LOAD_USER_NOTIFICATION_PROBE
.scope(
probe,
iam.change_own_secret_key_from_session(parent, "durableParentSecret123", "replacementParentSecret123", &session),
)
.await
.expect("durable current password authorizes the change");
assert_eq!(
iam.get_user(parent).await.expect("updated parent").credentials.secret_key,
"replacementParentSecret123"
);
}
#[tokio::test]
async fn current_session_can_change_its_parent_secret_and_revoke_itself() {
let iam = test_iam_sys().await;
let parent = "current-session-parent";
let password = "currentParentSecret123";
iam.create_user(
parent,
&AddOrUpdateUserReq {
secret_key: password.to_string(),
policy: None,
status: rustfs_madmin::AccountStatus::Enabled,
},
)
.await
.expect("create parent");
let session = rotation_test_session(parent, "current-password-session");
let owner = iam.get_user(parent).await.expect("parent").credentials;
iam.set_temp_user_from_parent(&session, &owner)
.await
.expect("publish session");
let probe = IamSys::<StsTestMockStore>::load_user_notification_probe(0, false, false);
let (_, _, revoked) = tokio::time::timeout(
std::time::Duration::from_secs(5),
crate::LOAD_USER_NOTIFICATION_PROBE.scope(
probe,
iam.change_own_secret_key_from_session(parent, password, "replacementParentSecret123", &session),
),
)
.await
.expect("rotation must release its session lock before revocation")
.expect("rotate current session");
assert_eq!(revoked, 1);
assert!(iam.get_user(&session.access_key).await.is_none());
assert_eq!(
iam.get_user(parent).await.expect("rotated parent").credentials.secret_key,
"replacementParentSecret123"
);
}
#[tokio::test]
async fn self_secret_change_cannot_undo_concurrent_disable_rotation_or_deletion() {
ensure_test_global_credentials();
+3 -96
View File
@@ -3019,13 +3019,6 @@ pub fn record_ecstore_rename_batch_terminal_missing(items: usize) {
#[inline(always)]
pub fn record_ecstore_rename_admission(batch: bool, items: usize, wait: Duration, timed_out: bool) {
if timed_out {
metrics::counter!(
"rustfs_ecstore_rename_admission_timeouts_total",
"mode" => if batch { "batch" } else { "unary" }
)
.increment(1);
}
if !put_stage_metrics_enabled() {
return;
}
@@ -3043,16 +3036,11 @@ pub fn record_ecstore_rename_admission(batch: bool, items: usize, wait: Duration
#[inline(always)]
pub fn record_ecstore_rename_quarantine(batch: bool, items: usize, hold: Duration) {
let mode = if batch { "batch" } else { "unary" };
let active_items = f64::from(u32::try_from(items).unwrap_or(u32::MAX));
let items = u64::try_from(items).unwrap_or(u64::MAX);
metrics::counter!("rustfs_ecstore_rename_quarantine_events_total", "mode" => mode).increment(1);
metrics::counter!("rustfs_ecstore_rename_quarantine_items_total", "mode" => mode).increment(items);
metrics::gauge!("rustfs_ecstore_rename_quarantine_active_items", "mode" => mode).increment(active_items);
if !put_stage_metrics_enabled() {
return;
}
let base = usize::from(batch) * 6;
let items = u64::try_from(items).unwrap_or(u64::MAX);
let hold_ns = u64::try_from(hold.as_nanos()).unwrap_or(u64::MAX);
ECSTORE_RENAME_QUARANTINE_COUNTS[base].fetch_add(1, Ordering::Relaxed);
ECSTORE_RENAME_QUARANTINE_COUNTS[base + 1].fetch_add(items, Ordering::Relaxed);
@@ -3062,25 +3050,17 @@ pub fn record_ecstore_rename_quarantine(batch: bool, items: usize, hold: Duratio
#[inline(always)]
pub fn record_ecstore_rename_quarantine_released(batch: bool, items: usize) {
let mode = if batch { "batch" } else { "unary" };
let active_items = f64::from(u32::try_from(items).unwrap_or(u32::MAX));
let items = u64::try_from(items).unwrap_or(u64::MAX);
metrics::counter!("rustfs_ecstore_rename_quarantine_released_items_total", "mode" => mode).increment(items);
metrics::gauge!("rustfs_ecstore_rename_quarantine_active_items", "mode" => mode).decrement(active_items);
if put_stage_metrics_enabled() {
let base = usize::from(batch) * 6;
ECSTORE_RENAME_QUARANTINE_COUNTS[base + 4].fetch_add(items, Ordering::Relaxed);
ECSTORE_RENAME_QUARANTINE_COUNTS[base + 4].fetch_add(u64::try_from(items).unwrap_or(u64::MAX), Ordering::Relaxed);
}
}
#[inline(always)]
pub fn record_ecstore_rename_quarantine_no_runtime(batch: bool, items: usize) {
let mode = if batch { "batch" } else { "unary" };
let items = u64::try_from(items).unwrap_or(u64::MAX);
metrics::counter!("rustfs_ecstore_rename_quarantine_no_runtime_items_total", "mode" => mode).increment(items);
if put_stage_metrics_enabled() {
let base = usize::from(batch) * 6;
ECSTORE_RENAME_QUARANTINE_COUNTS[base + 5].fetch_add(items, Ordering::Relaxed);
ECSTORE_RENAME_QUARANTINE_COUNTS[base + 5].fetch_add(u64::try_from(items).unwrap_or(u64::MAX), Ordering::Relaxed);
}
}
@@ -5110,79 +5090,6 @@ mod tests {
);
}
#[test]
fn ecstore_rename_fault_metrics_remain_visible_without_stage_metrics() {
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
set_put_stage_metrics_enabled(false);
record_ecstore_rename_admission(false, 1, Duration::from_nanos(10), false);
record_ecstore_rename_admission(false, 1, Duration::ZERO, true);
record_ecstore_rename_admission(true, 4, Duration::ZERO, true);
record_ecstore_rename_quarantine(false, 1, Duration::from_secs(1));
record_ecstore_rename_quarantine_released(false, 1);
record_ecstore_rename_quarantine(true, 3, Duration::from_secs(1));
record_ecstore_rename_quarantine_no_runtime(true, 3);
});
let rows = snapshotter.snapshot().into_vec();
let counter_by_mode = |name: &str, mode: &str| {
rows.iter()
.filter(|(composite, _, _, _)| {
composite.kind() == MetricKind::Counter
&& composite.key().name() == name
&& composite
.key()
.labels()
.any(|label| label.key() == "mode" && label.value() == mode)
})
.map(|(_, _, _, value)| match value {
DebugValue::Counter(value) => *value,
other => panic!("{name} is registered as a counter but holds {other:?}"),
})
.sum::<u64>()
};
assert_eq!(counter_by_mode("rustfs_ecstore_rename_admission_timeouts_total", "unary"), 1);
assert_eq!(counter_by_mode("rustfs_ecstore_rename_admission_timeouts_total", "batch"), 1);
assert_eq!(counter_total(&rows, "rustfs_ecstore_rename_quarantine_events_total"), Some(2));
assert_eq!(counter_total(&rows, "rustfs_ecstore_rename_quarantine_items_total"), Some(4));
assert_eq!(counter_by_mode("rustfs_ecstore_rename_quarantine_released_items_total", "unary"), 1);
assert_eq!(counter_by_mode("rustfs_ecstore_rename_quarantine_released_items_total", "batch"), 0);
assert_eq!(counter_by_mode("rustfs_ecstore_rename_quarantine_no_runtime_items_total", "unary"), 0);
assert_eq!(counter_by_mode("rustfs_ecstore_rename_quarantine_no_runtime_items_total", "batch"), 3);
let mut active_items = rows
.iter()
.filter(|(composite, _, _, _)| {
composite.kind() == MetricKind::Gauge && composite.key().name() == "rustfs_ecstore_rename_quarantine_active_items"
})
.map(|(composite, _, _, value)| {
let mode = composite
.key()
.labels()
.find(|label| label.key() == "mode")
.map(|label| label.value().to_string())
.expect("rename quarantine gauge must carry the bounded mode label");
let DebugValue::Gauge(value) = value else {
panic!("rename quarantine active items must be a gauge")
};
(mode, value.0)
})
.collect::<Vec<_>>();
active_items.sort_by(|left, right| left.0.cmp(&right.0));
assert_eq!(active_items, vec![("batch".to_owned(), 3.0), ("unary".to_owned(), 0.0)]);
assert!(
rows.iter()
.filter(|(composite, _, _, _)| composite.key().name().starts_with("rustfs_ecstore_rename_"))
.flat_map(|(composite, _, _, _)| composite.key().labels())
.all(|label| label.key() == "mode" && matches!(label.value(), "batch" | "unary")),
"fault metrics must use only the bounded rename mode label"
);
set_put_stage_metrics_enabled(false);
}
#[test]
fn ecstore_rename_batch_candidate_metrics_are_gated_and_bounded() {
let _guard = METRICS_FLAG_LOCK.lock().unwrap_or_else(|e| e.into_inner());

Some files were not shown because too many files have changed in this diff Show More