Compare commits

..

270 Commits

Author SHA1 Message Date
唐小鸭 c25d41a798 Merge branch 'main' into refactor/sse-module-split
Main moved the test that checks the SSE-KMS summary on an audit entry
from `rustfs/src/storage/helper.rs` to `rustfs/src/app/owned_audit_test.rs`.
Two conflicts follow from that move.

`rustfs/src/storage/helper.rs` takes main's side: the test is gone from
this file.

`rustfs/src/app/object/mod.rs` keeps main's split of the SSE imports and
adds the two extension traits this branch introduced. On this branch
`SseKmsPrincipal::from_request` is reached through `SseKmsPrincipalExt`,
so the moved test imports the trait and the test-only re-export carries
it.
2026-11-23 14:55:48 +08:00
Hauser Zhi 963e68ed30 test(rustfs): restore layer-owned regression coverage (#9585) 2026-11-23 14:20:38 +08:00
overtrue 5532994cf7 test(protocols): build the copy request-head envelope directly
Replace the copy request-head fixture's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers,
extensions, region, service, and credentials. The request-head
parity assertions are unchanged.
2026-11-23 14:11:25 +08:00
overtrue 93bda3c9fc test(multipart): build presigned part checksum envelopes directly
Replace the presigned checksum fixtures' from_s3s calls with
RequestEnvelope::from_parts, keeping method, URI, headers, and
extensions. Credentials stay absent. The checksum, ambiguous-value,
header, and verified-presign assertions are unchanged.
2026-11-23 13:36:26 +08:00
唐小鸭 23ebd00068 test(sse): expect only customer-key headers on SSE-C multipart replies
MP-03 recorded the extra `x-amz-server-side-encryption: AES256` header on
SSE-C CreateMultipartUpload and CompleteMultipartUpload responses as a
known deviation. The header is gone on main, so the case now checks the
intended headers directly; left as a marker it would report the deviation
as fixed and fail the run.

On both builds the base and this branch pass the case.
2026-11-23 13:30:36 +08:00
overtrue 7d0f38462d test(bucket): build the list-through v2 envelope directly
Replace the ListObjectsV2 seam's from_s3s call with
RequestEnvelope::from_parts, keeping method, URI, headers,
extensions, region, service, and credentials. The list output
mapping and migration header are unchanged.
2026-11-23 13:04:27 +08:00
overtrue 90443cf3cb test(multipart): build create replication and kms envelopes directly
Replace the ciphertext-replication and KMS create fixtures'
from_s3s calls with RequestEnvelope::from_parts, keeping method,
URI, headers, and extensions. Credentials stay absent. The refusal,
authorizer, and upload-id assertions are unchanged.
2026-11-23 12:58:27 +08:00
唐小鸭 9d5f34304b Merge branch 'main' into refactor/sse-module-split 2026-11-23 12:45:19 +08:00
overtrue 5b0b0d4fa7 test(authz): build owned authorization envelopes directly
Replace the test-only RequestEnvelope::from_s3s calls with
RequestEnvelope::from_parts, keeping method, URI, headers, extensions,
region, and service. Credentials stay absent. Authorization assertions
are unchanged.
2026-11-23 12:14:08 +08:00
overtrue 18c4d007a6 test(admin): build object-lambda test envelopes directly
Replace the five test-only RequestEnvelope::from_s3s calls with
RequestEnvelope::from_parts, keeping method, URI, headers, and extensions.
Credentials, region, and service stay absent. Production S3Router::call
still uses from_s3s.
2026-11-23 11:41:02 +08:00
overtrue d67bdb83b3 test(bucket): build the stale list-through GET envelopes directly
Replace the two RequestEnvelope::from_s3s calls in the stale-incarnation
fixture with RequestEnvelope::from_parts, keeping method GET, URI
/missing, empty headers, and empty extensions.
2026-11-23 11:06:33 +08:00
overtrue 918d6819fa test(bucket): build the create-bucket reqinfo envelope directly
Replace build_request_with_req_info plus from_s3s in the CreateBucket
and DeleteBucket fixture with RequestEnvelope::from_parts, keeping
method PUT, URI /, empty headers, and the ReqInfo extension.
2026-11-23 10:38:13 +08:00
overtrue 1352dc81d8 test(multipart): build the create generation envelope directly
Replace build_request plus from_s3s in the create-multipart generation
fixture with RequestEnvelope::from_parts, keeping the method, URI, and
server-context extension.
2026-11-23 10:06:50 +08:00
overtrue 6c507ca600 test(bucket): build remaining config mutation envelopes directly
Replace build_request plus from_s3s in the lifecycle, replication,
public-access-block, and shared config-delete fixtures with
RequestEnvelope::from_parts, keeping the method, URI, and extensions.
2026-11-23 09:35:32 +08:00
overtrue fe6497bd76 test(bucket): build config mutation envelopes directly
Replace build_request plus from_s3s in the logging, tagging, website,
object-lock, and notification fixtures with RequestEnvelope::from_parts,
keeping the method, URI, and extensions.
2026-11-23 09:01:11 +08:00
overtrue 5913301e45 test(multipart): build list and abort generation envelopes directly
Replace build_request plus from_s3s in the generation fixtures with
RequestEnvelope::from_parts, keeping the method, URI, and extensions.
2026-11-23 08:41:45 +08:00
唐小鸭 9120a28da1 test(sse): cover run-time state, authorization, leaks and stored form
Three groups of cases are added to the black-box suite, with what they
need to run.

Run-time state (14 cases). A write follows the state the process is in
now, a read follows what the object recorded: the master key across
restarts, KMS stopped, started and configured at run time, a deployment
moving between key sources, a changed backend, and keys disabled,
destroyed and rotated. New configurations: Local KMS with a master key,
Vault Transit, Vault KV2 and the Static backend. Vault is a development
server started by the driver with a token generated per run; when it
cannot be started its cases report an environment error.

Authorization and leaks (18 cases). Per-key authorization on bucket
defaults, both ends of a copy, multipart uploads, every read entry point,
anonymous access, internal work and audit entries. Every exchange of a
run is archived with secrets redacted, and four checks over the whole run
look for key material in responses and server logs, for internal headers,
and for unexpected internal-error messages.

Stored form (8 cases). What an encrypted object looks like on disk is
read with the repository's `dump_fileinfo` tool and held to one manifest
per build: every metadata key with its exact value or, for random values,
its shape. The cases also search the drives for plaintext, customer keys
and unwrapped data keys. `cross` records the stored form of everything
the writer stored.

Compared with the base on the default build, all levels: 382 verdicts and
887 exchanges equal, no blocking difference; 86 case runs pass on each
side. Three cases report a known deviation that predates this branch: the
multipart SSE-C response header (MP-03), an SSE-KMS write that turns from
400 into 503 after a refused KMS start (KS-09), and a read by a caller
without a grant that reveals whether the key was destroyed or KMS is
stopped (SEC-05). The manifests were written from the base binaries and
the branch stores the same form in both builds.

Each group was shown to fail when it should: Vault unavailable gives
environment errors, the two authorization configurations swapped fail the
matrix both ways, a planted key is found in a log and in a response, a
`rio-v2` binary registered as the default build fails the manifest and
the build check.
2026-11-23 08:41:36 +08:00
唐小鸭 32c762420f test(sse): prepare the black-box suite for P1 cases and more backends
The suite could only run P0 cases on six built-in configurations with one
shared site each. The next groups of cases need more than that:

- `run --level p0|p1|all`, and a `skip` verdict for a case the backend's
  capability table rules out.
- `register_config` lets a case module add a process configuration with
  what it needs before the process starts, once it answers, and at the
  end of the run. The two Local KMS configurations now use the same
  mechanism instead of special cases in the driver.
- `isolated` cases get a site of their own on a fresh data directory and
  may restart it with another configuration or environment.
- Exchange hooks and post-run checks, for modules that keep everything a
  run saw and judge it as a whole.
- Case modules are discovered by file name, and the binary registry can
  be shared between state directories.

The P0 results and the comparison with the base are unchanged.
2026-11-23 08:41:36 +08:00
唐小鸭 2c00909e91 Merge branch 'main' into refactor/sse-module-split
One conflict, in a test in `rustfs/src/storage/helper.rs`: main now builds
the SSE-KMS principal straight from the request, and this branch reaches
`from_request` through the `SseKmsPrincipalExt` trait. The merged test
keeps the trait import and passes the request directly.
2026-11-23 08:41:23 +08:00
shurkus e80f64cac2 fix(heal): create tmp source dir when healing transitioned objects (#9544)
* fix(heal): create tmp source dir when healing transitioned objects

* Skip local shard cleanup when transitioned metadata has no data directory

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 07:35:46 +08:00
GatewayJ e7248f2801 fix(ecstore): verify EC:0 shards on the owning peer and enforce NIXL shard I/O (#9526)
* fix(ecstore): verify remote shards over strict NIXL reads

* fix(ecstore): preserve EOF and repair semantics for remote shards

* fix(storage): use native request bodies for RDMA uploads

* perf(ecstore): verify EC=0 shards on the owning peer

* fix(ecstore): bound staged shard reads and test failed uploads

* test(protos): pass explicit timeouts in channel reset tests

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 07:29:10 +08:00
Chris An 45e7c91cd4 fix(ecstore): keep EC layout projections out of stored metadata (#9398)
* perf(ecstore): reduce allocations for bounded bitrot frames

* test(s3): cover dynamic block layouts over HTTP

* perf: measure quantized range read shape

* chore: checkpoint quantized read metrics draft

Save work in progress for collaboration. Counts omit retired readers and transient or cancelled hedges. Frame semantics, async recorder coverage and disabled-metrics overhead remain unresolved; these counters are not ready for performance conclusions.

Validation: rustfmt and ecstore check passed; io-metrics 120, quantized 4 and hashed-read 3 tests passed. No new live or performance validation.

* perf(ecstore): reduce dynamic layout read overhead

* fix(ecstore): avoid prefetching conservative short range tails

* perf(ecstore): compact deferred shard reader state

* perf(ecstore): include shard checksums in file buffer cap

* fix(ecstore): preserve bounded quantum frames during heal

* perf(ecstore): reuse owned quantized frame batches

* perf(ecstore): batch q reads and retain shared copy framing

* fix(ecstore): preserve typed quantized read errors

* perf(ecstore): avoid zero-fill and serial copies in local batch reads

The local batch reader zero-initialized every window at a nonzero offset
before reading it, and copied every shard serially inside one blocking
task. Two-segment q-window range reads (cross-shard, cross-block) pay
both costs twice per request.

Read each window with a positioned read into uninitialized Vec capacity,
and dispatch each shard separately when every window is at least 512 KiB,
where copies dominate blocking-pool round trips. Smaller windows keep one
coalesced dispatch.

* perf(ecstore): keep readahead pipelined for local batch windows

A single window-sized pread on cold pages waits on each kernel readahead
chunk in turn. Seek to the window start and fill the buffer with
read_to_end over a length-limited reader instead: it still reads into
uninitialized spare capacity, but its growing sequential reads keep
readahead pipelined. Warm windows cost the same.

* Revert "perf(ecstore): keep readahead pipelined for local batch windows"

This reverts commit c252fca525.

On the ESSD-backed cloud footprint, the growing read_to_end reads were
slower than one window-sized positioned read for cold windows at nonzero
offsets (cross-block -27% on 4 MiB layouts, cross-shard -21% on 64 KiB
layouts versus the previous batch reader). The local benchmark that
motivated the change ran on a WSL virtual disk and did not represent the
target storage. Keep the single positioned read into spare capacity and
the per-shard dispatch for large windows.

* perf(ecstore): choose the batch read method by window size

Measured on ESSD-backed cloud storage, a cold window of about 1 MiB is
fastest as one positioned read, which completes as a single device
request, while windows of 2 MiB and more are faster with growing
sequential reads that keep readahead pipelined (one large read waits on
each readahead chunk in turn). Use one positioned read up to 1.5 MiB and
a seek plus length-limited read_to_end above it. Both paths read into
uninitialized spare capacity; per-shard dispatch for large windows is
unchanged.

* perf(ecstore): read local batch windows with an exact readahead hint

Kernel readahead sizes its first request from the read size. A cold
16 KiB window at offset 0 pulled 64-128 KiB, and a single 2 MiB read was
split into serial readahead chunks that cached almost twice the window,
which is why neither the single positioned read nor growing sequential
reads won for every window size on block storage.

Announce each window with POSIX_FADV_WILLNEED, which submits exactly the
window at once, and then fill the exact spare capacity with positioned
reads. This replaces the size-based choice between the two read methods.
The hint is advisory and its failure does not fail the read. A residency
test checks that cold reads cache only their window; it failed with the
hint disabled (a 5-page window cached 32 pages).

* perf(ecstore): use half-shard read quantum at 1 MiB EC layout

* revert(release): defer certification rollout for 1.0.5 (#9254)

Revert e5563e6004 only on release/1.0.5. Its trusted verifier workflow and immutable-candidate integration are not available yet. Restore the previous publication path under the approved release policy; retain the completed product regression and preview acceptance requirements.

* fix(ecstore): preserve legacy full-shard framing for default 1 MiB layout

* perf(ecstore): enable direct-memory GET and coalesce cross-shard range reads for bounded-quantum blocks

* chore(ecstore): remove unused schedule_bitrot_reader_task wrapper

* fix(ecstore): run delete-recovery discovery off the metadata lane

Bucket-wide delete-recovery discovery starts with the server and walks the
whole bucket tree in pages of up to 4096 entries, one lstat per entry. Each
page ran on the per-disk namespace queue's foreground lane, which has a
single worker and also serves GET metadata reads. On a cold tree a page
holds that worker for hundreds of milliseconds, so every GET on the disk
waits behind it until the walk finishes.

Run the page on the queue's sync lane instead, as the delete-transaction
inspection already does for the same reason. The namespace lease and the
page bounds are unchanged.

The regression test occupies the foreground lane and requires a discovery
page to complete within ten seconds; it times out without this change.

* test(ecstore): align read_appending rollback assertions on error

* test(ecstore): satisfy needless_range_loop in deferred shard open test

Rust 1.100 clippy rejects indexing setup.attempted with the loop variable.
Iterate the same two entries instead; the assertions are unchanged.

* fix(ecstore): keep the EC block size projection out of user_defined

ObjectInfo::from_file_info_parts projected the persisted erasure block size
into user_defined as x-rustfs-internal-ec-block-size and
x-minio-internal-ec-block-size for every local version, including objects
written with the default layout. Writers that turn user_defined back into
stored metadata then persisted both keys: a metadata-replacing copy_object
(set_disk/ops/object.rs replacement_metadata) and put_object_metadata, used
by the replication status write-back. The same-version restore metadata
update also stopped matching its protected-metadata check, which made
restore_metadata_copy_preserves_tags_expiry_and_version_order fail.

The projection now lives in ObjectInfo::ec_block_size, read through
effective_ec_block_size(), so response headers are unchanged and stored
metadata keys stay what main writes. The put_object and new_multipart_upload
strips stay: internal PUT origins can still supply internal keys verbatim.

Changed assertions:
- from_file_info_projects_persisted_ec_block_size_for_responses and
  from_owned_file_info_preserves_restored_ec_block_size_projection asserted
  the key inside user_defined; they now assert the accessor and that neither
  spelling is in user_defined.

Tests added:
- default_layout_metadata_copy_persists_no_ec_block_size_projection
- default_layout_replication_status_writeback_persists_no_ec_block_size_projection

* fix(ecstore): split bounded frames on the coalesced shard write path

The encoder writes shards through BitrotWriterWrapper::write_shard_bytes
since #9346. That path wrote a shard as one bitrot frame, so a bounded read
quantum (frame smaller than the shard) failed with "data size exceeds shard
size" on every non-inline write. The defect exists only on the tree that
merges this branch with main, and only with RUSTFS_EC_READ_QUANTUM_ENABLE on;
the default layout never selects a bounded frame.

Shards larger than the frame now go through the same frame splitting as
write(). Protected writes never select a bounded quantum; a shard-integrity
spec together with bounded frames is refused instead of dropping the digest.

Red before, green after: bounded_quantum_heal_restores_exact_frames_and_range_bytes,
bounded_quantum_shards_pass_disk_verification_and_deep_heal,
version_only_copy_preserves_quantized_shared_data.

* test(ecstore): pin the exact key set of a replication status write-back

The default-layout write-back test now asserts the precise keys main adds
(the status keys, X-Amz-Replication-Status and the data-moved markers)
instead of a subset check.

* Drop legacy EC block-size projections when reading metadata

---------

Co-authored-by: Xiaoyang Han <lux1an@qq.com>
Co-authored-by: marshawcoco <marshawcoco@gmail.com>
2026-11-23 07:28:31 +08:00
overtrue 4a3088d752 test(gateway): retire the legacy configuration XML input bridge 2026-11-23 06:53:47 +08:00
overtrue 2fa5ead608 test(gateway): replace legacy HEAD inputs and stored configuration oracles 2026-11-23 06:48:43 +08:00
overtrue 393b847e21 refactor(gateway): retire legacy lifecycle input conversion 2026-11-23 06:48:32 +08:00
overtrue 49358e8829 test(gateway): cover tier lookups with native quota errors 2026-11-23 06:48:22 +08:00
overtrue 5f56f9d5de fix(gateway): pass client body timeouts across the native upload boundary 2026-11-23 06:48:22 +08:00
overtrue 4bd570a40e refactor(gateway): move archive errors and parity coverage to native paths 2026-11-23 06:48:22 +08:00
overtrue e7f831a26e test(gateway): isolate the tier lookup diagnostic configuration 2026-11-23 06:47:12 +08:00
overtrue dfe4a0506e test(gateway): route diagnostic PUT through signed dispatch 2026-11-23 06:47:12 +08:00
overtrue c4cab97dde test(gateway): exercise native object writes, deletes and part listings 2026-11-23 06:47:11 +08:00
Ramakrishna Chilaka 82988adc7d perf(ecstore): cut delete preflight fanout, dir openat2, and stage lock lookups (#9579)
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 05:30:05 +08:00
cxymds e48b3a4e0c fix(scanner): finish wide directory scans across cycle deadlines (#9516)
* fix(scanner): finish wide directory scans across cycle deadlines

* fix(scanner): resume durable per-disk progress across handoffs

* fix(scanner): bound checkpoint storage and resume verified page reads

* fix(scanner): keep recoverable pages across long cycle intervals

* test(scanner): share primary page fault injection

* fix(scanner): preserve progress across owner cancellation

Port the scanner fix from #9546.

* fix(scanner): recover abandoned checkpoint page bundles

Record staging before writing pages and persist cleanup with a replacement checkpoint. Restore checkpoints with background disk admission and update the affected tests to pass cancellation tokens.

* test(scanner): adapt cache and lifecycle cases to current scanner inputs

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 05:15:16 +08:00
Jinhao Hu c02ac79a68 fix(ecstore): preserve DualInFlight stripe order in ErasureDecodeReader (#9496)
* fix(ecstore): preserve DualInFlight stripe order in ErasureDecodeReader

In ErasureDecodeReader, poll_fill_result() previously extended
self.prefetched_bufs with lookahead stripes (queued_buffers, stripe
2k+1) before returning the primary stripe (buf, stripe 2k) to
poll_prefetch(). When a DualInFlight fill completed while output_buf
still had unconsumed bytes, poll_prefetch() pushed stripe 2k onto the
back of self.prefetched_bufs after stripe 2k+1, swapping adjacent
(2k, 2k+1) stripes on multi-block GetObject reads.

Return (buf, queued_buffers) from poll_fill_result() without mutating
self.prefetched_bufs, and extend self.prefetched_bufs with
queued_buffers in poll_prefetch() only after buf has been installed in
output_buf or pushed to self.prefetched_bufs. Also account for
non-empty self.prefetched_bufs when checking output_has_remaining and
deferring prefetch errors, and add a unit regression test.

* refactor(ecstore): factor FillBatch type alias in ErasureDecodeReader

Extract `type FillBatch = (Vec<u8>, VecDeque<Vec<u8>>)` for the
`poll_fill_result` return type to satisfy `clippy::type-complexity`.

---------

Co-authored-by: Jinhao Hu <jinhaohu@google.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 05:05:29 +08:00
Ramakrishna Chilaka 2fbb1f7585 perf(ecstore): optimize delete recovery and 1 MiB streaming ingest (#9558)
Eliminate the 1 MiB -> 2 MiB encode_buffer reallocation in small_ingest_capacity, make HardLimitReader::poll_read zero-copy via ReadBuf::take, remove redundant BufReader wrappers around StreamReader, borrow InlineData during DELETE Stage 1, and hand off local published delete receipts directly from Stage 2 to Stage 3.

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:39:13 +08:00
cxymds ac83905ebb fix(notify): preserve event origins across bucket recreation (#9505)
* fix(notify): bind bucket notifications to bucket incarnations

* fix(notify): use replication metadata boundary for event identity

* test(notify): remove redundant fixture clones

* test(notify): remove unused event fixture import

* test(notify): preserve bucket removal delivery after rule withdrawal

* fix(notify): retain originating incarnation in replication tasks

* fix(notify): retain deferred delete generation in event context

* fix(notify): capture fenced provenance for metadata events

Capture bucket-removal metadata under deletion fences, retain transition origins through queueing and deduplication, and bind tagging and ACL authorization to the verified storage generation.

* test(ci): register webhook cases and fix stale fixtures

Register both notification regressions without changing profile filters or count floors. Parse fixture signing times with explicit UTC, preserve primary admin checks before optional secondary checks, and simplify the notification failure fixture.

* test(ecstore): place lifecycle fixture exports before tests

* fix(notify): route metadata fixtures through storage boundary

* fix(notify): validate startup rules without republishing

* fix(auth): preserve metadata validation error precedence

* test(ci): align fixtures with current authority fences

* fix(ecstore): bound Linux batch read readahead

* test(notify): use owned requests for bucket generation checks

* test(admin): scope the router operation bound to the helper

* fix(notify): preserve provenance across reloads and scans

* test(ilm): cover unknown transition notification origin

---------

Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:34:28 +08:00
cxymds 49db44d177 fix(scanner): bound retries and validate cached bucket identities (#9423)
* feat(scanner): expose scan work and reuse observations

* fix(scanner): preserve baselines during backup catchup

Require decoded-primary provenance before accepting an unchanged baseline after its backup catches up. Keep current-revision CAS and publication fences, and align the real checkpoint fixture with the bounded-cycle carry contract.

* fix(scanner): cap superseded retries at the nominal cycle

* fix(usage): validate cached statistics against bucket identity

* feat(scanner): observe bucket reuse and production proof gates

* fix(ci): give the multipart refusal fixture its storage stack

* test(admin): bind snapshot fixtures to current bucket identities

* fix(scanner): require a measured baseline for admin usage overlays

* fix(scanner): reject unmeasured admin usage snapshots

Validate the persisted scanner baseline before identity filtering can mark
it as displayable. Cover two buckets with only one current identity and
adapt the backup catchup cache save calls to the merged API.

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
Co-authored-by: houseme <4829346+houseme@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-11-23 04:34:14 +08:00
cxymds 58b6b7285c fix(scanner): recover interrupted local drive scans (#9497)
* fix(scanner): recover interrupted local drive scans

* fix(scanner): bound initial local drive binding

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:17:34 +08:00
Hauser Zhi cc4aee70a0 chore(deps): update flake.lock (#9571)
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/2074cc6' (2026-11-12)
  → 'github:NixOS/nixpkgs/93a9ed0' (2026-11-21)
• Updated input 'rust-overlay':
    'github:oxalica/rust-overlay/5b87ee0' (2026-11-14)
  → 'github:oxalica/rust-overlay/52db205' (2026-11-21)
2026-11-23 04:16:55 +08:00
chapman 2cc25bcb25 fix(s3): map CompleteMultipartUpload checksum mismatch to BadDigest (#9494)
* fix(s3): map CompleteMultipartUpload checksum mismatch to BadDigest

Return structured rustfs_rio::ChecksumMismatch errors from SetDisks::complete_multipart_upload when a completion checksum header mismatches the upload's algorithm, checksum configuration, FULL_OBJECT digest or part-count suffix, or COMPOSITE digest, so the S3 usecase maps rejections to HTTP 400 BadDigest instead of 500 InternalError without publishing the object or retiring the upload.

Fixes #9272

* fix(ecstore): preserve legacy unconfigured-upload checksum behavior

Let unconfigured multipart uploads continue delegating want_checksum validation to Checksum::matches against the empty combined part-digest buffer instead of rejecting every non-empty header outright. Non-matching digests still return ChecksumMismatch (400 BadDigest), while empty-buffer digests such as CRC32 AAAAAA== preserve the legacy 200 echo behavior pinned by embedded_gateway_stack_test.

* fix(ecstore): reject zero-part full-object checksum suffixes

* fix(ecstore): accept stored-record full-object checksums

A wire -N suffix (including -0) sets MULTIPART without INCLUDES_MULTIPART, while stored multipart records carry both flags with want_parts == 0. Treat only the former as a suffixed claim so a matching stored-record FULL_OBJECT checksum still completes, and cover it alongside the existing -0 and -1 rejections.

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:16:46 +08:00
Chris An b19c06f4de fix(scanner): revisit compacted prefixes with active lifecycle rules (#9551)
Co-authored-by: cxymds <cxymds@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 04:13:57 +08:00
Hauser Zhi 6d115aaec9 fix(heal): admit replacement data directories on configured mounts (#9519)
* fix(heal): admit replacement data directories on configured mounts

Verify the mount ID of the pinned data directory against the expected mount root and retain the existing physical-device checks. Reject the newly exposed directory when the intended mount is missing.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* refactor(heal): probe replacement mounts as one pinned batch

Resolve each target once and check mount identity on the same handles before and after taking execution leases. Verify mount boundaries with bounded kernel lookups and resolve each local device once per batch.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* test(heal): reuse the privileged replacement mount fixture

Exercise configured subdirectories and unmount rejection in the existing independent-mount case. Reuse the mount namespace and keep the existing ignored-test ceiling.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(ci): remove stale form helper and unused hotpath dependencies

Remove the test helper left by the gateway merge. Keep profiling feature forwarding in protos and activate rio instrumentation only for profiling builds.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(ecstore): reuse the pinned replacement mount identity

Capture device, inode, and mount ID when opening the pinned root. Reuse that identity for live endpoint checks and avoid a duplicate lookup when the endpoint is the expected mount root.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(heal): bind replacement intent to the execution lease

Persist the identity of the admitted mounts and keep the live fence immediately before formatting. Compare ordered identity snapshots without allocating on the scan path.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(ecstore): report missing native pool recovery evidence

Distinguish failed proof stages without changing repair admission. Exercise four-node subdirectory replacement below write quorum and after a third survivor returns.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(ecstore): inspect native pool recovery evidence in one pass

Preflight pool slots before disk I/O and use the authenticated Inspect RPC as the capability check. Stop on the first ordered read failure before planning or applying a repair.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:13:48 +08:00
GatewayJ 1df7c9bd15 fix(s3): reject DELETE requests on ACL subresources (#9479)
* fix(s3): reject DELETE requests on ACL subresources

* fix(s3): keep ACL admission within the s3s footprint budget

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:13:39 +08:00
Ramakrishna Chilaka 964afcb0df fix(ecstore): resolve hot-path regressions in io_admission, authority cache, and delete discovery (#9572)
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 04:13:26 +08:00
GatewayJ 8c9fc97ae6 refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS (#9563)
* refactor(rdma): bind the NVIDIA cuObject server SDK in RustFS

* fix(rdma): preserve channel capacity and reuse contiguous registrations

* perf(rdma): transfer ownership of cuObject upload buffers

* fix(rdma): validate cuObject routing fields before transfer

* refactor(rdma): isolate the cuObject server SDK in a sys crate

* docs(rdma): document the workspace cuObject server bindings

* perf(cuobject): reuse channels and completion registrations

* fix(rdma): release eager PUT staging before requesting more chunks

* fix(rdma): consume CQ readiness and copy only retained PUT frames

* fix(rdma): release consumed streaming PUT frames before the next read

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:13:17 +08:00
Hauser Zhi ec8f72b1cf fix(notify): quarantine unreachable targets instead of failing the runtime (#9550)
* fix(notify): quarantine unreachable targets instead of failing the runtime

A target that cannot activate is a per-target health outcome, not a
lifecycle transition failure. Turning it into a transition error left
the generation permanently unconverged, so every notification admin call
re-entered the failing reconcile and answered 500, and the broken target
could not be removed because only the /reset DELETE route existed.

Publish the generation with the failed target quarantined, gate admin
access on the shared runtime_lifecycle_is_published() predicate, and
register the bare DELETE /v3/target/{target_type}/{target_name} route.
The one-shot initialize() API keeps its strict retry contract.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(notify): publish quarantined generations instead of rebuilding forever

is_converged() answered "did every target activate?" but was used as
"does the runtime need rebuilding?". One unreachable target therefore
left the generation permanently unpublished, and the 5s reconciler tore
the whole runtime down and rebuilt it on every tick: 9 full rebuilds
(measured: create + init probe + queue reopen + replay restart + close)
in 30s, which is where the delayed first events after a restart come from.

mark_published now always advances the applied generation and records
per-target completeness separately, so is_converged() means "published".
The reconciler's rebuild trigger and the admin availability gate are
correct with no call-site changes, and runtime_lifecycle_is_published()
is gone again. the one-shot initialize() API keeps its strict contract
through the new all_targets_activated() signal.

prepare_target no longer drops store-less targets whose init failed:
they stay quarantined like store-backed ones, so recovery never needs a
runtime rebuild and PrepareTargetResult::Failed disappears.

Measured on the issue #9545 scenario: 0 rebuilds in the 30s window that
previously saw 9, with the admin surface unchanged.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* style(notify): match the lifecycle module's log field shape

The quarantined-target warning carried its own message where every
sibling entry in this module labels itself "notify runtime lifecycle"
and lets the state field distinguish the outcome. Conforming keeps the
event stream uniform and drops the second copy of the sentence.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* perf(notify): share the dispatch entity and stop dropping rules on read errors

Three findings from a full pass over crates/notify.

The dispatch loop built one EntityTarget per matched target and deep-cloned
the whole Event into each one, plus two Strings. Every field is event-level
and every Target::save reads it without mutation, so build it once and share
it across the matched targets: one Event clone per event instead of one per
target.

get_bucket_rules turned any metadata read error into "no rules", and
rules_for_metadata then evicted the cache, so one transient store error
silently discarded every notification for that bucket. A failed read is not
authority to drop compiled rules; serve the last metadata-backed snapshot
and log it. Entries installed by set_bucket_rules carry no metadata snapshot
and stay unusable once a source is bound, which is the invariant the
store-loss test already pinned.

Cached rules are now shared by Arc instead of cloned per event.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(notify): stop cloning the event and target id on every dispatch

Two remaining per-target costs on the dispatch hot path, both paid on every
event for every matched target.

`Target::name()` is `self.id().to_string()`, which clones the two Strings in
`TargetID` and then formats a third. It was resolved unconditionally and used
only by `debug!` fields, and `target_for_task.id()` was called again at each
log site. Resolve the identifier once per target and hand that value to the
task.

`build_queued_payload` cloned the whole event into `vec![event.data.clone()]`
just so it could be serialized. `PluginEvent: Serialize`, so the record can
borrow: combined with the shared `EntityTarget`, a dispatch to N targets now
deep-clones the event once instead of N+1 times.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(admin): make the operation types as public as the router

`pub mod admin` exports `pub struct S3Router`, but the impl blocks are
bounded by `Operation`, which was `pub(crate)`. That trips
`-D private-bounds` on `--all-targets` and fails the workspace clippy
gate. `AdminRequest` and `AdminResponse` sit in the same position and are
widened alongside it, so the handler trait is nameable at the visibility
its only implementors already live at.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* chore(deps): make hotpath optional where no code uses it

Sixteen crates pulled `hotpath` in unconditionally while their sources
never reference it: it is only there to forward `hotpath`/`hotpath-*`
features. The unconditional edge is what the cargo unused-dependencies
lint reports. Marking the dependency optional keeps the feature
forwarding working and drops the profiling crate from builds that never
enable it.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(notify): share rule target ids and drop the over-broad read fallback

Matching an object key cloned every matched `TargetID` out of the rule
sets, and each of those owns two Strings. The sets now store
`Arc<TargetID>`, so a match collects reference-count bumps instead; the
insertion wraps once. `TargetID: Hash + Eq` and `Arc<T>: Borrow<T>` keep
the lookups unchanged.

This also reverts the earlier "keep the last rules when the metadata read
fails" fallback. `rules_from_metadata` already states the policy:
unreadable metadata is not authority to keep an old subscription, and
`notification_dispatch_follows_peer_reload_delete_and_recreation` pins it
- after `delete_bucket` the lookup fails and the compiled rules must go.
The only errors `get_bucket_metadata` produces are that absence and an
uninitialized metadata system, so the fallback bought nothing and cost
correctness. `rules_for_metadata` is back to the Option form, and
`cached_rules` no longer needs a provenance switch.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-23 04:13:08 +08:00
cxymds 7a294eff86 fix(iam): verify the parent password for Console STS rotations (#9538)
* fix(iam): verify the parent password for Console STS rotations

* fix(iam): revalidate STS sessions during password rotation

* fix(admin): scope test router operation bound to the helper

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:12:59 +08:00
cxymds 1b2615cdb5 fix(replication): recover permanently decommissioned sites (#9491)
* fix(replication): durably decommission unreachable sites

* fix(replication): declare native error macro at removal boundary

* fix(replication): preserve removal state and edit execution context

* fix(replication): use storage boundary aliases in removal tests

* fix(replication): sign local removal probes with the admin session

* fix(admin): scope legacy test helper bounds to the method

* test(connect): stabilize concurrent rotation timeout coverage

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:12:51 +08:00
CCWinston 05446be442 fix(connect): align agent v1 job schema and fail-closed fixture validation (#9487)
* fix(connect): align agent v1 job schema and fail-closed fixture validation

Align the Agent v1 job envelope schema with the Rust runtime constants and
make fixture validation fail closed instead of silently skipping unknown or
unapproved cases.

- Pin drive CPU, memory, output, sample-period and timeout limits to the
  runtime values and require 64-char lowercase hex keyIds plus canonical
  Base64URL encoded Ed25519 signatures and nonces.
- Select the schema for each reject vector from that vector's own base
  instead of always using the first accept-vector schema.
- Fail on schema gaps unless they are explicitly allowlisted, and fail on
  unknown bases, duplicate IDs, invalid pointers and stale allowlist entries.
- Enable jsonschema FormatChecker so date-time values are actually asserted.
- Add Python regression suites, the fixture verifier, the regression runner
  and a GitHub Actions workflow.

Verified with scripts/run_agent_v1_regression.sh:
- 25/25 Python tests pass, 16/16 standalone schema tests pass.
- Fixture manifest: ok=68 bad=0.
- Accept vectors 2/2; reject vectors 10 rejected by schema and 2 approved
  runtime semantic gaps.

* fix(connect): validate JSON Pointer array indices and root manifest coverage

Two fail-closed gaps in the fixture verifier:

- Array tokens were converted with int(), which also accepts "-1" and "01".
  A reject vector such as /items/-1 could invalidate a different element and
  still be reported as rejected. Validate each token against the RFC 6901
  array-index grammar before indexing, including for removal.
- The root manifest was never compared with the fixture sets on disk, so an
  empty or partial root still reported success. Require every fixture set to
  be listed exactly once at the root, and fail on missing, extra or duplicate
  entries.

Add regressions for negative and zero-padded indices, empty root manifests,
unlisted fixture sets and duplicate root entries.

* fix(ci): pin agent protocol workflow actions

* fix(ci): bound the agent protocol regression job

* fix(ci): register the agent protocol validation workflow

---------

Co-authored-by: WinstonCCC <WinstonCCC@users.noreply.github.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 04:12:43 +08:00
Hauser Zhi 3beac86c02 perf(protos): pre-size rename batch canonical body (#9577)
Reserve the exact canonical request size before encoding batch rename fields. This removes geometric Vec growth on both client digest attachment and server verification without changing canonical bytes.

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 04:09:18 +08:00
唐小鸭 8c3cf46acc fix(rio-v2): read encrypted objects back intact through the GET pipe (#9576)
* fix(rio-v2): resume DARE package reads after a mid-ciphertext Pending

DecryptReader reset `ciphertext_read` to zero every time it entered the
ciphertext loop. When the inner reader returned `Pending` partway through
a package, the next poll skipped the already-buffered header and refilled
the ciphertext buffer from its start, overwriting the bytes read before
the `Pending` and shifting the rest of the stream. A single-package object
then ended in "unexpected EOF while reading DARE ciphertext" and a
multi-package object in "DARE authentication failed".

The legacy GET path feeds the decrypt reader from a bounded duplex pipe,
so every rio-v2 encrypted object with a package straddling a point where
the reader outruns the producer failed to read back: stored sizes of
64 KiB + 1 to 128 KiB (64 KiB pipe, smaller than one package), 512 KiB + 1
to 1 MiB (512 KiB pipe), and larger objects whenever the next erasure
block arrived late. Stored data was never affected, so objects written
before this change read back correctly.

Keep the counter across polls: it starts at zero and is cleared only once
a package has been opened. The regression tests cover the reader behind a
pipe that reports `Pending` at each refill, and the GET reader stack
behind the pipe size production picks for inline-range, multi-megabyte,
and multipart objects.

* fix(rio-v2): fail multipart DARE reads that end before a listed part

A multipart DARE stream is the concatenation of each part's package
sequence. When the stream ended exactly on a part boundary, right after a
final-flagged package, DecryptReader had read no package of the next part
and took the clean EOF for an empty object, so a stream missing whole
trailing parts read back as complete. A full-object read was still caught
by the outer length limit, but a ranged read returned a short body without
an error.

The reader could not tell a missing part from an empty one, because an
empty part stores no package. The caller now supplies that distinction:
the multipart constructors document that only parts with stored bytes are
listed, a clean EOF before a listed part's first package is an
`UnexpectedEof`, and the ecstore read path drops zero-size parts from the
list it hands to the rio-v2 reader. An object whose last part is empty
keeps reading back, which the new ecstore test pins down.
2026-11-23 04:09:07 +08:00
Chris An 6988310d21 fix(build): restore static liblzma linking on macOS (#9580) 2026-11-23 03:53:47 +08:00
Chris An 163051a3ba fix(ci): include the scanner handoff test in e2e-full membership (#9581) 2026-11-23 03:53:32 +08:00
Wu Shuwen f75453e123 fix(policy): keep NumericGreaterThanIfExists strictly greater (#9549)
NumericGreaterThanIfExists was evaluated with i64::ge, so a request whose
condition value equals the policy threshold matched. Every other operator
keeps its comparison and only treats key absence as a match, and its
*IfExists variants are built from the generic wrapper; this one special case
silently widened a strict numeric bound into an inclusive one.

Evaluate it with i64::gt to preserve the operator's comparison while keeping
the absent-key behavior.
2026-11-23 03:50:06 +08:00
唐小鸭 2f9c531e59 fix(sse): drop the SSE-S3 header from SSE-C multipart and copy responses (#9575)
* fix(sse): drop the SSE-S3 header from SSE-C multipart responses

CreateMultipartUpload, UploadPart, UploadPartCopy and
CompleteMultipartUpload on an SSE-C upload answered with
`x-amz-server-side-encryption: AES256` next to the customer-key
headers. That header names a managed algorithm, so the response
described an SSE-S3 object.

SSE-C metadata and encryption material record `AES256` as their
server-side-encryption value. PutObject, GetObject and HeadObject
already leave it out of an SSE-C response; the four multipart
projections forwarded it unchanged. They now return only the
customer-algorithm and customer-key-MD5 headers for SSE-C. SSE-S3 and
SSE-KMS multipart responses are unchanged.

* fix(sse): drop the SSE-S3 header from SSE-C CopyObject responses

CopyObject to an SSE-C destination answered with
`x-amz-server-side-encryption: AES256` next to the customer-key
headers, for the same reason the multipart responses did: the SSE-C
material records `AES256` as its server-side-encryption value and the
response forwarded it. It now returns only the customer-algorithm and
customer-key-MD5 headers, as PutObject does. Copies to SSE-S3 and
SSE-KMS destinations are unchanged.
2026-11-23 03:49:56 +08:00
Ramakrishna Chilaka a05a735e36 perf(ecstore): trim open_write, metadata-only read, and part-txn syscalls (#9568)
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-23 03:49:46 +08:00
Pernav Jain 6632490a32 fix(policy): accept S3 lifecycle action aliases (#9467)
* fix(policy): accept S3 lifecycle action aliases

* fix(policy): export standard lifecycle action names

* fix(iam): preserve lifecycle policy storage compatibility

* test(admin): compare STS policy as JSON

* fix(ci): use IPv4 for runtime package setup

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: GatewayJ <835269233@qq.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:49:36 +08:00
cxymds 6256ea500e fix(ilm): continue tier recovery past unreadable objects (#9537)
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:49:24 +08:00
cxymds 40eea75614 fix(admin): report inventory coverage and cluster scanner activity (#9541)
* fix(admin): report inventory coverage and cluster scanner activity

Join the current bucket namespace with measured usage for matching bucket identities. Report the elected scanner coordinator and previous attempt to clients connected to any node, with explicit coverage when measurements are unavailable.

* fix(admin): verify scanner attempts and preserve inventory lookup budgets

Start identity validation after snapshot refresh. Record terminal scanner outcomes at the bounded wait boundary and trust the durable fence for successful completion. Assert that the real leader and followers agree on an active cycle and its completion.

* test(e2e): register the cluster scanner regression in distributed selection

The controlled follower test adds one unconditional case to the 4-node profile. Pin the resulting 111 test IDs so the distributed workflow reaches the test runner on both supported platforms.

---------

Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:49:13 +08:00
GatewayJ 357c308ee1 fix(nixl): bound native transfers and reclaim idle peer registrations (#9542)
* fix(s3): build native RDMA upload bodies for PUT requests

* fix(nixl): reclaim idle peer registrations after native completion

* fix(nixl): start peer idle expiry after the last transfer finishes

* fix(nixl): retain transfer permits and preserve cached peers on failure
2026-11-23 03:49:01 +08:00
Chris An 680f2f9356 fix(server): emit absolute encoded POST Object Location (#9513)
* fix(server): emit absolute encoded POST Object Location

Browser POST uploads with success_action_status=201 currently return a
relative, unencoded Location such as /bucket/a+b c%d.txt. Clients that
decode the field the way AWS formats it treat + as a space.

Rebuild PostResponse Location as an absolute URI from the request host,
scheme, and addressing style, percent-encoding the object key with RFC
3986 path rules (space as %20, slash preserved as a separator).

Fixes #9259

* test: use typo-safe UTF-8 fixtures for POST Object Location

crate-ci typo tokenizes the caf prefix in caf%C3%A9 as a misspelling of
calf. Keep a UTF-8 percent-encoding case, but avoid that false positive.

* fix(s3): preserve entity-like text in POST Object keys
2026-11-23 03:48:49 +08:00
Hauser Zhi 7347770cdf fix(scanner): scan online single drives marked as healing (#9522)
* Initial plan

* fix(scanner): scan online single drives marked as healing

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* fix(scanner): route healing marker through storage boundary

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* perf(scanner): skip unused heal disk inventory

Avoid building and cloning the cross-drive inventory for single-drive scans and scans with healing suppressed. Exercise durable usage publication and cursor advancement through the runtime cycle.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(scanner): use scan domain for test marker import

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

* refactor(scanner): scope heal inventory to coordinator workers

Build the inventory only for coordinator-owned cross-drive healing and expose the regression marker directly through the scan storage domain.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(ci): restore admin gateway runtime checks

Stream diagnostic uploads through the existing admission gate and retain rebalance metadata error diagnostics. Align the authorization regressions with the current implementation and remove the unused POST form test helper.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: houseme <4829346+houseme@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 03:48:38 +08:00
Hauser Zhi 7a0bec3985 fix(ecstore): harden remote rename handling (#9530)
* fix(ecstore): harden remote rename handling

Start a fresh bounded quarantine when a dispatched rename becomes ambiguous so detached disk work cannot be immediately replaced after the RPC deadline. Pre-size inline FileInfo MessagePack buffers from their resident payload to avoid proven growth without changing wire bytes or durability semantics.

Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(ecstore): expose rename quarantine fault metrics

Keep admission timeouts and quarantine lifecycle visible when detailed PUT diagnostics are disabled. Tie released accounting to permit ownership so runtime cancellation cannot leave the active gauge stale.

Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 03:48:24 +08:00
cxymds a2e0d6c997 docs: prompt for auto-testing coverage after issue fixes (#9515)
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-23 03:48:09 +08:00
Hauser Zhi d4a5f8aeb6 fix(ecstore): back off blocked delete recovery per key (#9521)
* fix(ecstore): back off blocked delete recovery per key

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(ecstore): avoid redundant delete recovery inspections

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(ecstore): compact delete recovery decision evidence

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(build): restore Windows and workspace validation

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(test): remove unused POST policy metadata helper

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-23 03:47:49 +08:00
overtrue f1e2b52344 test(admin): sign rebalance status requests with the native signer 2026-11-23 03:23:36 +08:00
overtrue 36d81605ec test(multipart): own method-only completion head and list envelopes
Header-free SSE-C and KMS completion checks build the owned HEAD and list requests, and each assertion stays on the same etag and version.
2026-11-23 03:07:07 +08:00
overtrue 7a13629e37 test(gateway): migrate lifecycle object tests to owned requests 2026-11-23 03:00:25 +08:00
overtrue a0895971cd test(object): own the remaining method-only get and head envelopes
Header-free marker, migration, and write-back reads build the owned request, and each assertion stays on the same response or error.
2026-11-23 02:25:14 +08:00
overtrue 3ac7d5cf4c test(object): own method-only get and head envelopes
Header-free GET and HEAD fixtures build the owned request, and each
assertion stays on the same response or error.
2026-11-23 01:51:04 +08:00
overtrue 38d1714eda test(bucket): own method-only metadata list envelopes
Five header-free listings call the owned metadata entry points, and each
assertion stays on the same error code.
2026-11-23 01:05:10 +08:00
overtrue c700b33bfc test(object): own method-only delete envelopes
Five header-free deletes call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-23 00:58:21 +08:00
overtrue 3b6591a286 test(object): own method-only copy envelopes
Ten header-free copies call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-23 00:43:53 +08:00
overtrue e5035df7a1 test(object): own the remaining method-only put envelopes
Three header-free puts call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-23 00:18:16 +08:00
overtrue 9b6d60e934 test(object): own method-only put envelopes
Twelve header-free puts call the owned entry point, and each assertion stays
on the same output and error code.
2026-11-22 23:45:26 +08:00
overtrue bb94ec983b test(object): own the invalid-storage-class put envelope
The storage-class rejection carries no request headers, so it uses the owned
request and still rejects the class before any store call.
2026-11-22 23:41:23 +08:00
overtrue 6a1b92b783 test(object): own the SSE-C put envelope
The boundary put carries no request headers, so it uses the owned request
and still stores the customer-key object.
2026-11-22 23:05:30 +08:00
唐小鸭 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
overtrue 818a6b6a14 test(multipart): own the retry copy envelope
The copy after the UploadPart permit is released carries no request headers,
so it uses the owned request and still checks the copied bytes.
2026-11-22 22:31:32 +08:00
overtrue 67d306b0de test(multipart): own the unconditional create envelope
The second create in the If-None-Match test carries no request headers, so
it uses the owned request and still requires an upload id.
2026-11-22 21:55:59 +08:00
overtrue a6f881b42d test(multipart): own the KMS upload-part envelope 2026-11-22 21:25:04 +08:00
overtrue dba23c4f55 test(multipart): own the KMS create envelope
The versioned KMS upload is created on the owned request, and the upload id
is still required before the encrypted part is written.
2026-11-22 20:54:59 +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
overtrue 0d17f5f713 test(multipart): own the KMS completion and replay envelope
The versioned KMS completion uses the same owned mapping on both attempts,
and the listing assertions stay in place.
2026-11-22 20:18:13 +08:00
overtrue e09df1f7cd test(multipart): own the other concurrent completion envelope
The second concurrent completion uses the same owned mapping, and exactly
one of the two commits still succeeds.
2026-11-22 19:45:16 +08:00
overtrue c5c65e112e test(multipart): own one concurrent completion envelope
The first concurrent completion still shares the durable quota, so exactly
one of the two commits.
2026-11-22 19:14:04 +08:00
overtrue dfa3d7a2cd test(multipart): own the If-Match completion refusal
A weak or nonmatching If-Match still fails as PreconditionFailed before the
existing object is overwritten.
2026-11-22 18:43:06 +08:00
overtrue 578025149b test(multipart): own the weak If-None-Match completion refusal
A weak If-None-Match ETag on complete is still rejected as unsupported.
2026-11-22 18:10:07 +08:00
overtrue bfc51cf3da test(multipart): own the DTO-only If-None-Match completion refusal
A DTO-only If-None-Match star still fails before the existing object is overwritten.
2026-11-22 17:38:36 +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
overtrue 78b35c3ea8 test(multipart): own the SSE-C completion checksum envelope
Keyless completion still fails before the plaintext checksum is disclosed, and a verified key still completes and replays.
2026-11-22 17:07:38 +08:00
overtrue 33aae31cb7 test(multipart): own the absent-binding completion refusal
An already-aborted upload is still refused before any completion audit is recorded.
2026-11-22 16:37:43 +08:00
overtrue f8924deb68 test(multipart): own the empty-parts completion rejection
The empty parts list is still rejected before the staged part is completed.
2026-11-22 16:07:34 +08:00
overtrue 9e8c426e6f test(multipart): own the staged-part completion envelope
The completion after an empty parts rejection still restores the staged part tag.
2026-11-22 15:43:16 +08:00
overtrue 9815b67c51 test(multipart): build the compressed complete envelope on the owned request
The compressed completion still walks part tags and still records logical
quota usage for the overwrite.
2026-11-22 14:38:02 +08:00
Hauser Zhi 496a34a6a7 chore(deps): drop hotpath shear ignore and refresh workspace deps (#9557)
* chore(shear): stop ignoring hotpath and clear shear findings

Remove hotpath from cargo-shear ignored so feature-only usage is reported,
drop unused deps found by shear --fix, delete empty access_owned stubs, and
suppress false-positive unlinked paths for #[path] test modules.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* chore(deps): refresh workspace deps and bump faster-hex to 2.0

Run cargo update and cargo upgrade for compatible requirements, including
faster-hex 1.0.0 to 2.0.0. Existing hex_string/hex_decode call sites remain
compatible.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(zstd): import seekable directly for security tests

Use zstd_safe::seekable in the security test and document why the
seekable dev-dependency stays: it enables the feature and must remain
visible to cargo-shear as a real usage.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(admin): avoid private-bounds on S3Router test helper

Move call_legacy to a free function so the pub(crate) OwnedOperation
bound is not attached to a public inherent impl.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* chore(deps): drop unused hotpath and demote rio md-5 to dev-deps

Remove hotpath from crates that only feature-forward it with no source
usage, keep rustfs-* hotpath feature links, make rio's hotpath optional
for its cfg-gated measure_block!, and move rio md-5 to dev-dependencies.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* chore(deps): refresh lockfile and bump arrow/jiff requirements

Run cargo update, cargo upgrade, and cargo upgrade --incompatible.
Bump arrow/parquet to 60.2.0 and jiff to 1.0.2.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(scanner): run service_cohort tests on a larger stack

Linux libtest defaults to a 2 MiB test-thread stack; two-pool EC fixtures
overflow it and abort. Run each service_cohort case on a dedicated 32 MiB
thread, matching scoped_entry_fallback.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* chore(deps): upgrade russh-sftp to 4.0 and refresh lockfile

Run cargo update, cargo upgrade, and cargo upgrade --incompatible.
Bump russh-sftp 3 to 4 (opaque SftpHandle wire type), plus lapin,
hashbrown, and russh. Adapt the SFTP Handler and tests to SftpHandle.

Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: RustFS <hello@rustfs.com>
2026-11-22 14:36:14 +08:00
overtrue 7c9ebadffe test(multipart): build the out-of-order complete envelope on the owned request
The out-of-order parts still go through the adapter's tag walk and still
fail as InvalidPartOrder.
2026-11-22 14:06:06 +08:00
overtrue e376e7d774 test(multipart): build the duplicate-part complete envelope on the owned request
The duplicate part numbers still go through the adapter's tag walk and still
must not fail as InvalidPartOrder.
2026-11-22 13:37:27 +08:00
overtrue d211df88d5 test(multipart): build the missing-parts-list complete envelope on the owned request
The empty CompleteMultipartUpload element still follows the adapter's Some branch
and checks InvalidRequest.
2026-11-22 13:08:17 +08:00
overtrue 21caf8bf34 test(multipart): build the missing-parts complete envelope on the owned request
The fixture has no multipart upload, so it follows the adapter's None branch
and still checks InvalidPart.
2026-11-22 12:32:41 +08:00
overtrue d3eaaa21a6 test(multipart): build the range copy envelope on the owned request
The range path still maps the copy DTO the same way as the adapter and checks
EntityTooLarge, permit release, and the copied bytes.
2026-11-22 11:57:28 +08:00
overtrue ad457a2d1c test(multipart): build the cancelled copy envelope on the owned request
The cancellation path still maps the copy DTO the same way as the adapter
and still panics if the copy finishes before cancellation.
2026-11-22 11:25:09 +08:00
overtrue fa3ea5b4e5 test(multipart): build the deleted-source copy envelope on the owned request
The deleted-source rejection still maps the copy DTO the same way as the adapter
and checks NoSuchKey or MethodNotAllowed on the owned error.
2026-11-22 10:50:06 +08:00
overtrue f3396952b6 test(multipart): build the saturated copy envelope on the owned request
The occupied UploadPart pool still maps the copy DTO the same way as the adapter
and checks SlowDown on the owned error.
2026-11-22 10:23:10 +08:00
overtrue 8736b49d08 test(multipart): build the uninitialized copy envelope on the owned request
The uninitialized-store rejection still maps the copy DTO the same way as the adapter
and checks InternalError on the owned error.
2026-11-22 09:47:55 +08:00
overtrue eec468e488 test(multipart): build the admission upload envelope on the owned request. 2026-11-22 09:10:40 +08:00
overtrue f2af45ee68 test(multipart): build the invalid-storage-class create envelope on the owned request
The storage-class rejection still converts the create DTO separately
and checks InvalidStorageClass on the legacy error.
2026-11-22 08:33:58 +08:00
overtrue 25b55febc5 test(multipart): build the part-copy part-number envelope on the owned request
The part-number rejection still maps the copy DTO the same way as the adapter
and checks InvalidArgument with the same message.
2026-11-22 08:05:27 +08:00
overtrue c2e50b3b10 test(multipart): build the part-number upload envelope on the owned request
The part-number rejection still converts the upload DTO separately
and checks InvalidArgument with the same message.
2026-11-22 07:36:17 +08:00
overtrue 6fde592da1 test(multipart): build the oversize upload envelope on the owned request
The declared-size rejection still converts the upload DTO separately
and checks EntityTooLarge without polling the body.
2026-11-22 07:03:43 +08:00
overtrue 98259d7c46 test(multipart): build the missing-body upload envelope on the owned request
The missing-body rejection still converts the upload DTO separately
and checks IncompleteBody on the legacy error.
2026-11-22 06:35:22 +08:00
overtrue b5a35fc2c7 test(multipart): build the baseline create envelope on the owned request
The direct fixture still converts the create DTO separately and checks
the legacy error code and message.
2026-11-22 06:06:39 +08:00
overtrue 11a7572bba test(multipart): build the reserved-key complete envelope on the owned request
The reserved-key complete rejection still converts the DTO through the seam
and checks InvalidArgument on the owned error.
2026-11-22 05:37:37 +08:00
overtrue 4c4dc84671 test(multipart): build the reserved-key create envelope on the owned request
The reserved-key rejection still converts the create DTO separately
and checks InvalidArgument on the legacy error.
2026-11-22 05:06:23 +08:00
overtrue 52986eefd5 test(bucket): build the list-v1 envelope on the owned request
The XML-safe marker listing still converts ListObjectsInput separately
and keeps the same GET envelope with an empty head.
2026-11-22 04:25:57 +08:00
overtrue 7a5ffcfee7 test(multipart): build the complete listing envelopes on the owned request
The version and V1 listing checks build method-only envelopes with owned_envelope.
The DTOs still carry the bucket and prefix, and the V2 seam stays.
2026-11-22 03:55:16 +08:00
overtrue 334d615a67 test(bucket): build the encryption lookup envelopes on the owned request
The uninitialized encryption test builds its method-only envelopes with owned_envelope.
The InternalError and MalformedXML assertions stay.
2026-11-22 03:26:14 +08:00
overtrue 0c813e1a9e test(bucket): build the core uninitialized envelopes on the owned request
The no-req_info envelope is built with owned_envelope.
The arm that carries req_info still goes through from_s3s.
2026-11-22 02:50:05 +08:00
overtrue 0de0b85374 test(lifecycle): build the object-lock envelope on the owned request
The object-lock replication test builds its method-only envelope with from_parts.
The existing ignore attribute and the replication-count assertions stay.
2026-11-22 02:23:15 +08:00
overtrue 78f78ce5ee test(multipart): build the complete setup envelopes on the owned request
The versioning and encryption setup calls build method-only envelopes with owned_envelope.
The requests that carry a body still use build_request.
2026-11-22 01:54:13 +08:00
overtrue 82ad3f0007 test(object): build the attributes lookup envelope on the owned request
The uninitialized-store attributes test builds its method-only envelope with from_parts.
The InternalError assertion is unchanged.
2026-11-22 01:25:00 +08:00
overtrue 82f094f4d5 test(lifecycle): build the suspend-versioning envelope on the owned request
The suspended-bucket helper builds its method-only envelope with from_parts.
The restore call that carries a body still uses build_request.
2026-11-22 00:50:23 +08:00
overtrue e1df1d569b test(multipart): build the upload-part claim envelopes on the owned request
The two method-only upload-part claim tests build their envelopes with owned_envelope.
Every refusal assertion stays.
2026-11-22 00:21:35 +08:00
overtrue 19487a6e34 test(multipart): build the list-parts envelope on the owned request
The list-parts owner lookup builds its method-only envelope with owned_envelope.
The later requests that set a URI still go through from_s3s.
2026-11-21 23:50:20 +08:00
overtrue 6177fc280f test(bucket): build the website lookup envelopes on the owned request 2026-11-21 23:19:40 +08:00
overtrue 14db51bba7 test(bucket): build the logging lookup envelope on the owned request
The missing-bucket logging lookup builds its envelope with owned_envelope.
The NoSuchBucket assertion stays.
2026-11-21 22:48:38 +08:00
overtrue 353de54fcc test(bucket): build the missing-lifecycle envelope on the owned request 2026-11-21 22:14:58 +08:00
overtrue 6a4f93bbaf test(bucket): build the tagging envelope on the owned request 2026-11-21 21:40:20 +08:00
overtrue 74fab85ba0 test(bucket): build the list-buckets envelope on the owned request 2026-11-21 21:00:03 +08:00
overtrue 44db2be5f9 test(multipart): build the abort envelope on the owned request 2026-11-21 20:25:10 +08:00
overtrue 3e41233589 test(multipart): build list envelopes on the owned request 2026-11-21 19:50:10 +08:00
overtrue f36a771389 test(bucket): build policy envelopes on the owned request 2026-11-21 19:04:31 +08:00
overtrue 0447e68073 test(bucket): build method-only envelopes on the owned request 2026-11-21 18:31:08 +08:00
overtrue 94dbca3840 test(object): build put envelopes on the owned request 2026-11-21 17:46:04 +08:00
overtrue d2939fb43b refactor(rpc): use owned empty bodies in RPC fallbacks 2026-11-21 17:15:08 +08:00
overtrue 9f7d1aa706 refactor(site-replication): return the owned repair response 2026-11-21 16:44:57 +08:00
overtrue 98675ddcbd refactor(storage): return the owned owner and initiator
List metadata and multipart tests copy id and display name into the legacy shapes. The owner helper no longer imports s3s.
2026-11-21 16:00:14 +08:00
overtrue 357e78c523 test(admin): build runtime-context probes on the owned envelope
The router production path is unchanged. A test-only caller builds the empty request.
2026-11-21 15:02:19 +08:00
overtrue 411caa97d7 test(storage): build object-lock helpers on the owned types
The fixtures keep the same Enabled, COMPLIANCE, GOVERNANCE, ON, and OFF spellings.
2026-11-21 14:22:24 +08:00
overtrue 317e895096 test(admin): pin the lifecycle staleness axis to the fixture instant
ExpiryUpdatedAt stays 2026-07-07T15:58:57.337315Z, the text in the fixture.
2026-11-21 13:40:35 +08:00
overtrue 7c55e265dd test(object): pin get-object condition answers to the legacy reader
The accepted and rejected header values are the answers of s3s 5761ddfe.
2026-11-21 13:07:23 +08:00
overtrue f858a65f41 refactor(bucket): serialize admission errors through the owned type
The admission test still checks the status, the retry header, and the body.
2026-11-21 12:32:03 +08:00
overtrue f96c324734 refactor(s3-types): serialize select errors through the owned type 2026-11-21 11:55:10 +08:00
overtrue 7e5b3e4137 refactor(object-meta): serialize retention dates on the owned timestamp 2026-11-21 10:55:08 +08:00
overtrue c749351780 refactor(storage): own the SSE header names
The response headers keep the same names. The anonymous KMS test builds
an owned request, and the missing-key test still asserts BAD_REQUEST.
2026-11-21 10:03:04 +08:00
Chris An 2381096448 fix(scanner): preserve restart progress and background admission (#9341)
* fix(scanner): retain unpublished bucket progress across leader changes

* test(scanner): verify remote completion reuse and publication floors

* fix(scanner): persist read-only checkpoint continuity

* test(scanner): avoid cloning the final activity fixture

* fix(scanner): resolve receipt owner before store startup

* fix(scanner): gate read-only handoff behind reader-first rollout

* test(scanner): accept consumed markers after heal startup

* test(scanner): run handoff rollback in the pinned release lane

* fix(scanner): preserve background admission during cache saves

* fix(scanner): admit remote cache publications as background I/O

* fix: handle disabled cgroup controllers in resource sampling

* fix(scanner): wait for namespace RPC preflight admission

* fix(scanner): align metric loops with current clippy

* fix: resolve Rust 1.100 workspace lint diagnostics

* fix(heal): simplify Linux test opt-in check

* chore(scanner): expose admission and allocator diagnostics

* fix(scanner): retry transient resource samples within one bracket

* fix(protos): retain cancelled RPC streams during response grace

* feat(diagnostics): track live Rust allocation bytes

* docs(diagnostics): explain unsafe allocator test scope

* fix(ecstore): reduce multipart recovery stack usage

* chore: refresh PR verification

* fix(protos): retain reset streams for the full cancelled burst

The branch's channel reset tests cancel 80 batches of 64 streams; main's 4096 cap spends the protocol-error budget on that burst, so keep the 8192 capacity under main's constant.

* fix(scanner): complete budget-stopped cycles with carried buckets pending

Align with main's partial-carry semantics: a work budget that stops a bucket whose certified value is carried completes the cycle with that bucket pending and the snapshot unconverged, instead of forcing the cycle incomplete.
2026-11-21 09:12:23 +08:00
Chris An 99a1803773 test(ci): fix storage fixture races (#9547)
* test(ci): make storage fixtures wait for their prerequisites

* test(ci): allow equal timestamps for parallel scanner probes
2026-11-21 09:11:53 +08:00
overtrue 5132be9c01 refactor(admin): serve the admin content-type header from http. 2026-11-21 09:05:08 +08:00
overtrue 13399d98fa refactor(s3-types): stop naming s3s in the region panic text
The region conversions and the oracle tests are unchanged. The footprint
counter was matching that name in the panic string.
2026-11-21 09:05:08 +08:00
overtrue ee3880ee84 refactor(restore): call the owned restore path from error tests
The error-code tests build the envelope and the lifecycle restore
request directly. The legacy test wrapper stays for the transition
fixtures that still call it.
2026-11-21 09:05:08 +08:00
overtrue af48bb8539 refactor(admin): drop the legacy body limit arm
Owned handlers already pass the RustFS body. The over-limit, exact-limit,
and transport-error checks stay on that body.
2026-11-21 09:05:08 +08:00
overtrue 850d7a2beb refactor(select): project gateway select fixtures without s3s
The engine projection tests build the gateway request directly.
The test-only s3s conversion is gone, and the member assertions stay
on the projection the use case calls.
2026-11-21 09:05:08 +08:00
overtrue 1acf30910f refactor(admin): build table-catalog tests on the owned request
The handler tests no longer construct an s3s request and convert it.
Region copying from a legacy request stays covered by
from_s3s_copies_every_named_extension. S3Request is gone from
rustfs/src/admin/handlers, and the s3s file count drops from 33 to 32.
2026-11-21 09:05:08 +08:00
Hauser Zhi 26757d5d5e fix(s3): clarify SlowDownRead and trim GET preflight buffering (#9524)
* fix(s3): clarify the SlowDownRead message

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(s3): size the primed GET chunk to one byte

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(rdma): return native upload request bodies

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-20 22:15:06 +00:00
Hauser Zhi d69742b1e1 test(rustfs): restore main verification after gateway migration (#9528)
* test(rustfs): restore main verification after gateway migration

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* test(object-lock): pass the ILM fixture context to metadata writes

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* test(heal): isolate retained delete proofs from recovery workers

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-20 23:48:38 +08:00
overtrue b86624520c test(connect): use the normal heartbeat schedule for a single replay 2026-11-20 17:56:49 +08:00
overtrue 489143b9cf fix(rebalance): exclude suspended pools from the capacity goal 2026-11-20 17:15:46 +08:00
overtrue e37aa27e40 fix(test): encode rollback digests with the workspace hex encoder 2026-11-20 14:54:34 +08:00
overtrue 6e417a458e test(upgrade): exercise the official 1.0.5 gateway baseline 2026-11-20 14:50:43 +08:00
overtrue 60ed7f1c40 test(upgrade): select mixed storage contracts by source revision 2026-11-20 14:32:11 +08:00
overtrue 7f2bd6b99b test(protocols): match the released error for a missing directory marker 2026-11-20 14:23:19 +08:00
overtrue a798df7906 refactor(protocols): prepare part copy routing and storage from one upload ID 2026-11-20 14:23:19 +08:00
overtrue 793632c0da docs(operations): document rollback after the S3 stack switch 2026-11-20 14:23:18 +08:00
overtrue 301133c1c8 test(gateway): check the release torrent error for boundary keys 2026-11-20 14:23:18 +08:00
overtrue a642ba2a89 chore(ci): tighten the s3s import limit to 33 files 2026-11-20 13:04:07 +08:00
overtrue d893d70b2e refactor(storage): return native errors from S3 storage helpers 2026-11-20 13:03:42 +08:00
overtrue cf15e4d1b6 refactor(http): verify control body checksums with the native hashers 2026-11-20 12:35:23 +08:00
overtrue 5a3e94bbbb chore(ci): ratchet the remaining s3s imports to 34 files 2026-11-20 12:21:40 +08:00
overtrue 29b389bf80 refactor(errors): keep API error codes native through storage handling 2026-11-20 12:21:15 +08:00
overtrue f94e8cae07 refactor(storage): use native listing and object lock inputs 2026-11-20 12:17:42 +08:00
overtrue 64675785fe refactor(bucket): return native S3 errors from admission and config writes 2026-11-20 12:01:48 +08:00
overtrue 5b703b61f9 test(ci): align storage guard fixtures with the surviving helper rule 2026-11-20 12:00:53 +08:00
overtrue 23420e357d refactor(multipart): use native S3 errors for upload validation and storage failures 2026-11-20 11:43:15 +08:00
overtrue 9da1edd8d6 test(e2e): compare complete persisted version maps 2026-11-20 11:39:25 +08:00
overtrue d87c058a4d fix(protocols): audit multipart uploads exactly once 2026-11-20 11:12:35 +08:00
overtrue 54cda17e58 refactor(storage): publish internal write events without legacy S3 responses 2026-11-20 11:12:35 +08:00
overtrue 49f6e815e7 refactor(multipart): retire legacy request envelopes from production 2026-11-20 11:12:35 +08:00
overtrue 58bbb17300 fix(gateway): preserve the missing torrent response for invalid keys 2026-11-20 11:01:04 +08:00
overtrue 310b977f05 test(e2e): compare release and candidate persistence bytes 2026-11-20 10:36:43 +08:00
overtrue bbe396219f refactor(storage): validate tags and website settings with native S3 types 2026-11-20 10:33:22 +08:00
overtrue e286691371 test(admin): exercise health and heal on the native router 2026-11-20 10:32:58 +08:00
overtrue 9ff399afee test(scanner): freeze legacy cache compatibility fixtures 2026-11-20 10:23:41 +08:00
overtrue 23c8c35710 refactor(storage): use native listing errors and write preconditions 2026-11-20 10:08:44 +08:00
Chris An 9c44c5ea6b refactor(admin): serve Object Lambda through native GetObject (#9529)
* test(storage): restore POST form metadata policy fixture

* test(storage): follow the current PUT path in contract checks

* fix(storage): verify archive transport EOF before parsing the final frame

* test(rustfs): restore main verification after gateway migration

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* refactor(storage): retire the legacy S3 storage edge

* fix(storage): bound the audited multipart copy future and trace LIST quorum causes

* test(storage): pin legacy codec answers and trim test dependencies

* refactor(admin): confine the legacy route adapter to parity tests

* fix(deps): align bindgen and prettyplease on syn 3 for FIPS builds

* refactor(admin): keep Object Lambda authorization and responses on the owned request path

* fix(storage): expose the typed legacy cause on owned errors

* refactor(admin): read and return native GetObject fields for Object Lambda

* ci: ratchet the legacy S3 footprint after the control-plane migration

* refactor(admin): remove the unused envelope-to-extensions adapter

* test(admin): guard the Object Lambda response token checks at their definition

* refactor(admin): serialize AssumeRole credentials without the legacy DTO

* test(admin): assert native range and error types at the test boundary

* test(admin): compare errors in the legacy route parity tests

* refactor(notify): initialize event rules from persisted notification types

* refactor(admin): return the idle rebalance response on the owned HTTP path

* refactor(storage): keep the persisted-to-legacy XML oracle in tests

* test(admin): compare extension refusals using the native error code

* fix(obs): filter verbose native gateway protocol events at every sink

* test(storage): preserve stream lengths and request facts on retired seams

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-20 10:08:35 +08:00
Chris An 31e0798637 refactor(storage): retire the legacy S3 storage edge (#9527)
* test(storage): restore POST form metadata policy fixture

* test(storage): follow the current PUT path in contract checks

* fix(storage): verify archive transport EOF before parsing the final frame

* test(rustfs): restore main verification after gateway migration

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* refactor(storage): retire the legacy S3 storage edge

* fix(storage): bound the audited multipart copy future and trace LIST quorum causes

* fix(deps): align bindgen and prettyplease on syn 3 for FIPS builds

* fix(storage): expose the typed legacy cause on owned errors

* test(storage): preserve stream lengths and request facts on retired seams

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-20 10:07:52 +08:00
Chris An 868af666e9 fix(storage): preserve archive errors and restore gateway CI checks (#9525)
* test(storage): restore POST form metadata policy fixture

* test(storage): follow the current PUT path in contract checks

* fix(storage): verify archive transport EOF before parsing the final frame

* test(rustfs): restore main verification after gateway migration

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(deps): align bindgen and prettyplease on syn 3 for FIPS builds

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-20 10:05:46 +08:00
Ramakrishna Chilaka 93ddf83ee1 perf(ecstore): trim redundant syscalls in multipart part preparation (#9498)
* perf(ecstore): trim redundant syscalls in multipart part preparation

Use io_get_object_open_path in the advisory clean-source cache probe, reuse validated part-path prefixes when constructing MultipartSourceAdmission in prepare_part_transaction, and create new.meta before snapshotting absent old-part markers so old.data.absent and old.meta.absent share new.meta's inode via linkat.

* test(ecstore): guard marker inode identity check on hardlink support

Probe hardlink support in the test fixture before asserting that old.data.absent and old.meta.absent share new.meta's inode, and assert empty fallback markers when hardlinking is unsupported.

* chore(storage): remove unused test helper PostObjectFormPolicy::with_metadata

Commit 5e5554987 removed the last caller in rustfs/src/storage/access.rs, leaving with_metadata unused under #[cfg(test)].

* fix(rustfs): align control-plane speedtest, rebalance logging, and admin/auth tests

Register streaming PostV3SpeedtestClientDevnull on the gateway control-plane host, log error diagnostics on corrupt rebalance metadata loads, avoid 43-char OIDC parent key collisions in s3_extension_tests, align AddUser gate test with 88b90c131, and split auth.rs at mod tests.

* chore(deps): bump rustfs-gateway to d32f1721 for Windows file-fallback cfg

Pulls in rustfs/gateway#1622 (d32f17219d75989167a05183dd3d04922615cbd5) which gates Unix-only file-region adaptation in rustfs-gateway so Windows Startup Smoke compiles cleanly.

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-20 06:47:35 +08:00
overtrue fbe3d1c9c8 test(app): add owned test seams and route authorize_head_object through storage_api 2026-11-20 06:05:13 +08:00
overtrue 6bec9362b1 test(storage): delete the legacy access tests the owned core now covers
The tests module of storage/access.rs, its mounted reader and probe
tests, and the signed-query regression module are gone; their ported
copies run on the owned core. The five registered tests are deleted with
their register entries. access.rs keeps the hooks, the parity support
other modules still use, and four pins on legacy-only helpers that no
gateway-side test pins yet.
2026-11-20 05:23:54 +08:00
overtrue e237d268ac test(storage): port the legacy access tests onto the owned authorization core
Each authorization test of storage/access.rs and its mounted files now
runs on the owned RequestEnvelope through the owned function its legacy
hook delegated to, with the same inputs and expected decisions. A shared
owned fixture replaces build_request and TestKms. The four access_owned
test files move under access_owned/tests and no longer build an s3s
request. Five tests that pin only legacy DTO helpers are registered for
retirement with their gateway-side replacements.
2026-11-20 05:23:40 +08:00
overtrue a52b51b764 refactor(app): drop s3s entrypoints and move test seams to owned types 2026-11-20 05:23:37 +08:00
overtrue e62c6112ea chore(ci): lower the s3s footprint ceilings to the measured values
files 50 -> 49 and s3_error_lines 103 -> 95, as scripts/check_s3s_footprint.sh
measures them after the upload drain tests stopped implementing an s3s
S3 service.
2026-11-20 05:23:37 +08:00
Hauser Zhi 88b90c1315 fix(obs): use seconds-scale buckets for HTTP durations (#9504)
* fix(obs): use seconds-scale buckets for HTTP durations

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(obs): reduce HTTP duration histogram bucket overhead

Keep the 2–3 ms interval and long-stream range with 16 finite bounds.
Match the three instrument names directly in the existing view.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix: restore authorization and storage test invariants

Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(notify): keep rule engine storage calls behind boundary

Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix: satisfy current CI architecture and clippy guards

Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Signed-off-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-19 18:53:11 +08:00
Hauser Zhi ec8dc7d1ca fix(http): send deferred HTTP/2 100 Continue (#9463)
* fix(http): send deferred HTTP/2 100 Continue

Backport upstream Expect handling onto Hyper 1.12.0 and cover the transport handshake and rejection boundaries.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* test(http): use uppercase Expect token in fixture

Preserve case-insensitive Expect coverage without triggering the spelling guard.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* perf(http): compact deferred Continue body state

Preserve the existing body size bound and H2 frame path while removing redundant state from the temporary Expect allocation. Cover spawned readers, size hints, trailers, and EOF.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* refactor(http): align Continue backport with upstream

Remove the local body-layout micro-optimization so the runtime patch exactly matches upstream Hyper PR #4217 while retaining RustFS regression coverage.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(storage): keep authorization tag lookup in infra

Move the store-backed ExistingObjectTag lookup behind the authorization core and keep legacy error conversion at the FS interface boundary.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(tests): align CI fixtures with current contracts

Distinguish AddUser primary and secondary admin gates, parse SigV4 civil time in UTC, and provide the required Object Lock snapshot for restore metadata copies.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: houseme <4829346+houseme@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-11-19 18:50:01 +08:00
Sébastien Bocahu 5e55549873 fix(ecstore): do not republish pool.bin for an unreachable drive (#9481)
* fix(ecstore): do not republish pool.bin for an unreachable drive

The pool.bin heal treated every drive whose state was not "ok" as a drive
to repair, offline and faulty drives included. A write cannot reach those
drives: while one was unreachable, each read repair republished pool.bin
to the reachable drives only, failed with SystemMetadataRepairRequired and
was retried, writing a new version every time. The drive came back one
version behind, while every node reported it ready.

In a set of three drives at EC:1, losing another drive in that window
left one current and one stale replica: pool.bin had no read quorum, the
node with the replaced drive could not start, and neither could any other
node that restarted.

Repair pool.bin only for a reachable drive that lacks the current copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ecstore): require replica damage before pool metadata heal

A timed-out or otherwise inconclusive metadata probe can leave a valid
pool.bin replica behind. Require confirmed missing, stale, or corrupt
metadata before publishing a new generation through the existing fence.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* style(admin): remove trailing whitespace in identity test

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(rustfs): restore gateway builds and clear CI lints

Backport 142cff57a and 2e286d322 from main. Reuse the admitted
request headers for POST archive controls and return the existing
S3 error type directly at both call sites.

Remove the unused form metadata projection left by the same merge
and keep the gateway policy test on the production field path.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Signed-off-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-19 18:49:24 +08:00
overtrue 55be4e3f79 fix(notify): route rule engine storage imports through the storage_api boundary 2026-11-19 17:34:58 +08:00
overtrue 5be4ef65e8 test(table-catalog): issue ordinary temporary credentials through the parent-bound path
Regular parents now fence STS sessions by durable generation, so a session
stored without one is rejected as an unknown key. Publish the test sessions
with set_temp_user_from_parent, as the STS handler does.
2026-11-19 16:59:19 +08:00
overtrue 24f3e783c2 fix(server): keep Connection off HTTP/2 answers and test the upload drain on the gateway stack
The three UploadPart timeout tests drove the early-response drain around
a hand-written s3s S3 service. They now drive it around the gateway
stack as production configures it (GatewayStack::assemble_serving, a
test-only constructor over the same configured builder), serving an
UploadPart handler that reads its whole body as RustFS's handler does.
Every assertion is kept: 400 RequestTimeout, the HTTP/1 transport
retained for the drain and drained of the late bytes, the HTTP/2 body
dropped alone, and other HTTP/2 and HTTP/3 streams still served.

The gateway times a stalled body out with its own request-body idle
bound, so that bound is what the fixture sets; it does not follow a
paused tokio clock, so the HTTP/1-and-HTTP/2 case runs in real time
(200 ms bound) instead of advancing a paused clock.

Kept as written, the HTTP/2 assertion failed: GatewayStack::call added
`Connection: close` to any answer whose connection intent is to close,
HTTP/2 included, where the header is forbidden and only the stream
ends. It is now added to HTTP/1 answers only.
2026-11-19 16:15:49 +08:00
overtrue 583df55d90 test(server): name the metadata route table case type for clippy 2026-11-19 16:15:49 +08:00
overtrue 670ae01f7a test(server): restore website, metadata listing and table isolation coverage on the gateway stack
The retired legacy metadata route carried the website-host and metadata=true listing case tables, and a test that its authorization attaches the table listing snapshot. Re-create both against the gateway stack, observing the listing a caller receives, and probe the native admin and control-plane hosts for the unsigned x-amz header refusal.
2026-11-19 16:15:49 +08:00
overtrue 3a1f0c09b3 fix(server): let the owned early-response drain take bodies the gateway leaves unread
The gateway stack was called through rustfs-gateway's tower adapter. Under the RustFS profile
that adapter wraps the request body, takes it back when the handler drops it unread, and reads
it in a task of its own spawned on the ambient runtime (unread_body.rs, Retention::settle). That
task took the body away from EarlyResponseBodyService before its abandon slot could see it, so
RustFS's own drain never ran: its task was no longer spawned under the HTTP/1-2 task owner,
graceful shutdown could report its children retired while a detached drain still held the
transport body, and the early-response drain metric and log went silent. On origin/main the
legacy stack was the default assembly, so the listener test never crossed the adapter.

GatewayStack::call now calls the service's own entry and keeps the adapter's connection
verdict (connection_intent_of). The inert drain_unread_request_bodies setting is removed.
EarlyResponseBodyService is again the only HTTP/1 unread-body drain, with Connection: close
and the configured idle bound.

The gateway-stack test that asserted the adapter's drain timeout now asserts that the stack
releases an unread body when it answers. The configured-timeout half moves to
gateway_rejected_http1_body_uses_the_configured_drain_timeout, which composes
EarlyResponseBodyService over the real gateway stack for a 1 s and a zero timeout.

Mutation: restoring the adapter call turns all three red:
http12_actual_early_body_drain_is_owned_until_release (the drain never starts),
rejected_http1_body_is_released_to_the_host_drain and
gateway_rejected_http1_body_uses_the_configured_drain_timeout.
2026-11-19 16:15:49 +08:00
overtrue eed50fc5ff test(e2e): run the differential against the only stack
Neither side of dual_stack_differential is started with the retired
stack selector any more, which the binary under test now refuses: both
sides run the binary under test, or side A runs the released reference
binary named by RUSTFS_E2E_REFERENCE_BINARY. RUSTFS_E2E_STACK_B is
gone; the injected-region control is unchanged.
2026-11-19 16:15:49 +08:00
overtrue e462fafb65 docs: describe the gateway stack as the only S3 stack in the CI gates and the changelog 2026-11-19 16:15:49 +08:00
overtrue 9c0bc265c3 ci: drop RUSTFS_S3_STACK from reference parity, nextest notes and the connect boundary guard 2026-11-19 16:15:49 +08:00
overtrue 74bf3ca5fa ci(nightly): run the dual-stack nightly on the gateway stack and archive the both-stack scripts 2026-11-19 16:15:49 +08:00
overtrue 31c4f4a7ff ci(acceptance): judge one server and drop the legacy reference run and the stack diff 2026-11-19 16:15:48 +08:00
overtrue 3fb8d861f0 ci(e2e): run the distributed, replication and migration-interop lanes on one stack 2026-11-19 16:15:48 +08:00
overtrue 4b386794e1 ci(mint): run one server on the gateway stack and drop the stack comparison 2026-11-19 16:15:48 +08:00
overtrue 23a2593aac ci: fold the gateway-stack lanes into the main lint, test and e2e jobs 2026-11-19 16:15:48 +08:00
overtrue 7b1befa6f9 chore(ci): shrink the s3s footprint to what the gateway-only stack keeps
server/layer.rs and server/hybrid.rs no longer reference s3s and leave
the edge allowlist; the baseline ceilings drop to the measured values
(files 50, s3_error! lines 103).
2026-11-19 16:15:48 +08:00
overtrue 2f3359df69 refactor(server): delete the five s3s patch layers the gateway stack replaces
SigV4HeaderGuard, S3ErrorMessageCompat, DoubleSlashListBucketsCompat,
VirtualHostStyleHint and ObjectAttributesEtagFix patched the s3s edge
and have no work left: the gateway_stack legacy_layers tests pin what
each made the legacy stack answer against the gateway stack alone. The
layer unit tests go with the layers, and the server-domain flag that
only gated VirtualHostStyleHint goes with it.

EmptyBodyContentLengthCompat keeps its admin, console and internode
halves and loses its S3 half, which the gateway stack replaces by
leaving the bodies of bodyless operations unread; its S3 tests now
assert that such requests pass through unchanged.
2026-11-19 16:15:48 +08:00
overtrue ea522c18b6 refactor(server): serve the outer tower stack with an owned body and error type
The S3 service under the middleware now answers in EdgeBody, a boxed
Bytes body, with a boxed error, instead of s3s::Body and
s3s::HttpError. The gateway stack, the native console and the refusals
written in server/http.rs meet in that one type; Swift and the
internode RPC lane convert into it from rustfs_s3_types::Body.
ControlBodyDigestService is generic over its inner response body, and
its control-plane XML body limit is a named constant equal to the limit
the s3s edge applied.
2026-11-19 16:15:48 +08:00
overtrue 9f13eb22a5 refactor(server)!: make the gateway stack the only S3 stack
Remove the S3Stack selector, the legacy s3s service assembly and the
gateway-stack cargo feature: the gateway stack, its native admin and
console hosts and the control-plane host are always assembled, and the
gateway crates are ordinary dependencies. The debug-only compile_error
guard goes with the feature.

RUSTFS_S3_STACK is retired: a server or an embedded server started with
it set, to any value including gateway or an empty string, refuses to
start with an error naming the variable and this release. The message
and its tests share one constant.

Tests that ran only on the legacy stack, or selected between stacks,
are retired; tests that ran on both now run on the gateway stack alone.
The s3s metadata/website route is no longer mounted and stays only
until the metadata-route branch replaces it.
2026-11-19 16:15:48 +08:00
overtrue fec2d4bb4b test: register the legacy-stack tests the gateway flip retires
Each entry names a legacy-only test, or the unit test of an s3s patch
layer, that the flip deletes, with the gateway-stack test that keeps
its contract (rustfs/backlog#2783). The commits that delete them delete
their entries.
2026-11-19 16:15:47 +08:00
overtrue 42a1417ed0 fix(notify): bind dispatch rules to bucket metadata snapshots 2026-11-19 10:15:02 +08:00
overtrue a3d6b59d03 feat(server): answer website hosts on the gateway stack before S3 routing
The gateway selection gains a website service, chosen by its host claim
before the Keystone refusal, the native console, the native admin and the
control plane, as the legacy metadata route claims those requests first.
A parity test sends both request classes to both stacks over one store.
2026-11-19 07:44:46 +08:00
overtrue 924eb06968 feat(gateway): serve metadata=true listings on the gateway stack
Install the RustFS dialect rows of ListObjectsV2WithMetadata and
ListObjectVersionsWithMetadata on the S3 table, let the early gate allow
them, and register one handler that runs the shared access phase, the
listing authorization and the shared listing answer. The rows keep their
overlaps with the standard listings and each other; the admin extension
rows they also shadow live on the control-plane host.
2026-11-19 07:44:46 +08:00
overtrue 5a44944095 refactor(app): serve website hosts and metadata listings through owned modules
The legacy MetadataRoute now hands website requests to an owned WebsiteHost,
which reads through the owned GetObject/HeadObject authorization and use
cases with an anonymous request envelope, and hands metadata=true listings
to an owned module that authorizes and answers them on the request envelope.
The WebsiteRead marker moves with the website rules.
2026-11-19 07:44:45 +08:00
overtrue 8541ab829a perf(gateway): attribute the owned PutObject path in hotpath profiles
The gateway PutObject path carried no hotpath measurement. Measure execute_put_object_owned under the label the use case had before the legacy edge split, and extend the contract test to require it.
2026-11-19 07:27:26 +08:00
overtrue b71c6fabc3 test(gateway): run the raw XML and error-code checks of GetObjectAttributes on both stacks
The legacy-only assertions now apply to the gateway stack too, with the five rows on which the gateway answers differently pinned explicitly.
2026-11-19 07:27:26 +08:00
overtrue ed5927cf5d test(gateway): hold the gateway stack to the key-floor and completion tables
The legacy-only tests for keys outside the floor and for CompleteMultipartUpload request shapes now run on both stacks. The gateway answers every NUL and over-long key with one uniform refusal before the bucket is consulted, and differs from the legacy table on six completion shapes; both are pinned explicitly.
2026-11-19 07:27:26 +08:00
overtrue c794df64b8 refactor(storage): rehome live helpers out of the legacy edge
Rename storage/ecfs_extend.rs to storage/s3_support.rs, point its request-marker
imports at storage::request_markers, and move parse_object_version_id and
ListObjectUnorderedQuery out of storage/ecfs.rs into it. The module no longer
depends on FS, S3Access or storage::access. Behaviour is unchanged.
2026-11-19 06:12:30 +08:00
overtrue 5e69593836 test(iam): align log boundary with conditional writer refusal 2026-11-19 04:21:09 +08:00
overtrue e811755b8d fix(iam): bind plugin registration to request owner snapshots
Authenticate the actual request signing secret against the authoritative regular-owner record before reading the registration body. Carry its epoch and identity revision through publication without rebinding to a newer owner.

Reject stale peer signing secrets and concurrent owner changes, including same-secret recreation, rotation back to an old secret, revision-only rewrites, and legacy-initialization readback races. Preserve the independent STS generation and unchanged-secret upsert policy.

Add deterministic real-store and handler regressions and document the secret-reuse boundary. This is a separate correction layer for #3266 above the generation-aware integration.

Validation: cargo fmt --all --check, git diff --check 05d9825, scripts/check_doc_paths.sh, and scripts/check_no_planning_docs.sh passed. Compilation, runtime tests, and Clippy are deferred as requested.
2026-11-19 04:21:09 +08:00
overtrue efed8a35d2 fix(iam): integrate plugin epochs with generation-aware identity writes 2026-11-19 04:21:09 +08:00
overtrue b656745305 fix(iam): bind plugin delegations to durable owner epochs 2026-11-19 04:21:09 +08:00
overtrue ef974ad719 fix(iam): fence regular-user STS sessions by durable parent generation 2026-11-19 04:21:09 +08:00
overtrue 3af84de8f1 test(storage): iterate quorum fixture disks directly 2026-11-19 04:21:09 +08:00
overtrue d19a2ac726 test(replication): verify per-bucket refresh bookkeeping 2026-11-19 04:21:09 +08:00
overtrue 0524cce44b fix(replication): scope target clients and health to source buckets 2026-11-19 04:21:09 +08:00
overtrue 0fac11d57b refactor(storage): mount access_owned and its probe test outside access.rs 2026-11-19 02:29:45 +08:00
overtrue 46c58d8758 refactor(storage): switch access_owned to owned error types and explicit imports 2026-11-19 02:29:45 +08:00
overtrue aa24d21807 refactor(storage): rewrite authorize_copy_object_tags over owned tags and move it to access_owned 2026-11-19 01:51:44 +08:00
overtrue 3afea8ecf9 refactor(storage): move the plain authorize-action selectors to authorization_actions 2026-11-19 01:51:44 +08:00
overtrue f1fdb8c2c3 fix(gateway): answer a custom code without a status as 500 like legacy
A custom error code nobody gave a status (the tier handlers' TierNotFound) was refused as a bare InternalError, so peers matching on the code never saw it. The legacy writer answers such an error 500 with its own code and message; handler_error now does the same for every status-less custom code. Errors with an unwritable header are still refused.
2026-11-19 01:21:28 +08:00
overtrue e0afeba48f refactor(storage): read existing object tags for policy inside the authorization module
The authorization core moved under storage/authorization still called the
legacy FS type for this lookup, a reverse dependency the layer guard refuses.
The lookup now lives beside its only policy caller and FS delegates to it.
2026-11-19 01:02:44 +08:00
Henry Guo 9e57f83885 feat(storage): add opt-in EC layouts and frame-aware local reads (#9255)
* perf(ecstore): reduce allocations for bounded bitrot frames

* test(s3): cover dynamic block layouts over HTTP

* perf: measure quantized range read shape

* chore: checkpoint quantized read metrics draft

Save work in progress for collaboration. Counts omit retired readers and transient or cancelled hedges. Frame semantics, async recorder coverage and disabled-metrics overhead remain unresolved; these counters are not ready for performance conclusions.

Validation: rustfmt and ecstore check passed; io-metrics 120, quantized 4 and hashed-read 3 tests passed. No new live or performance validation.

* perf(ecstore): reduce dynamic layout read overhead

* fix(ecstore): avoid prefetching conservative short range tails

* perf(ecstore): compact deferred shard reader state

* perf(ecstore): include shard checksums in file buffer cap

* fix(ecstore): preserve bounded quantum frames during heal

* perf(ecstore): reuse owned quantized frame batches

* perf(ecstore): batch q reads and retain shared copy framing

* fix(ecstore): preserve typed quantized read errors

* perf(ecstore): avoid zero-fill and serial copies in local batch reads

The local batch reader zero-initialized every window at a nonzero offset
before reading it, and copied every shard serially inside one blocking
task. Two-segment q-window range reads (cross-shard, cross-block) pay
both costs twice per request.

Read each window with a positioned read into uninitialized Vec capacity,
and dispatch each shard separately when every window is at least 512 KiB,
where copies dominate blocking-pool round trips. Smaller windows keep one
coalesced dispatch.

* perf(ecstore): keep readahead pipelined for local batch windows

A single window-sized pread on cold pages waits on each kernel readahead
chunk in turn. Seek to the window start and fill the buffer with
read_to_end over a length-limited reader instead: it still reads into
uninitialized spare capacity, but its growing sequential reads keep
readahead pipelined. Warm windows cost the same.

* Revert "perf(ecstore): keep readahead pipelined for local batch windows"

This reverts commit c252fca525.

On the ESSD-backed cloud footprint, the growing read_to_end reads were
slower than one window-sized positioned read for cold windows at nonzero
offsets (cross-block -27% on 4 MiB layouts, cross-shard -21% on 64 KiB
layouts versus the previous batch reader). The local benchmark that
motivated the change ran on a WSL virtual disk and did not represent the
target storage. Keep the single positioned read into spare capacity and
the per-shard dispatch for large windows.

* perf(ecstore): choose the batch read method by window size

Measured on ESSD-backed cloud storage, a cold window of about 1 MiB is
fastest as one positioned read, which completes as a single device
request, while windows of 2 MiB and more are faster with growing
sequential reads that keep readahead pipelined (one large read waits on
each readahead chunk in turn). Use one positioned read up to 1.5 MiB and
a seek plus length-limited read_to_end above it. Both paths read into
uninitialized spare capacity; per-shard dispatch for large windows is
unchanged.

* perf(ecstore): read local batch windows with an exact readahead hint

Kernel readahead sizes its first request from the read size. A cold
16 KiB window at offset 0 pulled 64-128 KiB, and a single 2 MiB read was
split into serial readahead chunks that cached almost twice the window,
which is why neither the single positioned read nor growing sequential
reads won for every window size on block storage.

Announce each window with POSIX_FADV_WILLNEED, which submits exactly the
window at once, and then fill the exact spare capacity with positioned
reads. This replaces the size-based choice between the two read methods.
The hint is advisory and its failure does not fail the read. A residency
test checks that cold reads cache only their window; it failed with the
hint disabled (a 5-page window cached 32 pages).

* perf(ecstore): use half-shard read quantum at 1 MiB EC layout

* revert(release): defer certification rollout for 1.0.5 (#9254)

Revert e5563e6004 only on release/1.0.5. Its trusted verifier workflow and immutable-candidate integration are not available yet. Restore the previous publication path under the approved release policy; retain the completed product regression and preview acceptance requirements.

* fix(ecstore): preserve legacy full-shard framing for default 1 MiB layout

* perf(ecstore): enable direct-memory GET and coalesce cross-shard range reads for bounded-quantum blocks

* chore(ecstore): remove unused schedule_bitrot_reader_task wrapper

* fix(ecstore): run delete-recovery discovery off the metadata lane

Bucket-wide delete-recovery discovery starts with the server and walks the
whole bucket tree in pages of up to 4096 entries, one lstat per entry. Each
page ran on the per-disk namespace queue's foreground lane, which has a
single worker and also serves GET metadata reads. On a cold tree a page
holds that worker for hundreds of milliseconds, so every GET on the disk
waits behind it until the walk finishes.

Run the page on the queue's sync lane instead, as the delete-transaction
inspection already does for the same reason. The namespace lease and the
page bounds are unchanged.

The regression test occupies the foreground lane and requires a discovery
page to complete within ten seconds; it times out without this change.

* test(ecstore): align read_appending rollback assertions on error

* fix: align multipart and EC read paths with current workspace APIs

---------

Co-authored-by: Xiaoyang Han <lux1an@qq.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-19 00:48:49 +08:00
overtrue 283332f6f8 refactor(gateway): drop the error conversions the owned authorization core made redundant
The gateway handlers, the owned envelope entry points, the protocol client and
the admin account-permissions probe now receive the owned S3 error directly.
2026-11-18 22:16:18 +08:00
overtrue 23fff7976b refactor(storage): import request markers and ReqInfo from their own modules
The admin account-permissions handler, the storage facade and the compat envelope
tests stop reaching them through storage::access.
2026-11-18 22:16:18 +08:00
overtrue 49274736f2 refactor(storage): move the test envelope payloads into storage/authorization 2026-11-18 22:16:18 +08:00
overtrue 9bc60944be refactor(storage): move the policy decision and discovery checks into storage/authorization
authorize_request_core, its entry points, the denial log and the ListBuckets and
action-potential discovery decisions return the owned S3 error type; the legacy
hooks and tests convert at the call. The two source-reading guards that looked
for the table data-plane functions in access.rs (moved by the previous slice)
now read storage/authorization/table_data_plane.rs.
2026-11-18 22:16:18 +08:00
overtrue 011d8bee6b refactor(storage): move authorization condition building into storage/authorization
The request facts, condition map and existing-object-tag conditions return the
owned S3 error type; the legacy tests convert at the call.
2026-11-18 22:16:18 +08:00
overtrue 66eb65da06 fix(iam): revoke group-only grants for existing OIDC credentials 2026-11-18 21:47:39 +08:00
overtrue 85898d94f9 test(server): name the legacy service through the listener's own import 2026-11-18 21:14:46 +08:00
overtrue caefc17dd1 test(gateway): build the layer fixture with the control-plane host's builder shape 2026-11-18 21:14:46 +08:00
overtrue c677030610 test(server): compare control-plane answers strictly and widen the caller table
A JSON comparison of two bodies that are not JSON no longer agrees, which
turns two vacuous cases into byte comparisons. The table gains unknown,
deleted and service-account keys and a repeated Authorization line, the
caller probe gains header and query session tokens, and the console
listener's isolation is pinned in front of the control-plane host.
2026-11-18 21:14:46 +08:00
overtrue 08deaeea38 fix(server): decide claimed control-plane requests before reading their body
The control-plane host ran S3Router::admit inside its handler, after the
gateway had buffered the whole body, so an anonymous chunked admin PUT
made the host hold up to 20 MiB before answering 403. The host now
attaches each request's head before the gateway reads it and decides it
by S3Router::admit at the route-authorization stage, holds at most the
legacy 1 MiB of a claimed body, and answers a repeated Authorization line
as legacy RustFS answers an anonymous caller, never serving it as one.
2026-11-18 21:14:46 +08:00
overtrue 17b01efc89 test(server): compare the content type of control-plane JSON answers 2026-11-18 21:14:46 +08:00
overtrue 88d8cc86b1 feat(server): remove the legacy fallback from the gateway stack
The gateway selection no longer holds the legacy service: claimed routes go to the control-plane host, and a selection without one answers 501. Tests drive every request class through both selections and assert neither reaches the other stack, and compare the host with the legacy stack over real IAM and signatures.
2026-11-18 21:14:46 +08:00
overtrue 640f872054 feat(gateway): serve claimed control-plane routes on a gateway host
The host dispatches every admin, table-catalog, profiling, STS form, replication, listen and Object Lambda request through S3Router::admit and the existing route table, with the legacy stack's identity, body ceiling and answers. Probe tests pin which requests reach a handler and as whom.
2026-11-18 21:14:46 +08:00
overtrue ee333a2774 refactor(admin): decide control-plane access by one owned rule
Design (T2.11): serve every route the admin router claims on the gateway
stack without the s3s service.

- Extension point: a RustFS-owned dialect on a second gateway service, the
  control-plane host. One claimed operation, rustfs:ControlPlane, takes the
  six RustFS claims (admin, MinIO alias, both table-catalog prefixes, both
  profiling triggers) exactly, with a trailing slash and every descendant,
  for every method; a RustFS form operation takes the STS form at /; the
  eight query-discriminated extension and Object Lambda rows are the
  gateway dialect's own S3-table operations. No gateway change is needed.
- Identity: the gateway verifies whatever is presented (floor admits
  header, presigned and anonymous; the caller secret is handed to every
  operation, as s3s hands it to every custom route) and the envelope is
  built with RequestEnvelope::from_gateway, the mechanism the native admin
  bridge already uses.
- Extracted here: S3Router::admit, check_access's rule over owned method,
  URI, headers and "signed", and router::dispatch, the route-table answer.
  The legacy S3Route impl now calls both; the console and Object Lambda
  branches stay with the legacy call, and an envelope-based Object Lambda
  entry is added for the gateway host.
2026-11-18 21:14:46 +08:00
overtrue 177572b0d9 fix(auth): enforce explicit denies on own-password and MFA changes 2026-11-18 21:13:39 +08:00
overtrue 2e286d3220 chore(rustfs): remove redundant S3 error conversions flagged by Clippy 2026-11-18 21:13:39 +08:00
overtrue cfa93b9b40 fix(iam): enforce account status permission on user upserts 2026-11-18 21:13:39 +08:00
overtrue 142cff57a3 fix(gateway): restore the gateway-stack build after the rename-batch merge
The squash of #9489 carried two hunks of an unlanded POST change that call
post_effective_headers, which main does not define, so every build with the
gateway-stack feature failed. Read the request headers as before; the POST
change reapplies cleanly on top. Also drops trailing whitespace that fails
cargo fmt --check.
2026-11-18 20:41:23 +08:00
Hauser Zhi 447f18db43 fix(ecstore): preserve degraded reads during cold startup (#9490)
* fix(ecstore): admit degraded local startup at read quorum

Keep absent local volumes in configured offline slots and admit existing native formats with nonvoting blank replacements. Preserve legacy validation and elected migration authority before degraded reads. Add startup, migration, readiness and real S3 cold-start regressions.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(ecstore): separate startup reads from metadata writers

Install committed startup metadata under a shared namespace fence when no writer work is required. Revalidate under the existing exclusive pipeline before bootstrap, recovery, repair, or topology side effects, and check fence validity at publication.

Cache existing-format read admission and avoid legacy scans below native read quorum for ineligible nonwriters. Cover shared-lock contention, authority bytes, released fences, and completed-process and cold-store retries.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(ecstore): separate legacy read compatibility from migration

Validate observed legacy layouts against an established native read quorum without requiring legacy migration quorum. Reuse known unavailable native slots to avoid repeated peer RPCs. Keep migration behind its original elected-writer, availability and strict-majority requirements, and grant no bootstrap authority to read-compatible outcomes.

Add full-loader regressions for blank plus unreachable or missing slots, both creator roles, conflicting evidence and unchanged authority files.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(ecstore): route startup test through storage facade

Use the existing internal NamespaceLocking re-export in the startup regression, preserving the architecture boundary checked by CI. Production code and the trait identity are unchanged.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* test(iam): preserve virtual parent collision invariant

Keep the federated binding regression focused on colliding regular and STS policy mappings. Virtual OIDC parent keys are now intentionally reserved and cannot identify regular users; that invariant already has direct IAM coverage.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(gateway): project POST form metadata safely

Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

* fix(gateway): preserve form authority across feature boundaries

Keep archive extraction decisions on projected POST form headers in gateway builds while preserving ordinary header handling without that feature. Update the checksum regression to model the signed form source instead of a forbidden wire object property.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>

---------

Signed-off-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-18 20:25:44 +08:00
Hauser Zhi 975e232a63 chore(deps): refresh dependabot dependency set (#9492) 2026-11-18 20:17:43 +08:00
Hauser Zhi d921f3cb24 perf(ecstore): batch remote rename fanout (#9489) 2026-11-18 20:17:11 +08:00
overtrue 62117054d9 fix(iam): serialize group edits against durable membership 2026-11-18 19:21:55 +08:00
overtrue 2f51a39c64 test(gateway): prove the gateway stack serves an unsigned x-amz-cf-id without SigV4HeaderGuard 2026-11-18 19:19:33 +08:00
overtrue 292c288896 build(gateway): pin the unsigned x-amz-cf-id reading of the RustFS profile 2026-11-18 19:19:33 +08:00
cxymds d8519549d1 test(ssec): honor deferred refusals and legacy error responses (#9503)
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-18 19:16:02 +08:00
cxymds c3efe4be2a fix(gateway): align POST controls and console isolation tests (#9501)
Co-authored-by: overtrue <anzhengchao@gmail.com>
2026-11-18 19:15:05 +08:00
925 changed files with 113680 additions and 42592 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-linux=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
sha256-darwin=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
sha256-linux=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
sha256-darwin=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=24a8cfaa1b9125bd69d7d4a7ff752a8ab8ed350c761d90ae8472ef52393e2686
sha256-linux=014257197fbbfbb48cab2864da9e10d96ee877d478fa29d119f8186532ea293d
sha256-darwin=d5f2a266740f695cf6734965a4d25b390e669aaaa2fc87805c45e42de83f13ca
sha256-linux=448ac2ebd537def9f2a63b8961d80a6521f7ef05f952834ec997faed52bfb901
+1 -1
View File
@@ -1 +1 @@
sha256=fd5683273bba1eae3b4402a4e854a5d168ace845bd0e5fc801f8e336485a4394
sha256=a304838fe8ded98a781d7e2e1cf5b22a5cbc11ddfdc4fbaeea91149e5f88d699
-2
View File
@@ -103,8 +103,6 @@ script-tests: ## Run shell script tests
$(RUSTFS_PYTHON_BIN) ./scripts/test_retain_validation_evidence.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_ci_timing_report.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_junit_diff.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_dual_stack.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_mint_stack_diff.py
$(RUSTFS_PYTHON_BIN) ./scripts/check_conformance_rulings.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/compat_matrix_report.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/s3-tests/test_report_compat.py
+9 -9
View File
@@ -143,7 +143,7 @@ setup = 'ecstore-base-stack'
# The multipart refusal fixture composes real-store setup, abort, quota and legal-hold futures.
[[profile.default.scripts]]
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access::tests::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access_owned::tests::generation_guards::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
setup = 'ecstore-base-stack'
# These handler/store fixtures and the relocated-pool GET compose deep storage
@@ -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_/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
threads-required = "num-test-threads"
# Real target-repair and rebalance-stop fixtures commit durable metadata while
@@ -466,7 +466,7 @@ filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair
setup = 'ecstore-base-stack'
[[profile.ci.scripts]]
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access::tests::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access_owned::tests::generation_guards::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
setup = 'ecstore-base-stack'
[[profile.ci.scripts]]
@@ -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_/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
threads-required = "num-test-threads"
# Match the real admin fixture capacity reservation without retries or changes
@@ -723,16 +723,15 @@ test-group = 'ecstore-serial-flaky'
# fixture as the existing smoke modules.
#
# Dual-stack differential (rustfs/backlog#2740): `dual_stack_differential::`
# starts two single-node servers from the same binary, one per
# RUSTFS_S3_STACK value, on random ports with isolated temp dirs, and runs one
# SDK script covering every operation of `impl S3 for FS` against both. Its
# starts two single-node servers on random ports with isolated temp
# dirs, and runs one SDK script covering every S3 operation against both. Its
# comparator unit tests need no server. It meets the admission criteria
# unchanged; the module clause admits a new differential test without another
# filter edit.
[profile.e2e-smoke]
default-filter = """
package(e2e_test) & (
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(/^(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(/^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::/)
@@ -961,10 +960,11 @@ 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::/)
& !test(/^(protocols|access_request_validation_test)::/)
& !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::/)
+2 -2
View File
@@ -9,9 +9,9 @@
# Adding a target is one more [[targets]] table, for example:
#
# [[targets]]
# name = "candidate-gateway"
# name = "candidate-tuned"
# binary = "candidate"
# env = { RUSTFS_S3_STACK = "gateway" }
# env = { RUSTFS_EXAMPLE_SETTING = "on" }
schema = 1
+8 -2
View File
@@ -114,8 +114,14 @@
}
],
"upgrade_sources": {
"basis": "Exactly the two previous-release sources pinned in .github/workflows/e2e-upgrade.yml are exercised today (source.version / source.asset / source.sha256). No other N-1/N-2 compatibility is claimed, and these digests are not inferred from tags.",
"basis": "The three previous-release sources pinned in .github/workflows/e2e-upgrade.yml are exercised today (source.version / source.asset / source.sha256). No other N-1/N-2 compatibility is claimed, and these digests are not inferred from tags.",
"sources": [
{
"version": "1.0.5",
"role": "gateway compatibility baseline",
"artifact_name": "rustfs-linux-x86_64-gnu-v1.0.5.zip",
"artifact_sha256": "5addae2f74756bf80104d0975e6347cda843bc2daffdfcd1f0cb80118b95cbd0"
},
{
"version": "1.0.1",
"role": "N-1",
@@ -130,6 +136,6 @@
}
],
"rollback_supported": false,
"rollback_basis": "Only the bucket-config-rollback case (rollback_to_previous_release_reads_current_bucket_metadata) is exercised. Full data-plane rollback is not certified and is never a default claim."
"rollback_basis": "The release upgrade lane checks bucket-config rollback. The hosted compatibility workflow also checks in-flight multipart rollback to 1.0.5. Full data-plane rollback is not certified and is never a default claim."
}
}
-2
View File
@@ -28,8 +28,6 @@ rustfs/src/app/storage_api.rs
rustfs/src/admin/router.rs
rustfs/src/app/metadata_route.rs
rustfs/src/server/http.rs
rustfs/src/server/layer.rs
rustfs/src/server/hybrid.rs
rustfs/src/protocols/client.rs
# e2e oracle: the test target that verifies S3 behaviour against s3s
+2 -2
View File
@@ -13,6 +13,6 @@
# s3_error_lines lines holding s3_error!, same scope, minus those the script
# header's rule clears (rustfs_s3_types's macro); fails closed
# ecstore_files Rust files referencing s3s paths under crates/ecstore/src
files=63
s3_error_lines=209
files=33
s3_error_lines=89
ecstore_files=0
+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
+4
View File
@@ -34,6 +34,10 @@ If you want the Kafka-backed HA Tempo path, use `docker-compose-example-for-rust
- **High Performance**: Optimized configurations for batching, compression, and memory management.
- **Standardized Protocols**: Built entirely on OpenTelemetry standards.
## HTTP Request Latency Percentiles
The main RustFS dashboard shows request latency percentiles in milliseconds. The HTTP server request, response-body chunk, and response-body stream histograms export bucket boundaries in seconds. During a rolling upgrade or rollback that changes the bucket layout, compute percentiles from nodes that share one layout and from a query window entirely on that layout. The bundled dashboard and recording rules use a five-minute window. The mean from `_sum` divided by `_count` remains usable across the change.
## GET Performance Optimization Dashboards
Three pre-built Grafana dashboards are included for monitoring RustFS GET performance optimization rollout:
+4
View File
@@ -34,6 +34,10 @@
- **高性能**: 针对批处理、压缩和内存管理进行了优化配置。
- **标准化协议**: 完全基于 OpenTelemetry 标准构建。
## HTTP 请求延迟分位数
RustFS 主仪表盘以毫秒显示请求延迟分位数。HTTP 服务的请求耗时、响应体分块延迟和响应体流传输耗时直方图以秒为单位导出桶边界。滚动升级或回滚导致桶边界变化时,只对采用同一套桶边界的节点和时间窗口计算分位数。自带仪表盘和记录规则使用五分钟窗口。变更期间仍可用 `_sum` 除以 `_count` 计算平均值。
## GET 性能优化仪表盘
包含三个预构建的 Grafana 仪表盘,用于监控 RustFS GET 性能优化发布:
-54
View File
@@ -1,54 +0,0 @@
# Copyright 2026 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
name: Both-stack leg
description: Prove which S3 stack one e2e leg's servers selected and upload the leg for the summary (call with if always)
inputs:
profile:
description: The nextest profile the leg ran
required: true
stack:
description: The stack the leg requested, legacy or gateway
required: true
logs:
description: Directory or file holding the servers' output
required: true
runs:
using: composite
steps:
- name: Prove which stack the servers selected
shell: bash
env:
PROFILE: ${{ inputs.profile }}
STACK: ${{ inputs.stack }}
LOGS: ${{ inputs.logs }}
run: |
# Outside the workspace: e2e_binary.py refuses a run whose source tree changed.
mkdir -p "$RUNNER_TEMP/leg"
junit="target/nextest/${PROFILE}/junit.xml"
if [ -s "$junit" ]; then cp "$junit" "$RUNNER_TEMP/leg/junit.xml"; fi
# A gateway leg stopped by its preflight has no output; the preflight's stack.json stays.
if [ -e "$LOGS" ]; then python3 scripts/dual_stack.py stack --expect "$STACK" --out "$RUNNER_TEMP/leg/stack.json" "$LOGS"; fi
- name: Upload the leg
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: dual-stack-leg-${{ inputs.profile }}-${{ inputs.stack }}
overwrite: true
path: ${{ runner.temp }}/leg
if-no-files-found: warn
retention-days: 7
@@ -1,56 +0,0 @@
# Copyright 2026 RustFS Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
name: Both-stack summary
description: Diff the legacy and gateway legs of this run (scripts/junit_diff.py) and upload one dated summary
inputs:
profiles:
description: Comma-separated nextest profiles whose two legs this run uploaded
required: true
runs:
using: composite
steps:
- name: Download the legs
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: dual-stack-leg-*
path: legs
- name: Diff every profile and write the summary
id: summary
shell: bash
env:
PROFILES: ${{ inputs.profiles }}
run: |
# The shell runs with -e; the exit status is reported after the summary is written.
set +e -u -o pipefail
date="$(date -u +%F)"
echo "date=${date}" >> "$GITHUB_OUTPUT"
mkdir -p legs
python3 scripts/dual_stack.py summary --profiles "$PROFILES" --legs legs --date "$date" --out-dir dual-stack
status=$?
if [ -f dual-stack/summary.md ]; then cat dual-stack/summary.md >> "$GITHUB_STEP_SUMMARY"; fi
exit "$status"
- name: Upload the dated summary
if: always() && steps.summary.outputs.date != ''
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: dual-stack-summary-${{ steps.summary.outputs.date }}
overwrite: true
path: dual-stack
if-no-files-found: error
retention-days: 30
+3 -2
View File
@@ -6,8 +6,9 @@ runs:
- name: Install runtime tools
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y libssl-dev ripgrep
# 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
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- name: Install cargo-nextest
+2
View File
@@ -22,6 +22,8 @@ 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.
+25 -1
View File
@@ -523,6 +523,30 @@
"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",
@@ -814,7 +838,7 @@
"monitor": "workflow",
"max_age_hours": 36,
"result_owner": "dual-stack-nightly.yml",
"disposition": "both-stack JUnit diff of the two profiles only ci.yml runs; the gateway legs are report-only until T2.10",
"disposition": "nightly run of the two e2e profiles only ci.yml runs, on the gateway stack, with the JUnit reports retained for 30 days",
"failure_owner": "watchdog",
"origin": "added"
},
@@ -0,0 +1,47 @@
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
+15 -187
View File
@@ -92,7 +92,6 @@ jobs:
connect: ${{ steps.scope.outputs.connect || 'true' }}
packages: ${{ steps.scope.outputs.packages }}
full_validation: ${{ steps.scope.outputs.full_validation || 'true' }}
gateway_smoke: ${{ steps.scope.outputs.gateway_smoke || 'true' }}
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
@@ -119,7 +118,7 @@ jobs:
echo "Base CI policy unavailable; running the full matrix."
fi
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=8$' "$GITHUB_OUTPUT"; then
printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'gateway_smoke=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT"
printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT"
echo "Base policy does not cover this workflow contract; retaining the full matrix."
fi
- name: Retain verification plan
@@ -564,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
@@ -581,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
@@ -676,54 +675,6 @@ jobs:
retention-days: 3
if-no-files-found: warn
test-and-lint-gateway-stack:
name: Test and Lint (gateway-stack)
# The gateway S3 stack (rustfs/backlog#2734) sits behind the rustfs
# `gateway-stack` feature, which no other pull-request lane lints or tests.
# Unlike the dormant feature lanes above, this one runs for every code
# change: each operation slice puts its handler tests and its refusal-matrix
# row behind the feature, and a lane that ran only on demand would let them
# rot behind a green pull request.
if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
needs: [ quick-checks, classify-changes ]
# Self-hosted for build scale and cache ownership: a workspace-scale Cargo
# build that reads the ci-dev cache written on this image.
runs-on: sm-standard-4
timeout-minutes: 90
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-dev-ea7eec74fe14
cache-save-if: 'false'
install-build-packaging-tools: 'false'
# A feature that does not compile fails here; nothing below is skipped
# into a pass.
- name: Run clippy with gateway-stack
run: cargo clippy --locked -p rustfs --all-targets --features gateway-stack -- -D warnings
# The gateway stack's own tests: the assembly, the operation table and
# its completeness, the shared handler sequence, the stack selection, and
# the embedded server driven through the whole middleware stack. The
# filter names modules, never operations.
- name: Run tests with gateway-stack
env:
# The same bounded link concurrency as the other feature lanes.
CARGO_BUILD_JOBS: "2"
run: |
cargo nextest run --profile ci --locked -p rustfs --features gateway-stack --no-tests fail \
--status-level all --final-status-level all \
-E 'test(/gateway_stack|gateway_handlers|server::stack::/) | binary(embedded_gateway_stack_test)'
build-rustfs-debug-binary:
name: Build RustFS Debug Binary
if: contains(fromJSON('["full", "e2e"]'), needs.classify-changes.outputs.mode) && (github.event_name != 'pull_request' || github.event.action != 'closed')
@@ -986,8 +937,6 @@ jobs:
# Retain the producer image and fixture paths until the runtime pilot passes.
runs-on: sm-standard-4
timeout-minutes: 30
env:
RUSTFS_S3_STACK: legacy
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -1108,125 +1057,6 @@ jobs:
path: ${{ runner.temp }}/rustfs-e2e-*/rustfs.log
retention-days: 3
# The same e2e-smoke suite against the same debug binary with the gateway
# S3 stack selected (rustfs/backlog#2734). Report-only: it is outside the
# Test and Lint aggregate and becomes required at T2.10. The test-binary
# download, identity, membership, run and completeness steps must stay
# identical to e2e-tests; scripts/ci_gate.py enforces that.
#
# When it runs: every push to main or gateway/integration, merge group,
# nightly schedule and manual dispatch, and every pull request that changes a
# gateway-stack input (GATEWAY_SMOKE_PATHS and the rustfs-gateway pins in
# scripts/ci_gate.py, published by Select CI scope as gateway_smoke).
# Why it is skipped on every other pull request: until T2.10 the gateway
# stack does not serve the whole smoke suite, so the lane fails on any
# revision. A pull request that touches none of its inputs can neither cause
# nor fix that failure, and a red check there says nothing about the change.
# Skipped is the honest state; a failure must never be rendered green, so no
# step here may carry continue-on-error. A selection that is missing or
# unreadable runs the lane. At T2.10, when the lane becomes required, it
# must run on every pull request again: delete the selection, do not extend
# it.
e2e-tests-gateway:
name: e2e-smoke (gateway, report-only until T2.10)
needs: [ classify-changes, build-rustfs-debug-binary ]
if: github.event_name != 'pull_request' || needs.classify-changes.outputs.gateway_smoke != 'false'
runs-on: sm-standard-2
timeout-minutes: 30
continue-on-error: true
env:
RUSTFS_S3_STACK: gateway
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Install verification runtime
uses: ./.github/actions/test-runtime
- name: Download E2E test binaries
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: e2e-test-binaries
path: ${{ runner.temp }}
- name: Verify E2E archive identity
run: python3 scripts/ci_test_artifact.py verify --configuration e2e --archive "$RUNNER_TEMP/e2e-tests.tar.zst"
- name: Set up Python
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
- name: Install awscurl
run: |
python3 -m pip install --user --upgrade pip "awscurl==0.44"
echo "AWSCURL_PATH=$HOME/.local/bin/awscurl" >> "$GITHUB_ENV"
- name: Verify awscurl
run: test -x "$AWSCURL_PATH"
# Download after the cache restore so the freshly built binary from the
# build job always wins over anything restored into target/debug.
- name: Download debug binary
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: rustfs-debug-binary
path: target/debug
- name: Make binary executable
run: chmod +x ./target/debug/rustfs
# Build the e2e test graph once. The archive is reused by the smoke
# selection guard, security exact-count check, and run below, avoiding a
# second compile of the same e2e_test target on cold runners (backlog#1645).
- name: Verify e2e smoke test membership
env:
NEXTEST_ARCHIVE: ${{ runner.temp }}/e2e-tests.tar.zst
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-smoke-list.json
run: |
cargo nextest list --profile e2e-smoke --archive-file "${NEXTEST_ARCHIVE}" --workspace-remap "$GITHUB_WORKSPACE" --extract-to "$GITHUB_WORKSPACE" --extract-overwrite --message-format json > "${NEXTEST_LISTING}"
python3 ./scripts/check_test_wiring.py --check-profile e2e-smoke "${NEXTEST_LISTING}"
./scripts/check_security_smoke_count.sh check "${NEXTEST_LISTING}"
# PR smoke subset of the in-repo e2e suite (backlog#1149 ci-4). The
# profile.e2e-smoke default-filter in .config/nextest.toml is the single
# wiring mechanism for e2e tests in CI — extend that filter instead of
# adding new e2e jobs here. Each test spawns its own rustfs server on a
# random port and reuses the downloaded debug binary above.
- name: Run e2e smoke suite
env:
NEXTEST_ARCHIVE: ${{ runner.temp }}/e2e-tests.tar.zst
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-smoke-logs
SAMPLER_INTERVAL_SECS: "15"
run: |
./scripts/ci/resource_sampler.sh start e2e-smoke
trap './scripts/ci/resource_sampler.sh stop' EXIT
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile e2e-smoke --cargo-metadata target/nextest/cargo-metadata.json --binaries-metadata target/nextest/binaries-metadata.json --workspace-remap "$GITHUB_WORKSPACE" --target-dir-remap "$GITHUB_WORKSPACE/target" \
--status-level all --final-status-level all --failure-output final
- name: Verify e2e smoke execution completeness
run: python3 scripts/ci_test_artifact.py evidence "$RUNNER_TEMP/rustfs-e2e-smoke-list.json" target/nextest/e2e-smoke/junit.xml
- name: Upload e2e smoke diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-smoke-gateway-diagnostics-${{ github.run_number }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/rustfs-e2e-smoke-logs/
${{ runner.temp }}/rustfs-e2e-smoke-list.json
if-no-files-found: warn
- name: Upload e2e smoke JUnit report
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-smoke-gateway-junit-${{ github.run_number }}-${{ github.run_attempt }}
path: target/nextest/e2e-smoke/junit.xml
if-no-files-found: warn
e2e-full:
name: End-to-End Tests (full merge gate)
# Merge gate only (backlog#1149 ci-5): the never-automated user-visible
@@ -1261,9 +1091,12 @@ jobs:
- name: Verify E2E archive identity
run: python3 scripts/ci_test_artifact.py verify --configuration e2e --archive "$RUNNER_TEMP/e2e-tests.tar.zst"
- name: Install network fault-injection tools
- name: Install network fault-injection tools and the persistence test clock
run: |
sudo apt-get install -y iptables
sudo apt-get install -y iptables libfaketime
clock_library="$(dpkg-query -L libfaketime | grep -E '/libfaketime[.]so[.]1$')"
test -f "$clock_library"
echo "RUSTFS_PERSISTENCE_CLOCK_LIBRARY=$clock_library" >> "$GITHUB_ENV"
sudo -n iptables --version
# The endpoint-blackhole heal scenario needs CAP_NET_ADMIN. Containerised
# runners can run iptables but not touch the rule set; the test then logs
@@ -1370,8 +1203,14 @@ jobs:
# default-filter in .config/nextest.toml is the single wiring mechanism —
# extend that filter, never add ad-hoc e2e jobs here. Reuses the downloaded
# debug binary; each test spawns its own rustfs server on a random port.
- name: Download pinned release for persistence byte parity
id: persistence-reference
uses: ./.github/actions/reference-binary
- name: Run e2e full suite
env:
RUSTFS_PERSISTENCE_REFERENCE_BINARY: ${{ steps.persistence-reference.outputs.path }}
RUSTFS_PERSISTENCE_XML_DIR: ${{ runner.temp }}/rustfs-persistence-xml
CARGO_BIN_EXE_rustfs: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs
RUSTFS_E2E_STARTUP_CAS_BINARY: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs
RUSTFS_E2E_STARTUP_CAS_BUILD_MANIFEST: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs.e2e-startup-cas-build.json
@@ -1390,6 +1229,7 @@ jobs:
path: |
target/nextest/e2e-full/junit.xml
${{ runner.temp }}/rustfs-e2e-full-list.json
${{ runner.temp }}/rustfs-persistence-xml
retention-days: 7
- name: Upload startup CAS evidence
@@ -1530,15 +1370,6 @@ 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
@@ -1580,7 +1411,6 @@ 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}" \
@@ -1612,7 +1442,6 @@ jobs:
- fips-provider
- test-and-lint-rio-v2
- test-and-lint-protocols
- test-and-lint-gateway-stack
- build-rustfs-debug-binary
- uring-integration
- e2e-tests
@@ -1648,7 +1477,6 @@ jobs:
- core-contract
- test-and-lint-rio-v2
- test-and-lint-protocols
- test-and-lint-gateway-stack
- build-rustfs-debug-binary
- build-rustfs-debug-binary-rio-v2
- uring-integration
+21 -68
View File
@@ -12,21 +12,18 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# Nightly both-stack diff of the two e2e profiles only ci.yml runs, e2e-smoke
# and e2e-full (rustfs/backlog#2772, T3.1). The other profiles carry a `stack`
# dimension in their own workflows, where the existing lane is the legacy leg.
# Nightly run of the two e2e profiles only ci.yml runs, e2e-smoke and e2e-full
# (rustfs/backlog#2772, T3.1), on the gateway stack, which is the only S3 stack.
# The workflow keeps its file and registry name from the period when it diffed two
# stacks. Each leg uploads its JUnit report and server logs for 30 days; the one
# comparison against the last legacy record (the `dual-stack-leg-<profile>-legacy`
# artifacts of the final both-stack run) is made by hand with scripts/junit_diff.py.
#
# One build serves every leg. One preflight starts that binary with
# RUSTFS_S3_STACK=gateway (scripts/dual_stack.py preflight); without a proven
# gateway start the gateway legs do not run and the summary says `skipped:
# gateway stack refuses startup: <why>`. Which stack a leg ran is read from the
# servers' own start-up line. The gateway legs are report-only until T2.10.
#
# Left out of both stacks: `dual_stack_differential::` (servers with an explicit
# Left out: `dual_stack_differential::` (servers with an explicit
# stack), `fake_s3_target::`, the upgrade write-readiness cases and one deadline
# case (no server), and `distributed_startup_regression_test::` (needs ci.yml's
# hooks-binary manifest). Both e2e-full stacks use ci.yml's pinned mc and
# Vault binaries and network fault-injection tools.
# hooks-binary manifest). e2e-full uses ci.yml's pinned mc and Vault binaries
# and network fault-injection tools.
name: dual-stack-nightly
@@ -50,13 +47,11 @@ defaults:
jobs:
build:
name: Build once and probe the gateway stack
name: Build once
if: github.repository == 'rustfs/rustfs'
# The runner and cache of ci.yml's build-rustfs-debug-binary.
runs-on: sm-standard-4
timeout-minutes: 60
outputs:
stacks: ${{ steps.preflight.outputs.stacks }}
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
@@ -86,47 +81,15 @@ jobs:
if-no-files-found: error
retention-days: 1
# Without a proven gateway start there is no gateway leg to run.
- name: Gateway preflight
id: preflight
run: |
if python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/preflight/stack.json"; then
echo 'stacks=["legacy","gateway"]' >> "$GITHUB_OUTPUT"
else
echo 'stacks=["legacy"]' >> "$GITHUB_OUTPUT"
fi
# The evidence stands in for a gateway leg that is skipped; a leg that runs overwrites it.
- name: Upload the preflight evidence for e2e-smoke
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: dual-stack-leg-e2e-smoke-gateway
path: ${{ runner.temp }}/preflight
if-no-files-found: warn
retention-days: 7
- name: Upload the preflight evidence for e2e-full
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: dual-stack-leg-e2e-full-gateway
path: ${{ runner.temp }}/preflight
if-no-files-found: warn
retention-days: 7
leg:
name: ${{ matrix.profile }} (${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
name: ${{ matrix.profile }}
needs: [ build ]
runs-on: sm-standard-4
timeout-minutes: 120
# Report-only until T2.10: the gateway stack cannot serve the suites yet.
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy:
fail-fast: false
matrix:
profile: [ e2e-smoke, e2e-full ]
stack: ${{ fromJSON(needs.build.outputs.stacks) }}
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
@@ -208,10 +171,9 @@ jobs:
run: |
"$RUSTFS_TEST_VAULT_BIN" version
- name: Run the profile on the ${{ matrix.stack }} stack
- name: Run the profile
env:
PROFILE: ${{ matrix.profile }}
RUSTFS_S3_STACK: ${{ matrix.stack }}
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/server-logs
run: |
chmod +x target/debug/rustfs
@@ -220,23 +182,14 @@ jobs:
filter="$filter & not test(=list_objects_v2_pagination_test::tests::test_list_objects_v2_deadline_rejects_unresponsive_peer)"
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile "$PROFILE" -p e2e_test -E "$filter"
- name: Prove the stack and upload the leg
- name: Upload the leg
if: always()
uses: ./.github/actions/dual-stack-leg
with: { profile: "${{ matrix.profile }}", stack: "${{ matrix.stack }}", logs: "${{ runner.temp }}/server-logs" }
summary:
name: Both-stack diff summary
needs: [ build, leg ]
if: github.repository == 'rustfs/rustfs' && always()
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
persist-credentials: false
- uses: ./.github/actions/dual-stack-summary
with:
profiles: e2e-smoke,e2e-full
name: e2e-nightly-${{ matrix.profile }}
overwrite: true
path: |
target/nextest/${{ matrix.profile }}/junit.xml
${{ runner.temp }}/server-logs
if-no-files-found: warn
retention-days: 30
+2 -33
View File
@@ -53,14 +53,11 @@ concurrency:
jobs:
distributed:
if: github.repository == 'rustfs/rustfs'
name: Distributed 4-node 4-disk e2e (${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
name: Distributed 4-node 4-disk e2e
# GitHub-hosted VM: loop and tmpfs mounts work here. sm-standard-4 is an
# ARC pod and rejects both (`mount -o loop` ENOENT, tmpfs "read-only").
runs-on: ubuntu-latest
timeout-minutes: 180
# The gateway leg is report-only until T2.10.
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
NO_PROXY: 127.0.0.1,localhost
@@ -132,11 +129,6 @@ jobs:
run: |
python3 scripts/e2e_binary.py build --bins --features e2e-test-hooks
# A gateway binary that refuses to start skips the suite; the summary says why.
- name: Gateway preflight
if: matrix.stack == 'gateway'
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
- name: Verify distributed e2e membership
env:
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-distributed-list.json
@@ -148,7 +140,6 @@ jobs:
env:
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-distributed-logs
FILTER: ${{ inputs.filter }}
RUSTFS_S3_STACK: ${{ matrix.stack }}
run: |
set -euo pipefail
rm -f target/nextest/e2e-distributed/junit.xml
@@ -159,19 +150,11 @@ jobs:
fi
test -s target/nextest/e2e-distributed/junit.xml
- name: Prove the stack and upload the leg
if: always()
uses: ./.github/actions/dual-stack-leg
with:
profile: e2e-distributed
stack: ${{ matrix.stack }}
logs: ${{ runner.temp }}/rustfs-e2e-distributed-logs
- name: Upload distributed e2e diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-distributed-${{ github.run_number }}-${{ matrix.stack }}
name: e2e-distributed-${{ github.run_number }}
path: |
target/nextest/e2e-distributed/junit.xml
${{ runner.temp }}/rustfs-e2e-distributed-list.json
@@ -191,20 +174,6 @@ jobs:
fi
done
dual-stack-summary:
name: Both-stack diff summary
needs: [distributed]
if: github.repository == 'rustfs/rustfs' && always()
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: ./.github/actions/dual-stack-summary
with:
profiles: e2e-distributed
alert-on-failure:
name: Alert on scheduled failure
needs: [distributed]
+8 -76
View File
@@ -54,18 +54,15 @@ concurrency:
jobs:
repl-nightly:
if: github.repository == 'rustfs/rustfs'
name: Replication e2e (nightly, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
name: Replication e2e (nightly)
# dual-node tests spawn two full rustfs servers each; the extra headroom
# over the per-PR sm-standard-2 e2e job keeps the parallel process fan-out
# from starving the runner. Mirrors the ILM serial lane's runner class.
runs-on: sm-standard-4
timeout-minutes: 45
# The gateway leg is report-only until T2.10.
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
RUSTFS_BUILD_FEATURES: ${{ matrix.stack == 'gateway' && 'gateway-stack' || '' }}
RUSTFS_BUILD_FEATURES: ""
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -99,11 +96,6 @@ jobs:
run: |
python3 scripts/e2e_binary.py build --bins --features "$RUSTFS_BUILD_FEATURES"
# A gateway binary that refuses to start skips the suite; the summary says why.
- name: Gateway preflight
if: matrix.stack == 'gateway'
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
- name: Verify replication e2e membership
env:
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-repl-nightly-list.json
@@ -114,22 +106,13 @@ jobs:
- name: Run replication e2e nightly suite
env:
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-repl-nightly-logs
RUSTFS_S3_STACK: ${{ matrix.stack }}
run: python3 scripts/e2e_binary.py run --features "$RUSTFS_BUILD_FEATURES" -- cargo nextest run --profile e2e-repl-nightly -p e2e_test
- name: Prove the stack and upload the leg
if: always()
uses: ./.github/actions/dual-stack-leg
with:
profile: e2e-repl-nightly
stack: ${{ matrix.stack }}
logs: ${{ runner.temp }}/rustfs-e2e-repl-nightly-logs
- name: Upload nextest junit report
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-replication-nightly-junit-${{ github.run_number }}-${{ matrix.stack }}
name: e2e-replication-nightly-junit-${{ github.run_number }}
path: |
target/nextest/e2e-repl-nightly/junit.xml
${{ runner.temp }}/rustfs-e2e-repl-nightly-list.json
@@ -139,12 +122,9 @@ jobs:
cluster-nightly:
if: github.repository == 'rustfs/rustfs'
name: Cluster fault e2e (nightly, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
name: Cluster fault e2e (nightly)
runs-on: sm-standard-4
timeout-minutes: 90
# The gateway leg is report-only until T2.10.
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
@@ -165,11 +145,6 @@ jobs:
run: |
python3 scripts/e2e_binary.py build --bins --features e2e-test-hooks
# A gateway binary that refuses to start skips the suite; the summary says why.
- name: Gateway preflight
if: matrix.stack == 'gateway'
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
- name: Verify cluster fault e2e membership
env:
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-nightly-list.json
@@ -181,22 +156,13 @@ jobs:
env:
CARGO_BIN_EXE_rustfs: ${{ github.workspace }}/target/debug/rustfs
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-nightly-logs
RUSTFS_S3_STACK: ${{ matrix.stack }}
run: python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile e2e-nightly -p e2e_test
- name: Prove the stack and upload the leg
if: always()
uses: ./.github/actions/dual-stack-leg
with:
profile: e2e-nightly
stack: ${{ matrix.stack }}
logs: ${{ runner.temp }}/rustfs-e2e-nightly-logs
- name: Upload cluster fault diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-cluster-nightly-${{ github.run_number }}-${{ matrix.stack }}
name: e2e-cluster-nightly-${{ github.run_number }}
path: |
target/nextest/e2e-nightly/junit.xml
${{ runner.temp }}/rustfs-e2e-nightly-list.json
@@ -206,15 +172,12 @@ jobs:
protocols-nightly:
if: github.repository == 'rustfs/rustfs'
name: Protocol e2e (nightly, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
name: Protocol e2e (nightly)
runs-on: sm-standard-4
timeout-minutes: 90
# The gateway leg is report-only until T2.10.
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
RUSTFS_BUILD_FEATURES: ${{ matrix.stack == 'gateway' && 'ftps,webdav,sftp,gateway-stack' || 'ftps,webdav,sftp' }}
RUSTFS_BUILD_FEATURES: ftps,webdav,sftp
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -238,11 +201,6 @@ jobs:
- name: Build protocol server
run: python3 scripts/e2e_binary.py build --features "$RUSTFS_BUILD_FEATURES"
# A gateway binary that refuses to start skips the suite; the summary says why.
- name: Gateway preflight
if: matrix.stack == 'gateway'
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
# The suite owns fixed protocol ports and serializes its internal cases.
- name: Verify protocol e2e membership
env:
@@ -254,28 +212,16 @@ jobs:
- name: Run protocol e2e nightly suite
env:
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-protocol-e2e-logs
RUSTFS_S3_STACK: ${{ matrix.stack }}
# These servers set no log level of their own; the stack proof reads their start-up line.
RUST_LOG: rustfs=info
# The servers inherit nextest's stdout (--no-capture): keep it where the stack proof reads it.
run: |
set -o pipefail
mkdir -p "$RUSTFS_E2E_LOG_DIR"
python3 scripts/e2e_binary.py run --features "$RUSTFS_BUILD_FEATURES" -- cargo nextest run -j 1 --profile e2e-protocols -p e2e_test --no-capture 2>&1 | tee "$RUSTFS_E2E_LOG_DIR/nextest.log"
- name: Prove the stack and upload the leg
if: always()
uses: ./.github/actions/dual-stack-leg
with:
profile: e2e-protocols
stack: ${{ matrix.stack }}
logs: ${{ runner.temp }}/rustfs-protocol-e2e-logs
- name: Upload protocol diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-protocol-nightly-${{ github.run_number }}-${{ matrix.stack }}
name: e2e-protocol-nightly-${{ github.run_number }}
path: |
target/nextest/e2e-protocols/junit.xml
${{ runner.temp }}/rustfs-e2e-protocols-list.json
@@ -283,20 +229,6 @@ jobs:
retention-days: 7
if-no-files-found: warn
dual-stack-summary:
name: Both-stack diff summary
needs: [repl-nightly, cluster-nightly, protocols-nightly]
if: github.repository == 'rustfs/rustfs' && always()
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: ./.github/actions/dual-stack-summary
with:
profiles: e2e-repl-nightly,e2e-nightly,e2e-protocols
alert-on-failure:
name: Alert on scheduled failure
needs: [repl-nightly, cluster-nightly, protocols-nightly]
+39 -7
View File
@@ -90,11 +90,16 @@ jobs:
- version: 1.0.1
asset: rustfs-linux-x86_64-gnu-v1.0.1.zip
sha256: 9742e183cb0dfb0d48fa909797af572fe47b7f827569036baa4156e0d3958ee5
- version: 1.0.5
asset: rustfs-linux-x86_64-gnu-v1.0.5.zip
sha256: 5addae2f74756bf80104d0975e6347cda843bc2daffdfcd1f0cb80118b95cbd0
revision: 34e6449ed90e3d3a106f6655342e0b3127f33082
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
UPGRADE_SOURCE_VERSION: ${{ matrix.source.version }}
UPGRADE_SOURCE_ASSET: ${{ matrix.source.asset }}
UPGRADE_SOURCE_SHA256: ${{ matrix.source.sha256 }}
UPGRADE_SOURCE_REVISION: ${{ matrix.source.revision }}
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -132,6 +137,13 @@ jobs:
unzip -q "$archive" -d "$SOURCE_DIR"
chmod +x "$SOURCE_DIR/rustfs"
test -x "$SOURCE_DIR/rustfs"
if [[ -n "$UPGRADE_SOURCE_REVISION" ]]; then
mkdir -p "$RUNNER_TEMP/rustfs-upgrade-logs"
version_log="$RUNNER_TEMP/rustfs-upgrade-logs/source-version.txt"
"$SOURCE_DIR/rustfs" --version | tee "$version_log"
grep -Fx "rustfs $UPGRADE_SOURCE_VERSION" "$version_log"
grep -Eq "^git commit[[:space:]]*:[[:space:]]*$UPGRADE_SOURCE_REVISION$" "$version_log"
fi
echo "RUSTFS_UPGRADE_SOURCE_BINARY=$SOURCE_DIR/rustfs" >> "$GITHUB_ENV"
echo "RUSTFS_E2E_LOG_DIR=$RUNNER_TEMP/rustfs-upgrade-logs" >> "$GITHUB_ENV"
@@ -151,12 +163,14 @@ jobs:
multipart-layout-upgrade:direct_upgrade_from_previous_release_preserves_multipart_layouts
multipart-layout-baseline:previous_release_baseline_replicates_multipart_layouts
)
if [[ "$UPGRADE_SOURCE_VERSION" == "1.0.0-rc.5" ]]; then
cases+=(odm-config-rollback:rc5_rollback_requires_restoring_odm_configuration)
cases+=(checkpoint-upgrade:rc5_checkpoint_upgrade_rewinds_signed_progress_without_losing_objects)
else
cases+=(legacy-delete-reservation:stable_upgrade_deletes_foreign_reservations_without_losing_live_objects)
fi
case "$UPGRADE_SOURCE_VERSION" in
1.0.0-rc.5)
cases+=(odm-config-rollback:rc5_rollback_requires_restoring_odm_configuration)
cases+=(checkpoint-upgrade:rc5_checkpoint_upgrade_rewinds_signed_progress_without_losing_objects) ;;
1.0.1) cases+=(legacy-delete-reservation:stable_upgrade_deletes_foreign_reservations_without_losing_live_objects) ;;
1.0.5) ;; # The bucket rollback case also completes an in-flight multipart upload.
*) echo "::error::Unknown upgrade source $UPGRADE_SOURCE_VERSION"; exit 1 ;;
esac
status=0
for entry in "${cases[@]}"; do
artifact="${entry%%:*}"
@@ -178,7 +192,7 @@ jobs:
exit "$status"
- name: Run mixed-version MPU recovery
if: ${{ !cancelled() && steps.verify_source.outcome == 'success' }}
if: ${{ !cancelled() && steps.verify_source.outcome == 'success' && matrix.source.version != '1.0.5' }}
timeout-minutes: 15
env:
NO_PROXY: 127.0.0.1,localhost,::1
@@ -199,6 +213,24 @@ jobs:
"$mpu_test" -- --exact --nocapture --test-threads=1 \
2>&1 | tee "$RUSTFS_E2E_LOG_DIR/test.log"
- name: Verify gateway baseline G09 evidence
if: ${{ success() && matrix.source.version == '1.0.5' }}
shell: bash
run: |
for field in mixed_version_reader_evidence mixed_version_writer_evidence rollback_payload_evidence; do
directory=mixed-version-upgrade
if [[ "$field" == rollback_payload_evidence ]]; then directory=bucket-config-rollback; fi
jq -e --arg field "$field" --arg current "$GITHUB_SHA" --arg previous "$UPGRADE_SOURCE_REVISION" \
'.gate == "G09" and .field == $field and .current_revision == $current and .previous_revision == $previous
and ($field != "rollback_payload_evidence" or .rollback_payload_replayed == true)' \
"$RUNNER_TEMP/rustfs-upgrade-g09-evidence/$directory/G09-$field.json"
done
jq -e --arg current "$GITHUB_SHA" --arg previous "$UPGRADE_SOURCE_REVISION" \
'.current_revision == $current and .previous_revision == $previous
and .part_sizes == [5242880, 5242880, 4096] and .bytes == (.part_sizes | add)
and (.rollback_read_sha256 | test("^[a-f0-9]{64}$")) and .rollback_read_sha256 == .roll_forward_read_sha256' \
"$RUNNER_TEMP/rustfs-upgrade-g09-evidence/bucket-config-rollback/inflight-multipart-rollback.json"
- name: Upload scanner/heal G09 evidence
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+19 -78
View File
@@ -15,31 +15,20 @@
# Gateway black-box acceptance lanes (rustfs/backlog#2775 T3.4, #2776 T3.5).
#
# Runs two suites of the rustfs/gateway repository against the candidate binary,
# once per S3 stack (RUSTFS_S3_STACK=legacy and =gateway), one server per stack:
# one server:
#
# - the conformance corpus, `--profile rustfs`. That profile describes the
# gateway edge, so scripts/check_conformance_rulings.py judges the gateway
# stack against .config/conformance-rulings.toml (red: an unruled failure, a
# ruled case failing differently, a stale ruling, a skip on the server's own
# answer) and publishes the legacy run as a reference that is never judged:
# it only has to serve, stay up and complete;
# - the client matrix, ci/compat/run_matrix.sh --external, judged per stack by
# - the conformance corpus, `--profile rustfs`, judged by
# scripts/check_conformance_rulings.py against .config/conformance-rulings.toml
# (red: an unruled failure, a ruled case failing differently, a stale ruling,
# a skip on the server's own answer);
# - the client matrix, ci/compat/run_matrix.sh --external, judged by
# scripts/compat_matrix_report.py (no `fail`, no `sut-unregistered`, every
# client ran; a client that could not be installed is reported as skipped).
# The legacy matrix is the baseline: every cell that passes on legacy must
# pass on gateway (`compare`).
#
# The suites are checked out at the rustfs/gateway rev Cargo.toml pins, so the
# suite and the framework under test never drift apart. The verdict of each
# stack is computed from what the run left on disk (startup record, the stack
# the server's own log names, runner exit code, liveness after the corpus,
# report), never from the exit status of an earlier step. Needs
# scripts/dual_stack.py and the `s3_stack` startup field of rustfs/rustfs#9367.
#
# The gateway stack is report-only until T2.10: its job may fail without failing
# the workflow, and its summary says what it observed (did not start, or how many
# cases ran, passed, failed and were answered 501). The stack comparison is
# report-only for the same reason; its conformance half is information only.
# suite and the framework under test never drift apart. The verdict is computed
# from what the run left on disk (startup record, runner exit code, liveness
# after the corpus, report), never from the exit status of an earlier step.
#
# Not a pull-request gate. Scheduled failures are owned by the scheduled-validation
# watchdog (.github/scheduled-validations.json).
@@ -166,21 +155,15 @@ jobs:
retention-days: 1
acceptance:
name: ${{ matrix.stack == 'gateway' && 'Acceptance (gateway, report-only until T2.10)' || 'Acceptance (legacy)' }}
name: Acceptance
needs: [ plan, build-candidate, build-gateway-tools ]
# GitHub-hosted like the s3-tests targets of reference-parity.yml: the job
# only runs prebuilt binaries and the pinned clients, none of which needs Docker.
runs-on: ubuntu-latest
# About 3x the 15 minutes the legacy job took in run 43325101234 (client install about
# About 3x the 15 minutes the job took in run 43325101234 (client install about
# 8, matrix about 3, corpus about 3), so a hung server costs 45 runner minutes, not more.
timeout-minutes: 45
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy:
fail-fast: false
matrix:
stack: [ legacy, gateway ]
env:
STACK: ${{ matrix.stack }}
ENDPOINT: http://127.0.0.1:9000
# The conformance suite signs with these fixed fixture credentials (the AWS
# documentation example pair), so the candidate is started with them and the
@@ -213,10 +196,8 @@ jobs:
name: gateway-acceptance-tools
path: tools
# Records `ready`, or what the process said when it exited, in lane/startup.txt. `ready`
# also needs the server's own `server_starting` log event to name the requested stack
# (its `s3_stack` field comes from rustfs/rustfs#9367; scripts/dual_stack.py reads it).
- name: Start candidate (${{ matrix.stack }} stack)
# Records `ready`, or what the process said when it exited, in lane/startup.txt.
- name: Start candidate
run: |
set -uo pipefail
chmod +x target/debug/rustfs tools/*
@@ -224,7 +205,7 @@ jobs:
target/debug/rustfs --version | tee lane/candidate-version.txt
# The four directories share the runner's one disk; the bypass is the CI case the
# physical-disk guard sanctions (as in mint.yml).
RUSTFS_S3_STACK="$STACK" RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true RUST_LOG=info target/debug/rustfs --address 127.0.0.1:9000 \
RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true RUST_LOG=info target/debug/rustfs --address 127.0.0.1:9000 \
--access-key "$ACCESS_KEY" --secret-key "$SECRET_KEY" "$RUNNER_TEMP"/data/rustfs{0..3} \
> lane/rustfs.log 2>&1 &
pid=$!
@@ -239,13 +220,8 @@ jobs:
exit 1
fi
if curl -sf "$ENDPOINT/health/ready" >/dev/null; then
if python3 scripts/dual_stack.py stack --expect "$STACK" --out lane/stack.json lane/rustfs.log > /dev/null; then
echo ready > lane/startup.txt
exit 0
fi
echo "did not start: stack not observed" > lane/startup.txt
cat lane/startup.txt
exit 1
echo ready > lane/startup.txt
exit 0
fi
sleep 1
done
@@ -338,58 +314,23 @@ jobs:
run: |
set -uo pipefail
status=0
python3 scripts/check_conformance_rulings.py --stack "$STACK" --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
python3 scripts/compat_matrix_report.py check --stack "$STACK" --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
python3 scripts/check_conformance_rulings.py --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
python3 scripts/compat_matrix_report.py check --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
exit "$status"
- name: Upload lane results
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: gateway-acceptance-lane-${{ matrix.stack }}
name: gateway-acceptance-lane
overwrite: true
path: |
lane/*.txt
lane/*.log
lane/report.json
lane/stack.json
lane/compat/matrix.json
lane/compat/probe.jsonl
lane/compat/sut.log
lane/compat/results/**
if-no-files-found: error
retention-days: 14
compare:
name: Compare stacks (report-only until T2.10)
needs: [ acceptance ]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 10
continue-on-error: true
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Download lane results
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: gateway-acceptance-lane-*
path: lanes
- name: Diff legacy and gateway
run: |
set -uo pipefail
status=0
{
python3 scripts/check_conformance_rulings.py \
--diff lanes/gateway-acceptance-lane-legacy lanes/gateway-acceptance-lane-gateway || status=1
echo
python3 scripts/compat_matrix_report.py diff \
--legacy lanes/gateway-acceptance-lane-legacy --gateway lanes/gateway-acceptance-lane-gateway || status=1
} > diff.md
cat diff.md
cat diff.md >> "$GITHUB_STEP_SUMMARY"
exit "$status"
+2 -52
View File
@@ -44,13 +44,6 @@
# well inside the 120-minute budget and buys deterministic infra. The
# docker-capable self-hosted `dind-sm-standard-2` label was the alternative but
# has fewer cores and reintroduces fleet-state risk for no reliability gain.
#
# Stack dimension (rustfs/backlog#2774, T3.3): one image, run with RUSTFS_S3_STACK=legacy and
# =gateway. `compare` (scripts/mint_stack_diff.py) holds the gate that every case legacy passes
# passes on gateway with no new failure. The gateway leg and `compare` are report-only until
# T2.10. A gateway server that refuses to start stops its leg at "Wait for RustFS ready", before
# mint runs; the summary says `skipped: gateway stack refuses startup: <why>`. The stack is read
# from the server's own start-up line (scripts/dual_stack.py stack).
name: mint
@@ -145,16 +138,8 @@ jobs:
retention-days: 1
mint:
name: mint (${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
name: mint
needs: [image]
# Report-only until T2.10: the gateway stack cannot serve the suites yet.
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy:
fail-fast: false
matrix:
stack: [legacy, gateway]
env:
STACK: ${{ matrix.stack }}
# GitHub-hosted: reliably provides a running Docker daemon + buildx +
# python3. See the header note (ci-2) for why the self-hosted sm-standard-4
# label was abandoned (no docker.sock on the pod its only run landed on).
@@ -194,7 +179,6 @@ jobs:
-e RUSTFS_SECRET_KEY="${S3_SECRET_KEY}" \
-e RUSTFS_VOLUMES="/data/rustfs{0...3}" \
-e RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true \
-e RUSTFS_S3_STACK="${STACK}" \
-e RUST_LOG=rustfs=info \
-v /tmp/rustfs-mint:/data \
rustfs-ci
@@ -291,47 +275,13 @@ jobs:
mkdir -p artifacts/rustfs-mint
docker logs rustfs-mint > artifacts/rustfs-mint/rustfs.log 2>&1 || true
- name: Prove which stack the server selected
if: always()
run: python3 scripts/dual_stack.py stack --expect "${STACK}" --out artifacts/stack.json artifacts/rustfs-mint
- name: Upload artifacts
if: always() && env.ACT != 'true'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: mint-${{ matrix.stack }}
name: mint
path: artifacts/**
compare:
name: Compare stacks (report-only until T2.10)
needs: [mint]
if: always()
continue-on-error: true
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Download both legs
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: mint-{legacy,gateway}
path: legs
# A leg that never uploaded leaves no directory: create both so that the
# comparison reports "no result" for it instead of failing to find it.
- name: Compare the stacks
run: |
# The shell runs with -e; the exit status is reported after the summary is written.
set +e -u -o pipefail
mkdir -p legs/mint-legacy legs/mint-gateway
python3 scripts/mint_stack_diff.py legs/mint-legacy legs/mint-gateway | tee report.txt
status="${PIPESTATUS[0]}"
{ echo '## Mint: gateway versus legacy'; echo; echo '```'; cat report.txt; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
exit "$status"
alert-on-failure:
name: Alert on scheduled failure
needs: [image, mint]
@@ -68,14 +68,11 @@ env:
jobs:
minio-source:
name: MinIO source (read-through, list-through, backfill, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
name: MinIO source (read-through, list-through, backfill)
# Keep this scheduled interoperability lane scoped to the upstream repo.
if: github.repository == 'rustfs/rustfs'
runs-on: ubuntu-latest
timeout-minutes: 90
# The gateway leg is report-only until T2.10.
continue-on-error: ${{ matrix.stack == 'gateway' }}
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
env:
NO_PROXY: 127.0.0.1,localhost
# Fixed credentials of the container this job starts and throws away;
@@ -140,11 +137,6 @@ jobs:
- name: Build the RustFS binary under test
run: python3 scripts/e2e_binary.py build --bins
# A gateway binary that refuses to start skips the suite; the summary says why.
- name: Gateway preflight
if: matrix.stack == 'gateway'
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
# The lane selects tests by module, so a rename would quietly shrink it.
# The committed digest in .config/e2e-odm-interop-selection.txt fails
# closed on that.
@@ -155,18 +147,9 @@ jobs:
- name: Run the interop cases against MinIO
env:
RUSTFS_S3_STACK: ${{ matrix.stack }}
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-logs
run: python3 scripts/e2e_binary.py run -- cargo nextest run --profile e2e-odm-interop -p e2e_test --no-tests=fail
- name: Prove the stack and upload the leg
if: always()
uses: ./.github/actions/dual-stack-leg
with:
profile: e2e-odm-interop
stack: ${{ matrix.stack }}
logs: ${{ runner.temp }}/rustfs-e2e-logs
- name: Build the MinIO interop report
if: always()
uses: ./.github/actions/odm-interop-report
@@ -190,7 +173,7 @@ jobs:
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: odm-interop-minio-${{ github.run_number }}-${{ github.run_attempt }}-${{ matrix.stack }}
name: odm-interop-minio-${{ github.run_number }}-${{ github.run_attempt }}
path: |
artifacts/odm-interop/minio
target/nextest/e2e-odm-interop/junit.xml
@@ -316,20 +299,6 @@ jobs:
target/nextest/e2e-odm-interop/junit.xml
retention-days: 14
dual-stack-summary:
name: Both-stack diff summary
needs: [minio-source]
if: github.repository == 'rustfs/rustfs' && always()
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: ./.github/actions/dual-stack-summary
with:
profiles: e2e-odm-interop
alert-on-failure:
name: Alert on scheduled failure
needs: [minio-source, cloud-source]
+37 -6
View File
@@ -1,10 +1,7 @@
name: S3-over-RDMA feature check
# 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.
# Compile the optional RDMA features independently. The cuObject tests link
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
# Not a required check and not part of the `Test and Lint` aggregate.
on:
@@ -12,6 +9,7 @@ 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"
@@ -70,9 +68,42 @@ 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]
needs: [nixl-check, cuobject-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')
+4 -4
View File
@@ -32,9 +32,9 @@
#
# The `differential` job adds the 73-operation dual-stack differential
# (crates/e2e_test/src/dual_stack_differential, rustfs/backlog#2740) against the
# same pinned reference: side A is the released binary (RUSTFS_E2E_REFERENCE_BINARY,
# started without RUSTFS_S3_STACK), side B is the candidate built above on its
# legacy stack. It reuses the candidate build artifact, never builds the candidate
# same pinned reference: side A is the released binary (RUSTFS_E2E_REFERENCE_BINARY),
# side B is the candidate built above.
# It reuses the candidate build artifact, never builds the candidate
# twice, and prints reference_side, version_a and version_b from the report the test
# wrote; it fails when side A was not the reference or both sides report the same
# version. Every (op, field, a, b) difference goes to the job summary. Report-only
@@ -310,7 +310,7 @@ jobs:
chmod +x target/debug/rustfs
test -x "$REFERENCE_PATH"
mkdir -p "$RUSTFS_E2E_LOG_DIR"
# Side A: the released binary. Side B: the candidate on its legacy stack.
# Side A: the released binary. Side B: the candidate.
export RUSTFS_E2E_REFERENCE_BINARY="$REFERENCE_PATH"
test_name='dual_stack_differential::tests::both_stacks_answer_every_operation_identically'
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- \
+12
View File
@@ -80,6 +80,18 @@ 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. |
+5
View File
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Deployment
- **The S3 protocol stack is now rustfs/gateway**, and it is the only S3 stack. The legacy s3s-based stack is removed, and so are the `RUSTFS_S3_STACK` environment variable and the `gateway-stack` cargo feature. There is no on-disk format change. `RUSTFS_S3_STACK` no longer selects anything: a server started with it set, to any value, refuses to start and prints `RUSTFS_S3_STACK is no longer supported; the gateway stack is the only S3 stack since <version>`, where `<version>` is the release's version. Remove the variable from service units, container environments, Helm values and orchestration files before upgrading. To roll back, follow the [S3 stack rollback procedure](docs/operations/s3-stack-rollback.md).
- Before upgrading, verify that the configured root access key is at least 3 bytes and the root secret key is at least 8 bytes. RustFS now rejects shorter values at startup and identifies the setting to update. Version 1.0.5 accepted these settings at startup and returned HTTP 500 when root requested STS credentials. Coordinate root credential changes across all nodes and clients. See [root credential rotation considerations](docs/operations/two-factor-auth.md#root-credentials-cannot-be-changed-at-runtime).
- Existing volumes created by older root-running container images must be writable by the non-root runtime identity before upgrading. The default container UID/GID is `10001:10001`; stop the affected instances, verify host mount paths, and for ordinary bind mounts run `sudo chown -R 10001:10001 /actual/data /actual/logs` on each RustFS data/log mount. Account for ACLs, NFS, Kubernetes, and rootless UID mappings. Image-build ownership changes do not migrate mounted data. See the Docker Quick Start in [README.md](README.md).
@@ -44,6 +46,8 @@ 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.
@@ -114,6 +118,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
+707 -548
View File
File diff suppressed because it is too large Load Diff
+58 -46
View File
@@ -23,6 +23,7 @@ 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
@@ -60,6 +61,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
@@ -71,6 +73,7 @@ members = [
"crates/zip", # ZIP file handling and compression
"crates/zstd-compat", # Fixed codec for dependencies requiring zstd 0.13
]
exclude = ["vendor/hyper"]
resolver = "3"
[workspace.package]
@@ -107,6 +110,7 @@ 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" }
@@ -139,6 +143,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" }
@@ -151,16 +156,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 = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.2.0", default-features = false }
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 }
# 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 = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.66.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", 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 = "ab5242b092f60c22a6cbace3950117f4702de36a", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.13.0", default-features = false }
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 }
# Async Runtime and Networking
async-channel = "2.5.0"
@@ -168,15 +173,15 @@ async_zip = { default-features = false, version = "0.0.19" }
mysql_async = { default-features = false, version = "0.37.1" }
async-compression = { version = "0.4.52" }
async-trait = "0.1.92"
async-nats = { version = "0.52.0", default-features = false }
async-nats = { version = "0.53.0", default-features = false }
axum = "0.8.9"
futures = "0.3.34"
futures-core = "0.3.34"
futures-lite = "2.6.1"
futures-util = "0.3.34"
pollster = "1.0.1"
pollster = "1.0.3"
pulsar = { default-features = false, version = "=6.9.0" }
lapin = { default-features = false, version = "4.12.3" }
lapin = { default-features = false, version = "4.13.0" }
hyper = { version = "1.12.0" }
h2 = { version = "0.4.20" }
hyper-rustls = { default-features = false, version = "0.27.10" }
@@ -209,18 +214,19 @@ quinn = { version = "0.11.12", default-features = false, features = [
] }
# Serialization and Data Formats
apache-avro = { version = "0.22.0", features = ["snappy", "zstandard"] }
bytes = { version = "1.12.1" }
apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
bytes = { version = "1.12.2" }
csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.0"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.2"
form_urlencoded = "1.2.3"
prost = "0.14.6"
quick-xml = "0.42.0"
rmp = { version = "0.8.15" }
rmp-serde = { version = "1.3.1" }
serde = { version = "1.0.229" }
serde-value = "0.7.0"
serde_ignored = { version = "0.1" }
serde_with = { version = "3", default-features = false, features = ["macros", "std"] }
serde_json = { version = "1.0.154" }
@@ -242,7 +248,7 @@ jsonwebtoken = { version = "12.0.0" }
openidconnect = { default-features = false, version = "4.1.0" }
pbkdf2 = "0.13.0"
p256 = { version = "0.14.0", features = ["ecdsa", "pkcs8"] }
rsa = { version = "=0.10.0-rc.18" }
rsa = { version = "0.10.0", features = ["pkcs1v15"] }
rustls = { default-features = false, version = "0.23.46" }
rustls-native-certs = "0.8"
rustls-pki-types = "1.16.0"
@@ -250,13 +256,13 @@ x509-parser = "0.18.1"
sha1 = "0.11.0"
sha2 = "0.11.1"
subtle = "2.6"
zeroize = { version = "1.9.1" }
zeroize = { version = "1.9.2" }
proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "0.2.43" }
jiff = { version = "1.0.2" }
time = { version = "0.3.55" }
# Database
@@ -273,18 +279,18 @@ tar-codec = "0.0.16"
tar-framing = "0.0.16"
atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.2" }
aws-config = { version = "1.13.3" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.131.0" }
aws-sdk-s3 = { default-features = false, version = "1.159.0" }
aws-sdk-sts = { default-features = false, version = "1.126.0" }
aws-sdk-kms = { default-features = false, version = "1.133.0" }
aws-sdk-s3 = { default-features = false, version = "1.161.0" }
aws-sdk-sts = { default-features = false, version = "1.128.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.2" }
aws-smithy-runtime-api = { version = "1.21.0" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
aws-smithy-runtime-api = { version = "1.22.0" }
aws-smithy-types = { version = "1.9.4" }
base64-simd = "0.8.0"
brotli = "9.1.1"
clap = { version = "4.6.7" }
brotli = "9.1.3"
clap = { version = "4.6.9" }
const-str = { version = "1.1.0" }
convert_case = "0.12.0"
criterion = { version = "0.8" }
@@ -292,16 +298,16 @@ crossbeam-queue = "0.3.14"
crossbeam-channel = "0.5.17"
crossbeam-deque = "0.8.8"
crossbeam-utils = "0.8.23"
datafusion = { default-features = false, version = "55.2.0" }
datafusion = { default-features = false, version = "55.3.0" }
derive_builder = "0.20.2"
ed25519-dalek = "3.0.0"
enumset = "1.1.15"
faster-hex = "1.0.0"
faster-hex = "2.0.0"
flate2 = "1.1.11"
glob = "0.3.4"
google-cloud-storage = "1.22.0"
google-cloud-auth = "1.19.0"
hashbrown = { version = "0.17.1" }
hashbrown = { version = "0.17.2" }
# Base32 for RFC 6238 TOTP shared secrets (RFC 4648 unpadded, the alphabet
# every authenticator app expects). Already in the graph transitively.
data-encoding = "2.11.1"
@@ -311,14 +317,15 @@ hostname = "0.4.2"
ipnetwork = { version = "0.21.1" }
lazy_static = "1.5.1"
libc = "0.2.191"
cuobject = { version = "0.1.0", default-features = false }
cxx = "1"
cxx-build = "1"
libsystemd = "0.7.2"
local-ip-address = "0.6.13"
log = "0.4"
memmap2 = "0.9.12"
nixl-sys = { git = "https://github.com/houseme/nixl", rev = "cc636c83f13d692e85b67e55aed092413d16fb41" }
lz4 = "1.28.1"
lz4_flex = { version = "=0.14.0", default-features = false, features = ["std", "frame"] }
lz4_flex = { version = "0.14.2", default-features = false, features = ["std", "frame"] }
matchit = "0.9.2"
md-5 = "0.11.0"
mime_guess = "2.0.5"
@@ -335,16 +342,16 @@ percent-encoding = "2.3.2"
# CLI needs its own QR encoder. No default features: the image/render backends
# pull in an image stack this only needs SVG and text output from.
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.17"
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.3" }
rand = { version = "0.10.4" }
ratelimit = "2.0.0"
rayon = "1.12.0"
rustfs-erasure-codec = { version = "9.1.0" }
reed-solomon-simd = "3.1.0"
regex = { version = "1.13.1" }
regex = { version = "1.13.2" }
rumqttc = { package = "rumqttc-next", version = "0.34.0" }
redis = { version = "1.8.1" }
redis = { version = "1.8.2" }
rustify = { version = "0.7", default-features = false }
rustix = { version = "1.1.6" }
rust-embed = { version = "8.14.0" }
@@ -358,13 +365,13 @@ legacy-s3s = { package = "s3s", git = "https://github.com/s3s-project/s3s", rev
serial_test = "4.0.1"
shadow-rs = { default-features = false, version = "2.0.0" }
siphasher = "1.0.4"
smallvec = { version = "1.16.5" }
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.1" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.3"
sysinfo = "0.40.4"
temp-env = "0.3.6"
tempfile = "3.27.0"
test-case = "3.4.1"
@@ -376,23 +383,23 @@ tracing-error = "0.2.1"
tracing-opentelemetry = { version = "0.34.0" }
tracing-subscriber = { version = "0.3.23" }
transform-stream = "0.3.1"
url = "2.5.8"
url = "2.5.9"
urlencoding = "2.1.3"
uuid = { version = "1.29.2" }
uuid = { version = "1.29.3" }
vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.0"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
xxhash-rust = { version = "0.8.19" }
zip = "9.5.1"
xxhash-rust = { version = "0.8.21" }
zip = "9.8.1"
zstd = "0.14.4"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
dial9 = { version = "0.5.8", default-features = false }
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
opentelemetry-otlp = { version = "0.33.1" }
@@ -403,12 +410,12 @@ opentelemetry-stdout = { version = "0.33.1" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
libunftp = { version = "0.25.0" }
libunftp = { version = "0.25.1" }
unftp-core = "0.1.1"
suppaftp = { version = "12.2.1" }
suppaftp = { version = "13.0.0" }
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] }
russh = { version = "0.65.1" }
russh-sftp = "3.0.1"
russh = { version = "0.65.4" }
russh-sftp = "4.0.0"
# WebDAV
dav-server = "0.12.0"
@@ -416,12 +423,15 @@ dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.4" }
# Preserve Unicode focus filters until rustfs/backlog#2302 is resolved.
hotpath = { version = "0.31.2", default-features = false }
hotpath = { version = "0.32.1", default-features = false }
# Snapshot testing for output format regression detection
insta = { version = "1.49" }
[workspace.metadata.cargo-shear]
ignored = ["hotpath", "rustfs"]
# The `#[path]` test modules under `rustfs/src/server/http/tests/` are linked by
# rustc (including the `http.rs` + `http/` sibling-directory rule), but cargo-shear
# resolves those nested `#[path]` attributes against the wrong base directory.
ignored-paths = ["rustfs/src/server/http/tests/**/*.rs"]
[profile.dev]
# Full debuginfo roughly doubles compile+link time and produces multi-GB
@@ -456,4 +466,6 @@ strip = "none"
# Pin upstream fixes until compatible crates.io releases are available.
[patch.crates-io]
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
zstd = { path = "crates/zstd-compat" }
+3 -4
View File
@@ -15,12 +15,11 @@ workspace = true
[features]
default = []
hotpath = ["hotpath/hotpath", "hotpath/tokio", "rustfs-io-core/hotpath"]
hotpath-alloc = ["hotpath", "hotpath/hotpath-alloc", "rustfs-io-core/hotpath-alloc"]
hotpath-cpu = ["hotpath", "hotpath/hotpath-cpu", "rustfs-io-core/hotpath-cpu"]
hotpath = ["rustfs-io-core/hotpath"]
hotpath-alloc = ["hotpath", "rustfs-io-core/hotpath-alloc"]
hotpath-cpu = ["hotpath", "rustfs-io-core/hotpath-cpu"]
[dependencies]
hotpath.workspace = true
# Internal crates
rustfs-io-core = { workspace = true }
serde = { workspace = true, features = ["derive"] }
+6
View File
@@ -129,6 +129,12 @@ when restoring `/rustfs/console` for a custom OEM build.
- `RUSTFS_SCANNER_MAX_CONCURRENT_SET_SCANS` (canonical)
- `RUSTFS_SCANNER_MAX_CONCURRENT_DISK_SCANS` (canonical)
- `RUSTFS_SCANNER_WALKERS_PER_DISK` (canonical)
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF` (canonical, default `false`)
Read-only restart continuity:
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF=true` enables reuse of unpublished scanner progress across verified read-only process restarts. Unset, false or invalid values disable both identity restoration and receipt creation. Existing receipts are still durably consumed before recovery starts, even when the feature is disabled.
- Deploy receipt-aware readers to every possible writer before enabling this flag. Before rolling back to an older binary, disable it on every node, start each node with all its drives present, wait for readiness, and shut down cleanly. Do not start the older binary until every node completes this preparation. Direct rollback after enabling receipt writes is unsupported: older startup/recovery paths can write without durably invalidating the receipt. See [the receipt and rollback contract](../../docs/architecture/scanner-usage-publication.md#read-only-restart-continuity).
Scanner cycle budget controls:
+5
View File
@@ -21,6 +21,11 @@ pub const APP_NAME: &str = "RustFS";
/// Cargo package version for this workspace member.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
/// Defaults to false. Enable only after all possible writers support receipt
/// consumption; disable and restart before rolling back to an older writer.
pub const ENV_SCANNER_READ_ONLY_HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
/// Default configuration logger level
/// Default value: error
/// Environment variable: RUSTFS_OBS_LOGGER_LEVEL
+3
View File
@@ -32,6 +32,9 @@ 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.
+2 -4
View File
@@ -349,10 +349,8 @@ pub const DEFAULT_INTERNODE_DATA_TRANSPORT: &str = "tcp-http";
/// Legacy alias for "tcp-http". Both values select the TCP/HTTP transport backend.
pub const INTERNODE_DATA_TRANSPORT_TCP: &str = "tcp";
/// Internode reads whose data moves over NIXL/UCX (InfiniBand rails or RoCE by
/// LID/GID, no IP needed); requests, writes and walks stay on TCP/HTTP. Requires
/// a binary built with the `nixl` feature and `RUSTFS_NIXL_ENABLE`; until the
/// NIXL agent is up, and for any read it cannot serve, it uses TCP/HTTP.
/// Shard reads and writes use NIXL/UCX and require an active NIXL agent on both peers.
/// Format metadata, directory walks and scanner requests use the control transport.
pub const INTERNODE_DATA_TRANSPORT_NIXL: &str = "nixl";
/// Known internode transport backend names accepted by the config parser.
+27
View File
@@ -152,6 +152,33 @@ pub const DEFAULT_SHARD_INTEGRITY_WRITE: bool = false;
pub const ENV_SHARD_INTEGRITY_FLEET_CONFIRMED: &str = "RUSTFS_SHARD_INTEGRITY_FLEET_CONFIRMED";
pub const DEFAULT_SHARD_INTEGRITY_FLEET_CONFIRMED: bool = false;
/// Request parsing switch for the per-object erasure-code block-size hint.
/// The default keeps the feature inert during rolling upgrades.
pub const ENV_EC_BLOCK_SIZE_HINT_ENABLE: &str = "RUSTFS_EC_BLOCK_SIZE_HINT_ENABLE";
pub const DEFAULT_EC_BLOCK_SIZE_HINT_ENABLE: bool = false;
/// Operator confirmation that every writer and reader in the fleet understands
/// the persisted erasure block-size geometry.
pub const ENV_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED: &str = "RUSTFS_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED";
pub const DEFAULT_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED: bool = false;
/// Write new EC shards with a bounded bitrot frame size so Range GETs do not
/// inherit the full persisted layout block as their physical read quantum.
/// The marker is only emitted after the fleet confirmation gate is enabled;
/// readers without this feature continue to consume legacy objects unchanged.
pub const ENV_EC_READ_QUANTUM_ENABLE: &str = "RUSTFS_EC_READ_QUANTUM_ENABLE";
pub const DEFAULT_EC_READ_QUANTUM_ENABLE: bool = false;
/// Operator confirmation that every reader and writer understands the
/// persisted EC read-quantum marker and its per-frame bitrot layout.
pub const ENV_EC_READ_QUANTUM_FLEET_CONFIRMED: &str = "RUSTFS_EC_READ_QUANTUM_FLEET_CONFIRMED";
pub const DEFAULT_EC_READ_QUANTUM_FLEET_CONFIRMED: bool = false;
const _: () = assert!(!DEFAULT_EC_BLOCK_SIZE_HINT_ENABLE);
const _: () = assert!(!DEFAULT_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED);
const _: () = assert!(!DEFAULT_EC_READ_QUANTUM_ENABLE);
const _: () = assert!(!DEFAULT_EC_READ_QUANTUM_FLEET_CONFIRMED);
const _: () = assert!(!DEFAULT_SHARD_INTEGRITY_WRITE);
const _: () = assert!(!DEFAULT_SHARD_INTEGRITY_FLEET_CONFIRMED);
+1 -1
View File
@@ -36,7 +36,7 @@ jsonwebtoken = { workspace = true, features = ["aws_lc_rs"] }
base64-simd = { workspace = true }
pbkdf2 = { workspace = true, optional = true }
rand = { workspace = true, features = ["serde"] }
rsa = { workspace = true, features = ["sha2"] }
rsa = { workspace = true }
serde = { workspace = true, features = ["derive"] }
sha2 = { workspace = true, optional = true }
thiserror.workspace = true
+16 -16
View File
@@ -13,9 +13,9 @@
// limitations under the License.
use rsa::{
Pkcs1v15Encrypt, RsaPrivateKey, RsaPublicKey,
Pkcs1v15Encrypt, PrivateKey, PublicKey,
pkcs8::{DecodePrivateKey, DecodePublicKey},
pss::{BlindedSigningKey, Signature, VerifyingKey},
pss::{Signature, SigningKey, VerifyingKey},
sha2::Sha256,
signature::{RandomizedSigner, Verifier},
traits::PublicKeyParts,
@@ -37,7 +37,7 @@ pub struct Token {
pub fn gencode(token: &Token, key: &str) -> Result<String> {
let data = serde_json::to_vec(token)?;
let mut rng = rand::rng();
let public_key = RsaPublicKey::from_public_key_pem(key).map_err(Error::other)?;
let public_key = PublicKey::from_public_key_pem(key).map_err(Error::other)?;
let encrypted_data = public_key.encrypt(&mut rng, Pkcs1v15Encrypt, &data).map_err(Error::other)?;
Ok(base64_simd::URL_SAFE_NO_PAD.encode_to_string(&encrypted_data))
}
@@ -51,7 +51,7 @@ pub fn parse(token: &str, key: &str) -> Result<Token> {
let encrypted_data = base64_simd::URL_SAFE_NO_PAD
.decode_to_vec(token.as_bytes())
.map_err(Error::other)?;
let private_key = RsaPrivateKey::from_pkcs8_pem(key).map_err(Error::other)?;
let private_key = PrivateKey::from_pkcs8_pem(key).map_err(Error::other)?;
let decrypted_data = private_key.decrypt(Pkcs1v15Encrypt, &encrypted_data).map_err(Error::other)?;
serde_json::from_slice(&decrypted_data).map_err(Error::other)
}
@@ -63,8 +63,8 @@ pub fn parse(token: &str, key: &str) -> Result<Token> {
pub fn sign_license_token(token: &Token, private_key_pem: &str) -> Result<String> {
let payload = serde_json::to_vec(token)?;
let mut rng = rand::rng();
let private_key = RsaPrivateKey::from_pkcs8_pem(private_key_pem).map_err(Error::other)?;
let signing_key = BlindedSigningKey::<Sha256>::new(private_key);
let private_key = PrivateKey::from_pkcs8_pem(private_key_pem).map_err(Error::other)?;
let signing_key = SigningKey::<Sha256>::new(private_key);
let signature: Signature = signing_key.try_sign_with_rng(&mut rng, &payload).map_err(Error::other)?;
let signature: Box<[u8]> = signature.into();
@@ -80,7 +80,7 @@ pub fn parse_signed_license_token(token: &str, public_key_pem: &str) -> Result<T
let signed_payload = base64_simd::URL_SAFE_NO_PAD
.decode_to_vec(token.as_bytes())
.map_err(Error::other)?;
let public_key = RsaPublicKey::from_public_key_pem(public_key_pem).map_err(Error::other)?;
let public_key = PublicKey::from_public_key_pem(public_key_pem).map_err(Error::other)?;
let signature_len = public_key.size();
if signed_payload.len() <= signature_len {
@@ -103,7 +103,7 @@ pub fn parse_license_with_public_key(license: &str, public_key: &str) -> Result<
mod tests {
use super::*;
use rsa::{
RsaPrivateKey,
PrivateKey,
pkcs8::{EncodePrivateKey, EncodePublicKey, LineEnding},
};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -112,8 +112,8 @@ mod tests {
fn test_sign_license_token_and_parse_signed_license_token() {
let mut rng = rand::rng();
let bits = 2048;
let private_key = RsaPrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
let public_key = RsaPublicKey::from(&private_key);
let private_key = PrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
let public_key = PublicKey::from(&private_key);
let private_key_pem = private_key
.to_pkcs8_pem(LineEnding::LF)
@@ -144,8 +144,8 @@ mod tests {
fn test_legacy_gencode_and_parse_roundtrip() {
let mut rng = rand::rng();
let bits = 2048;
let private_key = RsaPrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
let public_key = RsaPublicKey::from(&private_key);
let private_key = PrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
let public_key = PublicKey::from(&private_key);
let private_key_pem = private_key
.to_pkcs8_pem(LineEnding::LF)
@@ -173,8 +173,8 @@ mod tests {
#[test]
fn test_parse_signed_license_token_rejects_tampered_payload() {
let mut rng = rand::rng();
let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
let public_key = RsaPublicKey::from(&private_key);
let private_key = PrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
let public_key = PublicKey::from(&private_key);
let private_key_pem = private_key
.to_pkcs8_pem(LineEnding::LF)
.expect("failed to encode private key pem");
@@ -206,8 +206,8 @@ mod tests {
#[test]
fn test_parse_signed_license_token_rejects_invalid_token() {
let mut rng = rand::rng();
let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
let public_key = RsaPublicKey::from(&private_key);
let private_key = PrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
let public_key = PublicKey::from(&private_key);
let public_key_pem = public_key
.to_public_key_pem(LineEnding::LF)
.expect("failed to encode public key pem");
+22
View File
@@ -0,0 +1,22 @@
[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
@@ -0,0 +1,41 @@
// 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
@@ -0,0 +1,143 @@
// 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
@@ -0,0 +1,40 @@
// 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;
}
+22
View File
@@ -0,0 +1,22 @@
// 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.
//! Native bindings and SDK handle ownership for the NVIDIA cuObject server.
#![cfg(feature = "server")]
pub use cxx::Exception;
// SAFETY: this module declares the SDK ABI and the ownership of native handles.
#[allow(unsafe_code)]
mod sdk;
pub use sdk::*;
+149
View File
@@ -0,0 +1,149 @@
// 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 }
cuobject = { workspace = true, default-features = false, optional = true }
rustfs-cuobject-sys = { workspace = true, features = ["server"], 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:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
server = ["dep:bytes", "dep:rustfs-cuobject-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
+652 -226
View File
File diff suppressed because it is too large Load Diff
+72 -3
View File
@@ -1235,23 +1235,66 @@ 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", &self.children)?;
state.serialize_entry("children", 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", &self.replication_stats)?;
state.serialize_entry("replication_stats", replication)?;
state.serialize_entry("compacted", &self.compacted)?;
state.serialize_entry("failed_objects", &self.failed_objects)?;
state.serialize_entry("all_tier_stats", &self.all_tier_stats)?;
state.serialize_entry("all_tier_stats", tiers)?;
// 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() {
@@ -2534,6 +2577,32 @@ 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,6 +171,70 @@ 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,3 +321,110 @@ 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());
}
+6 -3
View File
@@ -98,7 +98,6 @@ rustfs-madmin.workspace = true
rustfs-filemeta.workspace = true
bytes = { workspace = true, features = ["serde"] }
aws-sdk-s3 = { workspace = true, default-features = false, features = ["sigv4a", "default-https-client", "rt-tokio"] }
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
aws-smithy-http-client = { workspace = true, default-features = false, features = ["rustls-aws-lc"] }
aws-smithy-types.workspace = true
async-trait = { workspace = true }
@@ -124,13 +123,12 @@ urlencoding.workspace = true
walkdir.workspace = true
base64-simd = { workspace = true }
rand = { workspace = true, features = ["serde"] }
chrono = { workspace = true, features = ["serde"] }
jiff = { workspace = true, features = ["serde"] }
hex-simd = { workspace = true }
md-5 = { workspace = true }
prost.workspace = true
sha2 = { workspace = true }
rustfs-s3-types = { workspace = true }
s3s = { workspace = true, features = ["minio"] }
zstd.workspace = true
time = { workspace = true, features = ["parsing", "formatting", "macros", "serde"] }
rcgen.workspace = true
@@ -140,8 +138,13 @@ rustls = { workspace = true, default-features = false, features = ["aws-lc-rs",
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"] }
opentelemetry-proto = { workspace = true }
russh = { workspace = true, features = ["serde"] }
russh-sftp = { workspace = true }
+3 -1
View File
@@ -29,7 +29,7 @@ Registered in [`src/lib.rs`](src/lib.rs). Grouped by concern:
| **distributed 4×4** | [`src/distributed/`](src/distributed) | Nightly `e2e-distributed` lane: S3, object lock/WORM, versioning, bucket/site replication, quota, expand/decommission/rebalance, concurrency, chaos, 4-node upgrade of historical data and IAM AK/SK. Map: [`docs/testing/distributed-e2e.md`](../../docs/testing/distributed-e2e.md) |
| **chaos / reliability** | [`src/chaos.rs`](src/chaos.rs), `reliability_disk_fault_test`, `heal_erasure_disk_rebuild_test`, `server_startup_failfast_test` | Disk offline/replace/corrupt, EC rebuild, heal, fail-fast startup |
| **upgrade compatibility** | `upgrade_compatibility_test` | Pinned previous-release writes followed by current-build reads on the same data directory |
| **dual-stack differential** | `dual_stack_differential` | Two single-node servers answer one SDK script for all 73 S3 operations and every differing `(op, field, a, b)` is reported. Side A is the binary under test on `RUSTFS_S3_STACK=legacy`; side B runs `RUSTFS_E2E_STACK_B`. Set `RUSTFS_E2E_REFERENCE_BINARY` to a released `rustfs` binary to make side A that binary instead (started without `RUSTFS_S3_STACK`, which older releases do not know). A missing, non-file or non-executable path fails the run; it never skips or falls back to the same-binary mode. The report in `<target>/dual-stack/<run>.json` records `reference_side` and each side's `--version` output |
| **dual-stack differential** | `dual_stack_differential` | Two single-node servers answer one SDK script for all 73 S3 operations and every differing `(op, field, a, b)` is reported. Both sides run the binary under test on its only (gateway) stack unless `RUSTFS_E2E_REFERENCE_BINARY` names a released `rustfs` binary, which then runs side A. A missing, non-file or non-executable path fails the run; it never skips or falls back to the same-binary mode. `RUSTFS_E2E_STACK_B_REGION` starts side B in another region to inject a difference. The report in `<target>/dual-stack/<run>.json` records `reference_side` and each side's `--version` output |
The external-tool `storage_metric_ownership_test` validates the OTLP/Collector/Prometheus path, including a rolling upgrade and node failures. See the [storage metrics guide](../../docs/operations/storage-metrics.md) for its required binaries and focused command.
@@ -211,6 +211,8 @@ the wiring source of truth. Committed test-ID digests under
**Endpoint blackhole scenario skipped** — `heal_erasure_disk_rebuild_test::tests::test_cluster_root_heal_recovers_after_target_endpoint_blackhole` installs a loopback `iptables` DROP rule and therefore needs `CAP_NET_ADMIN` (root or passwordless `sudo -n iptables`). A host where `iptables` is missing or cannot read the OUTPUT chain (typical inside an unprivileged container, where the nf_tables backend reports "Permission denied" even under `sudo`) logs a `heal_interruption_skipped` warning and returns without exercising heal. Set `RUSTFS_E2E_REQUIRE_NET_FAULT_INJECTION=1` on lanes that do provision the capability so a broken runner fails instead of skipping.
The full suite compares persisted bucket configurations and object records against the release pinned in `.config/reference-binary.toml`. Set `RUSTFS_PERSISTENCE_REFERENCE_BINARY` to the verified executable and `RUSTFS_PERSISTENCE_CLOCK_LIBRARY` to the absolute path of libfaketime (`libfaketime.so.1` on Linux or `libfaketime.1.dylib` on macOS). To retain the two sets of 13 XML documents for the gateway golden corpus, set `RUSTFS_PERSISTENCE_XML_DIR` to an output directory. CI includes them in the full suite's JUnit artifact.
**Reproduce a CI failure locally** — run the exact profile/lane:
```bash
@@ -0,0 +1,585 @@
// 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();
}
+52 -1
View File
@@ -34,7 +34,10 @@
#[cfg(test)]
mod tests {
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
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 hmac::{Hmac, KeyInit as _, Mac};
use http::header::HOST;
use rustfs_s3_types::Body;
@@ -396,6 +399,54 @@ 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(())
}
@@ -137,6 +137,40 @@ async fn test_bucket_policy_authenticated_user() -> Result<(), Box<dyn std::erro
.await
.map_err(|e| format!("DeleteObject failed: {}", e))?;
for (allowed, may_read) in [("s3:GetBucketPolicy", true), ("s3:PutBucketPolicy", false)] {
let policy = serde_json::json!({
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": { "AWS": [user_access] },
"Action": allowed,
"Resource": format!("arn:aws:s3:::{bucket_name}")
}]
})
.to_string();
admin_client
.put_bucket_policy()
.bucket(bucket_name)
.policy(&policy)
.send()
.await?;
let read = user_client.get_bucket_policy().bucket(bucket_name).send().await;
let write = user_client
.put_bucket_policy()
.bucket(bucket_name)
.policy(&policy)
.send()
.await;
if may_read {
read?;
let denied = write.expect_err("GetBucketPolicy must not grant PutBucketPolicy");
assert_eq!(denied.as_service_error().and_then(ProvideErrorMetadata::code), Some("AccessDenied"));
} else {
let denied = read.expect_err("PutBucketPolicy must not grant GetBucketPolicy");
assert_eq!(denied.as_service_error().and_then(ProvideErrorMetadata::code), Some("AccessDenied"));
write?;
}
}
info!("Test Passed!");
Ok(())
}
+16 -1
View File
@@ -170,6 +170,15 @@ impl DiskFaultHarness {
/// Start (or restart after [`Self::kill_server`]) the RustFS server with
/// all volume directories and the same address.
pub async fn start_server(&mut self) -> ChaosResult<()> {
self.start_server_with_readiness(false).await
}
/// Start a process once its node read-readiness probe passes.
pub async fn start_server_at_read_quorum(&mut self) -> ChaosResult<()> {
self.start_server_with_readiness(true).await
}
async fn start_server_with_readiness(&mut self, read_quorum_only: bool) -> ChaosResult<()> {
// The common helper always appends `env.temp_dir` as the final storage
// path: point it at the last disk for startup and pass the remaining
// disks explicitly, then restore it to the root so Drop cleans up
@@ -181,7 +190,13 @@ impl DiskFaultHarness {
let arg_refs: Vec<&str> = disk_args.iter().map(String::as_str).collect();
let env_refs: Vec<(&str, &str)> = self.extra_env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
let result = self.env.start_rustfs_server_with_env(arg_refs, &env_refs).await;
let result = if read_quorum_only {
self.env
.start_rustfs_server_with_env_at_read_quorum(arg_refs, &env_refs)
.await
} else {
self.env.start_rustfs_server_with_env(arg_refs, &env_refs).await
};
self.env.temp_dir = self.root.to_string_lossy().to_string();
result
}
+35 -5
View File
@@ -722,7 +722,7 @@ impl RustFSTestEnvironment {
cleanup_existing: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let binary_path = rustfs_binary_path();
self.start_rustfs_server_inner_with_binary(&binary_path, extra_args, extra_env, cleanup_existing)
self.start_rustfs_server_inner_with_binary(&binary_path, extra_args, extra_env, cleanup_existing, false)
.await
}
@@ -732,6 +732,7 @@ impl RustFSTestEnvironment {
extra_args: Vec<&str>,
extra_env: &[(&str, &str)],
cleanup_existing: bool,
read_quorum_only: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
if cleanup_existing {
self.cleanup_existing_processes().await?;
@@ -756,7 +757,7 @@ impl RustFSTestEnvironment {
self.process = Some(process);
// Wait for server to be ready
self.wait_for_server_ready().await?;
self.wait_for_server_ready_with_probe(read_quorum_only).await?;
Ok(())
}
@@ -770,7 +771,7 @@ impl RustFSTestEnvironment {
extra_args: Vec<&str>,
extra_env: &[(&str, &str)],
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, true)
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, true, false)
.await
}
@@ -782,7 +783,7 @@ impl RustFSTestEnvironment {
extra_args: Vec<&str>,
extra_env: &[(&str, &str)],
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, false)
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, false, false)
.await
}
@@ -800,6 +801,18 @@ impl RustFSTestEnvironment {
self.start_rustfs_server_inner(extra_args, extra_env, true).await
}
/// Start a degraded read-serving process using the node readiness probe.
/// ListBuckets retains its namespace write-quorum requirement.
pub async fn start_rustfs_server_with_env_at_read_quorum(
&mut self,
extra_args: Vec<&str>,
extra_env: &[(&str, &str)],
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let binary_path = rustfs_binary_path();
self.start_rustfs_server_inner_with_binary(&binary_path, extra_args, extra_env, true, true)
.await
}
/// Start RustFS server without cleaning up other running RustFS processes.
///
/// This is useful for tests that need multiple independent RustFS instances
@@ -828,8 +841,16 @@ impl RustFSTestEnvironment {
/// Fails immediately if the spawned server process has already exited
/// (e.g. a port bind failure) instead of polling out the full timeout.
pub async fn wait_for_server_ready(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
self.wait_for_server_ready_with_probe(false).await
}
async fn wait_for_server_ready_with_probe(
&mut self,
read_quorum_only: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
info!("Waiting for RustFS server to be ready on {}", self.address);
let client = self.create_s3_client();
let health_client = HttpClient::builder().no_proxy().timeout(Duration::from_secs(2)).build()?;
for i in 0..60 {
if let Some(process) = self.process.as_mut()
@@ -838,7 +859,16 @@ impl RustFSTestEnvironment {
return Err(format!("RustFS server process exited before becoming ready: {status}").into());
}
if TcpStream::connect(&self.address).await.is_ok() && client.list_buckets().send().await.is_ok() {
let ready = if read_quorum_only {
health_client
.get(format!("{}/minio/health/ready", self.url))
.send()
.await
.is_ok_and(|response| response.status().is_success())
} else {
TcpStream::connect(&self.address).await.is_ok() && client.list_buckets().send().await.is_ok()
};
if ready {
info!("✅ RustFS server is ready after {} attempts", i + 1);
return Ok(());
}
+36 -16
View File
@@ -13,8 +13,8 @@
// limitations under the License.
//! Over-the-wire smoke net for the embedded console listener (backlog#1154
//! peri-4). The console is a second HTTP listener that serves the full S3/admin
//! surface plus the unauthenticated console routes under `/rustfs/console`;
//! peri-4). The console is a second HTTP listener for the control-plane and
//! unauthenticated console routes under `/rustfs/console`;
//! before this test its behaviour was only covered by in-process router tests
//! (`rustfs/src/admin/console.rs`), so a misconfiguration that exposed
//! credentials through the public console endpoints or fail-opened the
@@ -26,13 +26,13 @@
//! * `/rustfs/console/license` exposes only the coarse `licensed` flag.
//! * the console SPA prefix dispatches to the static handler, never to the
//! S3 API (no S3 error XML), whether or not console assets are embedded.
//! * unauthenticated requests to the admin API and the S3 root on the console
//! listener are denied (403 AccessDenied) — the extra listener does not
//! fail-open the protected surface.
//! * unauthenticated admin API requests are denied with 403 AccessDenied.
//! * S3 root/object requests on the console listener return an empty 404,
//! including authenticated requests, before S3 dispatch.
//! * a listener with the console disabled (the main S3 port here) does not
//! serve the unauthenticated console endpoints at all.
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client, signed_request_with_client};
use std::error::Error;
use tokio::time::{Duration, sleep};
@@ -166,19 +166,39 @@ async fn test_console_over_the_wire_smoke() -> TestResult {
let admin_body = admin_response.text().await?;
assert!(admin_body.contains("AccessDenied"), "admin denial must be AccessDenied: {admin_body}");
// The console listener serves no S3 surface at all: an object route is not found there,
// signed or not, instead of reaching the S3 service and being denied by it.
let s3_root_response = client.get(format!("{console_base}/")).send().await?;
let signed_data_root = signed_request_with_client(
&client,
http::Method::GET,
&format!("{}/", env.url),
&env.access_key,
&env.secret_key,
None,
None,
)
.await?;
assert_eq!(
s3_root_response.status(),
reqwest::StatusCode::NOT_FOUND,
"the S3 root must not be served on the console listener"
);
assert!(
s3_root_response.text().await?.is_empty(),
"the console listener must not answer an object route with an S3 document"
signed_data_root.status(),
reqwest::StatusCode::OK,
"the same credentials must reach S3 on the data listener"
);
for path in ["/", "/console-object-bucket/key"] {
let url = format!("{console_base}{path}");
for signed in [false, true] {
let response = if signed {
signed_request_with_client(&client, http::Method::GET, &url, &env.access_key, &env.secret_key, None, None).await?
} else {
client.get(&url).send().await?
};
assert_eq!(
response.status(),
reqwest::StatusCode::NOT_FOUND,
"S3 route {path}, signed={signed} must be isolated from the console listener"
);
assert!(response.bytes().await?.is_empty(), "isolated S3 routes must not reach a handler");
}
}
// --- console disabled on a listener means no console surface at all ------
// The main S3 listener of this same process runs with the console disabled,
// so its console paths must not answer with the unauthenticated console
+1
View File
@@ -36,6 +36,7 @@ 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;
@@ -26,7 +26,7 @@ use aws_sdk_s3::types::{
DefaultRetention, ObjectLockConfiguration, ObjectLockEnabled, ObjectLockLegalHoldStatus, ObjectLockRetentionMode,
ObjectLockRule,
};
use chrono::{Duration as ChronoDuration, Utc};
use jiff::{SignedDuration, Timestamp};
fn delete_denied(error: &SdkError<DeleteObjectError>, context: &str) -> TestResult {
let code = error.as_service_error().and_then(ProvideErrorMetadata::code);
@@ -66,7 +66,7 @@ async fn four_node_four_drive_object_lock_worm_blocks_delete() -> TestResult {
.send()
.await?;
let retain_until = Utc::now() + ChronoDuration::days(1);
let retain_until = Timestamp::now() + SignedDuration::from_hours(24);
let compliance_key = "compliance.bin";
let compliance_version = put_object_with_retention(
@@ -176,7 +176,10 @@ async fn four_node_default_retention_is_visible_and_non_lock_bucket_rejects_conf
let retain_until = retention
.retain_until_date()
.ok_or("default retention omitted retain-until date")?;
assert!(retain_until.secs() > Utc::now().timestamp(), "default retention is not in the future");
assert!(
retain_until.secs() > Timestamp::now().as_second(),
"default retention is not in the future"
);
let versioning = reader.get_bucket_versioning().bucket(&bucket).send().await?;
assert_eq!(versioning.status().map(|status| status.as_str()), Some("Enabled"));
@@ -159,6 +159,7 @@ 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}"))?;
@@ -200,6 +201,24 @@ 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?;
@@ -234,6 +253,38 @@ 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
@@ -0,0 +1,111 @@
// 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
}
@@ -38,8 +38,8 @@ use aws_sdk_s3::types::{
BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, ObjectLockLegalHoldStatus, ObjectLockRetentionMode,
VersioningConfiguration,
};
use chrono::{DateTime, Utc};
use http::{Method, StatusCode};
use jiff::Timestamp;
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
@@ -526,8 +526,8 @@ async fn put_multipart(client: &Client, bucket: &str, key: &str) -> TestResult<V
Ok(body)
}
fn retention_deadline() -> TestResult<DateTime<Utc>> {
DateTime::<Utc>::from_timestamp(Utc::now().timestamp() + 24 * 3600, 0).ok_or_else(|| "retention deadline out of range".into())
fn retention_deadline() -> TestResult<Timestamp> {
Ok(Timestamp::now() + jiff::SignedDuration::from_hours(24))
}
/// Seed the deterministic inventory into the seed pool and record it.
@@ -654,7 +654,7 @@ pub(crate) async fn seed_manifest(run: &TopologyRun) -> TestResult<TopologyManif
let mut entry = ManifestEntry::body(&locked, &key, "compliance", Some(version_id.clone()), Some(version_id), &body);
entry.retention = Some(RetentionRecord {
mode: "COMPLIANCE".to_string(),
retain_until_unix: retain_until.timestamp(),
retain_until_unix: retain_until.as_second(),
});
entries.push(entry);
}
+26 -14
View File
@@ -31,7 +31,7 @@ use super::harness::{
use crate::common::{
AdminTransport, admin_add_canned_policy_via, admin_attach_user_policy_via, admin_create_user_via, init_logging,
};
use crate::upgrade_compatibility_test::wait_for_upgrade_write_readiness;
use crate::upgrade_compatibility_test::{UpgradeSourceCapabilities, wait_for_upgrade_write_readiness};
use aws_sdk_s3::Client;
use aws_sdk_s3::error::ProvideErrorMetadata;
use std::path::{Path, PathBuf};
@@ -427,7 +427,12 @@ async fn assert_history_and_iam(dist: &DistCluster, seed: &UpgradeSeed, context:
Ok(())
}
async fn compare_degraded_legacy_list_parts(dist: &mut DistCluster, seed: &UpgradeSeed, previous: &Path) -> TestResult {
async fn compare_degraded_legacy_list_parts(
dist: &mut DistCluster,
seed: &UpgradeSeed,
previous: &Path,
source: &UpgradeSourceCapabilities,
) -> TestResult {
let decoded = String::from_utf8(base64_simd::URL_SAFE_NO_PAD.decode_to_vec(seed.multipart_upload.as_bytes())?)?;
let (_, upload_dir) = decoded.split_once('.').ok_or("legacy upload ID lacks deployment delimiter")?;
let hash = sha256_hex(format!("{}/legacy-multipart.bin", seed.history_bucket).as_bytes());
@@ -489,16 +494,22 @@ async fn compare_degraded_legacy_list_parts(dist: &mut DistCluster, seed: &Upgra
// Three online disks retain metadata quorum but have no part directory;
// the fourth disk is offline. A legacy empty response is not a proof that
// the unavailable participant has no part.
let legacy = legacy.expect("previous coordinator should expose its legacy empty-list behavior");
assert!(legacy.parts().is_empty());
let current = current.expect_err("current coordinator must not infer empty from missing directories and offline disks");
assert_eq!(current.raw_response().expect("current S3 response").status().as_u16(), 503);
// Since #9149, SlowDownRead is reserved for GET/HEAD object reads; a
// ListParts read-quorum failure is reported as ServiceUnavailable.
assert_eq!(
current.as_service_error().and_then(|error| error.meta().code()),
Some("ServiceUnavailable")
);
let mut quorum_errors =
vec![current.expect_err("current coordinator must not infer empty from missing directories and offline disks")];
if source.requires_list_parts_read_quorum {
quorum_errors.push(legacy.expect_err("previous coordinator must require evidence from unavailable disks"));
} else {
assert!(
legacy
.expect("previous coordinator should expose its legacy empty-list behavior")
.parts()
.is_empty()
);
}
for error in quorum_errors {
assert_eq!(error.raw_response().expect("S3 response").status().as_u16(), 503);
assert_eq!(error.as_service_error().and_then(|error| error.meta().code()), Some("ServiceUnavailable"));
}
dist.cluster.start_node_from_binary(3, previous).await?;
wait_for_upgrade_write_readiness(&clients, &seed.history_bucket, "mixed-list-restored", CREDENTIAL_TIMEOUT).await?;
for (path, before) in original_files {
@@ -520,7 +531,7 @@ async fn compare_degraded_legacy_list_parts(dist: &mut DistCluster, seed: &Upgra
assert_eq!(listed.parts()[0].e_tag(), Some(seed.multipart_etag.as_str()));
}
eprintln!(
"MPU mixed degraded: one offline disk, three missing part directories; previous returned empty, current returned 503 SlowDownRead; original part restored on both"
"MPU mixed degraded: one offline disk, three missing part directories; checked each coordinator against its release contract; original part restored on both"
);
Ok(())
}
@@ -592,6 +603,7 @@ async fn replace_node_and_wait_for_write_readiness(dist: &mut DistCluster, seed:
async fn four_node_rolling_upgrade_preserves_history_and_iam_credentials() -> TestResult {
init_logging();
let previous = source_binary()?;
let source = UpgradeSourceCapabilities::from_binary(&previous).await?;
let mut dist = DistCluster::new_stopped(DistLayout::FourNodeFourDisk).await?;
dist.cluster.set_env("RUSTFS_STORAGE_CLASS_RRS", "EC:0");
capture_upgrade_logs(&mut dist, "rolling-upgrade")?;
@@ -601,7 +613,7 @@ async fn four_node_rolling_upgrade_preserves_history_and_iam_credentials() -> Te
replace_node_and_wait_for_write_readiness(&mut dist, &seed, 0).await?;
assert_history_and_iam(&dist, &seed, "one-current-node").await?;
compare_degraded_legacy_list_parts(&mut dist, &seed, &previous).await?;
compare_degraded_legacy_list_parts(&mut dist, &seed, &previous, &source).await?;
for node_idx in [1, 2] {
replace_node_and_wait_for_write_readiness(&mut dist, &seed, node_idx).await?;
@@ -12,21 +12,22 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! Dual-stack differential: one `rustfs` binary, two processes, one SDK script (rustfs/backlog#2740).
//! Differential: two `rustfs` processes, one SDK script (rustfs/backlog#2740).
//!
//! Stack A runs `RUSTFS_S3_STACK=legacy` of the binary under test, unless `RUSTFS_E2E_REFERENCE_BINARY`
//! names a released binary: then A is that binary, started without `RUSTFS_S3_STACK` (older
//! releases do not know it), and a bad path fails the run instead of falling back (see
//! `reference`). The report names which side is the reference and the `--version` each side ran. Stack B runs the value of `RUSTFS_E2E_STACK_B`
//! (default `legacy` until the gateway stack is assembled), and `RUSTFS_E2E_STACK_B_REGION`, when
//! set, starts B in another region so that a difference can be injected by hand. Both servers
//! Side B is the binary under test. Side A is the binary under test too, unless
//! `RUSTFS_E2E_REFERENCE_BINARY` names a released binary: then A is that binary, and a bad path
//! fails the run instead of falling back (see `reference`). The report names which side is the
//! reference and the `--version` each side ran. `RUSTFS_E2E_STACK_B_REGION`, when set, starts B
//! in another region so that a difference can be injected by hand. Neither side is given the
//! retired stack selector: the binary under test refuses to start with it, and the gateway stack
//! is its only S3 stack. Both servers
//! answer the script in `scenarios`, which covers every operation of `impl S3 for FS`; `compare`
//! reports each `(op, field, a, b)` on which the answers differ, and every run writes its report
//! to `<target>/dual-stack/<run>.json`. Two processes, not two embedded servers: bucket metadata
//! is process-global, so two stacks in one process would read each other's buckets.
mod compare;
mod reference;
pub(crate) mod reference;
mod scenarios;
use crate::common::{RustFSTestEnvironment, init_logging, rustfs_binary_path, workspace_root};
@@ -37,20 +38,18 @@ use std::time::{SystemTime, UNIX_EPOCH};
type BoxError = Box<dyn std::error::Error + Send + Sync>;
const STACK_A: &str = "legacy";
/// Label of a side that runs the binary under test.
const UNDER_TEST: &str = "under-test";
/// Label of side A in the report when it is the released reference binary.
const STACK_A_REFERENCE: &str = "reference";
const ENV_STACK_B: &str = "RUSTFS_E2E_STACK_B";
const ENV_STACK_B_REGION: &str = "RUSTFS_E2E_STACK_B_REGION";
/// Becomes `gateway` once rustfs/backlog#2734 T2.5 assembles the gateway stack.
const DEFAULT_STACK_B: &str = "legacy";
/// The region the negative control gives stack A explicitly, so an inherited `RUSTFS_REGION`
/// cannot erase the injected difference. Not `us-east-1`: that region answers GetBucketLocation
/// with an empty LocationConstraint and re-creating an owned bucket with 200, so it would not
/// report its own name and would add CreateBucket differences to the control.
const CONTROL_REGION_A: &str = "us-west-2";
const CONTROL_REGION_B: &str = "eu-west-1";
/// `normal` cases the legacy stack must answer with a 2xx. The comparison alone cannot tell a
/// `normal` cases side A must answer with a 2xx. The comparison alone cannot tell a
/// script that exercises real behavior from one in which both stacks fail the same way. Five of
/// the 73 fail on legacy by design of this script: PutBucketReplication (no registered remote
/// target), GetBucketReplication (so no configuration), PutBucketNotificationConfiguration (no
@@ -60,7 +59,6 @@ const MIN_NORMAL_SUCCESSES: usize = 68;
struct PairConfig {
side_a: SideA,
stack_b: String,
region_a: Option<String>,
region_b: Option<String>,
}
@@ -69,7 +67,6 @@ impl PairConfig {
fn from_env() -> Result<Self, BoxError> {
Ok(Self {
side_a: SideA::from_env()?,
stack_b: std::env::var(ENV_STACK_B).unwrap_or_else(|_| DEFAULT_STACK_B.to_owned()),
region_a: None,
region_b: std::env::var(ENV_STACK_B_REGION).ok(),
})
@@ -77,16 +74,16 @@ impl PairConfig {
fn stack_a_label(&self) -> &'static str {
match self.side_a {
SideA::SameBinary => STACK_A,
SideA::SameBinary => UNDER_TEST,
SideA::Reference(_) => STACK_A_REFERENCE,
}
}
}
/// Starts one server of the binary under test on `stack`, overriding its region only when asked.
async fn start_stack(stack: &str, region: Option<&str>) -> Result<RustFSTestEnvironment, BoxError> {
/// Starts one server of the binary under test, overriding its region only when asked.
async fn start_under_test(region: Option<&str>) -> Result<RustFSTestEnvironment, BoxError> {
let mut env = RustFSTestEnvironment::new().await?;
let mut vars = vec![("RUSTFS_S3_STACK", stack)];
let mut vars = Vec::new();
if let Some(region) = region {
vars.push(("RUSTFS_REGION", region));
}
@@ -94,8 +91,7 @@ async fn start_stack(stack: &str, region: Option<&str>) -> Result<RustFSTestEnvi
Ok(env)
}
/// Starts one server of a released binary. `RUSTFS_S3_STACK` is not passed: older releases do not
/// know it and have exactly one stack.
/// Starts one server of a released binary.
async fn start_reference(binary: &Path, region: Option<&str>) -> Result<RustFSTestEnvironment, BoxError> {
let mut env = RustFSTestEnvironment::new().await?;
let mut vars = Vec::new();
@@ -111,11 +107,11 @@ async fn start_reference(binary: &Path, region: Option<&str>) -> Result<RustFSTe
async fn spawn_pair(config: &PairConfig) -> Result<(RustFSTestEnvironment, RustFSTestEnvironment), BoxError> {
let side_a = async {
match &config.side_a {
SideA::SameBinary => start_stack(STACK_A, config.region_a.as_deref()).await,
SideA::SameBinary => start_under_test(config.region_a.as_deref()).await,
SideA::Reference(binary) => start_reference(binary, config.region_a.as_deref()).await,
}
};
tokio::try_join!(side_a, start_stack(&config.stack_b, config.region_b.as_deref()))
tokio::try_join!(side_a, start_under_test(config.region_b.as_deref()))
}
fn report_directory() -> PathBuf {
@@ -160,7 +156,7 @@ async fn run_differential(label: &str, config: &PairConfig) -> Run {
schema: 2,
run: format!("{label}-{millis}-{}", std::process::id()),
stack_a: config.stack_a_label().to_owned(),
stack_b: config.stack_b.clone(),
stack_b: UNDER_TEST.to_owned(),
reference_side: matches!(config.side_a, SideA::Reference(_)).then_some("a"),
version_a,
version_b,
@@ -235,7 +231,6 @@ mod tests {
init_logging();
let config = PairConfig {
side_a: SideA::SameBinary,
stack_b: STACK_A.to_owned(),
region_a: Some(CONTROL_REGION_A.to_owned()),
region_b: Some(CONTROL_REGION_B.to_owned()),
};
@@ -15,7 +15,7 @@
//! Which binary side A of the differential runs, and what it reports about itself.
//!
//! `RUSTFS_E2E_REFERENCE_BINARY` names a released `rustfs` binary to use as the reference. Unset,
//! side A is the binary under test on `RUSTFS_S3_STACK=legacy`. Set, it must resolve to an
//! side A is the binary under test. Set, it must resolve to an
//! executable file or the run fails: a reference that was asked for and silently replaced by the
//! binary under test would report an agreement with itself as agreement with the release.
@@ -28,9 +28,9 @@ pub(super) const ENV_REFERENCE_BINARY: &str = "RUSTFS_E2E_REFERENCE_BINARY";
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum SideA {
/// Both sides are the binary under test; A runs `RUSTFS_S3_STACK=legacy`.
/// Both sides are the binary under test.
SameBinary,
/// A is this released binary, started without `RUSTFS_S3_STACK`.
/// A is this released binary.
Reference(PathBuf),
}
@@ -78,7 +78,7 @@ fn is_executable(_metadata: &std::fs::Metadata) -> bool {
/// What `<binary> --version` printed, trimmed. Fails when the binary does not run, exits
/// non-zero, or prints nothing, because an empty version would report nothing as observed.
pub(super) async fn binary_version(binary: &Path) -> Result<String, BoxError> {
pub(crate) async fn binary_version(binary: &Path) -> Result<String, BoxError> {
let output = tokio::process::Command::new(binary).arg("--version").output().await?;
if !output.status.success() {
return Err(format!("{} --version failed with {}", binary.display(), output.status).into());
+2 -1
View File
@@ -29,6 +29,7 @@ use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::ServerSideEncryption;
use base64_simd::STANDARD as BASE64;
use http::header::{CONTENT_TYPE, HOST};
use jiff::Timestamp;
use md5::{Digest as Md5Digest, Md5};
use rustfs_s3_types::Body;
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
@@ -386,7 +387,7 @@ pub async fn create_key_with_specific_id(key_dir: &str, key_id: &str) -> Result<
"usage": "EncryptDecrypt",
"status": "Active",
"metadata": HashMap::<String, String>::new(),
"created_at": format!("{}[UTC]", chrono::Utc::now().to_rfc3339()),
"created_at": format!("{}[UTC]", Timestamp::now().strftime("%Y-%m-%dT%H:%M:%S%.fZ")),
"rotated_at": serde_json::Value::Null,
"created_by": "e2e-test",
"encrypted_key_material": BASE64.encode_to_string(key_data),
+11 -2
View File
@@ -12,6 +12,9 @@
// 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;
@@ -31,12 +34,15 @@ pub mod chaos;
#[cfg(test)]
pub mod fake_s3_target;
// Dual-stack differential (rustfs/backlog#2740): one binary, two processes on
// different RUSTFS_S3_STACK values, the same SDK script for every S3 operation,
// Differential (rustfs/backlog#2740): two processes, the binary under test against
// itself or a released reference binary, the same SDK script for every S3 operation,
// compared on status, error code, allowlisted headers and typed body fields.
#[cfg(test)]
mod dual_stack_differential;
#[cfg(test)]
mod persistence_parity;
// On-demand migration (backlog#2147): shared two-server environment, admin
// wrappers, and the harness self-test (backlog#2151). Behavior scenarios are
// added by later ODM tasks.
@@ -102,6 +108,9 @@ 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;
+27 -3
View File
@@ -23,13 +23,13 @@ use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{
ServerSideEncryption, ServerSideEncryptionByDefault, ServerSideEncryptionConfiguration, ServerSideEncryptionRule,
};
use chrono::{Duration as ChronoDuration, Utc};
use flate2::{
Compression,
write::{GzEncoder, ZlibEncoder},
};
use http::HeaderValue;
use http::header::{CONTENT_TYPE, HOST};
use jiff::{SignedDuration, Timestamp};
use md5::{Digest as Md5Digest, Md5};
use rustfs_s3_types::Body;
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
@@ -42,8 +42,8 @@ use tokio::io::AsyncWriteExt;
use uuid::Uuid;
fn encode_post_policy(conditions: Vec<serde_json::Value>) -> String {
let expiration = (Utc::now() + ChronoDuration::hours(1))
.format("%Y-%m-%dT%H:%M:%S.000Z")
let expiration = (Timestamp::now() + SignedDuration::from_hours(1))
.strftime("%Y-%m-%dT%H:%M:%S.000Z")
.to_string();
let policy = serde_json::json!({
"expiration": expiration,
@@ -1543,6 +1543,30 @@ async fn test_anonymous_post_object_honors_success_action_status() -> Result<(),
let uploaded = get_out.body.collect().await?.into_bytes();
assert_eq!(uploaded.as_ref(), expected_body.as_slice(), "uploaded object body should match");
// An empty redirect is rejected when rendering the response, after storage succeeds.
for (field, value, expected_status) in [
("success_action_status", "200", reqwest::StatusCode::OK),
("success_action_status", "204", reqwest::StatusCode::NO_CONTENT),
("success_action_redirect", "", reqwest::StatusCode::BAD_REQUEST),
] {
let key = format!("{field}-{value}.txt");
let form = reqwest::multipart::Form::new()
.text("key", key.clone())
.text(field, value)
.part("file", reqwest::multipart::Part::bytes(expected_body.clone()).file_name("upload.txt"));
let response = local_http_client()
.post(format!("{}/{bucket}", env.url))
.multipart(form)
.send()
.await?;
assert_eq!(response.status(), expected_status);
if value.is_empty() {
assert!(response.text().await?.contains("<Code>InvalidArgument</Code>"));
}
let stored = admin_client.get_object().bucket(bucket).key(key).send().await?;
assert_eq!(stored.body.collect().await?.into_bytes().as_ref(), expected_body.as_slice());
}
Ok(())
}
@@ -283,6 +283,7 @@ async fn test_cold_degraded_object_mutations_require_only_storage_quorum() -> Te
#[tokio::test]
async fn test_degraded_cluster_read_quorum_follows_erasure_layout() -> TestResult {
crate::common::init_logging();
assert_single_node_cold_start_with_missing_volume().await?;
for (node_count, parity) in [(3, 1), (4, 2), (6, 3), (6, 2), (4, 0)] {
let read_quorum = node_count - parity;
@@ -430,6 +431,138 @@ async fn test_degraded_cluster_read_quorum_follows_erasure_layout() -> TestResul
Ok(())
}
async fn assert_single_node_cold_start_with_missing_volume() -> TestResult {
for drive_count in [2, 3, 4] {
let mut server = crate::chaos::DiskFaultHarness::new(drive_count).await?;
server.set_env("RUSTFS_STORAGE_CLASS_STANDARD", format!("EC:{}", drive_count / 2));
server.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false");
server.set_env("RUSTFS_OBS_METRICS_EXPORT_ENABLED", "false");
server.set_env("RUSTFS_HEALTH_ENDPOINT_ENABLE", "true");
server.set_env("RUST_LOG", "warn");
server.start_server_at_read_quorum().await?;
let client = server.env.create_s3_client();
let client = Client::from_conf(
client
.config()
.to_builder()
.retry_config(aws_sdk_s3::config::retry::RetryConfig::standard().with_max_attempts(1))
.build(),
);
let bucket = format!("missing-volume-{drive_count}");
client.create_bucket().bucket(&bucket).send().await?;
let small = vec![17; 4096];
let large = vec![73; 8 * 1024 * 1024];
for (key, body) in [("small", &small), ("large", &large)] {
client
.put_object()
.bucket(&bucket)
.key(key)
.body(Bytes::copy_from_slice(body).into())
.send()
.await?;
for disk in 0..drive_count {
let census = crate::chaos::census_object_version_on_disk(server.disk_path(disk), &bucket, key, None)?;
assert!(census.is_complete(), "seed shard must exist before restart: {census:?}");
}
}
server.kill_server();
let missing = drive_count - 1;
server.take_disk_offline(missing)?;
server.start_server_at_read_quorum().await?;
for (key, body) in [("small", &small), ("large", &large)] {
assert_quorum_object_body(&client, &bucket, key, body).await?;
let head = client.head_object().bucket(&bucket).key(key).send().await?;
assert_eq!(head.content_length(), Some(i64::try_from(body.len())?));
}
let listing = client.list_objects_v2().bucket(&bucket).send().await?;
let keys: Vec<_> = listing.contents().iter().filter_map(|object| object.key()).collect();
assert_eq!(keys, ["large", "small"]);
let put = client
.put_object()
.bucket(&bucket)
.key("degraded-write")
.body(Bytes::from_static(b"degraded write").into())
.send()
.await;
if drive_count == 2 {
let error = put.expect_err("one of two drives cannot commit a new object");
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(503));
let error = client
.delete_object()
.bucket(&bucket)
.key("large")
.send()
.await
.expect_err("one of two drives cannot commit an object deletion");
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(503));
assert_quorum_object_body(&client, &bucket, "large", &large).await?;
} else {
put?;
assert_quorum_object_body(&client, &bucket, "degraded-write", b"degraded write").await?;
client.delete_object().bucket(&bucket).key("degraded-write").send().await?;
}
assert!(
!server.disk_path(missing).exists(),
"degraded startup and S3 operations must leave the root absent"
);
if drive_count == 2 {
server.kill_server();
std::fs::create_dir(server.disk_path(missing))?;
server.start_server_at_read_quorum().await?;
for (key, body) in [("small", &small), ("large", &large)] {
assert_quorum_object_body(&client, &bucket, key, body).await?;
client.head_object().bucket(&bucket).key(key).send().await?;
}
assert_eq!(client.list_objects_v2().bucket(&bucket).send().await?.contents().len(), 2);
let error = client
.put_object()
.bucket(&bucket)
.key("empty-root-write")
.body(Bytes::from_static(b"must remain unavailable").into())
.send()
.await
.expect_err("an empty replacement cannot restore write quorum");
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(503));
assert!(
!server
.disk_path(missing)
.join(crate::storage_api::RUSTFS_META_BUCKET)
.join("format.json")
.exists(),
"read admission must not format the empty replacement"
);
}
server.kill_server();
server.bring_disk_online(missing)?;
server.start_server_at_read_quorum().await?;
for (key, body) in [("small", &small), ("large", &large)] {
assert_quorum_object_body(&client, &bucket, key, body).await?;
}
for key in ["degraded-write", "empty-root-write"] {
let error = client
.head_object()
.bucket(&bucket)
.key(key)
.send()
.await
.expect_err("rejected or deleted degraded write must stay absent after recovery");
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(404));
}
client
.put_object()
.bucket(&bucket)
.key("recovery-write")
.body(Bytes::from_static(b"recovered write").into())
.send()
.await?;
assert_quorum_object_body(&client, &bucket, "recovery-write", b"recovered write").await?;
}
Ok(())
}
#[tokio::test]
async fn test_cold_start_read_quorum_follows_erasure_layout() -> TestResult {
crate::common::init_logging();
@@ -864,6 +864,70 @@ 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]
@@ -962,3 +1026,101 @@ 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(())
}
+7 -7
View File
@@ -29,7 +29,7 @@ use aws_sdk_s3::types::{
DefaultRetention, ObjectLockConfiguration, ObjectLockEnabled, ObjectLockLegalHold, ObjectLockLegalHoldStatus, ObjectLockMode,
ObjectLockRetention, ObjectLockRetentionMode, ObjectLockRule,
};
use chrono::{DateTime, Duration, Utc};
use jiff::{SignedDuration, Timestamp};
use tracing::info;
use crate::common::RustFSTestEnvironment;
@@ -126,10 +126,10 @@ pub async fn put_object_with_retention(
key: &str,
data: &[u8],
mode: ObjectLockRetentionMode,
retain_until: DateTime<Utc>,
retain_until: Timestamp,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
// AWS SDK requires UTC time without timezone offset (e.g., "2026-01-24T11:20:14Z")
let retain_until_str = retain_until.format("%Y-%m-%dT%H:%M:%SZ").to_string();
let retain_until_str = retain_until.strftime("%Y-%m-%dT%H:%M:%SZ").to_string();
let retain_until_datetime =
aws_sdk_s3::primitives::DateTime::from_str(&retain_until_str, aws_sdk_s3::primitives::DateTimeFormat::DateTime)?;
@@ -181,10 +181,10 @@ pub async fn put_object_retention(
key: &str,
version_id: Option<&str>,
mode: ObjectLockRetentionMode,
retain_until: DateTime<Utc>,
retain_until: Timestamp,
bypass_governance: bool,
) -> Result<(), Box<SdkError<PutObjectRetentionError>>> {
let retain_until_datetime = aws_sdk_s3::primitives::DateTime::from_secs(retain_until.timestamp());
let retain_until_datetime = aws_sdk_s3::primitives::DateTime::from_secs(retain_until.as_second());
let retention = ObjectLockRetention::builder()
.mode(mode.clone())
@@ -253,6 +253,6 @@ pub async fn delete_object_with_bypass(
}
/// Calculate a future retain_until date
pub fn future_retain_until(days: i64) -> DateTime<Utc> {
Utc::now() + Duration::days(days)
pub fn future_retain_until(days: i64) -> Timestamp {
Timestamp::now() + SignedDuration::from_hours(days * 24)
}
@@ -34,7 +34,7 @@ use aws_sdk_s3::types::{
CompletedMultipartUpload, CompletedPart, Delete, MetadataDirective, ObjectIdentifier, ObjectLockLegalHoldStatus,
ObjectLockMode, ObjectLockRetentionMode,
};
use chrono::{DateTime, Duration, Utc};
use jiff::{SignedDuration, Timestamp};
use tracing::info;
/// Initialize test logging
@@ -67,7 +67,7 @@ async fn put_bucket_deny_policy(
}
fn retention_timestamp(days: i64) -> aws_sdk_s3::primitives::DateTime {
let retain_until = future_retain_until(days).format("%Y-%m-%dT%H:%M:%SZ").to_string();
let retain_until = future_retain_until(days).strftime("%Y-%m-%dT%H:%M:%SZ").to_string();
aws_sdk_s3::primitives::DateTime::from_str(&retain_until, aws_sdk_s3::primitives::DateTimeFormat::DateTime)
.expect("retention timestamp should parse")
}
@@ -118,13 +118,14 @@ where
);
}
fn parse_s3_datetime(value: &aws_sdk_s3::primitives::DateTime) -> DateTime<Utc> {
fn parse_s3_datetime(value: &aws_sdk_s3::primitives::DateTime) -> Timestamp {
let formatted = value
.fmt(DateTimeFormat::DateTime)
.expect("S3 timestamp should format as RFC3339");
DateTime::parse_from_rfc3339(&formatted)
.expect("S3 timestamp should parse as RFC3339")
.with_timezone(&Utc)
let normalized = formatted
.strip_suffix('Z')
.map_or(formatted.clone(), |prefix| format!("{prefix}+00:00"));
Timestamp::strptime("%Y-%m-%dT%H:%M:%S%.f%:z", normalized).expect("S3 timestamp should parse as RFC3339")
}
// ============================================================================
@@ -470,7 +471,7 @@ async fn test_get_object_retention_returns_configured_values() {
let bucket = "test-get-retention";
let key = "retained-object";
let retain_until = future_retain_until(30);
let retain_until_expected = retain_until.format("%Y-%m-%dT%H:%M:%SZ").to_string();
let retain_until_expected = retain_until.strftime("%Y-%m-%dT%H:%M:%SZ").to_string();
env.create_object_lock_bucket(bucket).await.unwrap();
@@ -1924,7 +1925,7 @@ async fn test_copy_object_retention_uses_destination_policy() {
.await
.unwrap();
let copy_started = Utc::now();
let copy_started = Timestamp::now();
client
.copy_object()
.copy_source(format!("{src_bucket}/{src_key}"))
@@ -1947,7 +1948,7 @@ async fn test_copy_object_retention_uses_destination_policy() {
assert_eq!(retention.mode().map(|value| value.as_str()), Some("GOVERNANCE"));
let retain_until = parse_s3_datetime(retention.retain_until_date().expect("retain-until date should be present"));
assert!(
retain_until < copy_started + Duration::days(3),
retain_until < copy_started + SignedDuration::from_hours(3 * 24),
"destination default retention should not inherit the source's longer retention"
);
@@ -2008,7 +2009,7 @@ async fn test_copy_object_retention_uses_destination_policy() {
.expect("explicit retain-until date should be present"),
);
assert!(
explicit_retain_until > Utc::now() + Duration::days(20),
explicit_retain_until > Timestamp::now() + SignedDuration::from_hours(20 * 24),
"explicit retention should override the shorter bucket default"
);
@@ -2088,7 +2089,7 @@ async fn test_multipart_default_retention_fixed_at_create() {
.await
.unwrap();
let create_started = Utc::now();
let create_started = Timestamp::now();
let create_output = client.create_multipart_upload().bucket(bucket).key(key).send().await.unwrap();
let upload_id = create_output.upload_id().unwrap();
@@ -2131,7 +2132,7 @@ async fn test_multipart_default_retention_fixed_at_create() {
assert_eq!(retention.mode().map(|value| value.as_str()), Some("GOVERNANCE"));
let retain_until = parse_s3_datetime(retention.retain_until_date().expect("retain-until date should be present"));
assert!(
retain_until < create_started + Duration::days(3),
retain_until < create_started + SignedDuration::from_hours(3 * 24),
"CompleteMultipartUpload should keep the default retention calculated at create time"
);
}
+449
View File
@@ -0,0 +1,449 @@
// 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.
//! Compare bytes produced by S3 writes to independent, single-drive volumes.
use crate::common::{RustFSTestEnvironment, admin_request, rustfs_binary_path, signed_s3_request_with_headers};
use crate::dual_stack_differential::reference::binary_version;
use crate::fake_s3_target::{FAKE_ACCESS_KEY, FAKE_SECRET_KEY, FakeS3Target};
use crate::on_demand_migration::common::{ODM_ADMIN_ROUTE, ODM_MODULE_SWITCH_ENV, OdmSourceSpec};
use crate::replication_extension_test::send_set_replication_target_request;
use crate::storage_api::persistence_parity::{BucketMetadata, RUSTFS_META_BUCKET};
use crate::upgrade_compatibility_test::{set_bucket_quota, write_multipart};
use aws_sdk_s3::Client;
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{BucketCannedAcl, Tag, Tagging};
use http::{HeaderMap, Method};
use md5::{Digest, Md5};
use rustfs_filemeta::{FileMeta, MetaObject};
use serde_value::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
type Error = Box<dyn std::error::Error + Send + Sync>;
const CONFIGS: &str = "persisted-configs";
const OBJECTS: &str = "persisted-objects";
const FIRST_PART_SIZE: usize = 5 * 1024 * 1024;
const LOGS: &str = "rustfs-access-logs";
fn bucket_metadata(volume: &Path, bucket: &str) -> Result<BucketMetadata, Error> {
let key = BucketMetadata::new(bucket).save_file_path();
let object = volume.join(RUSTFS_META_BUCKET).join(&key);
let meta = FileMeta::load(&std::fs::read(object.join("xl.meta"))?)?;
let info = meta.into_fileinfo(RUSTFS_META_BUCKET, &key, "", true, false, true)?;
info.validate_for_metadata_read()?;
let [part] = info.parts.as_slice() else { return Err("bucket metadata must have one part".into()) };
let size = usize::try_from(info.size)?;
if info.erasure.data_blocks != 1 || size != part.size || size > info.erasure.block_size {
return Err("bucket metadata exceeds the single-drive, single-stripe fixture".into());
}
let framed = if info.inline_data() {
info.data.ok_or("missing inline bucket metadata")?.to_vec()
} else {
let directory = info.data_dir.ok_or("missing bucket metadata data directory")?;
std::fs::read(object.join(directory.to_string()).join(format!("part.{}", part.number)))?
};
let algorithm = info.erasure.get_checksum_info(part.number).algorithm;
let (digest, payload) = framed.split_at_checked(algorithm.size()).ok_or("truncated bucket metadata")?;
if digest.is_empty() || payload.len() != size || algorithm.hash_encode(payload).as_ref() != digest {
return Err("invalid bucket metadata shard checksum or size".into());
}
BucketMetadata::check_header(payload)?;
let fields = &payload[4..];
if bucket == CONFIGS {
// The production decoder defaults a missing field to empty. Require the ACL field on disk
// so dropping it cannot look like the expected zero-byte document.
let keys: BTreeMap<&str, serde::de::IgnoredAny> = rmp_serde::from_slice(fields)?;
if !keys.contains_key("BucketAclConfigJSON") {
return Err("missing BucketAclConfigJSON field".into());
}
}
Ok(BucketMetadata::unmarshal(fields)?)
}
type VersionFields = BTreeMap<String, Value>;
fn read_object(volume: &Path, key: &str) -> Result<(MetaObject, VersionFields), Error> {
let meta = FileMeta::load(&std::fs::read(volume.join(OBJECTS).join(key).join("xl.meta"))?)?;
let [version] = meta.versions.as_slice() else {
return Err(format!("{key}: expected one version").into());
};
let object = version.parse_version_meta()?.object.ok_or("missing V2 object")?;
if object.mod_time.is_none() || object.data_dir.is_none_or(|id| id.is_nil()) {
return Err(format!("{key}: missing modification time or data directory").into());
}
Ok((object, nonvolatile_fields(&version.meta, key)?))
}
fn nonvolatile_fields(raw: &[u8], key: &str) -> Result<VersionFields, Error> {
// The production reader skips unknown keys and supplies defaults for some missing keys.
// Keep the raw maps so both the version envelope and V2Obj preserve every field and value.
let mut fields: VersionFields = rmp_serde::from_slice(raw)?;
let Some(Value::Map(object_fields)) = fields.get_mut("V2Obj") else {
return Err(format!("{key}: missing raw V2Obj map").into());
};
for volatile in ["MTime", "DDir"] {
let value = object_fields
.get_mut(&Value::String(volatile.to_owned()))
.ok_or_else(|| format!("{key}: missing {volatile}"))?;
*value = Value::Unit;
}
Ok(fields)
}
async fn put_xml(env: &RustFSTestEnvironment, query: &str, xml: &str) -> Result<(), Error> {
let mut headers = HeaderMap::new();
headers.insert("content-md5", base64_simd::STANDARD.encode_to_string(Md5::digest(xml)).parse()?);
let response = signed_s3_request_with_headers(
Method::PUT,
&format!("{}/{CONFIGS}?{query}", env.url),
Some(xml.to_owned()),
Some("application/xml"),
&env.access_key,
&env.secret_key,
&headers,
)
.await?;
if !response.status().is_success() {
return Err(format!("PUT ?{query} failed with {}", response.status()).into());
}
Ok(())
}
struct Snapshot {
configs: BTreeMap<&'static str, Vec<u8>>,
objects: BTreeMap<&'static str, VersionFields>,
multipart_files: BTreeMap<String, Vec<u8>>,
}
async fn capture(binary: &Path, target: &FakeS3Target, clock: &str, clock_library: &str) -> Result<Snapshot, Error> {
let mut env = RustFSTestEnvironment::new().await?;
let queue = tempfile::tempdir()?;
let clock_loader = if cfg!(target_os = "macos") {
"DYLD_INSERT_LIBRARIES"
} else {
"LD_PRELOAD"
};
let options = [
(clock_loader, clock_library),
("DYLD_FORCE_FLAT_NAMESPACE", "1"),
("FAKETIME", clock),
("FAKETIME_DONT_FAKE_MONOTONIC", "1"),
("TZ", "UTC"),
("RUSTFS_NOTIFY_ENABLE", "true"),
("RUSTFS_NOTIFY_WEBHOOK_ENABLE_PRIMARY", "on"),
("RUSTFS_NOTIFY_WEBHOOK_ENDPOINT_PRIMARY", target.endpoint()),
(
"RUSTFS_NOTIFY_WEBHOOK_QUEUE_DIR_PRIMARY",
queue.path().to_str().ok_or("non-UTF8 queue path")?,
),
("RUSTFS_OUTBOUND_ALLOW_ORIGINS", target.endpoint()),
("RUSTFS_REPLICATION_ALLOW_LOOPBACK_TARGET", "true"),
(ODM_MODULE_SWITCH_ENV, "true"),
("RUSTFS_NEW_BUCKET_DURABILITY_MODE", "strict"),
("RUSTFS_SCANNER_CYCLE", "1"),
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
];
env.start_rustfs_server_from_binary_without_cleanup(binary, vec![], &options)
.await?;
let client = env.create_s3_client();
write_configs(&env, &client, target).await?;
write_objects(&client).await?;
env.stop_server();
read_snapshot(Path::new(&env.temp_dir))
}
async fn write_configs(env: &RustFSTestEnvironment, client: &Client, target: &FakeS3Target) -> Result<(), Error> {
env.create_test_bucket(LOGS).await?;
env.create_test_bucket(OBJECTS).await?;
env.create_test_bucket("persistence-warehouse").await?;
env.create_test_bucket("persistence-migration").await?;
client
.create_bucket()
.bucket(CONFIGS)
.object_lock_enabled_for_bucket(true)
.send()
.await?;
macro_rules! golden {
($path:literal) => {
include_str!(concat!("../../ecstore/tests/fixtures/bucket-config-goldens/", $path, ".in.xml"))
};
}
let target_request = serde_json::json!({
"endpoint": target.address(), "credentials": {"accessKey": FAKE_ACCESS_KEY, "secretKey": FAKE_SECRET_KEY},
"targetbucket": "interop-dr", "type": "replication", "secure": false,
"deploymentID": "0b6f3c2a-5e6a-4d2b-9c1e-7a8f9d0e1b2c"
});
let response = send_set_replication_target_request(env, CONFIGS, false, target_request).await?;
if !response.status().is_success() {
return Err(format!("set remote target failed with {}", response.status()).into());
}
let target_arn: String = response.json().await?;
let replication = golden!("replication/rustfs").replace("arn:rustfs:replication:", "arn:minio:replication:");
if !replication.contains(&format!("<Bucket>{target_arn}</Bucket>")) {
return Err("registered target does not match the golden replication destination".into());
}
for (query, xml) in [
("versioning", golden!("versioning/minio")),
("notification", golden!("notification/rustfs")),
("replication", replication.as_str()),
("lifecycle", golden!("lifecycle/minio")),
("object-lock", golden!("object_lock/rustfs")),
("encryption", golden!("encryption/minio")),
("tagging", golden!("tagging/rustfs")),
("cors", golden!("cors/rustfs")),
("logging", golden!("logging/rustfs")),
("website", golden!("website/rustfs")),
("accelerate", golden!("accelerate/rustfs")),
("requestPayment", golden!("request_payment/rustfs")),
("publicAccessBlock", golden!("public_access_block/rustfs")),
] {
put_xml(env, query, xml).await?;
}
client
.put_bucket_acl()
.bucket(CONFIGS)
.acl(BucketCannedAcl::Private)
.send()
.await?;
let acl = client.get_bucket_acl().bucket(CONFIGS).send().await?;
let owner = acl.owner().and_then(|owner| owner.id()).ok_or("ACL owner missing")?;
let [grant] = acl.grants() else { return Err("expected exactly one ACL grant".into()) };
let grantee = grant.grantee().ok_or("missing ACL grantee")?;
if owner.is_empty()
|| grant.permission().map(|p| p.as_str()) != Some("FULL_CONTROL")
|| grantee.r#type().as_str() != "CanonicalUser"
|| grantee.id().is_some()
{
return Err("GET ACL changed its canonical owner grant".into());
}
let policy = serde_json::json!({
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny", "Principal": "*", "Action": "s3:DeleteObject",
"Resource": format!("arn:aws:s3:::{CONFIGS}/protected/*"),
}],
});
client
.put_bucket_policy()
.bucket(CONFIGS)
.policy(policy.to_string())
.send()
.await?;
set_bucket_quota(env, CONFIGS, 16 * 1024 * 1024).await?;
let migration = OdmSourceSpec::for_fake_source(target, "migration-source");
for (path, body) in [
("/iceberg/v1/buckets/persistence-warehouse".to_owned(), None),
(format!("{ODM_ADMIN_ROUTE}/persistence-migration"), Some(migration.to_json().to_string())),
] {
let (status, _) = admin_request(&env.url, Method::PUT, &path, body, &env.access_key, &env.secret_key).await?;
if !status.is_success() {
return Err(format!("configuring {path} failed with {status}").into());
}
}
Ok(())
}
async fn write_objects(client: &Client) -> Result<(), Error> {
for key in ["put", "tagged"] {
client
.put_object()
.bucket(OBJECTS)
.key(key)
.metadata("purpose", "byte-parity")
.body(ByteStream::from_static(b"persisted object contents"))
.send()
.await?;
}
client
.copy_object()
.bucket(OBJECTS)
.key("copy")
.copy_source(format!("{OBJECTS}/put"))
.send()
.await?;
let tags = Tagging::builder()
.tag_set(Tag::builder().key("type").value("persisted").build()?)
.build()?;
client
.put_object_tagging()
.bucket(OBJECTS)
.key("tagged")
.tagging(tags)
.send()
.await?;
write_multipart(client, OBJECTS, "multipart", &[vec![0x31; FIRST_PART_SIZE], vec![0x32; 100]]).await?;
Ok(())
}
fn read_snapshot(volume: &Path) -> Result<Snapshot, Error> {
let b = bucket_metadata(volume, CONFIGS)?;
let configs = BTreeMap::from([
("acl", b.bucket_acl_config_json),
("accelerate", b.accelerate_config_xml),
("cors", b.cors_config_xml),
("encryption", b.encryption_config_xml),
("lifecycle", b.lifecycle_config_xml),
("logging", b.logging_config_xml),
("notification", b.notification_config_xml),
("object_lock", b.object_lock_config_xml),
("public_access_block", b.public_access_block_config_xml),
("request_payment", b.request_payment_config_xml),
("tagging", b.tagging_config_xml),
("versioning", b.versioning_config_xml),
("website", b.website_config_xml),
("durability", b.durability_config_json),
("policy", b.policy_config_json),
("quota", b.quota_config_json),
("replication", b.replication_config_xml),
("targets", b.bucket_targets_config_json),
("table", bucket_metadata(volume, "persistence-warehouse")?.table_bucket_config_json),
("odm", bucket_metadata(volume, "persistence-migration")?.on_demand_migration_config_json),
]);
let mut objects = BTreeMap::new();
for key in ["put", "copy", "tagged"] {
let (_, fields) = read_object(volume, key)?;
objects.insert(key, fields);
}
let (multipart, _) = read_object(volume, "multipart")?;
if multipart.part_numbers != [1, 2] || multipart.part_sizes != [FIRST_PART_SIZE, 100] {
return Err("xl.meta does not describe both uploaded parts".into());
}
let directory = volume
.join(OBJECTS)
.join("multipart")
.join(multipart.data_dir.ok_or("missing multipart data directory")?.to_string());
let mut multipart_files = BTreeMap::new();
for entry in std::fs::read_dir(directory)? {
let entry = entry?;
let name = entry.file_name().into_string().map_err(|_| "invalid multipart file name")?;
if name.starts_with("part.") {
let bytes = std::fs::read(entry.path())?;
if bytes.is_empty() {
return Err(format!("empty multipart file {name}").into());
}
multipart_files.insert(name, bytes);
}
}
for name in ["part.1", "part.2", "part.1.meta", "part.2.meta"] {
if !multipart_files.contains_key(name) {
return Err(format!("missing multipart file {name}").into());
}
}
Ok(Snapshot {
configs,
objects,
multipart_files,
})
}
fn save_xml_samples(root: &Path, side: &str, snapshot: &Snapshot) -> Result<(), Error> {
let directory = root.join(side);
std::fs::create_dir_all(&directory)?;
let families: [&str; 13] = [
"accelerate",
"cors",
"encryption",
"lifecycle",
"logging",
"notification",
"object_lock",
"public_access_block",
"replication",
"request_payment",
"tagging",
"versioning",
"website",
];
for family in families {
let bytes = snapshot
.configs
.get(family)
.ok_or_else(|| format!("missing XML family {family}"))?;
std::fs::write(directory.join(format!("{family}.xml")), bytes)?;
}
Ok(())
}
#[tokio::test]
async fn persistence_byte_parity() -> Result<(), Error> {
let reference = PathBuf::from(
std::env::var_os("RUSTFS_PERSISTENCE_REFERENCE_BINARY").ok_or("missing pinned RUSTFS_PERSISTENCE_REFERENCE_BINARY")?,
);
let candidate = rustfs_binary_path();
if binary_version(&reference).await? == binary_version(&candidate).await? {
return Err("reference and candidate binaries report identical build identities".into());
}
// The quota writer records the process wall clock inside its JSON document. Keep raw bytes
// comparable while the SDK's signature clock and both servers' monotonic timers advance normally.
let clock_library = std::env::var("RUSTFS_PERSISTENCE_CLOCK_LIBRARY")?;
if !Path::new(&clock_library).is_absolute() || !Path::new(&clock_library).is_file() {
return Err("RUSTFS_PERSISTENCE_CLOCK_LIBRARY must name an absolute libfaketime path".into());
}
let clock = time::OffsetDateTime::now_utc()
.format(time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"))?;
let target = FakeS3Target::start().await?;
target.create_bucket("migration-source");
target.create_bucket_with_object_lock("interop-dr");
let reference = capture(&reference, &target, &clock, &clock_library).await?;
let candidate = capture(&candidate, &target, &clock, &clock_library).await?;
if let Some(directory) = std::env::var_os("RUSTFS_PERSISTENCE_XML_DIR") {
save_xml_samples(Path::new(&directory), "reference", &reference)?;
save_xml_samples(Path::new(&directory), "candidate", &candidate)?;
}
if reference.configs.len() != 20 || candidate.configs.len() != 20 {
return Err("expected 13 XML and seven JSON fields on each side".into());
}
for (&field, expected) in &reference.configs {
// Canned ACLs acknowledge the write and return one owner grant without persisting an ACL document.
if expected.is_empty() != (field == "acl") || candidate.configs.get(field) != Some(expected) {
return Err(format!("incorrect or different persisted bucket config: {field}").into());
}
}
for (key, expected) in &reference.objects {
if candidate.objects.get(key) != Some(expected) {
return Err(format!("different persisted xl.meta fields: {key}").into());
}
}
if candidate.multipart_files != reference.multipart_files {
return Err("different multipart part files or part metadata".into());
}
eprintln!(
"Compared {} bucket fields (canned ACL empty), {} full object records and multipart part files",
reference.configs.len(),
reference.objects.len()
);
Ok(())
}
#[test]
fn version_comparison_preserves_unknown_fields_and_absent_values() -> Result<(), Error> {
let mut sample = serde_json::json!({"Type": 1, "v": 1, "V2Obj": {"DDir": vec![1; 16], "MTime": 1}});
let fields = |value: &serde_json::Value| nonvolatile_fields(&rmp_serde::to_vec(value)?, "fixture");
let original = fields(&sample)?;
sample["V2Obj"]["DDir"] = serde_json::json!(vec![2; 16]);
sample["V2Obj"]["MTime"] = serde_json::json!(2);
assert_eq!(fields(&sample)?, original);
sample["V2Obj"]["Future"] = serde_json::Value::Null;
let with_nil = fields(&sample)?;
assert_ne!(with_nil, original);
sample["V2Obj"]["Future"] = serde_json::json!(false);
let with_value = fields(&sample)?;
assert_ne!(with_value, with_nil);
sample["FutureEnvelope"] = serde_json::json!(1);
assert_ne!(fields(&sample)?, with_value);
assert!(fields(&serde_json::json!({"V2Obj": {"MTime": 1}})).is_err());
Ok(())
}
@@ -573,6 +573,15 @@ impl NodeService for MinimalLockNodeService {
Err(Status::unimplemented("lock-only test server"))
}
type RenameDataBatchStream = ResponseStream<rustfs_protos::proto_gen::node_service::RenameDataBatchResult>;
async fn rename_data_batch(
&self,
_request: Request<rustfs_protos::proto_gen::node_service::RenameDataBatchRequest>,
) -> Result<Response<Self::RenameDataBatchStream>, Status> {
Err(Status::unimplemented("lock-only test server"))
}
async fn rename_multipart_data(
&self,
_request: Request<rustfs_protos::proto_gen::node_service::RenameDataRequest>,
@@ -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};
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging, local_http_client};
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("--ignored")
.arg("--include-ignored")
.arg("--nocapture")
.env(NAMESPACE_ENV, "1")
.status()?;
@@ -1524,6 +1524,110 @@ 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")]
+332 -11
View File
@@ -465,7 +465,7 @@ pub(crate) async fn set_replication_target_with_options(
Ok(arn)
}
async fn send_set_replication_target_request(
pub(crate) async fn send_set_replication_target_request(
source_env: &RustFSTestEnvironment,
source_bucket: &str,
update: bool,
@@ -2075,12 +2075,18 @@ 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 replication_enabled: watch::Receiver<bool>,
mut gate: ReplicationProxyGate,
mut held_tagging: watch::Receiver<Option<String>>,
mut response_hold: ReplicationResponseHoldRuntime,
) -> Response<Full<bytes::Bytes>> {
@@ -2091,8 +2097,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 !*replication_enabled.borrow() {
if replication_enabled.changed().await.is_err() {
while !*gate.enabled.borrow() {
if gate.enabled.changed().await.is_err() {
return proxy_error_response("replication gate closed");
}
}
@@ -2117,6 +2123,12 @@ 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);
@@ -2153,7 +2165,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).await?;
start_replication_counting_proxy_with_tag_hold(backend_url, tasks, None).await?;
Ok((proxy_url, request_count, replication_enabled))
}
@@ -2161,9 +2173,11 @@ 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,
@@ -2180,6 +2194,10 @@ 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 {
@@ -2192,7 +2210,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 replication_enabled = task_replication_enabled.clone();
let gate = gate.clone();
let held_tagging = task_held_tagging.clone();
let response_hold = response_hold_runtime.clone();
connections.spawn(async move {
@@ -2200,7 +2218,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 replication_enabled = replication_enabled.clone();
let gate = gate.clone();
let held_tagging = held_tagging.clone();
let response_hold = response_hold.clone();
async move {
@@ -2210,7 +2228,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
&backend_url,
&client,
&request_count,
replication_enabled,
gate,
held_tagging,
response_hold,
)
@@ -2252,6 +2270,309 @@ 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,
@@ -8222,7 +8543,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).await?;
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
let add_status = site_replication_add(
&site_a_env,
@@ -8479,9 +8800,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).await?;
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks, None).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).await?;
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
let site_a_client = site_a_env.create_s3_client();
let site_b_client = site_b_env.create_s3_client();
@@ -0,0 +1,208 @@
// 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;
}
}
+6
View File
@@ -57,6 +57,12 @@ pub(crate) mod replication_extension {
pub(crate) use super::BucketTargetSys;
}
#[cfg(test)]
pub(crate) mod persistence_parity {
pub(crate) use super::RUSTFS_META_BUCKET;
pub(crate) use rustfs_ecstore::api::bucket::metadata::BucketMetadata;
}
#[cfg(test)]
pub(crate) mod upgrade_compatibility {
pub(crate) use super::{DiskOption, Endpoint, RUSTFS_META_MULTIPART_BUCKET, new_disk};
+251 -15
View File
@@ -46,9 +46,12 @@ type BoxError = Box<dyn std::error::Error + Send + Sync>;
const SOURCE_BINARY_ENV: &str = "RUSTFS_UPGRADE_SOURCE_BINARY";
const G09_EVIDENCE_DIR_ENV: &str = "RUSTFS_SCANNER_HEAL_G09_EVIDENCE_DIR";
const RC2_COMMIT: &str = "e9f53180273b32a9c2b0aa8b5a384047bc7e875c";
const RC5_COMMIT: &str = "40a2470feb567201165a5b809b7598bb4b1f68f5";
const STABLE_1_0_1_COMMIT: &str = "6de965ae3c965a78ff819fbcd7acd4aa44177d92";
const STABLE_1_0_4_COMMIT: &str = "46337942d55f3a8e6a97b147ca98d9ea8115555d";
const STABLE_1_0_5_COMMIT: &str = "34e6449ed90e3d3a106f6655342e0b3127f33082";
const STABLE_1_0_6_COMMIT: &str = "de9009d882644effc2628e777650025c3d8e7c65";
const SSE_MASTER_KEY_ENV: &str = "RUSTFS_SSE_S3_MASTER_KEY";
const SSE_MASTER_KEY: &str = "QkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkI=";
const PLAIN_BUCKET: &str = "upgrade-plain-data";
@@ -142,6 +145,41 @@ fn current_source_revision() -> Result<String, BoxError> {
Ok(revision.to_string())
}
pub(crate) struct UpgradeSourceCapabilities {
supports_delete_recovery: bool,
supports_multipart_publication: bool,
pub(crate) requires_list_parts_read_quorum: bool,
}
impl UpgradeSourceCapabilities {
fn from_revision(revision: &str) -> Result<Self, BoxError> {
// 1.0.4 supports the delete decision protocol (#8468). Version 1.0.5 also
// shipped native MPU publication (#8919) and strict ListParts evidence (#9037, #9149).
match revision {
RC2_COMMIT | RC5_COMMIT | STABLE_1_0_1_COMMIT => Ok(Self {
supports_delete_recovery: false,
supports_multipart_publication: false,
requires_list_parts_read_quorum: false,
}),
STABLE_1_0_4_COMMIT => Ok(Self {
supports_delete_recovery: true,
supports_multipart_publication: false,
requires_list_parts_read_quorum: false,
}),
STABLE_1_0_5_COMMIT | STABLE_1_0_6_COMMIT => Ok(Self {
supports_delete_recovery: true,
supports_multipart_publication: true,
requires_list_parts_read_quorum: true,
}),
_ => Err(format!("no pinned upgrade expectations for source revision {revision}").into()),
}
}
pub(crate) async fn from_binary(binary: &Path) -> Result<Self, BoxError> {
Self::from_revision(&binary_source_revision(binary).await?)
}
}
async fn binary_source_revision(binary: &Path) -> Result<String, BoxError> {
let output = tokio::process::Command::new(binary).arg("--version").output().await?;
if !output.status.success() {
@@ -225,6 +263,25 @@ mod g09_evidence_tests {
use super::*;
use tempfile::TempDir;
#[test]
fn pinned_upgrade_sources_keep_distinct_delete_and_list_parts_contracts() -> TestResult {
for (revision, delete_recovery, multipart_publication, list_parts_quorum) in [
(RC2_COMMIT, false, false, false),
(RC5_COMMIT, false, false, false),
(STABLE_1_0_1_COMMIT, false, false, false),
(STABLE_1_0_4_COMMIT, true, false, false),
(STABLE_1_0_5_COMMIT, true, true, true),
(STABLE_1_0_6_COMMIT, true, true, true),
] {
let source = UpgradeSourceCapabilities::from_revision(revision)?;
assert_eq!(source.supports_delete_recovery, delete_recovery, "{revision}");
assert_eq!(source.supports_multipart_publication, multipart_publication, "{revision}");
assert_eq!(source.requires_list_parts_read_quorum, list_parts_quorum, "{revision}");
}
assert!(UpgradeSourceCapabilities::from_revision("ffffffffffffffffffffffffffffffffffffffff").is_err());
Ok(())
}
#[test]
fn source_revision_parser_requires_lowercase_forty_byte_sha() -> TestResult {
let binary = Path::new("rustfs");
@@ -365,7 +422,7 @@ async fn complete_pending_multipart(
.await?)
}
async fn write_multipart(client: &Client, bucket: &str, key: &str, parts: &[Vec<u8>]) -> TestResult {
pub(crate) async fn write_multipart(client: &Client, bucket: &str, key: &str, parts: &[Vec<u8>]) -> TestResult {
let pending = stage_multipart(client, bucket, key, parts).await?;
complete_pending_multipart(client, bucket, key, &pending).await?;
Ok(())
@@ -1011,8 +1068,7 @@ async fn exercise_mixed_cluster(
vec![u8::try_from(MULTIPART_WORKERS - 1)?; 64 * 1024]
);
// 1.0.4 already implements the delete decision protocol. Use a separate
// old-writer key so the original seed still spans the entire rollout.
// Use a separate old-writer key so the original seed still spans the entire rollout.
if previous_has_delete_recovery {
let key = format!(".upgrade-delete/{phase}/previous-writer");
previous_client
@@ -1702,6 +1758,129 @@ mod upgrade_write_readiness_tests {
}
}
async fn stop_scanner_handoff_server(env: &mut RustFSTestEnvironment) -> TestResult {
let process = env.process.as_mut().ok_or("handoff server is not running")?;
signal_process(process.id(), "TERM")?;
tokio::time::timeout(Duration::from_secs(90), async {
loop {
if let Some(status) = process.try_wait()? {
assert!(status.success(), "handoff shutdown failed: {status}");
return Ok::<(), BoxError>(());
}
sleep(Duration::from_millis(50)).await;
}
})
.await??;
env.process.take();
Ok(())
}
fn scanner_handoff_identity(env: &RustFSTestEnvironment) -> Result<String, BoxError> {
let receipt: Value = serde_json::from_slice(&std::fs::read(Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown"))?)?;
assert_eq!(receipt["schema"], 1);
assert_eq!(receipt["owner"], env.address);
Ok(receipt["checkpoint_instance_id"]
.as_str()
.ok_or("handoff receipt omitted checkpoint identity")?
.to_owned())
}
async fn assert_scanner_handoff_consumed(marker: &Path) -> TestResult {
let marker = tokio::fs::read_to_string(marker).await?;
// Heal may replace the startup marker with its ordinary timestamp before
// readiness. Neither form carries the prior checkpoint identity.
assert!(
marker == "running" || marker.parse::<u64>().is_ok(),
"readiness must expose an ordinary unclean marker, never a handoff receipt"
);
Ok(())
}
#[tokio::test]
async fn scanner_read_only_handoff_requires_explicit_opt_in() -> TestResult {
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
assert!(std::env::var_os(HANDOFF).is_none(), "this scenario tests the unset default");
let mut env = RustFSTestEnvironment::new().await?;
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
env.start_rustfs_server_without_cleanup(vec![]).await?;
stop_scanner_handoff_server(&mut env).await?;
assert!(!marker.exists(), "the default must not create a receipt");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
stop_scanner_handoff_server(&mut env).await?;
let previous = scanner_handoff_identity(&env)?;
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
assert_scanner_handoff_consumed(&marker).await?;
stop_scanner_handoff_server(&mut env).await?;
assert_eq!(scanner_handoff_identity(&env)?, previous, "opted-in read-only boots retain identity");
for disabled in ["invalid", "false"] {
let before_disabled = scanner_handoff_identity(&env)?;
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, disabled)])
.await?;
assert_scanner_handoff_consumed(&marker).await?;
stop_scanner_handoff_server(&mut env).await?;
assert!(!marker.exists(), "disabled shutdown must not recreate the receipt");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
stop_scanner_handoff_server(&mut env).await?;
assert_ne!(scanner_handoff_identity(&env)?, before_disabled, "opt-out breaks the prior lineage");
}
Ok(())
}
// Exercise the receipt protocol in the existing pinned-release rollback lane.
async fn assert_scanner_handoff_prepares_legacy_rollback(previous_binary: &Path) -> TestResult {
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
let mut env = RustFSTestEnvironment::new().await?;
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
stop_scanner_handoff_server(&mut env).await?;
let previous = scanner_handoff_identity(&env)?;
// Complete the current reader's rollback preparation before any old writer
// opens storage, including an old writer with all background services off.
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "false")])
.await?;
assert_scanner_handoff_consumed(&marker).await?;
stop_scanner_handoff_server(&mut env).await?;
assert!(!marker.exists());
env.start_rustfs_server_from_binary_without_cleanup(
previous_binary,
vec![],
&[
("RUSTFS_SCANNER_ENABLED", "false"),
("RUSTFS_HEAL_ENABLED", "false"),
("RUSTFS_HEAL_AUTO_HEAL_ENABLE", "false"),
("RUSTFS_HEAL_MRF_ENABLE", "false"),
],
)
.await?;
let client = env.create_s3_client();
env.create_test_bucket("handoff-rollback").await?;
client
.put_object()
.bucket("handoff-rollback")
.key("legacy-write")
.body(ByteStream::from_static(b"legacy writer survived rollback preparation"))
.send()
.await?;
env.stop_server();
assert!(!marker.exists(), "the legacy crash cannot resurrect a consumed receipt");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
assert_eq!(
read_object(&client, "handoff-rollback", "legacy-write", None).await?.1,
b"legacy writer survived rollback preparation"
);
stop_scanner_handoff_server(&mut env).await?;
assert_ne!(
scanner_handoff_identity(&env)?,
previous,
"a legacy write must not retain the old lineage"
);
Ok(())
}
/// Pins the published old writer's limitation and the supported recovery
/// procedure. This is not a promise that mixed-version ODM is supported.
/// Replace the loss assertion when ODM gains independent persistence;
@@ -2293,7 +2472,7 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
let previous_binary = source_binary()?;
// Bind the expected protocol to the verified release source, never to the
// DELETE result itself. The older CI source pins retain their 503 contract.
let previous_has_delete_recovery = binary_source_revision(&previous_binary).await? == STABLE_1_0_4_COMMIT;
let source = UpgradeSourceCapabilities::from_binary(&previous_binary).await?;
let evidence_context = g09_evidence_context(&previous_binary).await?;
let current_binary = rustfs_binary_path();
let mut cluster = RustFSTestClusterEnvironment::new(MIXED_NODE_COUNT).await?;
@@ -2315,17 +2494,21 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
cluster.stop_node(0)?;
cluster.start_node_from_binary(0, &current_binary).await?;
let mut mixed_deleted_keys = Vec::new();
if let Some(key) = exercise_mixed_cluster(&cluster, "one-current-node", 0, 1, previous_has_delete_recovery).await? {
if let Some(key) = exercise_mixed_cluster(&cluster, "one-current-node", 0, 1, source.supports_delete_recovery).await? {
mixed_deleted_keys.push(key);
}
// One controlled out-of-policy attempt proves fail-closed behavior below
// native write quorum; positive MPU writers remain paused while mixed.
assert_mixed_pending_refusal(&cluster, &pending, &sources).await?;
let mixed_completion = if source.supports_multipart_publication {
let clients = cluster.create_all_clients()?;
Some(finish_pending_multipart(&clients, &pending, pending_parts.concat()).await?)
} else {
assert_mixed_pending_refusal(&cluster, &pending, &sources).await?;
None
};
for (node_idx, phase) in [(1, "two-current-nodes"), (2, "one-previous-node")] {
cluster.stop_node(node_idx)?;
cluster.start_node_from_binary(node_idx, &current_binary).await?;
if let Some(key) = exercise_mixed_cluster(&cluster, phase, 0, 3, previous_has_delete_recovery).await? {
if let Some(key) = exercise_mixed_cluster(&cluster, phase, 0, 3, source.supports_delete_recovery).await? {
mixed_deleted_keys.push(key);
}
}
@@ -2335,6 +2518,13 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
let clients = cluster.create_all_clients()?;
wait_for_drive_readmission(&clients, MIXED_BUCKET, "homogeneous-current", DRIVE_READMISSION_TIMEOUT).await?;
let completed_pending = finish_pending_multipart(&clients, &pending, pending_parts.concat()).await?;
if let Some(mixed) = mixed_completion {
assert_eq!(
completed_pending.version_id, mixed.version_id,
"full upgrade changed the completed version"
);
assert_eq!(completed_pending.etag, mixed.etag, "full upgrade changed the completed ETag");
}
exercise_homogeneous_multipart(&cluster, "homogeneous-current").await?;
verify_load_bodies(&clients, "homogeneous-previous", "multipart").await?;
assert_mixed_deletes_visible(&clients, &mixed_deleted_keys).await?;
@@ -2451,7 +2641,7 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
"phases": phases,
"objects_per_phase": objects_per_phase,
"mixed_load": "plain-put",
"mixed_delete_protocol_supported": previous_has_delete_recovery,
"mixed_delete_protocol_supported": source.supports_delete_recovery,
"mixed_deleted_keys": mixed_deleted_keys,
"homogeneous_multipart_phases": ["homogeneous-previous", "homogeneous-current", "homogeneous-rollback"],
"multipart_objects_per_homogeneous_phase": MULTIPART_WORKERS * MULTIPART_UPLOADS_PER_WORKER,
@@ -2461,7 +2651,7 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
"all nodes list every mixed-version object after homogeneous-current convergence",
"the previous-release seed survives the baseline restart and every upgrade phase",
"previous readers read every current-native MPU body after quiescent rollback",
"same legacy upload resumes with identical body, ETag and version after full upgrade"
"the same previous-release upload remains readable after full upgrade and rollback"
],
}),
)?;
@@ -2483,9 +2673,13 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
"previous-release writer publishes objects readable by current node",
"mixed phases retain 16x16 plain PUT writers while positive multipart writers are paused",
"16x16 multipart load runs in homogeneous previous, current and rollback phases",
"one-current-node Complete returns typed 503 and preserves actual source authority and parts",
"the same legacy upload completes and replays once fully upgraded without adding a version",
if previous_has_delete_recovery {
if source.supports_multipart_publication {
"one-current-node Complete and replay return the same version and ETag, and all readers agree on the body"
} else {
"one-current-node Complete returns typed 503 and preserves actual source authority and parts"
},
"fully upgraded readers see the same body, ETag and sole version after replay",
if source.supports_delete_recovery {
"mixed-version DELETE succeeds and stays absent through every reader after upgrade and rollback"
} else {
"modern DELETE fails closed and preserves every byte while old peers remain"
@@ -2832,7 +3026,7 @@ async fn restart_from_binary(env: &mut RustFSTestEnvironment, binary: &Path, ser
env.start_rustfs_server_from_binary(binary, vec![], server_env).await
}
async fn set_bucket_quota(env: &RustFSTestEnvironment, bucket: &str, quota_bytes: u64) -> TestResult {
pub(crate) async fn set_bucket_quota(env: &RustFSTestEnvironment, bucket: &str, quota_bytes: u64) -> TestResult {
let path = format!("/rustfs/admin/v3/quota/{bucket}");
let body = serde_json::json!({ "quota": quota_bytes, "quota_type": "HARD" }).to_string();
let deadline = Instant::now() + QUOTA_READINESS_TIMEOUT;
@@ -3386,9 +3580,12 @@ async fn direct_upgrade_from_previous_release_preserves_bucket_configuration() -
#[tokio::test]
#[ignore = "requires a pinned previous RustFS release binary"]
async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestResult {
use sha2::Digest;
init_logging();
let previous_binary = source_binary()?;
let evidence_context = g09_evidence_context(&previous_binary).await?;
assert_scanner_handoff_prepares_legacy_rollback(&previous_binary).await?;
let replication_target = FakeS3Target::start().await?;
replication_target.create_bucket(ROLLBACK_REPLICA_BUCKET);
@@ -3423,6 +3620,16 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
let multipart_bytes = multipart_parts.concat();
write_multipart(&new_client, ROLLBACK_BUCKET, multipart_key, &multipart_parts).await?;
// This release can finish an upload staged by the current gateway.
let inflight = if binary_source_revision(&previous_binary).await? == STABLE_1_0_5_COMMIT {
env.create_test_bucket(PENDING_MULTIPART_BUCKET).await?;
let parts = [vec![1; LAYOUT_PART_SIZE], vec![2; LAYOUT_PART_SIZE], vec![3; 4096]];
let pending = stage_multipart(&new_client, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, &parts).await?;
Some((pending, parts.concat()))
} else {
None
};
restart_from_binary(&mut env, &previous_binary, &server_env).await?;
let old_client = env.create_s3_client();
@@ -3438,6 +3645,16 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
assert_eq!(encryption, Some(ServerSideEncryption::Aes256));
assert_eq!(body, multipart_bytes, "the multipart object did not survive the rollback");
let rollback_multipart = if let Some((pending, expected)) = inflight {
assert_pending_parts(&old_client, &pending).await?;
complete_pending_multipart(&old_client, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, &pending).await?;
let (_, body) = read_object(&old_client, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, None).await?;
assert_eq!(body, expected);
Some((pending.part_sizes, body))
} else {
None
};
// A PUT on the rolled-back release must still honour the encryption
// configuration it decoded out of the current build's metadata blob.
let post_rollback_key = "rollback/written-after-rollback";
@@ -3478,6 +3695,25 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
post_rollback_bytes
);
if let Some((part_sizes, rollback_read)) = rollback_multipart {
let (_, current_read) = read_object(&current_again, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, None).await?;
assert_eq!(current_read, rollback_read);
if let Some(context) = &evidence_context {
let evidence = serde_json::json!({
"previous_revision": context.previous_revision,
"current_revision": context.current_revision,
"part_sizes": part_sizes,
"bytes": current_read.len(),
"rollback_read_sha256": hex_simd::encode_to_string(sha2::Sha256::digest(&rollback_read), hex_simd::AsciiCase::Lower),
"roll_forward_read_sha256": hex_simd::encode_to_string(sha2::Sha256::digest(&current_read), hex_simd::AsciiCase::Lower),
});
std::fs::write(
context.directory.join("inflight-multipart-rollback.json"),
serde_json::to_vec_pretty(&evidence)?,
)?;
}
}
if let Some(context) = evidence_context.as_ref() {
write_g09_evidence(
context,
-3
View File
@@ -154,7 +154,6 @@ arc-swap.workspace = true
async-trait.workspace = true
bytes = { workspace = true, features = ["serde"] }
byteorder = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
jiff = { workspace = true, features = ["serde"] }
thiserror.workspace = true
flatbuffers.workspace = true
@@ -184,7 +183,6 @@ rmp.workspace = true
rmp-serde.workspace = true
tokio-util = { workspace = true, features = ["io", "compat", "rt"] }
tokio-stream = { workspace = true, features = ["sync"] }
hmac = { workspace = true }
sha2 = { workspace = true }
hex-simd = { workspace = true }
tempfile.workspace = true
@@ -259,7 +257,6 @@ windows-sys = { workspace = true, features = [
windows-sys = { workspace = true, features = ["Win32_System_Ioctl"] }
[dev-dependencies]
s3s = { workspace = true, features = ["minio"] }
aws-smithy-async.workspace = true
rustfs-s3-ops.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util", "fs"] }
+27 -19
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};
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info, get_server_info_with_inventory};
}
pub mod bitrot {
@@ -72,10 +72,11 @@ pub mod bucket {
ExpiryState, LifecycleOps, ManualTransitionCancelCheck, ManualTransitionProgressSink,
ManualTransitionQueueSnapshot, ManualTransitionRunExecution, ManualTransitionRunOptions,
ManualTransitionRunReport, RestoreRequestOps, TransitionState, TransitionedObject, apply_expiry_rule,
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,
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,
run_stale_multipart_upload_cleanup_once, validate_transition_tier,
};
}
@@ -348,7 +349,7 @@ pub mod bucket {
pub mod utils {
pub use crate::bucket::utils::{
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args,
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args, check_object_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,
};
@@ -454,13 +455,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_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_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,
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,
store_data_usage_in_backend, verified_account_bucket_usage,
};
pub use crate::data_usage::{get_bucket_usage_memory, lookup_degraded_bucket_usage_baseline};
}
@@ -469,6 +470,7 @@ 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")]
@@ -503,7 +505,7 @@ pub mod disk {
PoolMetaNativeInspection, PoolMetaNativeObject, PoolMetaNativeRecoveryRequest, PoolMetaNativeRecoveryResponse,
QUOTA_MUTATION_FENCE_METADATA_SUFFIX, RUSTFS_META_BUCKET, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, STORAGE_FORMAT_FILE, SnapshotLeaseToken,
UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
UNCLEAN_SHUTDOWN_MARKER_PATH, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
validate_batch_read_version_item_count, validate_format_control_path,
};
pub use crate::disk::{
@@ -615,15 +617,21 @@ pub mod object {
};
pub use crate::erasure::codec::shard_emit::ShardEmitter;
pub use crate::object_api::{
BLOCK_SIZE_V2, ERASURE_ALGORITHM, EncryptionResolutionError, EncryptionResolutionErrorKind, GetObjectBodyCacheHook,
GetObjectBodyCacheHookLookup, GetObjectBodySource, GetObjectReadCondition, GetObjectReadMetadata, GetObjectReader,
GetObjectSink, GetObjectSinkSegmentFactory, GetObjectSinkSegments, GetObjectSinkStream, GetObjectSinkWriter,
NamespaceLockFence, ObjectEncryptionResolver, ObjectInfo, ObjectLockConfigSnapshot, ObjectMutationHook, ObjectOptions,
PutObjReader, QuotaAdmission, RangedDecompressReader, ReadEncryptionMaterial, ReadEncryptionMode, ReadEncryptionRequest,
BLOCK_SIZE_V2, ClientEcBlockSizeHint, DEFAULT_EC_BLOCK_SIZE, EC_BLOCK_SIZE_CANDIDATES, EC_BLOCK_SIZE_HINT_INTERNAL_KEY,
EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX, EC_BLOCK_SIZE_HINT_METADATA_KEY, EC_BLOCK_SIZE_HINT_REASON_HEADER,
EC_BLOCK_SIZE_HINT_STATUS_HEADER, EC_BLOCK_SIZE_INFO_INTERNAL_KEY, EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
EC_BLOCK_SIZE_RESPONSE_HEADER, EC_READ_QUANTUM_INFO_INTERNAL_KEY, EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX,
ERASURE_ALGORITHM, EcBlockSizeHintError, EcBlockSizeHintIgnoreReason, EcBlockSizeHintOutcome, EncryptionResolutionError,
EncryptionResolutionErrorKind, GetObjectBodyCacheHook, GetObjectBodyCacheHookLookup, GetObjectBodySource,
GetObjectReadCondition, GetObjectReadMetadata, GetObjectReader, GetObjectSink, GetObjectSinkSegmentFactory,
GetObjectSinkSegments, GetObjectSinkStream, GetObjectSinkWriter, NamespaceLockFence, ObjectEncryptionResolver,
ObjectInfo, ObjectLockConfigSnapshot, ObjectMutationHook, ObjectOptions, PutObjReader, QuotaAdmission,
RangedDecompressReader, ReadEncryptionMaterial, ReadEncryptionMode, ReadEncryptionRequest, ResolvedEcBlockSize,
SCANNER_PUBLICATION_LEASE_FENCE_METADATA_KEY, ScannerPublicationCommitScope, ScannerPublicationCommitStartError,
ScannerPublicationCommitState, ShardIntegrityWriteMode, StreamConsumer, WriteCommitGuard, WriteCompletion,
get_object_body_cache_plaintext_len, lookup_get_object_body_cache_hook, register_get_object_body_cache_hook,
register_object_mutation_hook, unregister_get_object_body_cache_hook, unregister_object_mutation_hook,
get_object_body_cache_plaintext_len, is_supported_ec_block_size, lookup_get_object_body_cache_hook,
parse_ec_block_size_hint, register_get_object_body_cache_hook, register_object_mutation_hook, resolve_ec_block_size_hint,
take_ec_block_size_hint, unregister_get_object_body_cache_hook, unregister_object_mutation_hook,
with_get_object_read_condition,
};
pub use crate::store::{
@@ -763,8 +771,8 @@ pub mod storage {
pub use crate::store::external_rpc_disk;
pub use crate::store::{
BootstrapLocalTarget, ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk,
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, init_local_disks,
init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc,
init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
prewarm_local_disk_id_map_with_instance_ctx,
};
pub use crate::store::{HealObjectAbsenceProof, HealObjectStorageResult};
File diff suppressed because it is too large Load Diff
@@ -51,15 +51,20 @@ impl LcAuditEvent {
}
}
pub(crate) fn emit_transition_failed_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT);
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_complete_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionComplete, 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_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo) {
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo, incarnation_id: uuid::Uuid) {
let event_name = transitioned_expiration_event_name(source.delete_marker, deleted.delete_marker);
let object = ObjectInfo {
bucket: source.bucket.clone(),
@@ -69,12 +74,17 @@ 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);
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
}
pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source: &ObjectInfo, deleted: ObjectInfo) {
pub(crate) fn emit_non_transitioned_expiration_event(
action: IlmAction,
source: &ObjectInfo,
deleted: ObjectInfo,
incarnation_id: uuid::Uuid,
) {
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);
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
}
/// Emit the lifecycle expiration event for one version removed by the batch
@@ -83,9 +93,15 @@ pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source:
/// 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) {
pub(crate) fn emit_noncurrent_expiration_event(
bucket: &str,
target: &ObjectToDelete,
deleted: &DeletedObject,
failed: bool,
incarnation_id: uuid::Uuid,
) {
if let Some((event_name, object)) = noncurrent_expiration_event(bucket, target, deleted, failed) {
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
}
}
@@ -131,9 +147,10 @@ fn noncurrent_expiration_event(
Some((event_name, object))
}
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str) {
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str, incarnation_id: Option<uuid::Uuid>) {
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;
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
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 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,7 +1566,12 @@ 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,
@@ -1606,12 +1611,12 @@ pub struct TransitionState {
compensation_scheduled_tasks: AtomicI64,
compensation_running_tasks: AtomicI64,
compensation_buckets: Arc<Mutex<HashSet<String>>>,
// (bucket, object, version) currently queued or being transitioned. A single
// (incarnation, 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<(String, String, String)>>>,
in_flight_transitions: Arc<Mutex<HashSet<TransitionKey>>>,
last_day_stats: Arc<Mutex<HashMap<String, LastDayTierStats>>>,
}
@@ -1677,28 +1682,29 @@ impl TransitionState {
})
}
fn transition_key(oi: &ObjectInfo) -> (String, String, String) {
fn transition_key(oi: &ObjectInfo, incarnation: Option<Uuid>) -> TransitionKey {
(
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 (bucket, object, version). Returns
/// Try to claim a transition for this exact (incarnation, 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) -> bool {
let key = Self::transition_key(oi);
fn reserve_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) -> bool {
let key = Self::transition_key(oi, incarnation);
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) {
let key = Self::transition_key(oi);
fn release_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) {
let key = Self::transition_key(oi, incarnation);
match self.in_flight_transitions.lock() {
Ok(mut set) => set.remove(&key),
Err(poisoned) => poisoned.into_inner().remove(&key),
@@ -1902,6 +1908,7 @@ 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);
@@ -1914,7 +1921,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) {
if !self.reserve_transition(oi, notification_bucket_incarnation) {
self.record_scanner_transition_state();
return TransitionEnqueueOutcome::AlreadyInFlight;
}
@@ -1923,7 +1930,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);
self.release_transition(oi, notification_bucket_incarnation);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1948,7 +1955,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);
self.release_transition(oi, notification_bucket_incarnation);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1967,6 +1974,7 @@ impl TransitionState {
}
let task = TransitionTask {
notification_bucket_incarnation,
obj_info: oi.clone(),
src: src.clone(),
event: event.clone(),
@@ -2010,7 +2018,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi);
self.release_transition(oi, notification_bucket_incarnation);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2063,7 +2071,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi);
self.release_transition(oi, notification_bucket_incarnation);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2071,7 +2079,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)
self.queue_transition_task_outcome(None, oi, event, src, None, None)
.await
.is_handled()
}
@@ -2166,9 +2174,10 @@ impl TransitionState {
..Default::default()
};
if let Err(err) =
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()))
.await
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 (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(
@@ -2195,7 +2204,7 @@ impl TransitionState {
"Lifecycle tier operation failed"
);
}
emit_transition_failed_event(obj_info_for_event);
emit_transition_failed_event(obj_info_for_event, incarnation_id);
} 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(
@@ -2217,11 +2226,11 @@ impl TransitionState {
}
transition_state.add_lastday_stats(&task.event.storage_class, ts);
emit_transition_complete_event(obj_info_for_event);
emit_transition_complete_event(obj_info_for_event, incarnation_id);
}
// 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);
transition_state.release_transition(&task.obj_info, task.notification_bucket_incarnation);
TransitionState::add_counter(&transition_state.active_tasks, -1);
transition_state.record_scanner_transition_state();
}
@@ -2826,7 +2835,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))
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.await
{
TransitionEnqueueOutcome::Queued | TransitionEnqueueOutcome::AlreadyInFlight => {
@@ -3084,6 +3093,7 @@ async fn recover_configured_tier_free_versions(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
});
}
@@ -3223,6 +3233,7 @@ 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,
@@ -4059,9 +4070,11 @@ fn transitioned_cleanup_tuple(oi: &ObjectInfo) -> Result<(&str, &str, &str), std
Ok((&transitioned.name, &transitioned.version_id, &transitioned.tier))
}
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc) {
/// 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>) {
if let Some(lc) = runtime_sources::bucket_lifecycle_config(&oi.bucket).await {
enqueue_transition_with_lifecycle(oi, &lc, &src).await;
enqueue_transition_with_lifecycle(oi, &lc, &src, notification_bucket_incarnation).await;
}
}
@@ -4534,10 +4547,20 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
let deadline = options.max_duration.map(|duration| tokio::time::Instant::now() + duration);
loop {
let page = api
.clone()
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
.await?;
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)
};
for (index, object) in page.objects.iter().enumerate() {
if manual_transition_cancel_requested(&options).await {
@@ -4559,7 +4582,16 @@ 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).await;
enqueue_transition_with_lifecycle_report(
Some(api.clone()),
object,
&lc,
&src,
&options,
&mut report,
Some(bucket_incarnation_id),
)
.await;
if report.has_enqueue_backpressure() {
report.next_marker.clone_from(&previous_marker);
report.next_version_idmarker.clone_from(&previous_version_marker);
@@ -4865,6 +4897,7 @@ 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
@@ -4917,7 +4950,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)
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id, notification_bucket_incarnation)
.await;
report.record_enqueue_outcome(outcome);
return outcome.is_handled();
@@ -4927,7 +4960,12 @@ async fn enqueue_transition_with_lifecycle_report(
false
}
async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecycleConfiguration, src: &LcEventSrc) -> bool {
async fn enqueue_transition_with_lifecycle(
oi: &ObjectInfo,
lc: &PersistedLifecycleConfiguration,
src: &LcEventSrc,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
let event = lc.eval(&oi.to_lifecycle_opts()).await;
match event.action {
IlmAction::TransitionAction | IlmAction::TransitionVersionAction => {
@@ -4938,8 +4976,9 @@ async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecy
return false;
}
runtime_sources::transition_state_handle()
.queue_transition_task(oi, &event, src)
.queue_transition_task_outcome(None, oi, &event, src, None, notification_bucket_incarnation)
.await
.is_handled()
}
_ => false,
}
@@ -5121,7 +5160,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
}
};
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
// The transitioned version is gone; evict any cached body for this object
// so it does not linger until TTL (ODC-26).
@@ -5134,7 +5173,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
//audit_log_lifecycle(oi, ILMExpiry, tags);
emit_transitioned_expiration_event(oi, &dobj);
emit_transitioned_expiration_event(oi, &dobj, bucket_incarnation_id);
Ok(dobj)
}
@@ -5152,12 +5191,22 @@ pub fn gen_transition_objname(bucket: &str) -> Result<String, Error> {
Ok(obj)
}
pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditEvent) -> Result<(), Error> {
async fn transition_object(
api: Arc<ECStore>,
oi: &ObjectInfo,
lae: LcAuditEvent,
notification_bucket_incarnation: Option<Uuid>,
) -> (Option<Uuid>, Result<(), Error>) {
let time_ilm = Metrics::time_ilm(lae.event.action);
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 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 etag = if let Some(etag) = &oi.etag { etag } else { "" };
let etag = etag.to_string();
@@ -5175,12 +5224,13 @@ pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditE
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)();
result
(notification_bucket_incarnation, result)
}
#[allow(
@@ -5791,12 +5841,22 @@ 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(oi, event, src)
.queue_transition_task_outcome(None, oi, event, src, None, notification_bucket_incarnation)
.await
.is_handled()
}
async fn acquire_lifecycle_publication_guard(api: &ECStore, bucket: &str) -> Result<rustfs_lock::NamespaceLockGuard, Error> {
@@ -5845,10 +5905,14 @@ 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;
@@ -6034,7 +6098,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).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).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
@@ -6050,7 +6114,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);
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj, bucket_incarnation_id);
if lc_event.action != IlmAction::NoneAction {
let mut num_versions = 1_u64;
@@ -6202,12 +6266,12 @@ fn lifecycle_deleted_object(oi: &ObjectInfo, dobj: &ObjectInfo) -> DeletedObject
}
}
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo) {
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo, bucket_incarnation_id: Uuid) {
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).await;
replication_sink::schedule_delete(oi.bucket.clone(), delete_object, Some(bucket_incarnation_id)).await;
}
async fn lifecycle_delete_config_snapshot(api: &ECStore, oi: &ObjectInfo) -> Result<DeleteReplicationConfigSnapshot, Error> {
@@ -6597,6 +6661,7 @@ mod tests {
next_object_marker: truncated.then(|| "object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated,
}
}
@@ -9114,6 +9179,160 @@ 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() {
@@ -9181,7 +9400,7 @@ mod tests {
.await
.expect("queue should remain open")
.expect("first queued transition task should be present");
state.release_transition(&first_task.obj_info);
state.release_transition(&first_task.obj_info, first_task.notification_bucket_incarnation);
assert!(
deferred.await,
@@ -9940,8 +10159,8 @@ mod tests {
..Default::default()
};
assert!(state.reserve_transition(&oi), "first claim must succeed");
assert!(!state.reserve_transition(&oi), "duplicate claim must be rejected");
assert!(state.reserve_transition(&oi, None), "first claim must succeed");
assert!(!state.reserve_transition(&oi, None), "duplicate claim must be rejected");
// A different object is independent.
let other = ObjectInfo {
@@ -9950,11 +10169,11 @@ mod tests {
version_id: None,
..Default::default()
};
assert!(state.reserve_transition(&other), "distinct object must claim independently");
assert!(state.reserve_transition(&other, None), "distinct object must claim independently");
// After release, the same object can be re-claimed (later lifecycle pass).
state.release_transition(&oi);
assert!(state.reserve_transition(&oi), "re-claim after release must succeed");
state.release_transition(&oi, None);
assert!(state.reserve_transition(&oi, None), "re-claim after release must succeed");
}
#[tokio::test]
@@ -9996,10 +10215,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.await;
let second = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10027,10 +10246,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None, None)
.await;
let second = state
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None)
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10063,7 +10282,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))
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.await;
assert_eq!(outcome, TransitionEnqueueOutcome::Queued);
@@ -10100,14 +10319,14 @@ mod tests {
};
let failed = state
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()))
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()), None)
.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()))
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()), None)
.await;
assert_eq!(retried, TransitionEnqueueOutcome::Queued);
assert_eq!(state.transition_rx.len(), 1);
@@ -10608,7 +10827,7 @@ mod tests {
let lc = latest_transition_lifecycle();
let object = current_object(ReplicationStatusType::Pending);
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner).await;
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner, None).await;
assert!(!queued);
}
@@ -10624,7 +10843,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).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(handled);
assert_eq!(report.eligible, 1);
@@ -10646,7 +10865,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).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10665,7 +10884,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).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10680,7 +10899,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).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10793,7 +11012,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).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -14138,7 +14357,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).await });
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object, None).await });
assert!(
tokio::time::timeout(StdDuration::from_millis(100), &mut admission)
.await
@@ -14957,6 +15176,37 @@ 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))
@@ -15029,6 +15279,7 @@ mod tests {
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
}
);
@@ -15225,12 +15476,14 @@ 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
@@ -15250,21 +15503,27 @@ 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());
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!(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");
remove_seeded_free_version(&disks, &bucket, "owned").await;
api.tier_config_mgr()
.write()
@@ -15484,6 +15743,121 @@ 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,6 +124,9 @@ 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);
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false, bucket_incarnation_id);
}
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()).await;
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone(), Some(bucket_incarnation_id)).await;
}
for (i, err) in errors.iter().enumerate() {
@@ -66,8 +66,12 @@ pub(crate) fn lifecycle_action_waits_for_replication(action: IlmAction) -> bool
)
}
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object).await;
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;
}
#[cfg(test)]
@@ -20,7 +20,9 @@ use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::bucket::lifecycle::bucket_lifecycle_ops::enqueue_recovered_free_version_with_cancel;
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::disk::RUSTFS_META_BUCKET;
use crate::error::Result;
use crate::object_api::ObjectInfo;
@@ -28,9 +30,10 @@ 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::{ListOperations as _, StorageObjectInfoOrErr, StorageWalkOptions},
list::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;
@@ -45,7 +48,6 @@ 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)]
@@ -143,6 +145,8 @@ 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,
}
@@ -161,6 +165,7 @@ impl TierCleanupRetryReport {
scanned: 0,
enqueued: 0,
failed: 0,
unreadable_objects: 0,
scan_truncated: false,
}
}
@@ -267,6 +272,7 @@ 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() {
@@ -290,6 +296,7 @@ pub struct FreeVersionRecoveryStats {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -300,6 +307,7 @@ pub struct FreeVersionRecoveryPage {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -343,6 +351,7 @@ 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,
};
@@ -472,6 +481,7 @@ async fn list_tier_free_versions_for_tier(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
};
@@ -505,6 +515,7 @@ 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() {
@@ -535,7 +546,7 @@ async fn list_tier_free_versions_for_tier(
};
let bucket_walk_limit = remaining_scan_objects;
let (tx, mut rx) = mpsc::channel::<ObjectInfoOrErr>(100);
let (tx, mut rx) = mpsc::channel::<Result<TierRecoveryEntry>>(100);
let cancel = cancel_token.child_token();
let mut draining_after_truncation = false;
let mut drain_deadline = None;
@@ -559,14 +570,7 @@ async fn list_tier_free_versions_for_tier(
match action {
RecoveryWalkTestAction::SendItems(items) => {
for item in items {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
return Ok(());
}
}
@@ -574,35 +578,16 @@ async fn list_tier_free_versions_for_tier(
}
RecoveryWalkTestAction::SendItemsThenError(items, err) => {
for item in items {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
return Ok(());
}
}
let _ = tx
.send(ObjectInfoOrErr {
item: None,
err: Some(err),
})
.await;
let _ = tx.send(Err(err)).await;
return Ok(());
}
RecoveryWalkTestAction::SendItemsThenHang(items, started) => {
for item in items {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
return Ok(());
}
}
@@ -614,14 +599,11 @@ async fn list_tier_free_versions_for_tier(
let mut index = 0usize;
loop {
if tx
.send(ObjectInfoOrErr {
item: Some(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}),
err: None,
})
.send(Ok(TierRecoveryEntry::Version(Box::new(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}))))
.await
.is_err()
{
@@ -639,7 +621,7 @@ async fn list_tier_free_versions_for_tier(
}
}
api.walk(cancel, &bucket_name, "", tx, recovery_walk_options(bucket_walk_limit, object_marker))
api.walk_for_tier_recovery(cancel, &bucket_name, tx, recovery_walk_options(bucket_walk_limit, object_marker))
.await
}
});
@@ -669,21 +651,25 @@ async fn list_tier_free_versions_for_tier(
},
};
page.scanned_entries += 1;
if let Some(err) = item.err {
cancel.cancel();
receive_error = Some(err);
break;
}
let entry = match item {
Ok(entry) => entry,
Err(err) => {
cancel.cancel();
receive_error = Some(err);
break;
}
};
if draining_after_truncation {
continue;
}
let Some(oi) = item.item else {
continue;
let name = match &entry {
TierRecoveryEntry::Version(oi) => oi.name.as_str(),
TierRecoveryEntry::Unreadable { object } => object.as_str(),
};
if last_seen_object.as_deref() != Some(oi.name.as_str()) && scanned_objects >= bucket_walk_limit {
if last_seen_object.as_deref() != Some(name) && scanned_objects >= bucket_walk_limit {
// The disk listing limit follows S3-visible counting rules and
// does not charge metadata containing only hidden/free versions.
// Enforce the repair budget again at the decoded-object boundary.
// Charge the recovery budget by key, including unreadable metadata.
page.truncated = true;
page.next_bucket_marker = Some(bucket.name.clone());
page.next_object_marker = last_seen_object.clone();
@@ -692,9 +678,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, &oi.name);
record_scanned_object(&mut last_seen_object, &mut scanned_objects, name);
if let Some(cursor) = &truncated_after
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != oi.name.as_str())
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != name)
{
page.truncated = true;
cancel.cancel();
@@ -702,6 +688,14 @@ 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(),
@@ -756,6 +750,18 @@ 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)
}
@@ -823,6 +829,7 @@ mod tests {
next_object_marker: None,
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -843,6 +850,7 @@ mod tests {
next_object_marker: Some("object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -863,6 +871,7 @@ 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());
@@ -973,6 +982,7 @@ mod tests {
next_object_marker: None,
scanned_entries: DEFAULT_FREE_VERSION_RECOVERY_SCAN_LIMIT,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
+1 -1
View File
@@ -1405,7 +1405,7 @@ impl BucketMetadata {
/// | public access block | Fails closed in `get_public_access_block_config`: degrading grants the anonymous access the operator asked to block. |
/// | quota | Fails closed in `get_quota_config`; the enforcement path in `quota::checker` already re-parses the raw JSON and refuses on error. |
/// | lifecycle | `get_lifecycle_config` fails closed, so GetBucketLifecycle reports the fault instead of NoSuchLifecycleConfiguration. ILM, scanner and expiry-header consumers still degrade to "no rules": nothing is deleted or moved on the strength of an unreadable rule set, and the bucket keeps serving reads and writes. |
/// | notification | `get_notification_config` fails closed, so GetBucketNotificationConfiguration reports the fault and startup leaves that one bucket's rules unchanged instead of clearing them; other buckets are unaffected. |
/// | notification | `get_notification_config` fails closed, so GetBucketNotificationConfiguration reports the fault and startup skips that bucket's rule registration; metadata-bound server dispatch suppresses external delivery for the unreadable snapshot. Other buckets are unaffected. |
/// | tagging, CORS, logging, website, accelerate, request payment | The getter fails closed so the matching GET API reports the fault instead of "not configured". Per-request consumers (CORS response headers) still degrade to "not configured", which is the restrictive direction. |
/// | bucket ACL | Safe to degrade: it only shapes an optional response. |
///
+382 -18
View File
@@ -2090,6 +2090,74 @@ 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)
}
@@ -2135,6 +2203,20 @@ 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
@@ -2169,6 +2251,11 @@ 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)]
@@ -2253,6 +2340,7 @@ impl BucketMetadataSys {
.await?;
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, persisted, &guard)
.await
.map(|_| ())
}
#[cfg(test)]
@@ -2291,6 +2379,12 @@ 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(|| {
@@ -2550,7 +2644,7 @@ impl BucketMetadataSys {
metadata: BucketMetadata,
persisted: bool,
namespace_guard: &rustfs_lock::NamespaceLockGuard,
) -> Result<()> {
) -> Result<bool> {
self.revoke_pending_bucket_creation(bucket).await;
if !persisted {
let _publish_guard = self
@@ -2563,7 +2657,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(());
return Ok(false);
}
let removed = map.remove(bucket).is_some();
drop(map);
@@ -2574,7 +2668,7 @@ impl BucketMetadataSys {
clear_bucket_overrides(bucket);
clear_on_demand_migration(bucket);
}
return Ok(());
return Ok(true);
}
let _publish_guard = self
.lock_metadata_publish(bucket, namespace_guard, "refreshed bucket metadata publish")
@@ -2587,7 +2681,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(());
return Ok(false);
}
map.insert(bucket.to_string(), Arc::clone(&metadata));
drop(map);
@@ -2596,7 +2690,7 @@ impl BucketMetadataSys {
sync_bucket_target_sys(bucket, &metadata).await;
sync_bucket_overrides(bucket, &metadata);
sync_on_demand_migration(bucket, &metadata);
Ok(())
Ok(true)
}
pub async fn get(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
@@ -2612,6 +2706,10 @@ impl BucketMetadataSys {
}
}
pub(crate) async fn cached_metadata(&self) -> Vec<Arc<BucketMetadata>> {
self.metadata_map.read().await.values().cloned().collect()
}
pub async fn set(&self, bucket: String, bm: Arc<BucketMetadata>) {
self.revoke_pending_bucket_creation(&bucket).await;
bump_local_meta_mutation_gen();
@@ -2876,25 +2974,35 @@ 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));
}
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));
// 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(());
}
}
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
.await
Err(Error::other("bucket metadata changed repeatedly during peer reload"))
}
pub async fn get_config(&self, bucket: &str) -> Result<(Arc<BucketMetadata>, bool)> {
@@ -3471,7 +3579,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 gen_before = current_local_meta_mutation_gen();
let mut gen_before = current_local_meta_mutation_gen();
let cached_authority = can_use_local_authority_cache
.then(|| {
self.local_authority_cache
@@ -3495,6 +3603,43 @@ 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),
@@ -5760,6 +5905,64 @@ mod tests {
assert_eq!(tags.tag_set.len(), WRITERS, "every concurrent rewrite must survive: {tags:?}");
}
#[tokio::test]
async fn notification_snapshots_follow_periodic_refresh_after_lost_peer_signals() {
let (dirs, store) = isolated_store_over_temp_disks().await;
let writer = BucketMetadataSys::new(store.clone());
let peer = Arc::new(RwLock::new(BucketMetadataSys::new(store.clone())));
let bucket = "notification-periodic-snapshots";
for dir in &dirs {
std::fs::create_dir_all(dir.path().join(bucket)).expect("create empty fixture bucket");
}
let mut original = BucketMetadata::new(bucket);
original.notification_config_xml = concat!(
"<NotificationConfiguration><QueueConfiguration><Event>s3:ObjectCreated:Put</Event>",
"<Queue>arn:rustfs:sqs:us-east-1:inert:webhook</Queue></QueueConfiguration></NotificationConfiguration>"
)
.as_bytes()
.to_vec();
original.parse_all_configs().expect("parse inert subscription");
writer
.persist_new_and_set(original)
.await
.expect("persist initial subscription");
peer.read().await.reload_from_store(bucket).await.expect("prime peer cache");
let old = peer.read().await.get(bucket).await.expect("cached original snapshot");
let mut removed = (*old).clone();
removed.notification_config_xml = b"<NotificationConfiguration/>".to_vec();
removed.parse_all_configs().expect("parse removed subscription");
writer
.persist_new_and_set(removed)
.await
.expect("persist removal without peer callback");
assert!(Arc::ptr_eq(&old, &peer.read().await.get(bucket).await.expect("peer remains stale")));
// Exercise the timer's actual one-pass entry point, not the peer RPC.
refresh_buckets_metadata_once(peer.clone()).await;
let snapshots = peer.read().await.cached_metadata().await;
assert_eq!(snapshots.len(), 1);
assert!(!Arc::ptr_eq(&old, &snapshots[0]));
assert_eq!(old.bucket_incarnation_id, snapshots[0].bucket_incarnation_id);
assert_eq!(snapshots[0].notification_config_xml, b"<NotificationConfiguration/>");
assert!(
snapshots[0]
.notification_config
.as_ref()
.expect("parsed removal")
.behavior()
.queue_routes
.is_empty()
);
for dir in &dirs {
std::fs::remove_dir(dir.path().join(bucket)).expect("remove empty fixture bucket without peer callback");
}
refresh_buckets_metadata_once(peer.clone()).await;
assert!(peer.read().await.cached_metadata().await.is_empty());
assert!(peer.read().await.get(bucket).await.is_err());
}
/// Pins the peer reload-notification contract (`reload_from_store`, the
/// LoadBucketMetadata RPC path): only metadata actually read from
/// persisted storage enters the cache. A load miss errors out and leaves
@@ -6919,4 +7122,165 @@ 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");
}
}
@@ -1070,8 +1070,9 @@ mod tests {
.unwrap_or_else(|| panic!("signed request must contain {name}"))
}
fn signing_time(headers: &[(String, String)]) -> chrono::NaiveDateTime {
chrono::NaiveDateTime::parse_from_str(recorded_header(headers, "x-amz-date"), "%Y%m%dT%H%M%SZ")
fn signing_time(headers: &[(String, String)]) -> jiff::Timestamp {
let value = recorded_header(headers, "x-amz-date").trim_end_matches('Z');
jiff::Timestamp::strptime("%Y%m%dT%H%M%S%z", format!("{value}+0000"))
.expect("SDK signing timestamp must use the SigV4 format")
}
@@ -1086,8 +1087,8 @@ mod tests {
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect(),
);
let server_time = chrono::DateTime::<chrono::Utc>::from(self.clock.now()).naive_utc()
+ chrono::Duration::seconds(self.skew_seconds);
let server_time = jiff::Timestamp::try_from(self.clock.now()).expect("clock timestamp")
+ jiff::SignedDuration::from_secs(self.skew_seconds);
let (status, body) = if headers.len() == 1 {
(
403,
@@ -1098,7 +1099,7 @@ mod tests {
};
let response = http::Response::builder()
.status(status)
.header("date", server_time.format("%a, %d %b %Y %H:%M:%S GMT").to_string())
.header("date", server_time.strftime("%a, %d %b %Y %H:%M:%S GMT").to_string())
.header("content-type", "application/xml")
.header("content-length", body.len())
.body(SdkBody::from(body))
@@ -1136,7 +1137,7 @@ mod tests {
for error_code in ["RequestTimeTooSkewed", "SignatureDoesNotMatch"] {
for skew_seconds in [-600, 600] {
let (client, headers, clock) = clock_skew_client(error_code, skew_seconds, REPLICATION_TARGET_RETRY_POLICY).await;
let initial = chrono::DateTime::<chrono::Utc>::from(clock.now()).naive_utc();
let initial = jiff::Timestamp::try_from(clock.now()).expect("clock timestamp");
client
.get_object()
.bucket("bucket")
@@ -1163,12 +1164,12 @@ mod tests {
assert_eq!(signing_time(&headers[0]), initial, "the first attempt must use the injected clock");
assert_eq!(
signing_time(&headers[1]),
initial + chrono::Duration::seconds(skew_seconds),
initial + jiff::SignedDuration::from_secs(skew_seconds),
"{error_code}: retry must apply the measured offset exactly"
);
assert_eq!(
signing_time(&headers[2]),
initial + chrono::Duration::seconds(skew_seconds + 17),
initial + jiff::SignedDuration::from_secs(skew_seconds + 17),
"{error_code}: the next operation must apply cached skew to the advanced signing clock"
);
let signature = |index: usize| {
@@ -13,6 +13,8 @@
// 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,7 +89,11 @@ impl ReplicationLifecycleBridge {
}
}
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
pub(crate) async fn schedule_delete(
bucket: String,
delete_object: DeletedObject,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
#[cfg(test)]
{
SCHEDULED_DELETE_OBJECTS
@@ -98,6 +102,7 @@ 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,6 +22,10 @@ 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,13 +110,16 @@ 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).await;
schedule_replication(object, storage, decision, op_type, notification_bucket_incarnation).await;
}
pub async fn schedule_delete(delete_object: DeletedObjectReplicationInfo) {
@@ -148,8 +151,16 @@ impl ReplicationObjectBridge {
}
}
pub async fn schedule_storage_delete(delete_object: DeletedObject, bucket: String, event_type: String) {
/// 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>,
) {
Self::schedule_delete(DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket,
event_type,
@@ -158,10 +169,18 @@ impl ReplicationObjectBridge {
.await;
}
pub async fn schedule_storage_deletes(delete_objects: Vec<DeletedObject>, bucket: String, event_type: String) {
/// 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>,
) {
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,7 +1016,9 @@ 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);
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type);
// 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);
roi.retry_count = entry.retry_count.max(0) as u32;
roi
}
@@ -3171,12 +3173,13 @@ 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);
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type, notification_bucket_incarnation);
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;
@@ -3185,7 +3188,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);
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type, notification_bucket_incarnation);
let _ = pool.queue_replica_task(ri).await;
}
}
@@ -3194,6 +3197,7 @@ 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());
@@ -3209,6 +3213,7 @@ 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,
@@ -3350,7 +3355,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);
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata, None);
roi.retry_count = retry_count;
if let Some(pool) = runtime_sources::replication_pool() {
pool.queue_replica_task(roi).await
@@ -5205,6 +5210,117 @@ 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");
@@ -5219,7 +5335,7 @@ mod tests {
..Default::default()
};
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object);
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object, None);
assert!(ri.ssec);
assert_eq!(ri.checksum, Some(checksum));
@@ -5235,8 +5351,12 @@ 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);
let live = replicate_object_info_from_object_info(
object.clone(),
test_replicate_decision(&[target]),
ReplicationType::Metadata,
None,
);
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");

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