Compare commits

..

15 Commits

Author SHA1 Message Date
overtrue cb93d21f1e ci(security): gate advisories with time-bounded exception registry
Add .config/advisory-exceptions.toml (schema_version=1) and scripts/security/check_advisories.py to enforce pinned cargo-deny (0.20.2), advisory-db freshness (<=24h verified cache fallback), bidirectional deny.toml alignment, 90-day max UTC validity windows, exact version scope matching, and PR base-diff approval checks.

Wire security-advisories into ci.yml (ALWAYS_JOBS, required-checks, alert-on-failure, PLAN_CONTRACT=10), align daily audit.yml while preserving all four cargo-deny categories, and register --self-test in make script-tests.

Historical RUSTSEC-2023-0071 (transitive rsa 0.9.10 via openidconnect 4.1.0; direct rsa upgraded to patched 0.10.0 in PR #9492) retains its expired 2026-07 review window and intentionally fails closed until maintainer risk acceptance or upstream upgrade lands.

Refs: rustfs/backlog#2668
2026-11-27 06:54:29 +08:00
Peter van Mourik 7d41d22e5f fix(ecstore): skip rebalance re-copy when target holds the version (#9588)
* fix(ecstore): skip rebalance re-copy when target holds the version

A rebalance that stops after an object version is committed on the target pool and before its source copy is removed leaves that version in both pools. The next run uploaded every part of a multipart object again and only found the existing copy when the create-only completion was refused, so a retry cost the whole object.

Look up the pool the copy would be written to before starting the multipart upload, and settle on it when it already holds the strictly equivalent version. Decommission with a capacity owner already does this; callers without one now do too. A lookup that fails or finds no equivalent copy falls through to the unchanged copy path.

* fix(ecstore): require write quorum before skipping the rebalance re-copy

The pre-check settled on the target copy whenever an object read returned the equivalent version. That read answers from read quorum: on a 2+2 set with two drives offline it still returns matching metadata, the entry reported the version as moved, and the source copy was removed while the target held two readable shards. The copy path it replaced needs a write quorum to start, so it kept the source in that state.

Count the drives of the target set that hold the version in the committed data directory, once per drive slot and in one fanout, and settle only when a write quorum of them agree. A copy below that leaves the decision to the unchanged copy path.

Add a rebalance entry test on a 2+2 target: with two target drives offline the source survives and stays readable; with the drives back the entry completes on the committed copy without rewriting it.

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 05:17:59 +08:00
hector 08575786c6 ci: remove schedule-only rio-v2 lanes from CI (#9652)
The rio-v2 test, debug-binary, and e2e jobs in ci.yml ran only on the
nightly schedule and manual dispatch. Drop them, the ci-feat-rio cache
warm job that existed for them, and the merge-gate entries that named
them. The rio-v2 feature and minio-interop workflow stay. Default debug,
e2e, and S3 lanes are unchanged.

Bump the CI plan contract so a base planner that still lists those jobs
cannot authorize the new required set.

Co-authored-by: hector <majinghe@users.noreply.github.com>
Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-27 05:17:00 +08:00
Chris An ac6253cf38 fix(policy,s3select,rpc): harden policy, S3 Select, and RPC auth (#9640)
* fix(policy): scope NotAction Allow to named action families

Confine Allow statements built from NotAction to the action families named in their exclusion list so S3 NotAction policies on wildcard or bucket resources cannot implicitly grant admin, STS, or KMS actions. Fail closed when both Action and NotAction are empty, preserve explicit Deny + NotAction reach across all action families, and preserve explicit admin NotAction coverage for sibling admin actions.

Refs: rustfs/backlog#3321

* fix(policy,utils): eliminate exponential wildcard matching

Replace recursive backtracking in wildcard matching (rustfs-policy and rustfs-utils) with iterative O(name.len())-space dynamic programming that collapses consecutive '*' wildcards and preserves allocation-free fast paths for literal and single-'*' patterns. Also cap versioning ExcludedPrefixes count (100) and byte length (1024) in validate_bucket_versioning_update as defense in depth.

Refs: rustfs/backlog#3318

* fix(policy): prefer parent over raw sub for aws:userid variable

Share a single resolve_userid_values helper between VariableResolver::resolve and resolve_multiple that prefers the issuer-scoped parent claim over raw sub, aligning the ${aws:userid} policy variable with the aws:userid condition key derived in auth facts while retaining sub as a fallback when parent is absent.

Refs: rustfs/backlog#3339

* fix(policy): treat anonymous-matching principals as public

Add Principal::is_public() matching either '*' or the empty anonymous account '' through the same wildcard matcher used during request authorization, and switch execute_put_bucket_policy and execute_get_bucket_policy_status to use it so empty and leading-'?' principals cannot bypass BlockPublicPolicy or evade public status classification.

Refs: rustfs/backlog#3357

* fix(s3select): restrict SQL functions to an explicit allowlist

Replace unfiltered DataFusion default scalar, aggregate, and window UDF registration in SimpleFunctionMetadataManager with an explicit S3 Select allowlist, register allowlisted scalar aliases directly, and remove the session scalar-function fallback from MetadataProvider::get_function_meta.

Wrap retained expanding scalar functions (concat, concat_ws, to_char) and any manually registered count-sized functions (repeat, lpad, rpad) with a pre-allocation result-size guard that also re-wraps scalar UDFs produced during expression simplification.

Refs: rustfs/backlog#3317

* fix(s3select): bound SQL operator and nesting depth at parse

Add BoundedRustFsDialect enforcing a per-parse infix/postfix operator budget (MAX_SELECT_OPERATORS) via Dialect::parse_infix returning ParserError::RecursionLimitExceeded, and wire it into both ExtParser::parse_sql and legacy_json_source_from_input.

Also bound set-operation keyword counts before parsing (preventing deeply nested SetExpr chains from overflowing on drop) and bound nested field-access chains during statement preparation.

Refs: rustfs/backlog#3319

* fix(s3select): bound uncompressed record sizes and decoding

Apply RecordSizeTracker (MAX_SELECT_RECORD_BYTES) across uncompressed plain, ScanRange, and ScanRange header reads in EcObjectStore, recognizing CR, LF, and CRLF line endings for default CSV inputs without a custom RecordDelimiter.

Bound session batch sizes and disable batch coalescing for CSV and JSON Lines, replace DataFusion's unbounded stock listing table scan with a byte-bounded, memory-pool-accounted DelimitedSelectTable, keep multi-record JSON Lines schema sampling within the session memory pool budget, and add a StreamFilterOutput physical optimizer rule so FilterExec streams filtered batches without re-coalescing.

Refs: rustfs/backlog#3348

* fix(rpc): gate gRPC boot-epoch proofs on verified signatures

Stop computing and attaching secret-keyed boot-epoch, replay-cache, and msgpack capability response proofs before gRPC authentication runs in RpcRequestPathService::call.

Gate proof generation on an RpcSignatureVerified request marker raised by check_auth only after the internode HMAC signature has verified, including post-HMAC rejections (stale boot epoch, replay-scope retries, replay detection, and replay-cache/background admission resource exhaustion) required for cluster recovery.

Verify the method-bound v2 HMAC signature before returning replay_scope_required in verify_tonic_rpc_signature_with_policy so unsigned, legacy-only, or forged callers never trigger a post-HMAC rejection reason or consume replay-cache capacity.

Refs: rustfs/backlog#3326

* fix(keystone): namespace parent_user by Keystone user ID

Set Credentials.parent_user in KeystoneAuthProvider::keystone_token_to_credentials to the namespaced Keystone identity (keystone:<user_id>, matching access_key) instead of the bare Keystone username.

This prevents an external Keystone username from colliding with a local IAM user or the root access key in service-account ownership checks and the is-admin handler while keeping the username available in Credentials.name and claims["keystone_username"].

Update the keystone unit tests and HTTP/3 external stack test expectations, and add regression coverage verifying colliding usernames are never placed in parent_user.

Refs: rustfs/backlog#3362

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-27 05:16:41 +08:00
Hauser Zhi 5d8974ea40 fix(ecstore): bound PUT waits on a departing peer (#9642)
* fix(ecstore): stop bucket presence checks at read quorum

A metadata-only bucket probe can finish after the existing read quorum has confirmed the volume. Preserve full error reduction when quorum has not been reached and keep ordered bucket info and mutation callers on their existing path.

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

* perf(ecstore): bound PUT rename dialing after write quorum

Share a post-quorum connection deadline across remote rename producers. Unresolved connections can be skipped before dispatch while active mutations drain under the normal namespace owner.

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

* perf(ecstore): simplify quorum probes and rename fanout

Keep presence-only probes typed as unit results and share their cross-set error reduction with bucket-info queries. Reuse one path owner across disk rename tasks and allocate a connect deadline only when there is a spare.

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

* perf(ecstore): bound PUT rename preparation after quorum

Apply a single pre-dispatch deadline to remote routing and permit admission. Encode the request once those resources are available and keep existing ownership for dispatched mutations.

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

* test: fix SSE-C lint and native multipart copy-heal setup

Count warning matches directly and bind native multipart staging to the real bucket incarnation while preserving the historical version fixture.

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

* test(ecstore): qualify retention fixture metadata type

The default test build includes this fixture without the test-util imports.

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

* test(scanner): seed checkpoint owner metadata directly

Keep the production object threshold and physical checkpoint barriers while avoiding a full PUT for every fixture entry.

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

* fix(ecstore): serialize Windows trash cleanup per entry

Keep the per-path lease in the physical deletion worker and compile Unix-only test helpers only on their supported platforms.

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: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 03:56:43 +08:00
Hauser Zhi 594488a650 fix(sosapi): distinguish pending and invalid usage proof (#9655)
* fix(sosapi): distinguish pending and invalid usage proof

Expose neutral bucket usage states from the existing snapshot cache. Maintain the legacy scalar projection and map only pending certification to undefined SOSAPI usage.

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

* ci(test): isolate three disk-bound ECStore probes

Reserve nextest capacity for the physical Apply barrier and the two same-name multipart probes in the CI profile. Preserve their deadlines, assertions, and internal concurrency.

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: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 03:15:34 +08:00
Hauser Zhi 0ef63577e8 fix(s3): correct Object Lock read responses (#9654)
* fix(s3): correct Object Lock read responses

Classify missing bucket, key, version, and lock metadata through the shared Object Lock read path. Reuse bucket metadata authority to avoid a duplicate namespace probe on Legal Hold reads.

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

* test(ecstore): drain fixture writes before cache publication

Wait for the fixture PUT rename fanout before exercising the cache generation fence. Report a read that ends before the publication barrier immediately.

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: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 01:29:57 +08:00
Hauser Zhi 2e9e206d02 fix(ecstore): reject startup without a local endpoint (#9638)
* fix(ecstore): reject startup without a local endpoint

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* perf(ecstore): resolve startup DNS once per host

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(ecstore): reject zero-port storage endpoints

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(ecstore): bound startup DNS by the topology deadline

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(server): exit promptly after a startup DNS timeout

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* perf(ecstore): skip unused endpoint identity scans

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* fix(log-analyzer): track startup DNS failures

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

* test(ecstore): preserve fresh copy-heal upload initiation

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
Signed-off-by: Hauser Zhi <housemecn@gmail.com>

---------

Signed-off-by: Hauser Zhi <housemecn@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: Chris An <anzhengchao@gmail.com>
2026-11-27 01:18:31 +08:00
Hauser Zhi 4eb6f3d624 perf(obs): export stage peaks with less summary contention (#9658)
Track the maximum of each sampled stage window. Keep the existing
summary API and row format while exposing the maxima separately.
Unlock before sorting and format stage rows into shared buffers.

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-11-27 00:37:22 +08:00
Hauser Zhi 9f536da60d fix(ecstore): preserve grouped directory fsync admission (#9657)
Keep each writer's disk permit with the physical directory sync
and acquire one global permit per admitted batch. Route non-inline
grouped commits through the same admission and rollback path.

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:16 +08:00
Hauser Zhi a66c7c986f fix(s3): skip redundant reads for plain bulk deletes (#9649)
* fix(s3): skip redundant reads for plain bulk deletes

Plain unversioned DeleteObjects entries use source metadata read under the storage write lock. Skip the advisory read that duplicates lock acquisition per request entry, preserve condition and version boundaries, and exercise 16 duplicate DELETE entries while a writer holds the key.

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

* test(s3): use the storage facade for the delete barrier

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

* fix(s3): skip redundant bulk preflight for suspended versions

Apply the same locked-source path to unconditioned, versionless entries in suspended buckets. Verify that duplicate requests reach storage while a writer owns the object and that the suspended delete publishes its marker.

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

* fix(test): import the delete barrier through the public API

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: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:11 +08:00
Hauser Zhi dbb9ca60fc fix(perf): validate steady Warp rates and tail latency (#9637)
* fix(perf): validate steady Warp rates and tail latency

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

* test(server): count plaintext SSE-C warnings directly

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: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:05 +08:00
Hauser Zhi 873f728e55 fix(ecstore): size workers and batch deletes by available CPUs (#9636)
* fix(ecstore): size workers and batch deletes by available CPUs

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

* perf(ecstore): route delete markers only when needed

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: qunjiazhu <qunjiazhu@gmail.com>
Co-authored-by: Chris An <anzhengchao@gmail.com>
2026-11-27 00:37:00 +08:00
Hauser Zhi 94f8ec5706 perf(ecstore): diagnose PUT snapshots and trim bucket stat allocations (#9644)
* feat(obs): split single PUT Object Lock snapshot timings

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

* perf(ecstore): borrow bucket names during stat fanout

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

* fix(ci): restore SSE-C lint and storage regression coverage

Require quorum evidence before treating missing multipart part directories as empty. Keep historical object times separate from upload initiation and align the IAM, quota, namespace lock, and retention fixtures with their current contracts.

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

* test(e2e): expect tagging authorization on tagged writes

Backport the OPA contract assertions from 961b0c79c8 and their formatting from c269a1233d.

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: qunjiazhu <qunjiazhu@gmail.com>
2026-11-27 00:34:52 +08:00
Hauser Zhi 9a65ac95f7 fix(ecstore): bound compressed GetObject range reads (#9639)
* fix(ecstore): bound compressed GetObject range reads

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

* chore(ci): tighten compressed reader error ratchet

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

* perf(ecstore): stream object ranges directly to callers

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

* perf(ecstore): decode compression indexes without reframing

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

* perf(rio): reuse verified plaintext block buffers

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

* test(server): count SSE-C warnings without collecting

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

* test(admin): distinguish explicit and implicit IAM denials

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: qunjiazhu <qunjiazhu@gmail.com>
2026-11-27 00:34:45 +08:00
118 changed files with 10199 additions and 2894 deletions
+62
View File
@@ -0,0 +1,62 @@
# Machine-enforced RustSec advisory exception registry.
#
# Validated by `scripts/security/check_advisories.py` in both `ci.yml`
# (`security-advisories`, required via `Test and Lint`) and daily `audit.yml`.
#
# Rules (rustfs/backlog#2668):
# - Every `[advisories].ignore` entry in `deny.toml` must match an entry here
# bidirectionally; comment-only or untracked ignores fail closed.
# - Timestamps use strict UTC RFC 3339 (`YYYY-MM-DDTHH:MM:SSZ`).
# - Maximum validity window is 90 days (`expires_at - approved_at <= 90d`).
# - Expired exceptions fail closed; renewals require explicit maintainer review
# and cannot be auto-extended or self-approved in a PR.
schema_version = 1
[[exceptions]]
advisory_id = "RUSTSEC-2023-0071"
crate = "rsa"
affected_versions = "=0.9.10"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "Transitive rsa 0.9.10 pulled exclusively via openidconnect 4.1.0 <- rustfs-iam; direct workspace rsa consumers already upgraded to patched rsa 0.10.0 in PR #9492. Historical 2026-07 review window has expired and requires maintainer risk-acceptance sign-off or upstream openidconnect upgrade to rsa >=0.10.0 before promotion."
mitigation = "crates/iam/src/oidc uses openidconnect only for public-key JWS ID-token verification and rejects signed or encrypted UserInfo responses (crates/iam/src/oidc/runtime.rs), exposing no remote RSA private-key decryption oracle on rsa 0.9.10. Track upstream openidconnect migration off rsa 0.9.x."
approved_at = "2026-05-06T07:47:19Z"
expires_at = "2026-07-31T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/2769"
[[exceptions]]
advisory_id = "RUSTSEC-2026-0543"
crate = "chrono"
affected_versions = "=0.4.45"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "chrono is marked unmaintained with no patched release; retained temporarily at compatibility boundaries and transitive datafusion/arrow/openidconnect dependencies during the jiff 1.0 migration reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no CVE or memory-safety vulnerability; core server timestamp paths already migrated to jiff 1.0 in PR #9492 while remaining compatibility boundaries and upstream crates transition off chrono."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
[[exceptions]]
advisory_id = "RUSTSEC-2026-0555"
crate = "chrono-tz"
affected_versions = "=0.10.4"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "chrono-tz is marked unmaintained with no patched release; pulled transitively by arrow-array 59.3.3 and datafusion-functions 55.3.0 during the jiff migration reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no known security vulnerability; confined to transitive DataFusion/Arrow SQL timezone handling until upstream removes chrono-tz."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
[[exceptions]]
advisory_id = "RUSTSEC-2026-0542"
crate = "humantime"
affected_versions = "=2.4.0"
owner = "rustfs-maintainers"
tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
reason = "humantime is marked unmaintained through chrono with no patched release; used by rustfs-madmin and transitively by object_store 0.13.2 / datafusion 55.3.0 as temporarily reviewed in PR #9492."
mitigation = "Informational unmaintained advisory with no known security vulnerability; limited to duration formatting and tracked for removal alongside the remaining chrono/jiff migration."
approved_at = "2026-11-18T12:17:44Z"
expires_at = "2026-11-30T23:59:59Z"
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
+2
View File
@@ -43,6 +43,7 @@ script-tests: ## Run shell script tests
$(RUSTFS_PYTHON_BIN) ./scripts/test_internode_msgpack_peer_canary.py
./scripts/test_internode_msgpack_peer_canary_runner.sh
./scripts/test_object_batch_bench_enhanced.sh
$(RUSTFS_PYTHON_BIN) ./scripts/test_warp_raw_quality.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_inline_docker_lab.py
./scripts/test_package_service_scripts.sh
./scripts/test_hotpath_warp_ab_gate.sh
@@ -92,6 +93,7 @@ script-tests: ## Run shell script tests
$(RUSTFS_PYTHON_BIN) ./scripts/test_ci_merge_queue.py
$(RUSTFS_PYTHON_BIN) -m unittest discover -s scripts/ci -p 'test_*.py'
$(RUSTFS_PYTHON_BIN) ./scripts/check_security_coverage.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/security/check_advisories.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/check_scheduled_validation_freshness.py --self-test
$(RUSTFS_PYTHON_BIN) ./scripts/test_security_workflow.py
$(RUSTFS_PYTHON_BIN) ./scripts/test_nightly_candidate.py
+12
View File
@@ -416,6 +416,18 @@ threads-required = "num-test-threads"
filter = 'package(rustfs-ecstore) & test(/^store::object::tests::(canceled_create_retains_usage_cleanup_namespace_owner|batch_delete_excludes_recovery_on_nonzero_pool|delete_excludes_recovery_with_(disjoint|identical|overlapping)_pool_lock_clients)$/)'
threads-required = "num-test-threads"
# Isolate the physical Apply barrier and same-name multipart lock probes from
# competing disk fixtures. Keep their deadlines and internal concurrency.
[[profile.ci.overrides]]
filter = """
package(rustfs-ecstore) & (
test(=core::pools::native_recovery::integration_tests::pool_meta_native_physical_runtime_fork_after_apply_latches_original_gate)
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_key_writes_succeed_on_unversioned_versioned_and_hard_quota_buckets)
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_object_write_lock_does_not_block_other_keys_on_versioned_bucket)
)
"""
threads-required = "num-test-threads"
# These eight-disk decommission fixtures exercise concurrent retries,
# free-version cleanup, and real capacity probes under production lock deadlines.
# Reserve the run's capacity so unrelated IO cannot exhaust those budgets.
-21
View File
@@ -1301,27 +1301,6 @@
"origin": "baseline",
"alert_contract": "independent"
},
{
"workflow": ".github/workflows/package-deb-rpm.yml",
"name": "Package DEB/RPM",
"roles": [
"release"
],
"events": [
"workflow_run",
"workflow_dispatch"
],
"cadence": "event",
"timezone": "UTC",
"schedule": [],
"owner": "@overtrue",
"policy": "active",
"monitor": "none",
"result_owner": "package-deb-rpm.yml",
"disposition": "After a successful tag push of Build and Release, wrap the published Linux zips as deb and rpm assets and refresh SHA256SUMS and SHA512SUMS. Dispatch with a tag backfills an existing release. manual-main-packages.yml still only uploads workflow artifacts.",
"monitor_reason": "Event-driven release packaging has no periodic freshness obligation.",
"origin": "package-deb-rpm"
},
{
"workflow": ".github/workflows/package.yml",
"name": "Build candidate packages",
+2 -2
View File
@@ -43,7 +43,7 @@ A hosted runner is also the only choice for a few things the pods cannot do: `mo
`Swatinem/rust-cache` builds its key from the OS, architecture, toolchain and lockfile. It does not include the runner label or image, so a cache written on an `sm-standard-4` pod and one written on `ubuntu-latest` would overwrite each other under the same `shared-key`.
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-rio`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
- The `ci-dev` key ends in a digest of `warm-ci-dev`'s build commands. Changing what that job warms therefore needs a new key, or readers keep restoring the old artifacts: `scripts/ci_gate.py --check-workflow` prints the key the commands require and fails until the writer and every reader in `ci.yml` and `reference-parity.yml` name it.
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted`, `e2e-upgrade-server-hosted`, `e2e-upgrade-tests-hosted`).
- Moving a job between pools therefore means renaming its key. The new key is empty until a run from `main` (a scheduled run, or a manual dispatch of that workflow from `main`) saves it; until then that lane does a cold build. The `build.yml` aarch64 release legs append `-ubicloud-arm` for this reason. `cache-warm.yml` does not write those keys.
@@ -81,6 +81,6 @@ Rows using `macos-latest-xlarge` or a label starting with `sm-`, `dind-`, `ubicl
## Release stages
The [candidate release pipeline](../../docs/operations/release-pipeline.md) builds Linux first and defers paid desktop capacity until acceptance. The daily `build.yml` schedule selects Linux; the Sunday 16:17 UTC schedule selects macOS and Windows. Manual dispatch can still select any platform list. All six platforms remain required before publication. The pipeline records and promotes the exact tested bytes. Reusable builder workflows have no public-release credentials. `package-deb-rpm.yml` is the default-branch listener that attaches deb and rpm assets after a legacy tag-triggered Build and Release run; it does not compile the server. Keep periodic development builds, PR verification and field-test chains separate when their contracts differ; do not re-enable disabled workflows as part of a source-file migration.
The [candidate release pipeline](../../docs/operations/release-pipeline.md) builds Linux first and defers paid desktop capacity until acceptance. The daily `build.yml` schedule selects Linux; the Sunday 16:17 UTC schedule selects macOS and Windows. Manual dispatch can still select any platform list. All six platforms remain required before publication. The pipeline records and promotes the exact tested bytes. Builder workflows have no public-release credentials. Keep periodic development builds, PR verification and field-test chains separate when their contracts differ; do not re-enable disabled workflows as part of a source-file migration.
Larger runners remain billed for public repositories; see [GitHub runner billing](https://docs.github.com/en/actions/concepts/runners/larger-runners#billing). Actual spending comes from organization billing, not runner labels or an estimated build duration.
+33 -2
View File
@@ -21,6 +21,9 @@ on:
- '**/Cargo.toml'
- '**/Cargo.lock'
- 'deny.toml'
- '.config/advisory-exceptions.toml'
- 'scripts/security/check_advisories.py'
- 'scripts/security/test_check_advisories.py'
- '.github/actions/**'
- '.github/workflows/**'
- 'scripts/release/**'
@@ -46,6 +49,9 @@ on:
- '**/Cargo.toml'
- '**/Cargo.lock'
- 'deny.toml'
- '.config/advisory-exceptions.toml'
- 'scripts/security/check_advisories.py'
- 'scripts/security/test_check_advisories.py'
- '.github/actions/**'
- '.github/workflows/**'
- 'scripts/release/**'
@@ -107,6 +113,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
fetch-depth: 2
persist-credentials: false
# cargo-deny compiles nothing, so the full setup composite (apt packages,
@@ -134,12 +141,36 @@ jobs:
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Install cargo-deny
id: install-cargo-deny
uses: taiki-e/install-action@7623a79cdfecb99d681017af368ca353d9f49bb5 # v2
with:
tool: cargo-deny
tool: cargo-deny@0.20.2
- name: Run cargo-deny
run: cargo deny check --hide-inclusion-graph advisories sources bans licenses
run: cargo deny --locked check --hide-inclusion-graph advisories sources bans licenses
- name: Enforce time-bounded advisory exception registry
if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'"
env:
GH_TOKEN: ${{ github.token }}
CI_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
if [[ -n "$CI_BASE_SHA" ]]; then
git cat-file -e "${CI_BASE_SHA}^{commit}" 2>/dev/null || git fetch --no-tags --depth=1 origin "$CI_BASE_SHA"
fi
mkdir -p artifacts/advisories
python3 scripts/security/check_advisories.py \
--output artifacts/advisories/advisories-gate.json \
--raw-log artifacts/advisories/cargo-deny.log
- name: Upload advisory audit evidence
if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'"
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: audit-advisories-${{ github.run_number }}-${{ github.run_attempt }}
path: artifacts/advisories
if-no-files-found: error
retention-days: 7
workflow-pin-report:
name: Workflow Pin Report
-37
View File
@@ -197,43 +197,6 @@ jobs:
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# Readers: test-and-lint-rio-v2 (nightly schedule, merge group, dispatch),
# build-rustfs-debug-binary-rio-v2 (nightly schedule / manual dispatch only —
# dormant rio-v2 variant, see rustfs/backlog#1835 and
# docs/architecture/minio-file-format-compat.md).
# The second build below stays despite the reduced cadence: it warms the
# rio-v2,e2e-test-hooks feature resolution the scheduled build restores,
# which keeps that lane inside its 30-minute timeout.
warm-ci-feat-rio:
name: Warm ci-feat-rio
runs-on: sm-standard-4
timeout-minutes: 120
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Setup Rust environment
id: setup
uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-rio
cache-save-if: 'true'
install-build-packaging-tools: 'false'
- name: Build ci-feat-rio superset
if: steps.setup.outputs.cache-hit != 'true'
env:
# --all-targets links the same test binaries as the reader lane.
CARGO_BUILD_JOBS: "2"
run: |
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
# sequence rather than as `--features swift,sftp`, which is a combination no
# lane actually compiles; running both leaves the union in target/.
+58 -172
View File
@@ -113,7 +113,7 @@ jobs:
printf '%s\n' 'mode=full' >> "$GITHUB_OUTPUT"
echo "Base CI policy unavailable; running the full matrix."
fi
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=8$' "$GITHUB_OUTPUT"; then
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=10$' "$GITHUB_OUTPUT"; then
printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT"
echo "Base policy does not cover this workflow contract; retaining the full matrix."
fi
@@ -168,6 +168,60 @@ jobs:
- name: Run shared quick checks
uses: ./.github/actions/quick-checks
# Required dependency advisory and time-bounded exception gate (rustfs/backlog#2668).
# Runs on every non-closed event, including documentation-only PRs, because a
# RustSec advisory can be published or an exception can expire without lockfile edits.
security-advisories:
name: Security Advisories
if: github.event_name != 'pull_request' || github.event.action != 'closed'
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
fetch-depth: 2
persist-credentials: false
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- name: Setup Rust cache
uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
cache-all-crates: false
cache-on-failure: true
shared-key: rustfs-cargo-deny
save-if: 'false'
- name: Install cargo-deny
id: install-cargo-deny
uses: taiki-e/install-action@7623a79cdfecb99d681017af368ca353d9f49bb5 # v2
with:
tool: cargo-deny@0.20.2
- name: Run security advisories gate
env:
GH_TOKEN: ${{ github.token }}
CI_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
run: |
if [[ -n "$CI_BASE_SHA" ]]; then
git cat-file -e "${CI_BASE_SHA}^{commit}" 2>/dev/null || git fetch --no-tags --depth=1 origin "$CI_BASE_SHA"
fi
mkdir -p artifacts/advisories
python3 scripts/security/check_advisories.py \
--output artifacts/advisories/advisories-gate.json \
--raw-log artifacts/advisories/cargo-deny.log
- name: Upload security advisories evidence
if: "!cancelled() && steps.install-cargo-deny.outcome == 'success'"
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: security-advisories-${{ github.run_number }}-${{ github.run_attempt }}
path: artifacts/advisories
if-no-files-found: error
retention-days: 7
# Clippy runs beside the test-binary build instead of in front of it. The two
# share no compiler output: Clippy writes check-mode metadata, the archive
# needs codegen and linked test binaries, and both restore the third-party
@@ -531,73 +585,9 @@ jobs:
done
cargo clippy --locked -p rustfs --lib "${args[@]}" -- -D warnings
test-and-lint-rio-v2:
name: Test and Lint (rio-v2)
# Specialized boundary, hardware and alternate-feature lanes run only on
# the nightly schedule and manual dispatch. They do not gate a merge: the
# nightly run reports a regression within a day, and repeating these builds
# on every PR revision and merge group bought no earlier signal worth the
# runner occupancy. Workspace lint and tests, the core contract, the debug
# build, E2E smoke and the S3 lanes remain the pull-request gate.
if: needs.classify-changes.outputs.mode == 'full' && contains(fromJSON('["schedule", "workflow_dispatch"]'), github.event_name)
needs: [ quick-checks, classify-changes ]
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-feat-rio
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Protect Connect test home
run: chmod go-w "$(realpath "$HOME")"
- name: Run rio-v2 clippy lints
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
env:
# Match the main nextest lane's #5394 link-I/O guard. A cold feature
# cache otherwise fans out enough rust-lld processes to exhaust this
# job's 90-minute budget before any test starts.
CARGO_BUILD_JOBS: "2"
run: |
# --profile ci so the quarantine list (and its junit flaky markers)
# covers this leg too; the default profile is the local no-retry
# profile and silently ignored quarantined flakes here (rustfs#6703).
mkdir -p artifacts/workspace
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 -p rustfs-sse --features rio-v2 \
2>&1 | tee artifacts/workspace/nextest.log
cargo test -p rustfs --doc --features rio-v2
- name: Upload rio-v2 test reports and diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: junit-test-and-lint-rio-v2-${{ github.run_number }}-${{ github.run_attempt }}
path: |
target/nextest/ci/junit.xml
artifacts/workspace
retention-days: 3
if-no-files-found: error
test-and-lint-protocols:
name: "Test and Lint (${{ matrix.features.name }})"
# Same cadence as test-and-lint-rio-v2 above.
# Nightly schedule and manual dispatch only. This lane does not gate a merge.
if: needs.classify-changes.outputs.mode == 'full' && contains(fromJSON('["schedule", "workflow_dispatch"]'), github.event_name)
needs: [ quick-checks, classify-changes ]
runs-on: sm-standard-4
@@ -774,47 +764,6 @@ jobs:
if-no-files-found: error
retention-days: 1
build-rustfs-debug-binary-rio-v2:
name: Build RustFS Debug Binary (rio-v2)
# Dormant rio-v2 variant (rustfs/backlog#1835): the feature ships in no
# default build, so this full-suite lane runs only on the nightly schedule
# and manual dispatch. Per-PR cfg-seam coverage stays with
# test-and-lint-rio-v2. Lifecycle and the promote-or-delete condition:
# docs/architecture/minio-file-format-compat.md ("rio-v2 variant lifecycle").
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
needs: [ quick-checks ]
runs-on: sm-standard-4
timeout-minutes: 30
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-feat-rio
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Build debug binary with rio-v2
run: python3 scripts/e2e_binary.py build --bins --features rio-v2,e2e-test-hooks
- name: Upload debug binary
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-debug-binary-rio-v2
overwrite: true
path: |
target/debug/rustfs
target/debug/rustfs.e2e.json
if-no-files-found: error
retention-days: 1
uring-integration:
name: io_uring Integration (real)
# The pull_request trigger includes `closed` purely so the concurrency
@@ -1252,65 +1201,6 @@ jobs:
if-no-files-found: warn
retention-days: 7
e2e-tests-rio-v2:
name: End-to-End Tests (rio-v2)
# Inherits the schedule/dispatch-only gate through needs: on every other
# event build-rustfs-debug-binary-rio-v2 is skipped, so this job skips
# with it (see the dormant-variant comment on that job).
needs: [ build-rustfs-debug-binary-rio-v2 ]
runs-on: sm-standard-2
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Clean up previous test run
run: |
rm -rf /tmp/rustfs
rm -f /tmp/rustfs.log
- name: Download debug binary
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: rustfs-debug-binary-rio-v2
path: target/debug
- name: Make binary executable
run: chmod +x ./target/debug/rustfs
- name: Setup Rust toolchain for s3s-e2e installation
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
# The sm-standard-* custom runner images (introduced in #4884) ship no C
# toolchain, unlike GitHub-hosted ubuntu-latest. Installing s3s-e2e below
# compiles it from source on a cache miss, and build scripts need cc.
- name: Install build tools for s3s-e2e compilation
run: |
sudo apt-get update
sudo apt-get install -y build-essential cmake pkg-config libssl-dev
- name: Install s3s-e2e test tool
uses: taiki-e/cache-cargo-install-action@7447f04c51f2ba27ca35e7f1e28fab848c5b3ba7 # v2
with:
tool: s3s-e2e
git: https://github.com/s3s-project/s3s.git
rev: 62cb4a71dd759a6ec56b64c4c42fcc183a2c6a52
- name: Run end-to-end tests
run: |
s3s-e2e --version
python3 scripts/e2e_binary.py run --features rio-v2,e2e-test-hooks -- ./scripts/e2e-run.sh ./target/debug/rustfs /tmp/rustfs
- name: Upload test logs
if: failure()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: e2e-test-logs-rio-v2-${{ github.run_number }}-${{ github.run_attempt }}
path: /tmp/rustfs.log
retention-days: 3
s3-implemented-tests:
name: S3 Implemented Tests
needs: [ build-rustfs-debug-binary ]
@@ -1434,21 +1324,19 @@ jobs:
- classify-changes
- typos
- quick-checks
- security-advisories
- workspace-clippy
- workspace-lint-and-build
- workspace-tests
- core-contract
- connect-feature-boundaries
- fips-provider
- test-and-lint-rio-v2
- test-and-lint-protocols
- build-rustfs-debug-binary
- uring-integration
- e2e-tests
- s3-implemented-tests
- s3-lifecycle-behavior-tests
- build-rustfs-debug-binary-rio-v2
- e2e-tests-rio-v2
- e2e-full
runs-on: ubuntu-latest
timeout-minutes: 10
@@ -1471,18 +1359,16 @@ jobs:
- required-checks
- typos
- quick-checks
- security-advisories
- workspace-clippy
- workspace-lint-and-build
- workspace-tests
- core-contract
- test-and-lint-rio-v2
- test-and-lint-protocols
- build-rustfs-debug-binary
- build-rustfs-debug-binary-rio-v2
- uring-integration
- e2e-tests
- e2e-full
- e2e-tests-rio-v2
- s3-implemented-tests
- s3-lifecycle-behavior-tests
if: >-
-380
View File
@@ -1,380 +0,0 @@
# Copyright 2026 RustFS Team
# SPDX-License-Identifier: Apache-2.0
# Attach the eight Linux deb/rpm packages to a tag release built by
# Build and Release. GitHub reads workflow_run only from the default
# branch, so this file has to live on main even when the tag workflow
# itself runs from a release branch. It wraps that build's Linux zip
# artifact with build_deb.sh and build_rpm.sh after the zip matches
# the release SHA256SUMS. It does not compile RustFS and it does not
# replace an existing package asset.
#
# Dispatch with the tag to backfill a release while the build artifacts
# still exist. That upload is a live release write; run it from main
# only after this workflow is merged.
name: Package DEB/RPM
on:
workflow_run:
workflows: ["Build and Release"]
types: [completed]
workflow_dispatch:
inputs:
tag:
description: "Release tag to package, such as 1.0.7. No leading v."
required: true
type: string
build_run_id:
description: "Successful Build and Release run ID for that tag. Leave empty to select the newest successful run."
required: false
type: string
default: ""
permissions:
contents: write
actions: read
concurrency:
group: package-deb-rpm-${{ github.event.workflow_run.head_branch || github.event.inputs.tag || github.run_id }}
cancel-in-progress: false
jobs:
resolve:
name: Resolve release build
if: >-
github.repository == 'rustfs/rustfs' &&
(github.event_name == 'workflow_dispatch' ||
(github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_branch != 'main'))
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
version: ${{ steps.resolve.outputs.version }}
build_type: ${{ steps.resolve.outputs.build_type }}
build_run_id: ${{ steps.resolve.outputs.build_run_id }}
tag: ${{ steps.resolve.outputs.tag }}
steps:
- name: Resolve build run
id: resolve
shell: bash
env:
GH_TOKEN: ${{ github.token }}
EVENT_NAME: ${{ github.event_name }}
REPOSITORY: ${{ github.repository }}
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
WORKFLOW_RUN_ID: ${{ github.event.workflow_run.id }}
INPUT_TAG: ${{ github.event.inputs.tag }}
INPUT_RUN_ID: ${{ github.event.inputs.build_run_id }}
run: |
set -euo pipefail
fail() {
printf '%s\n' "$1" >&2
exit 1
}
tag=""
build_run_id=""
case "$EVENT_NAME" in
workflow_run)
tag="${HEAD_BRANCH}"
build_run_id="${WORKFLOW_RUN_ID}"
;;
workflow_dispatch)
tag="${INPUT_TAG}"
build_run_id="${INPUT_RUN_ID}"
;;
*) fail "unsupported event: ${EVENT_NAME}" ;;
esac
semver_core='(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)'
prerelease_id='(alpha|beta|rc)\.(0|[1-9][0-9]*)'
if [[ "$tag" =~ ^${semver_core}(-${prerelease_id})?-preview\.(0|[1-9][0-9]*)$ ]]; then
build_type=preview
elif [[ "$tag" =~ ^${semver_core}-${prerelease_id}$ ]]; then
build_type=prerelease
elif [[ "$tag" =~ ^${semver_core}$ ]]; then
build_type=release
else
fail "tag is not a supported strict package version"
fi
if [[ -n "$build_run_id" ]]; then
[[ "$build_run_id" =~ ^[1-9][0-9]*$ ]] || fail "build run ID must be a positive decimal integer"
else
build_run_id=$(gh api --method GET \
"repos/${REPOSITORY}/actions/workflows/build.yml/runs" \
-f branch="$tag" -f status=success -F per_page=1 \
--jq '.workflow_runs[0].id // empty')
[[ "$build_run_id" =~ ^[1-9][0-9]*$ ]] || fail "no successful build run found for tag"
fi
run_json=$(gh api "repos/${REPOSITORY}/actions/runs/${build_run_id}")
run_id=$(jq -r '.id // empty' <<<"$run_json")
run_status=$(jq -r '.status // empty' <<<"$run_json")
run_conclusion=$(jq -r '.conclusion // empty' <<<"$run_json")
run_event=$(jq -r '.event // empty' <<<"$run_json")
run_path=$(jq -r '.path // empty' <<<"$run_json")
head_sha=$(jq -r '.head_sha // empty' <<<"$run_json")
run_head_branch=$(jq -r '.head_branch // empty' <<<"$run_json")
[[ "$run_id" == "$build_run_id" ]] || fail "run metadata ID mismatch"
[[ "$run_status" == completed && "$run_conclusion" == success ]] || fail "selected build run is not successful"
[[ "$run_event" == push ]] || fail "selected build run is not a tag push"
[[ "$run_path" == .github/workflows/build.yml ]] || fail "selected run is not Build and Release"
[[ "$head_sha" =~ ^[0-9a-f]{40}$ ]] || fail "selected build run has an invalid head SHA"
[[ "$run_head_branch" == "$tag" ]] || fail "tag and build run head branch do not match"
tag_json=$(gh api "repos/${REPOSITORY}/git/ref/tags/${tag}")
tag_type=$(jq -r '.object.type // empty' <<<"$tag_json")
tag_sha=$(jq -r '.object.sha // empty' <<<"$tag_json")
depth=0
while [[ "$tag_type" == tag && "$depth" -lt 5 ]]; do
tag_json=$(gh api "repos/${REPOSITORY}/git/tags/${tag_sha}")
tag_type=$(jq -r '.object.type // empty' <<<"$tag_json")
tag_sha=$(jq -r '.object.sha // empty' <<<"$tag_json")
depth=$((depth + 1))
done
[[ "$tag_type" == commit && "$tag_sha" == "$head_sha" ]] || fail "release tag commit and build run head SHA do not match"
{
printf 'version=%s\n' "$tag"
printf 'build_type=%s\n' "$build_type"
printf 'build_run_id=%s\n' "$build_run_id"
printf 'tag=%s\n' "$tag"
} >> "$GITHUB_OUTPUT"
package:
name: Package (${{ matrix.arch }}-${{ matrix.libc }})
needs: resolve
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
include:
- arch: x86_64
libc: gnu
deb_arch: amd64
deb_depends: "libc6 (>= 2.31)"
rpm_depends: "glibc >= 2.31"
- arch: aarch64
libc: gnu
deb_arch: arm64
deb_depends: "libc6 (>= 2.31)"
rpm_depends: "glibc >= 2.31"
- arch: x86_64
libc: musl
deb_arch: amd64
deb_depends: ""
rpm_depends: ""
- arch: aarch64
libc: musl
deb_arch: arm64
deb_depends: ""
rpm_depends: ""
steps:
- name: Checkout packaging recipe
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Install DEB and RPM tools
shell: bash
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y ruby ruby-dev build-essential rpm fakeroot cpio
sudo gem install fpm --version 1.17.0 --no-document
- name: Download the build artifact
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: rustfs-linux-${{ matrix.arch }}-${{ matrix.libc }}-v${{ needs.resolve.outputs.version }}
path: binary-artifact
run-id: ${{ needs.resolve.outputs.build_run_id }}
github-token: ${{ github.token }}
- name: Check the artifact against the published checksum
shell: bash
env:
GH_TOKEN: ${{ github.token }}
REPOSITORY: ${{ github.repository }}
TAG: ${{ needs.resolve.outputs.tag }}
ARCH: ${{ matrix.arch }}
LIBC: ${{ matrix.libc }}
VERSION: ${{ needs.resolve.outputs.version }}
run: |
set -euo pipefail
zip_name="rustfs-linux-${ARCH}-${LIBC}-v${VERSION}.zip"
[[ "$zip_name" =~ ^rustfs-linux-(x86_64|aarch64)-(gnu|musl)-v[0-9A-Za-z.-]+[.]zip$ ]]
[[ -f "binary-artifact/${zip_name}" ]]
mkdir -p "$RUNNER_TEMP/source"
gh release download "$TAG" --repo "$REPOSITORY" \
--pattern SHA256SUMS --dir "$RUNNER_TEMP/source"
digest=$(sha256sum "binary-artifact/${zip_name}" | awk '{print $1}')
python3 scripts/release/refresh_release_checksums.py verify \
--checksum "$RUNNER_TEMP/source/SHA256SUMS" \
--name "$zip_name" \
--digest "$digest" \
--digest-length 64
mkdir -p ./bin
unzip -q "binary-artifact/${zip_name}" -d ./bin
[[ -f ./bin/rustfs ]]
chmod 755 ./bin/rustfs
- name: Build deb and rpm
shell: bash
env:
BUILD_TYPE: ${{ needs.resolve.outputs.build_type }}
VERSION: ${{ needs.resolve.outputs.version }}
ARCH: ${{ matrix.arch }}
LIBC: ${{ matrix.libc }}
DEB_ARCH: ${{ matrix.deb_arch }}
DEB_DEPENDS: ${{ matrix.deb_depends }}
RPM_DEPENDS: ${{ matrix.rpm_depends }}
run: |
set -euo pipefail
normalized=$(./scripts/release/package_versions.sh "$BUILD_TYPE" "$VERSION" "" "$ARCH" "$LIBC")
declare -A meta=()
while IFS= read -r line; do
key=${line%%=*}
value=${line#*=}
case "$key" in
deb_version|rpm_version|rpm_release|deb_file|rpm_file) meta[$key]="$value" ;;
*) printf 'unexpected package metadata %s\n' "$key" >&2; exit 1 ;;
esac
done <<<"$normalized"
[[ "${#meta[@]}" -eq 5 ]]
export DEB_VERSION="${meta[deb_version]}"
export RPM_VERSION="${meta[rpm_version]}"
export RPM_RELEASE="${meta[rpm_release]}"
export DEB_FILE="${meta[deb_file]}"
export RPM_FILE="${meta[rpm_file]}"
export RPM_ARCH="$ARCH"
bash scripts/release/build_deb.sh
bash scripts/release/build_rpm.sh
expected=$(sha256sum ./bin/rustfs | awk '{print $1}')
unpack=$(mktemp -d)
dpkg-deb --extract "$DEB_FILE" "$unpack"
[[ "$(sha256sum "$unpack/usr/bin/rustfs" | awk '{print $1}')" == "$expected" ]]
rm -rf "$unpack"
unpack=$(mktemp -d)
rpm2cpio "$RPM_FILE" | (cd "$unpack" && cpio --extract --make-directories --quiet ./usr/bin/rustfs)
[[ "$(sha256sum "$unpack/usr/bin/rustfs" | awk '{print $1}')" == "$expected" ]]
rm -rf "$unpack"
printf '%s\n%s\n' "$DEB_FILE" "$RPM_FILE" > "$RUNNER_TEMP/package-names"
- name: Upload packages to the GitHub release
shell: bash
env:
GH_TOKEN: ${{ github.token }}
REPOSITORY: ${{ github.repository }}
TAG: ${{ needs.resolve.outputs.tag }}
run: |
set -euo pipefail
mapfile -t names < "$RUNNER_TEMP/package-names"
[[ "${#names[@]}" -eq 2 ]]
for file in "${names[@]}"; do
[[ -f "$file" && "$file" =~ ^[A-Za-z0-9._-]+$ ]]
digest=$(sha256sum "$file" | awk '{print $1}')
existing=$(gh api "repos/${REPOSITORY}/releases/tags/${TAG}" \
--jq ".assets[] | select(.name == \"${file}\") | .digest")
if [[ -z "$existing" ]]; then
gh release upload "$TAG" "$file" --repo "$REPOSITORY"
elif [[ "$existing" == "sha256:${digest}" ]]; then
printf 'release already has %s\n' "$file"
else
printf 'existing release asset %s has a different digest\n' "$file" >&2
exit 1
fi
done
- name: Upload package artifacts
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: packages-${{ matrix.arch }}-${{ matrix.libc }}
path: |
*.deb
*.rpm
if-no-files-found: error
retention-days: 30
checksums:
name: Refresh release checksums
needs: [resolve, package]
if: github.repository == 'rustfs/rustfs' && needs.resolve.result == 'success' && needs.package.result == 'success'
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout checksum helper
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Download built packages
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
pattern: packages-*
merge-multiple: true
path: packages
- name: Rewrite SHA256SUMS and SHA512SUMS
shell: bash
env:
GH_TOKEN: ${{ github.token }}
REPOSITORY: ${{ github.repository }}
TAG: ${{ needs.resolve.outputs.tag }}
BUILD_TYPE: ${{ needs.resolve.outputs.build_type }}
VERSION: ${{ needs.resolve.outputs.version }}
run: |
set -euo pipefail
mapfile -t files < <(find packages -type f \( -name '*.deb' -o -name '*.rpm' \) | sort)
[[ "${#files[@]}" -eq 8 ]]
declare -A present=()
for file in "${files[@]}"; do
present["$(basename "$file")"]=1
done
for arch in x86_64 aarch64; do
for libc in gnu musl; do
normalized=$(./scripts/release/package_versions.sh "$BUILD_TYPE" "$VERSION" "" "$arch" "$libc")
while IFS= read -r line; do
key=${line%%=*}
value=${line#*=}
case "$key" in
deb_file|rpm_file)
[[ -n "${present[$value]:-}" ]] || { printf 'missing package %s\n' "$value" >&2; exit 1; }
;;
esac
done <<<"$normalized"
done
done
mkdir -p "$RUNNER_TEMP/checksums"
gh release download "$TAG" --repo "$REPOSITORY" \
--pattern SHA256SUMS --pattern SHA512SUMS \
--dir "$RUNNER_TEMP/checksums"
python3 scripts/release/refresh_release_checksums.py refresh \
--checksum "$RUNNER_TEMP/checksums/SHA256SUMS" \
--output "$RUNNER_TEMP/checksums/SHA256SUMS.next" \
--algorithm sha256 --digest-length 64 \
"${files[@]}"
python3 scripts/release/refresh_release_checksums.py refresh \
--checksum "$RUNNER_TEMP/checksums/SHA512SUMS" \
--output "$RUNNER_TEMP/checksums/SHA512SUMS.next" \
--algorithm sha512 --digest-length 128 \
"${files[@]}"
# Checksums are the only assets this workflow replaces. Package
# bytes uploaded above are left in place.
mv "$RUNNER_TEMP/checksums/SHA256SUMS.next" "$RUNNER_TEMP/checksums/SHA256SUMS"
mv "$RUNNER_TEMP/checksums/SHA512SUMS.next" "$RUNNER_TEMP/checksums/SHA512SUMS"
gh release upload "$TAG" \
"$RUNNER_TEMP/checksums/SHA256SUMS" \
"$RUNNER_TEMP/checksums/SHA512SUMS" \
--repo "$REPOSITORY" --clobber
verify=$(mktemp -d)
gh release download "$TAG" --repo "$REPOSITORY" \
--pattern SHA256SUMS --pattern SHA512SUMS --dir "$verify" --clobber
cmp "$RUNNER_TEMP/checksums/SHA256SUMS" "$verify/SHA256SUMS"
cmp "$RUNNER_TEMP/checksums/SHA512SUMS" "$verify/SHA512SUMS"
+2
View File
@@ -106,6 +106,8 @@ when restoring `/rustfs/console` for a custom OEM build.
## Distributed endpoint locality
- `RUSTFS_LOCAL_ENDPOINT_HOST` identifies this server's host in a distributed `RUSTFS_VOLUMES` topology without resolving every peer during startup. Set it to exactly one host, without a scheme, port, or path. It is accepted only for orchestrated URL topologies and must match at least one endpoint on the RustFS server port; invalid or unmatched values fail startup. Leave it unset to retain DNS-based locality discovery.
- DNS-based discovery resolves each configured hostname once successfully per startup and reuses the result across drives and pools. If discovery finds no local endpoint, startup exits before opening the service listener. Check that this member's advertised hostname resolves to an address on a local interface and that its endpoint port matches `RUSTFS_ADDRESS`. The next start resolves the hosts again.
- A finite, positive `RUSTFS_STARTUP_TOPOLOGY_WAIT_TIMEOUT` bounds how long endpoint discovery waits for DNS, including lookups and retry delays. If it expires during startup, the CLI reports the error and exits without waiting for an already-running system resolver call.
## Scanner environment aliases
+1 -1
View File
@@ -192,7 +192,7 @@ the same profile for membership and execution with one nightly worker.
| --- | --- | --- |
| Smoke subset (`e2e-smoke` profile) | `e2e-tests` job, every PR | **Active** (backlog#1149 ci-4) |
| Full single-node suite (`e2e-full` profile) | `e2e-full` job, merge queue + main | **Active** (backlog#1149 ci-5) |
| `s3s-e2e` black-box | `e2e-tests` + `e2e-tests-rio-v2` jobs | **Active** (external conformance tool) |
| `s3s-e2e` black-box | `e2e-tests` job | **Active** (external conformance tool) |
| ILM / lifecycle (ignored) | `test-ilm-integration-serial` lane, `-j1` | **Active** (backlog#1148 ilm-1) |
| KMS suite | `e2e-full` job, merge queue + main | **Active** |
| Direct and mixed-version rolling upgrades from pinned previous release | `e2e-upgrade.yml`, release tags + weekly schedule + manual dispatch | **Active** |
@@ -680,13 +680,11 @@ async fn test_copy_object_does_not_inherit_source_legal_hold() {
.key("implicit-copy")
.send()
.await
.unwrap();
.expect_err("copy should not inherit the source hold");
assert_eq!(implicit_legal_hold.raw_response().map(|response| response.status().as_u16()), Some(404));
assert_eq!(
implicit_legal_hold
.legal_hold()
.and_then(|value| value.status())
.map(|value| value.as_str()),
Some("OFF")
implicit_legal_hold.as_service_error().and_then(ProvideErrorMetadata::code),
Some("NoSuchObjectLockConfiguration")
);
client
@@ -2028,12 +2026,12 @@ async fn test_copy_object_retention_uses_destination_policy() {
.key("no-default-copy")
.send()
.await
.unwrap();
let no_default_retention = no_default_retention
.retention()
.expect("retention response should be present");
assert!(no_default_retention.mode().is_none());
assert!(no_default_retention.retain_until_date().is_none());
.expect_err("copy should have no retention without a destination default");
assert_eq!(no_default_retention.raw_response().map(|response| response.status().as_u16()), Some(404));
assert_eq!(
no_default_retention.as_service_error().and_then(ProvideErrorMetadata::code),
Some("NoSuchObjectLockConfiguration")
);
let retained_version_id = put_object_with_retention(
&client,
+13 -11
View File
@@ -230,10 +230,10 @@ pub mod bucket {
ObjectLockConfigState, ScannerBucketIncarnationReadGuard, acquire_bucket_metadata_transaction_lock,
acquire_bucket_metadata_transaction_lock_for_incarnation, acquire_scanner_bucket_incarnation_fence,
acquire_scanner_bucket_incarnation_read_fence, capture_bucket_metadata_incarnation, delete, delete_if_incarnation,
delete_if_incarnation_at, delete_under_transaction_lock, get, get_accelerate_config, get_bucket_policy,
get_bucket_policy_raw, get_bucket_targets_config, get_config_from_disk, get_cors_config, get_durability_config,
get_etag_config, get_global_bucket_metadata_sys, get_lifecycle_config, get_logging_config, get_notification_config,
get_object_lock_config, get_object_lock_config_state, get_on_demand_migration_config,
delete_if_incarnation_at, delete_under_transaction_lock, find_object_lock_config_state, get, get_accelerate_config,
get_bucket_policy, get_bucket_policy_raw, get_bucket_targets_config, get_config_from_disk, get_cors_config,
get_durability_config, get_etag_config, get_global_bucket_metadata_sys, get_lifecycle_config, get_logging_config,
get_notification_config, get_object_lock_config, get_object_lock_config_state, get_on_demand_migration_config,
get_on_demand_migration_config_in, get_public_access_block_config, get_quota_config, get_replication_config,
get_request_payment_config, get_s3_tagging_config, get_sse_config, get_tagging_config, get_versioning_config,
get_website_config, init_bucket_metadata_sys, list_bucket_targets, reload_bucket_metadata, remove_bucket_metadata,
@@ -452,13 +452,15 @@ pub mod data_usage {
#[cfg(feature = "test-util")]
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
pub use crate::data_usage::{
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, 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,
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
load_bucket_scan_progress_for_admin, load_bucket_usage_certification_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,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
store_data_usage_in_backend, verified_account_bucket_usage,
@@ -212,17 +212,18 @@ pub fn get_global_transition_state() -> Arc<TransitionState> {
crate::runtime::global::current_ctx().transition_state()
}
fn resolve_transition_worker_count() -> (i64, i64, i64) {
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
fn resolve_transition_worker_count(parallelism: std::num::NonZeroUsize) -> (i64, i64, i64) {
let configured = env::var(ENV_TRANSITION_WORKERS)
.ok()
.and_then(|value| value.parse::<i64>().ok())
.filter(|value| *value > 0)
.unwrap_or(fallback);
let mut effective = configured;
.unwrap_or_else(|| {
i64::try_from(parallelism.get())
.unwrap_or(i64::MAX)
.min(DEFAULT_TRANSITION_WORKERS_CAP)
});
let absolute_max = resolve_transition_workers_absolute_max();
effective = std::cmp::min(effective, absolute_max);
(configured, absolute_max, effective)
(configured, absolute_max, configured.min(absolute_max))
}
fn resolve_transition_workers_absolute_max() -> i64 {
@@ -2085,7 +2086,7 @@ impl TransitionState {
}
pub async fn init(api: Arc<ECStore>) {
let (configured, absolute_max, n) = resolve_transition_worker_count();
let (configured, absolute_max, n) = resolve_transition_worker_count(api.ctx.worker_parallelism());
let transition_state = runtime_sources::transition_state_handle();
debug!(
event = EVENT_LIFECYCLE_WORKER_STATE,
@@ -2100,8 +2101,7 @@ impl TransitionState {
"Lifecycle worker configuration resolved"
);
//self.objAPI = objAPI
Self::update_workers(api, n).await;
Self::resize_workers_to(api, n, n, absolute_max);
}
pub fn pending_tasks(&self) -> usize {
@@ -2270,18 +2270,15 @@ impl TransitionState {
Self::update_workers_inner(api, n).await;
}
pub async fn update_workers_inner(api: Arc<ECStore>, n: i64) {
let mut n = n;
let requested = n;
if n == 0 {
let (_, _, effective) = resolve_transition_worker_count();
n = effective;
}
// Allow environment override of maximum workers
let absolute_max = resolve_transition_workers_absolute_max();
n = n.clamp(0, absolute_max);
Self::resize_workers_to(api, n, requested, absolute_max);
pub async fn update_workers_inner(api: Arc<ECStore>, requested: i64) {
let (effective, absolute_max) = if requested == 0 {
let (_, absolute_max, effective) = resolve_transition_worker_count(api.ctx.worker_parallelism());
(effective, absolute_max)
} else {
let absolute_max = resolve_transition_workers_absolute_max();
(requested.clamp(0, absolute_max), absolute_max)
};
Self::resize_workers_to(api, effective, requested, absolute_max);
}
fn resize_workers_to(api: Arc<ECStore>, n: i64, requested: i64, absolute_max: i64) {
@@ -2477,19 +2474,16 @@ fn is_lifecycle_expiry_already_gone(err: &Error) -> bool {
/// `_RUSTFS_ILM_EXPIRATION_WORKERS` silent override and the
/// `RUSTFS_DEFAULT_EXPIRY_WORKERS` zero-fallback were undocumented, unset in
/// every known deployment, and are removed (backlog#1832).
fn expiry_worker_count() -> usize {
let default = std::cmp::min(num_cpus::get(), 16);
match env::var(ENV_MAX_EXPIRY_WORKERS) {
Ok(value) => match value.parse::<usize>() {
Ok(workers) if workers > 0 => workers,
_ => default,
},
Err(_) => default,
}
fn expiry_worker_count(parallelism: std::num::NonZeroUsize) -> usize {
env::var(ENV_MAX_EXPIRY_WORKERS)
.ok()
.and_then(|value| value.parse::<usize>().ok())
.filter(|workers| *workers > 0)
.unwrap_or(parallelism.get().min(16))
}
pub async fn init_background_expiry(api: Arc<ECStore>) {
let workers = expiry_worker_count();
let workers = expiry_worker_count(api.ctx.worker_parallelism());
ExpiryState::resize_workers(workers, api.clone()).await;
let _ = spawn_tier_free_version_recovery_once(api.clone(), &TIER_FREE_VERSION_RECOVERY_STARTED);
@@ -9740,19 +9734,24 @@ mod tests {
#[test]
#[serial]
fn expiry_worker_count_resolves_all_env_states() {
let default = std::cmp::min(num_cpus::get(), 16);
let default = std::thread::available_parallelism().map_or(1, usize::from).min(16);
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
with_expiry_worker_env(None, || {
assert_eq!(expiry_worker_count(), default, "unset env must fall back to min(cpus, 16)");
assert_eq!(expiry_worker_count(parallelism), default, "unset env must fall back to min(cpus, 16)");
});
with_expiry_worker_env(Some("0"), || {
assert_eq!(expiry_worker_count(), default, "zero must fall back instead of spawning zero workers");
assert_eq!(
expiry_worker_count(parallelism),
default,
"zero must fall back instead of spawning zero workers"
);
});
with_expiry_worker_env(Some("4"), || {
assert_eq!(expiry_worker_count(), 4, "a valid positive value must win");
with_expiry_worker_env(Some("32"), || {
assert_eq!(expiry_worker_count(parallelism), 32, "an explicit count may exceed the default cap");
});
with_expiry_worker_env(Some("not-a-number"), || {
assert_eq!(expiry_worker_count(), default, "garbage must fall back to the default");
assert_eq!(expiry_worker_count(parallelism), default, "garbage must fall back to the default");
});
}
@@ -9948,9 +9947,13 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_uses_fallback_when_env_missing() {
with_transition_worker_env(None, None, || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
let (configured, absolute_max, effective) = resolve_transition_worker_count(parallelism);
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
let cpus = std::thread::available_parallelism().map_or(1, usize::from);
let fallback = i64::try_from(cpus)
.expect("available parallelism fits in i64")
.min(DEFAULT_TRANSITION_WORKERS_CAP);
assert_eq!(configured, fallback);
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
assert_eq!(effective, fallback);
@@ -9961,7 +9964,7 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_honors_positive_env_value() {
with_transition_worker_env(Some("4"), Some("32"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 4);
assert_eq!(absolute_max, 32);
@@ -9973,7 +9976,7 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_clamps_to_absolute_max() {
with_transition_worker_env(Some("64"), Some("16"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 64);
assert_eq!(absolute_max, 16);
@@ -9985,7 +9988,7 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_ignores_non_positive_absolute_max() {
with_transition_worker_env(Some("4"), Some("0"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 4);
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
@@ -9993,7 +9996,7 @@ mod tests {
});
with_transition_worker_env(Some("4"), Some("-1"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
assert_eq!(configured, 4);
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
@@ -10005,9 +10008,13 @@ mod tests {
#[serial]
fn resolve_transition_worker_count_falls_back_for_zero_value() {
with_transition_worker_env(Some("0"), Some("32"), || {
let (configured, absolute_max, effective) = resolve_transition_worker_count();
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
let (configured, absolute_max, effective) = resolve_transition_worker_count(parallelism);
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
let cpus = std::thread::available_parallelism().map_or(1, usize::from);
let fallback = i64::try_from(cpus)
.expect("available parallelism fits in i64")
.min(DEFAULT_TRANSITION_WORKERS_CAP);
assert_eq!(configured, fallback);
assert_eq!(absolute_max, 32);
assert_eq!(effective, fallback);
+61 -33
View File
@@ -151,6 +151,15 @@ pub enum ObjectLockConfigState {
Fabricated,
}
// Only namespace probes can name the requested bucket. Internal metadata
// storage errors must not be mistaken for absence of that bucket.
fn bucket_namespace_error(bucket: &str, error: Error) -> Error {
match error {
Error::VolumeNotFound => Error::BucketNotFound(bucket.to_owned()),
error => error,
}
}
enum BucketMetadataAuthority {
Authoritative(Arc<BucketMetadata>),
Fabricated,
@@ -1695,6 +1704,24 @@ pub async fn get_object_lock_config_state(bucket: &str) -> Result<ObjectLockConf
bucket_meta_sys.get_object_lock_config_state(bucket).await
}
/// Read Object Lock state from authoritative bucket metadata.
///
/// `Ok(None)` means the bucket is confirmed missing. An existing bucket with
/// no Object Lock configuration returns `Some(ConfirmedAbsent)`.
///
/// # Errors
///
/// Returns storage, migration, or validation errors when the state cannot be read.
pub async fn find_object_lock_config_state(bucket: &str) -> Result<Option<ObjectLockConfigState>> {
let bucket_meta_sys_lock = get_bucket_metadata_sys()?;
let bucket_meta_sys = bucket_meta_sys_lock.read().await.clone();
match bucket_meta_sys.find_object_lock_config_state(bucket).await {
Err(Error::BucketNotFound(name)) if name == bucket => Ok(None),
result => result,
}
}
pub(crate) async fn get_object_lock_config_state_in(
ctx: &crate::runtime::instance::InstanceContext,
bucket: &str,
@@ -3201,15 +3228,15 @@ impl BucketMetadataSys {
Box::pin(async {
let store = self.object_store();
let options = crate::storage_api_contracts::bucket::BucketOptions::default();
let info = if require_write_quorum {
store.get_bucket_info_from_sets(bucket, &options).await
if require_write_quorum {
store.get_bucket_info_from_sets(bucket, &options).await.map(|_| ())
} else {
store.get_bucket_info_from_sets_at_read_quorum(bucket, &options).await
};
info.map(|_| ())
store.check_bucket_presence_at_read_quorum(bucket).await
}
}),
)
.await?;
.await
.map_err(|err| bucket_namespace_error(bucket, err))?;
if guard.is_lock_lost() {
return Err(Error::other(format!(
"bucket namespace lock was lost before lazy bucket metadata publish: {bucket}"
@@ -3369,14 +3396,18 @@ impl BucketMetadataSys {
}
pub async fn get_object_lock_config_state(&self, bucket: &str) -> Result<ObjectLockConfigState> {
match self.get_metadata_authority(bucket).await? {
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm),
BucketMetadataAuthority::Fabricated => match self.migrate_legacy_metadata(bucket).await? {
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm),
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
BucketMetadataAuthority::Fabricated => Ok(ObjectLockConfigState::Fabricated),
},
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
self.find_object_lock_config_state(bucket).await?.ok_or(Error::ConfigNotFound)
}
async fn find_object_lock_config_state(&self, bucket: &str) -> Result<Option<ObjectLockConfigState>> {
let authority = match self.get_metadata_authority(bucket).await? {
BucketMetadataAuthority::Fabricated => self.migrate_legacy_metadata(bucket).await?,
authority => authority,
};
match authority {
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm).map(Some),
BucketMetadataAuthority::Fabricated => Ok(Some(ObjectLockConfigState::Fabricated)),
BucketMetadataAuthority::MissingBucket => Ok(None),
}
}
@@ -3516,7 +3547,8 @@ impl BucketMetadataSys {
self.object_store()
.get_bucket_info_from_sets(bucket, &crate::storage_api_contracts::bucket::BucketOptions::default()),
)
.await?;
.await
.map_err(|err| bucket_namespace_error(bucket, err))?;
let (mut metadata, persisted) = await_bucket_namespace_operation(
Some(&namespace_guard),
@@ -3769,19 +3801,12 @@ impl BucketMetadataSys {
#[cfg(test)]
self.authority_disk_loads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (bucket_info_res, metadata_res) = tokio::join!(
let (bucket_presence_res, metadata_res) = tokio::join!(
Box::pin(await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata snapshot existence check",
async {
store
.get_bucket_info_from_sets_at_read_quorum(
bucket,
&crate::storage_api_contracts::bucket::BucketOptions::default(),
)
.await
},
store.check_bucket_presence_at_read_quorum(bucket),
)),
Box::pin(await_bucket_namespace_operation(
Some(guard),
@@ -3790,8 +3815,8 @@ impl BucketMetadataSys {
load_bucket_metadata_parse_with_presence(Arc::clone(&store), bucket, false),
)),
);
match bucket_info_res {
Ok(_) => {}
match bucket_presence_res {
Ok(()) => {}
Err(Error::VolumeNotFound) => return Ok(BucketMetadataAuthority::MissingBucket),
Err(err) => return Err(err),
}
@@ -4564,14 +4589,17 @@ mod tests {
sys.get_bucket_policy("migration-write-failure").await,
Err(Error::ConfigNotFound)
));
assert!(sys.get_object_lock_config_state("migration-write-failure").await.is_err());
assert!(sys.find_object_lock_config_state("migration-write-failure").await.is_err());
assert!(sys.get("migration-write-failure").await.is_err());
sys.legacy_migration_write_error.store(false, Ordering::Relaxed);
let loads_before = sys.lazy_disk_loads.load(Ordering::Relaxed);
assert!(sys.find_object_lock_config_state("missing-bucket").await.unwrap().is_none());
assert!(matches!(
sys.get_object_lock_config_state("missing-bucket").await,
Err(Error::ConfigNotFound)
));
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), loads_before + 1);
assert!(matches!(sys.get_bucket_policy("missing-bucket").await, Err(Error::ConfigNotFound)));
assert!(matches!(sys.get_bucket_policy_raw("missing-bucket").await, Err(Error::ConfigNotFound)));
@@ -5290,14 +5318,14 @@ mod tests {
// be lazily republished as a live bucket generation.
let mut deleted_lazy = BucketMetadata::new("deleted-lazy-bucket");
deleted_lazy.policy_config_json = b"stale-generation".to_vec();
sys.persist_and_set(deleted_lazy)
sys.persist_new_and_set(deleted_lazy)
.await
.expect("stale metadata should persist");
.expect("stale committed metadata should persist");
sys.metadata_map.write().await.remove("deleted-lazy-bucket");
assert!(
sys.get_config("deleted-lazy-bucket").await.is_err(),
"lazy load must fail when the physical bucket no longer exists"
);
assert!(matches!(
sys.get_config("deleted-lazy-bucket").await,
Err(Error::BucketNotFound(name)) if name == "deleted-lazy-bucket"
));
assert!(sys.get("deleted-lazy-bucket").await.is_err());
// (d) The namespace generation fence must be acquired before lazy
@@ -2175,6 +2175,10 @@ fn verify_tonic_rpc_signature_with_policy(
&& has_v2_auth_headers(headers)
&& tonic_boot_epoch_challenge(headers).is_ok_and(|challenge| challenge.is_some());
if replay_scope_strict && !bootstrap {
// The server answers this rejection with its boot-epoch proof so a signed peer can retry
// with a replay scope. Verify the method-bound v2 HMAC first so unsigned, legacy-only, or
// forged callers are rejected for the signature itself without consuming replay-cache slots.
verified_tonic_rpc_nonce(audience, path, headers, true)?;
return Err(std::io::Error::other("RPC replay-scoped authentication required"));
}
@@ -3291,6 +3295,64 @@ mod tests {
);
}
#[test]
fn replay_scope_strictness_reports_missing_scope_only_to_signed_callers() {
ensure_test_rpc_secret();
let path = "/node_service.NodeService/ReadVersion";
let mut headers = gen_tonic_signature_headers("node-a:9000", "node_service.NodeService", "ReadVersion", None)
.expect("v2 compatibility headers should build");
let signed = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &headers, false, true, false)
.expect_err("strict replay scope must reject a signed v2-only request");
assert_eq!(signed.to_string(), "RPC replay-scoped authentication required");
assert_eq!(tonic_rpc_auth_failure_reason(&signed), "replay_scope_required");
// A body-digested v2-only mutation must also verify its v2 HMAC before reporting
// `replay_scope_required`, without inserting its nonce into the replay cache for a
// request that is rejected prior to execution.
let digest = hex_simd::encode_to_string(Sha256::digest(b"strict-body"), hex_simd::AsciiCase::Lower);
let mutation_path = "/node_service.NodeService/WriteAll";
let mutation_headers = gen_tonic_signature_headers("node-a:9000", "node_service.NodeService", "WriteAll", Some(&digest))
.expect("body-digested v2 headers should build");
let mutation_nonce = Uuid::parse_str(
mutation_headers[RPC_NONCE_HEADER]
.to_str()
.expect("v2 nonce header must be ASCII"),
)
.expect("body-digested v2 nonce must be a UUID");
let mutation_rejected =
verify_tonic_rpc_signature_with_policy("node-a:9000", mutation_path, &mutation_headers, false, true, false)
.expect_err("strict replay scope must reject a signed body-digested v2-only request");
assert_eq!(mutation_rejected.to_string(), "RPC replay-scoped authentication required");
assert!(
!LOCAL_RPC_NONCE_CACHE
.lock()
.expect("nonce cache lock")
.contains_nonce(&mutation_nonce),
"rejected replay_scope_required requests must not consume replay-cache slots"
);
let cross_method =
verify_tonic_rpc_signature_with_policy("node-a:9000", "/node_service.NodeService/Ping", &headers, false, true, false)
.expect_err("a v2 signature bound to another method must not report replay_scope_required");
assert_eq!(cross_method.to_string(), "Invalid RPC v2 signature");
let wrong_audience = verify_tonic_rpc_signature_with_policy("node-b:9000", path, &headers, false, true, false)
.expect_err("a v2 signature bound to another audience must not report replay_scope_required");
assert_eq!(wrong_audience.to_string(), "Invalid RPC v2 signature");
headers.insert(RPC_SIGNATURE_V2_HEADER, HeaderValue::from_static("invalid"));
let forged = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &headers, false, true, false)
.expect_err("a forged v2 signature must be rejected as invalid_v2_signature");
assert_eq!(forged.to_string(), "Invalid RPC v2 signature");
let legacy = gen_signature_headers(TONIC_RPC_PREFIX, &Method::GET).expect("legacy auth headers should build");
for unsigned_or_legacy in [legacy, HeaderMap::new()] {
let error = verify_tonic_rpc_signature_with_policy("node-a:9000", path, &unsigned_or_legacy, false, true, false)
.expect_err("a request without v2 metadata must be rejected as v2_required");
assert_eq!(error.to_string(), "RPC v2 authentication required");
}
}
#[test]
fn boot_epoch_response_proof_binds_audience_challenge_and_epoch() {
ensure_test_rpc_secret();
+240 -48
View File
@@ -32,8 +32,8 @@ use crate::disk::{
DeleteRecoveryInspection, DeleteRecoveryPage, DeleteRecoveryRpcOperation, DeleteRecoveryRpcReply, DiskAPI, DiskInfo,
DiskInfoOptions, DiskLocation, DiskOption, FileInfoVersions, FileReader, FileWriter, GuardedDeleteVersionsPayload,
GuardedFileInfoVersions, PartTransactionAction, PoolMetaNativeRecoveryRequest, PoolMetaNativeRecoveryResponse,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, SnapshotLeaseToken, UpdateMetadataOpts, VolumeInfo,
WalkDirOptions, batch_read_version_one_by_one,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataGuards, RenameDataObservation, RenameDataResp,
RenameDispatchDeadline, SnapshotLeaseToken, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, batch_read_version_one_by_one,
disk_store::{
DEFAULT_RUSTFS_DRIVE_ACTIVE_MONITORING, ENV_RUSTFS_DRIVE_ACTIVE_MONITORING, SKIP_IF_SUCCESS_BEFORE,
get_drive_active_check_interval, get_drive_active_check_timeout, get_drive_disk_info_timeout, get_drive_list_dir_timeout,
@@ -3313,6 +3313,25 @@ fn validate_decoded_file_info(file_info: &FileInfo) -> Result<()> {
file_info.validate_for_metadata_read().map_err(Into::into)
}
// Dropping preparation is safe only before the mutation enters the transport.
async fn before_rename_dispatch<T>(mut deadline: Option<RenameDispatchDeadline>, prepare: impl Future<Output = T>) -> Option<T> {
let Some(deadline) = deadline.as_mut() else {
return Some(prepare.await);
};
tokio::select! {
biased;
result = prepare => Some(result),
() = async {
let at = deadline.wait_for(Option::is_some).await.ok().and_then(|deadline| *deadline);
if let Some(at) = at {
time::sleep_until(at).await;
} else {
std::future::pending::<()>().await;
}
} => None,
}
}
impl RemoteDisk {
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_borrowed(
@@ -3335,6 +3354,7 @@ impl RemoteDisk {
dst_volume: &str,
dst_path: &str,
items: Vec<RenameBatchClientItem<'_>>,
dispatch_deadline: Option<RenameDispatchDeadline>,
) -> std::result::Result<RemoteRenameBatchStream, RenameBatchStartError> {
if self.rename_admission.is_none() || items.is_empty() || items.len() > 16 {
return Err(RenameBatchStartError::NotDispatched(DiskError::UnsupportedDisk));
@@ -3354,20 +3374,35 @@ impl RemoteDisk {
if let Some(error) = self.offline_bypass_error() {
return Err(RenameBatchStartError::NotDispatched(error));
}
let routing = super::client::node_service_rename_batch_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
);
let mut client = match tokio::time::timeout_at(deadline, routing).await {
Ok(Ok(Some(client))) => client,
Ok(Ok(None)) => return Err(RenameBatchStartError::UnsupportedBeforeStream),
Ok(Err(error)) => {
return Err(RenameBatchStartError::NotDispatched(DiskError::RemoteClientUnavailable(
error.to_string(),
)));
}
Err(_) => return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout)),
};
let prepared = before_rename_dispatch(dispatch_deadline, async {
let routing = super::client::node_service_rename_batch_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
);
let client = match tokio::time::timeout_at(deadline, routing).await {
Ok(Ok(Some(client))) => client,
Ok(Ok(None)) => return Err(RenameBatchStartError::UnsupportedBeforeStream),
Ok(Err(error)) => {
return Err(RenameBatchStartError::NotDispatched(DiskError::RemoteClientUnavailable(
error.to_string(),
)));
}
Err(_) => return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout)),
};
let admission = self
.acquire_rename_admission_until(items.len(), deadline)
.await
.map_err(RenameBatchStartError::NotDispatched)?;
let guard = RenameBatchCallGuard {
admission,
deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
Ok((client, guard))
})
.await
.ok_or(RenameBatchStartError::NotDispatched(DiskError::DiskNotFound))?;
let (mut client, mut guard) = prepared?;
let mut request_items = Vec::with_capacity(items.len());
for item in items {
let item_index = u32::try_from(item.slot)
@@ -3393,21 +3428,11 @@ impl RemoteDisk {
crate::cluster::rpc::set_tonic_canonical_body_digest(&mut request, &canonical_body)
.map_err(Error::other)
.map_err(RenameBatchStartError::NotDispatched)?;
let admission = self
.acquire_rename_admission_until(request.get_ref().items.len(), deadline)
.await
.map_err(RenameBatchStartError::NotDispatched)?;
let guard = RenameBatchCallGuard {
admission,
deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
let call_timeout = deadline.saturating_duration_since(tokio::time::Instant::now());
if call_timeout == Duration::ZERO {
guard.release_without_quarantine();
return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout));
}
let mut guard = guard;
guard.mark_dispatched();
let response = match self
.execute_peer_batch_with_timeout(
@@ -3433,7 +3458,6 @@ impl RemoteDisk {
Ok(guard.into_stream(response.into_inner(), expected_mask))
}
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_borrowed_with_fence(
&self,
src_volume: &str,
@@ -3443,6 +3467,36 @@ impl RemoteDisk {
dst_path: &str,
scanner_publication_lease_token: Option<Uuid>,
) -> Result<RenameDataResp> {
self.rename_data_observed(
src_volume,
src_path,
fi,
dst_volume,
dst_path,
RenameDataGuards {
scanner_publication_lease_token,
..Default::default()
},
)
.await
.result
}
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_observed(
&self,
src_volume: &str,
src_path: &str,
fi: &FileInfo,
dst_volume: &str,
dst_path: &str,
guards: RenameDataGuards,
) -> RenameDataObservation {
let RenameDataGuards {
scanner_publication_lease_token,
dispatch_deadline,
..
} = guards;
let multipart_rename = src_volume == crate::disk::RUSTFS_META_MULTIPART_BUCKET;
let pool_meta_cas = rustfs_utils::http::metadata_compat::contains_key_str(
&fi.metadata,
@@ -3453,7 +3507,7 @@ impl RemoteDisk {
|| dst_path != "pool.bin"
|| scanner_publication_lease_token.is_some())
{
return Err(DiskError::UnsupportedDisk);
return RenameDataObservation::unknown(Err(DiskError::UnsupportedDisk));
}
trace!(
event = EVENT_REMOTE_DISK_RPC,
@@ -3469,11 +3523,36 @@ impl RemoteDisk {
"Remote disk RPC started"
);
self.execute_with_timeout_for_op(
let mut dispatch_expired = false;
let result = Self::execute_with_timeout_for_op(
self,
"rename_data",
|| async {
let prepare_started = rustfs_io_metrics::put_stage_timer();
let collect_prepare_timing = prepare_started.is_some();
let prepared = before_rename_dispatch(dispatch_deadline, async {
let get_client_started = collect_prepare_timing.then(Instant::now);
let client = self.get_client_with_msgpack_policy().await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_REMOTE_CLIENT_GET_CLIENT,
get_client_started,
);
let (client, policy) = client?;
let rename_deadline = tokio::time::Instant::now() + get_max_timeout_duration();
let rename_admission = self.acquire_rename_admission_until(1, rename_deadline).await?;
let rename_admission_guard = RenameBatchCallGuard {
admission: rename_admission,
deadline: rename_deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
Ok::<_, DiskError>((client, policy, rename_admission_guard))
})
.await;
let Some(prepared) = prepared else {
dispatch_expired = true;
return Err(DiskError::DiskNotFound);
};
let (mut client, mut policy, mut rename_admission_guard) = prepared?;
let msgpack_encode_started = collect_prepare_timing.then(Instant::now);
let file_info_bin = Bytes::from(encode_file_info_msgpack(fi)?);
rustfs_io_metrics::record_put_object_stage_duration_from(
@@ -3486,13 +3565,6 @@ impl RemoteDisk {
file_info_bin.len(),
);
}
let get_client_started = collect_prepare_timing.then(Instant::now);
let client = self.get_client_with_msgpack_policy().await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_REMOTE_CLIENT_GET_CLIENT,
get_client_started,
);
let (mut client, mut policy) = client?;
let bucket_incarnation_id = crate::store::bucket_heal_scope_for_object(dst_volume, dst_path)
.map(|scope| Bytes::copy_from_slice(scope.incarnation.as_bytes()))
.unwrap_or_default();
@@ -3504,13 +3576,6 @@ impl RemoteDisk {
let scanner_publication_lease = scanner_publication_lease_token
.map(|token| Bytes::copy_from_slice(token.as_bytes()))
.unwrap_or_default();
let rename_deadline = tokio::time::Instant::now() + get_max_timeout_duration();
let rename_admission = self.acquire_rename_admission_until(1, rename_deadline).await?;
let mut rename_admission_guard = RenameBatchCallGuard {
admission: rename_admission,
deadline: rename_deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
let rpc_kind = if multipart_rename {
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_MULTIPART
} else if pool_meta_cas {
@@ -3673,7 +3738,11 @@ impl RemoteDisk {
},
get_max_timeout_duration(),
)
.await
.await;
RenameDataObservation {
result,
rejected_before_publication: dispatch_expired,
}
}
/// Delete a path while binding the target-side operation to a scanner
@@ -6484,6 +6553,66 @@ mod tests {
}
}
#[tokio::test(start_paused = true)]
async fn rename_dispatch_budget_only_starts_after_the_quorum_signal() {
use futures::FutureExt as _;
let (tx, rx) = tokio::sync::watch::channel(None);
let mut dial = std::pin::pin!(before_rename_dispatch(Some(rx), std::future::pending::<()>()));
assert!(dial.as_mut().now_or_never().is_none());
time::advance(Duration::from_secs(2)).await;
assert!(dial.as_mut().now_or_never().is_none(), "quorum has not been reached");
tx.send_replace(Some(time::Instant::now() + Duration::from_secs(1)));
assert!(dial.as_mut().now_or_never().is_none(), "quorum grants a connection grace period");
time::advance(Duration::from_secs(1)).await;
assert_eq!(dial.await, None, "only the unresolved connection expires");
assert_eq!(before_rename_dispatch(Some(tx.subscribe()), std::future::ready(8)).await, Some(8));
}
#[tokio::test]
async fn rename_dispatch_budget_does_not_cancel_a_dispatched_rpc() {
use futures::FutureExt as _;
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind rename peer");
peer.peer.serve_rename_data();
let gate = Arc::new(TestFormatReadGate::default());
*peer.peer.rename_data_reply_gate.lock().expect("rename reply gate") = Some(gate.clone());
let disk = remote_disk_for_addr(&peer.addr).await;
let (tx, rx) = tokio::sync::watch::channel(None);
let file_info = sample_rename_data_file_info();
let mut rename = std::pin::pin!(disk.rename_data_observed(
"tmp",
"source",
&file_info,
"bucket",
"object",
RenameDataGuards {
dispatch_deadline: Some(rx),
..Default::default()
},
));
time::timeout(Duration::from_secs(5), async {
tokio::select! {
() = gate.entered.notified() => {},
_ = rename.as_mut() => panic!("rename completed before the peer received it"),
}
})
.await
.expect("peer should receive the authenticated mutation");
tx.send_replace(Some(time::Instant::now()));
assert!(rename.as_mut().now_or_never().is_none(), "the dispatched mutation must continue to drain");
gate.release.cancel();
let observed = rename.await;
assert!(!observed.rejected_before_publication());
observed.result.expect("remote rename should return success");
peer.stop().await;
}
#[tokio::test]
async fn multipart_rename_old_peer_rejects_without_legacy_fallback() {
runtime_sources::ensure_test_rpc_secret();
@@ -6540,7 +6669,7 @@ mod tests {
for (object, calls) in [("object", 1), ("other-object", 2)] {
let result = remote
.start_rename_data_batch("tmp", "source", "bucket", object, rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", object, rename_batch_client_items(&file_infos), None)
.await;
assert!(matches!(result, Err(RenameBatchStartError::UnsupportedBeforeStream)));
assert_eq!(
@@ -6577,7 +6706,7 @@ mod tests {
for width in [2_usize, 4] {
let file_infos = (0..width).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos), None)
.await
.unwrap_or_else(|_| panic!("{width}-item real batch must start"));
assert_eq!(
@@ -6615,6 +6744,62 @@ mod tests {
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_dispatch_budget_releases_waiting_batch_admission_without_dispatch() {
use std::task::Poll;
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind rename batch peer");
peer.peer.serve_rename_batch_results(usize::MAX);
temp_env::async_with_vars([(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true"))], async {
let remote = remote_disk_for_addr(&peer.addr).await;
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let capacity = rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT;
let held = Arc::clone(&gate)
.acquire_many_owned(u32::try_from(capacity - 1).expect("valid permit count"))
.await
.expect("reserve all but one permit");
let file_infos = [sample_rename_data_file_info(), sample_rename_data_file_info()];
let (tx, rx) = tokio::sync::watch::channel(None);
let mut rename = std::pin::pin!(remote.start_rename_data_batch(
"tmp",
"source",
"bucket",
"object",
rename_batch_client_items(&file_infos),
Some(rx),
));
time::timeout(
Duration::from_secs(5),
std::future::poll_fn(|cx| {
assert!(rename.as_mut().poll(cx).is_pending(), "batch must wait for two permits");
if gate.available_permits() == 0 {
Poll::Ready(())
} else {
Poll::Pending
}
}),
)
.await
.expect("the queued batch must reserve the spare permit");
tx.send_replace(Some(time::Instant::now()));
let result = time::timeout(Duration::from_secs(5), rename)
.await
.expect("elapsed dispatch budget must release the batch waiter");
assert!(matches!(result, Err(RenameBatchStartError::NotDispatched(DiskError::DiskNotFound))));
assert_eq!(peer.peer.rename_batch_calls(), 0, "expiry must not send a mutation to the peer");
assert_eq!(gate.available_permits(), 1, "the cancelled acquire must release its reservation");
drop(held);
assert_eq!(gate.available_permits(), capacity);
})
.await;
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_batch_real_partial_eof_quarantines_only_missing_items() {
@@ -6633,7 +6818,7 @@ mod tests {
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let file_infos = (0..4).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos), None)
.await
.unwrap_or_else(|_| panic!("real partial batch must start"));
@@ -7200,7 +7385,7 @@ mod tests {
fn msgpack_eligible_requests_bind_one_policy_and_bounded_local_retry() {
let source = rustfs_protos::compat_manifest::production_source(include_str!("remote_disk.rs"), "remote_disk.rs");
for function in [
"rename_data_borrowed_with_fence",
"rename_data_observed",
"write_metadata",
"update_metadata",
"read_version",
@@ -7550,6 +7735,7 @@ mod tests {
rename_batch_result_limit: Arc<StdMutex<Option<usize>>>,
serve_rename_data: Arc<AtomicBool>,
rename_data_disks: Arc<StdMutex<Vec<String>>>,
rename_data_reply_gate: Arc<StdMutex<Option<Arc<TestFormatReadGate>>>>,
object_read_all_disks: Arc<StdMutex<Vec<String>>>,
format_data: Bytes,
read_all_data: Bytes,
@@ -7584,6 +7770,7 @@ mod tests {
rename_batch_result_limit: Arc::default(),
serve_rename_data: Arc::default(),
rename_data_disks: Arc::default(),
rename_data_reply_gate: Arc::default(),
object_read_all_disks: Arc::default(),
format_data,
read_all_data,
@@ -7711,6 +7898,11 @@ mod tests {
.lock()
.expect("rename data disks lock poisoned")
.push(request.disk);
let gate = peer.rename_data_reply_gate.lock().expect("rename reply gate lock").take();
if let Some(gate) = gate {
gate.entered.notify_one();
gate.release.cancelled().await;
}
let payload = serde_json::to_string(&RenameDataResp {
sign: Some(vec![1]),
..Default::default()
+69 -73
View File
@@ -44,7 +44,7 @@ use crate::{
};
use futures::{
future::join_all,
stream::{FuturesUnordered, StreamExt},
stream::{self, StreamExt},
};
use http::HeaderMap;
use rustfs_filemeta::FileInfo;
@@ -540,39 +540,39 @@ impl Sets {
// pub default_parity_count: usize,
// }
struct DelObj {
// set_idx: usize,
orig_idx: usize,
obj: ObjectToDelete,
#[derive(Default)]
struct SetDeleteBatch {
indices: Vec<usize>,
objects: Vec<ObjectToDelete>,
}
fn apply_delete_objects_results(
del_objects: &mut [DeletedObject],
del_errs: &mut [Option<Error>],
set_objects: &[DelObj],
dobjects: &[DeletedObject],
indices: &[usize],
deleted: Vec<DeletedObject>,
errs: Vec<Option<Error>>,
) {
let mut deleted = deleted.into_iter();
for (i, err) in errs.into_iter().enumerate() {
let obj = set_objects
let index = *indices
.get(i)
.expect("delete_objects should return errors aligned with input objects");
del_errs[obj.orig_idx] = err;
del_objects[obj.orig_idx] = dobjects
.get(i)
.expect("delete_objects should return objects aligned with input objects")
.clone();
del_errs[index] = err;
del_objects[index] = deleted
.next()
.expect("delete_objects should return objects aligned with input objects");
}
}
fn apply_delete_accounting_results(
accounting: &mut [Option<DeleteAccounting>],
set_objects: &[DelObj],
set_accounting: &[Option<DeleteAccounting>],
indices: &[usize],
set_accounting: Vec<Option<DeleteAccounting>>,
) {
for (obj, value) in set_objects.iter().zip(set_accounting.iter()) {
accounting[obj.orig_idx] = value.clone();
for (&index, value) in indices.iter().zip(set_accounting) {
accounting[index] = value;
}
}
@@ -583,43 +583,60 @@ impl Sets {
objects: Vec<ObjectToDelete>,
opts: ObjectOptions,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
let [first, rest @ ..] = objects.as_slice() else {
return (Vec::new(), Vec::new(), Vec::new());
};
if let [set] = self.disk_set.as_slice() {
return set.delete_objects_with_accounting(bucket, objects, opts).await;
}
let first_set = self.get_hashed_set_index(&first.object_name);
let Some(prefix_len) = rest
.iter()
.position(|object| self.get_hashed_set_index(&object.object_name) != first_set)
.map(|offset| offset + 1)
else {
return self.disk_set[first_set]
.delete_objects_with_accounting(bucket, objects, opts)
.await;
};
let mut del_objects = vec![DeletedObject::default(); objects.len()];
let mut del_errs = vec![None; objects.len()];
let mut accounting = vec![None; objects.len()];
let mut set_obj_map = HashMap::new();
for (i, obj) in objects.iter().enumerate() {
let idx = self.get_hashed_set_index(obj.object_name.as_str());
set_obj_map.entry(idx).or_insert_with(Vec::new).push(DelObj {
orig_idx: i,
obj: obj.clone(),
});
let mut objects = objects.into_iter().enumerate();
let (indices, first_objects) = objects.by_ref().take(prefix_len).unzip();
let mut batches = HashMap::new();
batches.insert(
first_set,
SetDeleteBatch {
indices,
objects: first_objects,
},
);
for (index, object) in objects {
let set_index = self.get_hashed_set_index(&object.object_name);
let batch = batches.entry(set_index).or_default();
batch.indices.push(index);
batch.objects.push(object);
}
let max_concurrent = set_obj_map.len().min(num_cpus::get()).max(1);
let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
let mut futures = FuturesUnordered::new();
let bucket = bucket.to_owned();
let mut pending = stream::iter(batches)
.map(|(set_index, batch)| {
let disks = self.get_disks(set_index);
let opts = opts.clone();
async move {
let (deleted, errors, accounting) = disks.delete_objects_with_accounting(bucket, batch.objects, opts).await;
(batch.indices, deleted, errors, accounting)
}
})
.buffer_unordered(self.ctx.worker_parallelism().get());
for (set_index, set_objects) in set_obj_map {
let disks = self.get_disks(set_index);
let objects = set_objects.iter().map(|entry| entry.obj.clone()).collect::<Vec<_>>();
let bucket = bucket.clone();
let opts = opts.clone();
let semaphore = semaphore.clone();
futures.push(async move {
let _permit = semaphore
.acquire_owned()
.await
.expect("delete_objects semaphore should remain open");
let (deleted, errors, accounting) = disks.delete_objects_with_accounting(&bucket, objects, opts).await;
(set_objects, deleted, errors, accounting)
});
}
while let Some((set_objects, deleted, errors, set_accounting)) = futures.next().await {
apply_delete_objects_results(&mut del_objects, &mut del_errs, &set_objects, &deleted, errors);
apply_delete_accounting_results(&mut accounting, &set_objects, &set_accounting);
while let Some((indices, deleted, errors, set_accounting)) = pending.next().await {
apply_delete_objects_results(&mut del_objects, &mut del_errs, &indices, deleted, errors);
apply_delete_accounting_results(&mut accounting, &indices, set_accounting);
}
(del_objects, del_errs, accounting)
@@ -1569,35 +1586,14 @@ mod tests {
let mut del_objects = vec![DeletedObject::default(); 3];
let mut del_errs = vec![None, None, None];
let early_batch = vec![DelObj {
orig_idx: 1,
obj: ObjectToDelete {
object_name: "second".to_string(),
..Default::default()
},
}];
let early_indices = [1];
let early_objects = vec![DeletedObject {
object_name: "second".to_string(),
found: true,
..Default::default()
}];
let late_batch = vec![
DelObj {
orig_idx: 2,
obj: ObjectToDelete {
object_name: "third".to_string(),
..Default::default()
},
},
DelObj {
orig_idx: 0,
obj: ObjectToDelete {
object_name: "first".to_string(),
..Default::default()
},
},
];
let late_indices = [2, 0];
let late_objects = vec![
DeletedObject {
object_name: "third".to_string(),
@@ -1611,12 +1607,12 @@ mod tests {
},
];
apply_delete_objects_results(&mut del_objects, &mut del_errs, &early_batch, &early_objects, vec![None]);
apply_delete_objects_results(&mut del_objects, &mut del_errs, &early_indices, early_objects, vec![None]);
apply_delete_objects_results(
&mut del_objects,
&mut del_errs,
&late_batch,
&late_objects,
&late_indices,
late_objects,
vec![Some(Error::other("third failed")), None],
);
+74
View File
@@ -58,6 +58,7 @@ type SharedDataMovementStream = Arc<Mutex<Box<dyn AsyncRead + Unpin + Send + Syn
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_DATA_MOVEMENT: &str = "data_movement";
const EVENT_DATA_MOVEMENT_MULTIPART_ABORT_FAILED: &str = "data_movement_multipart_abort_failed";
const EVENT_DATA_MOVEMENT_EQUIVALENT_TARGET: &str = "data_movement_equivalent_target";
const DATA_MOVEMENT_MULTIPART_ABORT_RETRY_ATTEMPTS: usize = 3;
const DATA_MOVEMENT_MULTIPART_ABORT_RETRY_DELAY_SECS: u64 = 60;
@@ -1636,6 +1637,57 @@ async fn find_data_movement_target_info(
}
}
/// The pool that already holds this exact source version, for a caller that
/// carries no decommission capacity owner: rebalance, and a decommission
/// without a capacity reservation. A run that stops after the target commit
/// and before the source cleanup leaves the version in both pools; without
/// this lookup the next run uploads every part again and learns of the copy
/// only when the create-only completion is refused. Only the strict identity
/// match settles here; the looser matches stay with the completion path. A
/// lookup that fails or finds no equivalent copy leaves the decision to the
/// normal path, which repeats the lookup and reports its own stage.
///
/// The caller removes the source on this answer, so the copy must also be on
/// a write quorum of the target set's drives. The object read behind the
/// identity match answers from read quorum; a copy held only there leaves the
/// decision to the normal path too, which needs a write quorum to start.
async fn find_equivalent_multipart_target(
store: &ECStore,
src_pool_idx: usize,
bucket: &str,
object_info: &ObjectInfo,
new_multipart_opts: &ObjectOptions,
compare_part_checksums: bool,
) -> Option<usize> {
let target_pool_idx = store
.select_data_movement_pool_idx(bucket, &object_info.name, -1, new_multipart_opts, false)
.await
.ok()?;
if !should_check_data_movement_resume_target(src_pool_idx, target_pool_idx) {
return None;
}
let target = find_data_movement_target_info(store, target_pool_idx, bucket, object_info)
.await
.ok()??;
if !is_equivalent_data_movement_object_identity(object_info, &target, true, compare_part_checksums) {
return None;
}
let object = encode_dir_object(object_info.name.as_str());
store
.pools
.get(target_pool_idx)?
.get_disks_by_key(object.as_str())
.holds_version_on_write_quorum(
bucket,
object.as_str(),
object_info.version_id.unwrap_or_else(uuid::Uuid::nil),
target.data_dir,
)
.await
.ok()?
.then_some(target_pool_idx)
}
/// How a data-movement copy settled on its target pool.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DataMovementCopy {
@@ -2012,6 +2064,28 @@ async fn migrate_object_inner(
)
})?;
}
} else if let Some(target_pool_idx) = find_equivalent_multipart_target(
store.as_ref(),
pool_idx,
&bucket,
&object_info,
&new_multipart_opts,
preserve_part_checksums,
)
.await
{
info!(
event = EVENT_DATA_MOVEMENT_EQUIVALENT_TARGET,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DATA_MOVEMENT,
result = "skipped",
operation = op_label,
bucket = bucket.as_str(),
object = object_info.name.as_str(),
target_pool = target_pool_idx,
"data movement multipart copy skipped for an equivalent target"
);
return Ok(DataMovementCopy::Committed);
}
let (res, target_pool_idx, expected_bucket_incarnation_id) = match store
.handle_new_multipart_upload_with_pool_idx(
+165 -55
View File
@@ -230,50 +230,126 @@ pub async fn lookup_degraded_bucket_usage_baseline(store: Arc<ECStore>, bucket:
.and_then(|cached| cached.degraded_baseline.get(bucket).copied())
}
/// Whether a cached usage snapshot can certify the current bucket's byte count.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BucketUsageStatus {
Certified(u64),
Pending(BucketUsagePendingReason),
Unavailable(BucketUsageUnavailableReason),
}
/// Why otherwise readable usage cannot yet certify this bucket.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BucketUsagePendingReason {
SnapshotNotReady,
BucketPending,
MissingBucketProof,
PreviousIncarnation,
}
/// Which part of a purported certification was invalid.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BucketUsageUnavailableReason {
InvalidSnapshotProof,
InvalidBucketIncarnation,
}
#[derive(Debug, Clone, Copy)]
enum SnapshotCertification {
Ready,
Pending,
Invalid,
}
/// An immutable sample with its bucket certification metadata checked once.
#[derive(Debug, Clone)]
struct UsageSnapshot {
info: DataUsageInfo,
can_certify_buckets: bool,
certification: SnapshotCertification,
}
impl UsageSnapshot {
fn new(info: DataUsageInfo) -> Self {
let pending = &info.usage_snapshot_pending_buckets;
let can_certify_buckets = info.is_complete_bucket_usage_snapshot()
&& !info.usage_snapshot_observational
&& info.scanner_cycle.is_some()
&& info.scanner_epoch.is_some()
&& u64::try_from(pending.len()).ok() == Some(info.usage_snapshot_pending_bucket_count)
&& match info.usage_snapshot_converged {
Some(true) => pending.is_empty(),
Some(false) => !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]),
None => false,
};
Self {
info,
can_certify_buckets,
}
fn new(info: DataUsageInfo, invalid_certification_claim: bool) -> Self {
let certification = if invalid_certification_claim
|| info.usage_snapshot_admin_projection
|| (info.usage_snapshot_complete && (info.usage_snapshot_partial || info.usage_snapshot_bootstrap_pending))
{
SnapshotCertification::Invalid
} else if info.usage_snapshot_bootstrap_pending || info.usage_snapshot_observational || !info.usage_snapshot_complete {
SnapshotCertification::Pending
} else if !info.is_complete_bucket_usage_snapshot() {
SnapshotCertification::Invalid
} else {
let pending = &info.usage_snapshot_pending_buckets;
if u64::try_from(pending.len()).ok() != Some(info.usage_snapshot_pending_bucket_count) {
SnapshotCertification::Invalid
} else {
match info.usage_snapshot_converged {
Some(true) if pending.is_empty() => SnapshotCertification::Ready,
Some(false) if !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]) => {
SnapshotCertification::Ready
}
None if pending.is_empty() => SnapshotCertification::Pending,
_ => SnapshotCertification::Invalid,
}
}
};
let certification = match certification {
SnapshotCertification::Ready if info.scanner_cycle.is_none() || info.scanner_epoch.is_none() => {
SnapshotCertification::Pending
}
other => other,
};
Self { info, certification }
}
fn clone_info(&self) -> DataUsageInfo {
self.info.clone()
}
fn certified_bucket_usage(&self, bucket: &str, incarnation: uuid::Uuid) -> Option<u64> {
if !self.can_certify_buckets
|| incarnation.is_nil()
|| self
.info
.usage_snapshot_pending_buckets
.binary_search_by(|pending| pending.as_str().cmp(bucket))
.is_ok()
{
return None;
fn bucket_usage_certification(&self, bucket: &str, incarnation: uuid::Uuid) -> BucketUsageStatus {
use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady};
use BucketUsageStatus::{Certified, Pending, Unavailable};
use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof};
if incarnation.is_nil() {
return Unavailable(InvalidBucketIncarnation);
}
match self.certification {
SnapshotCertification::Invalid => return Unavailable(InvalidSnapshotProof),
SnapshotCertification::Pending => return Pending(SnapshotNotReady),
SnapshotCertification::Ready => {}
}
if self
.info
.usage_snapshot_pending_buckets
.binary_search_by(|pending| pending.as_str().cmp(bucket))
.is_ok()
{
return Pending(BucketPending);
}
let Some((usage, proof)) = self
.info
.buckets_usage
.get(bucket)
.and_then(|usage| usage.bucket_incarnation.as_deref().map(|proof| (usage, proof)))
else {
return Pending(MissingBucketProof);
};
match uuid::Uuid::parse_str(proof) {
Ok(id) if id == incarnation => Certified(usage.size),
Ok(id) if !id.is_nil() => Pending(PreviousIncarnation),
_ => Unavailable(InvalidBucketIncarnation),
}
}
}
impl BucketUsageStatus {
fn certified_bytes(self) -> Option<u64> {
match self {
Self::Certified(bytes) => Some(bytes),
Self::Pending(_) | Self::Unavailable(_) => None,
}
let usage = self.info.buckets_usage.get(bucket)?;
let certified = uuid::Uuid::parse_str(usage.bucket_incarnation.as_deref()?).ok()?;
(certified == incarnation).then_some(usage.size)
}
}
@@ -330,6 +406,7 @@ fn cache_data_usage_snapshot_result<T>(
Some(match result {
Ok(LoadedUsageBaseline {
info,
invalid_certification_claim,
mut degraded_baseline,
observed_unavailable,
}) => {
@@ -352,7 +429,7 @@ fn cache_data_usage_snapshot_result<T>(
degraded_baseline.entry(bucket.clone()).or_insert(*size);
}
}
let snapshot = UsageSnapshot::new(info);
let snapshot = UsageSnapshot::new(info, invalid_certification_claim);
let projected = project(&snapshot);
*cache = Some(CachedDataUsageSnapshot {
snapshot: Some(snapshot),
@@ -1349,6 +1426,8 @@ pub async fn load_data_usage_from_backend(store: Arc<ECStore>) -> Result<DataUsa
/// baseline derived from it.
struct LoadedUsageBaseline {
info: DataUsageInfo,
/// Certification failures detected before normalization can demote the sample.
invalid_certification_claim: bool,
degraded_baseline: HashMap<String, u64>,
/// True when the observed snapshot could not be read (a transport error,
/// not absence): the cached loader then carries the previous refresh's
@@ -1365,7 +1444,8 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc<ECStore>) -> Resu
// The observed-newness gate below compares against the snapshot as
// persisted, before normalization demotes or discards anything.
let authoritative_as_persisted = loaded_snapshot.snapshot_identity();
let (info, mut degraded_baseline) = normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await;
let (info, mut degraded_baseline, invalid_certification_claim) =
normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await;
// A bucket without a converged scanner cycle behind it — a freshly joined
// replica whose every cycle is superseded by the sustained replication
@@ -1391,6 +1471,7 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc<ECStore>) -> Resu
Ok(LoadedUsageBaseline {
info,
invalid_certification_claim,
degraded_baseline,
observed_unavailable,
})
@@ -1570,10 +1651,12 @@ fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) {
}
}
fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) {
if data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot() {
fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) -> bool {
let invalid_complete_claim = data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot();
if invalid_complete_claim {
data_usage_info.usage_snapshot_complete = false;
}
invalid_complete_claim
}
fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo) {
@@ -1608,14 +1691,16 @@ fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo)
async fn normalize_loaded_data_usage(
mut data_usage_info: DataUsageInfo,
authoritative_format: bool,
) -> (DataUsageInfo, HashMap<String, u64>) {
) -> (DataUsageInfo, HashMap<String, u64>, bool) {
info!("Loaded data usage info from backend with {} buckets", data_usage_info.buckets_count);
if !authoritative_format {
data_usage_info.usage_snapshot_complete = false;
}
populate_backward_compatible_usage_maps(&mut data_usage_info);
validate_complete_usage_snapshot(&mut data_usage_info);
let invalid_complete_claim = validate_complete_usage_snapshot(&mut data_usage_info);
let invalid_certification_claim =
invalid_complete_claim || (authoritative_format && data_usage_info.usage_snapshot_observational);
let degraded_baseline = data_usage_info.bucket_sizes.clone();
discard_incomplete_bucket_usage(&mut data_usage_info);
@@ -1642,7 +1727,7 @@ async fn normalize_loaded_data_usage(
}
}
(data_usage_info, degraded_baseline)
(data_usage_info, degraded_baseline, invalid_certification_claim)
}
/// Load the persisted data usage snapshot through a small in-process cache.
@@ -1663,7 +1748,21 @@ pub async fn load_bucket_usage_from_backend_cached(
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<Option<u64>, Error> {
project_data_usage_from_backend_cached(store, |snapshot| snapshot.certified_bucket_usage(bucket, incarnation)).await
Ok(load_bucket_usage_certification_from_backend_cached(store, bucket, incarnation)
.await?
.certified_bytes())
}
/// Inspect the certification for one bucket in the cached authoritative usage snapshot.
///
/// # Errors
/// Returns an error when the snapshot cannot be read or decoded.
pub async fn load_bucket_usage_certification_from_backend_cached(
store: Arc<ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<BucketUsageStatus, Error> {
project_data_usage_from_backend_cached(store, |snapshot| snapshot.bucket_usage_certification(bucket, incarnation)).await
}
// Project under the cache guard so scalar readers never copy the snapshot's
@@ -1745,6 +1844,7 @@ async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<Da
.map(|info| LoadedUsageBaseline {
info,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
});
let loaded_at = tokio::time::Instant::now();
@@ -3970,7 +4070,7 @@ mod tests {
legacy.bucket_sizes.insert("large".to_string(), 0);
legacy.buckets_count = 2;
let (normalized, degraded_baseline) = normalize_loaded_data_usage(legacy, false).await;
let (normalized, degraded_baseline, _) = normalize_loaded_data_usage(legacy, false).await;
assert_eq!(normalized.buckets_count, 0);
assert!(normalized.buckets_usage.is_empty());
@@ -4017,7 +4117,7 @@ mod tests {
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
info.buckets_count = 2;
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert_eq!(normalized.buckets_count, 2);
assert!(normalized.usage_snapshot_complete);
@@ -4052,7 +4152,7 @@ mod tests {
info.bucket_sizes.insert("partial".to_string(), 196_870_144);
info.buckets_count = 1;
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert_eq!(normalized.buckets_count, 0);
assert!(!normalized.buckets_usage.contains_key("control"));
@@ -4067,7 +4167,7 @@ mod tests {
info.buckets_count = 2;
assert!(!data_usage_contains_bucket(&info, "missing"));
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
assert!(!normalized.usage_snapshot_complete);
assert!(normalized.buckets_usage.is_empty());
@@ -4076,7 +4176,7 @@ mod tests {
#[tokio::test]
async fn complete_empty_snapshot_remains_authoritative() {
let (normalized, _) = normalize_loaded_data_usage(
let (normalized, _, _) = normalize_loaded_data_usage(
DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
usage_snapshot_complete: true,
@@ -4341,7 +4441,7 @@ mod tests {
async fn partial_admin_observation_does_not_promote_a_legacy_baseline() {
let (legacy, observed) = usage_snapshots_with_missing_observed_set();
let (selected, current_format) = select_admin_data_usage_snapshot(legacy, false, Some(observed));
let (normalized, _) = normalize_loaded_data_usage(selected, current_format).await;
let (normalized, _, _) = normalize_loaded_data_usage(selected, current_format).await;
assert!(normalized.is_valid_partial_snapshot());
assert!(!normalized.is_complete_bucket_usage_snapshot());
@@ -4463,7 +4563,7 @@ mod tests {
async fn install_data_usage_snapshot_cache_for_test(info: DataUsageInfo, age: Duration) {
let degraded_baseline = info.bucket_sizes.clone();
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(info)),
snapshot: Some(UsageSnapshot::new(info, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now()
.checked_sub(age)
@@ -4499,6 +4599,7 @@ mod tests {
LoadedUsageBaseline {
degraded_baseline: info.bucket_sizes.clone(),
info,
invalid_certification_claim: false,
observed_unavailable: false,
}
}
@@ -4919,6 +5020,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: expected,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -5118,7 +5220,7 @@ mod tests {
observed.usage_snapshot_converged = Some(false);
observed.usage_snapshot_authoritative_baseline = Some(baseline.snapshot_identity());
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(observed)),
snapshot: Some(UsageSnapshot::new(observed, false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5157,7 +5259,7 @@ mod tests {
(loaded.scanner_epoch, loaded.scanner_cycle) = loaded_position;
let expected = if accept { &loaded } else { &previous };
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(previous.clone())),
snapshot: Some(UsageSnapshot::new(previous.clone(), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5184,7 +5286,7 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let expected = data_usage_info_for_test("bucket", 3, 42, SystemTime::UNIX_EPOCH + Duration::from_secs(2));
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(expected.clone())),
snapshot: Some(UsageSnapshot::new(expected.clone(), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::from([("bucket".to_string(), 42)]),
@@ -5230,7 +5332,7 @@ mod tests {
let now = SystemTime::now();
let future = now + rustfs_data_usage::USAGE_LAST_UPDATE_FUTURE_TOLERANCE + Duration::from_secs(60);
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future))),
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future), false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5329,7 +5431,10 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let refresh_generation = data_usage_snapshot_generation();
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::from([("observed-only".to_string(), 7_u64), ("covered".to_string(), 1)]),
@@ -5340,6 +5445,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::from([("covered".to_string(), 2_u64)]),
invalid_certification_claim: false,
observed_unavailable: true,
}),
loaded_at,
@@ -5363,7 +5469,10 @@ mod tests {
let loaded_at = tokio::time::Instant::now();
let refresh_generation = data_usage_snapshot_generation();
let mut cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -5375,6 +5484,7 @@ mod tests {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -6552,7 +6662,7 @@ mod tests {
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
*snapshot_cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(successor)),
snapshot: Some(UsageSnapshot::new(successor, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -6624,7 +6734,7 @@ mod tests {
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
*snapshot_cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(successor)),
snapshot: Some(UsageSnapshot::new(successor, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -6677,7 +6787,7 @@ mod tests {
};
let stale = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(stale)),
snapshot: Some(UsageSnapshot::new(stale, false)),
last_load_failed: false,
loaded_at: tokio::time::Instant::now(),
degraded_baseline: HashMap::new(),
@@ -8127,7 +8237,7 @@ mod tests {
// memory. Selecting that newer view must not erase local mutations.
let (selected, current_format) = select_admin_data_usage_snapshot(baseline, true, Some(observed));
assert_eq!(selected.scanner_cycle, Some(11));
let (selected, _) = normalize_loaded_data_usage(selected, current_format).await;
let (selected, _, _) = normalize_loaded_data_usage(selected, current_format).await;
let mut distributed = selected.clone();
apply_bucket_usage_memory_overlay_if_authoritative(&mut distributed, false).await;
assert_eq!((distributed.objects_total_count, distributed.objects_total_size), (2, 20));
@@ -82,10 +82,9 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
assert!(reject_admin_usage_projection(&snapshot).is_err());
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
assert!(
UsageSnapshot::new(snapshot)
.certified_bucket_usage("bucket", incarnation)
.is_none()
assert_eq!(
UsageSnapshot::new(snapshot, false).bucket_usage_certification("bucket", incarnation),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
}
@@ -381,10 +380,9 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
assert!(
UsageSnapshot::new(second)
.certified_bucket_usage(bucket, new_identity)
.is_none()
assert_eq!(
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
let quota = load_data_usage_from_backend_cached(store.clone())
.await
@@ -20,7 +20,7 @@ fn scalar_projection_borrows_snapshot_and_preserves_unknown_and_zero() {
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
let cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(info)),
snapshot: Some(UsageSnapshot::new(info, false)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -66,7 +66,10 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
);
cache = Some(CachedDataUsageSnapshot {
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH))),
snapshot: Some(UsageSnapshot::new(
data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
false,
)),
last_load_failed: false,
loaded_at,
degraded_baseline: HashMap::new(),
@@ -78,6 +81,7 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
Ok(LoadedUsageBaseline {
info: data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
loaded_at,
@@ -99,6 +103,7 @@ fn projected_publication_moves_bucket_maps_into_cache() {
Ok(LoadedUsageBaseline {
info,
degraded_baseline: HashMap::new(),
invalid_certification_claim: false,
observed_unavailable: false,
}),
tokio::time::Instant::now(),
@@ -167,41 +172,106 @@ fn projected_publication_moves_bucket_maps_into_cache() {
}
#[test]
fn certified_bucket_usage_rejects_unproven_and_pending_data() {
fn bucket_usage_certification_distinguishes_pending_and_unavailable_proof() {
use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady};
use BucketUsageStatus::{Certified, Pending, Unavailable};
use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof};
let id = uuid::Uuid::from_u128(7);
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
info.usage_snapshot_converged = Some(true);
info.scanner_cycle = Some(1);
info.scanner_epoch = Some(1);
info.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some(id.to_string());
let certified = UsageSnapshot::new(info.clone());
assert_eq!(certified.certified_bucket_usage("known", id), Some(42));
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::from_u128(8)), None);
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::nil()), None);
let mut legacy = info.clone();
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = None;
assert_eq!(UsageSnapshot::new(legacy.clone()).certified_bucket_usage("known", id), None);
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some("corrupt".into());
assert_eq!(UsageSnapshot::new(legacy).certified_bucket_usage("known", id), None);
let mut pending = info.clone();
pending.usage_snapshot_converged = Some(false);
pending.usage_snapshot_pending_buckets = vec!["other".into()];
pending.usage_snapshot_pending_bucket_count = 1;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), Some(42));
pending.usage_snapshot_pending_buckets = vec!["known".into()];
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_bucket_count = 0;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_buckets = vec!["z".into(), "a".into()];
pending.usage_snapshot_pending_bucket_count = 2;
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
pending.usage_snapshot_pending_buckets = vec!["other".into(), "other".into()];
assert_eq!(UsageSnapshot::new(pending).certified_bucket_usage("known", id), None);
let mut observational = info.clone();
observational.usage_snapshot_observational = true;
assert_eq!(UsageSnapshot::new(observational).certified_bucket_usage("known", id), None);
info.usage_snapshot_converged = None;
assert_eq!(UsageSnapshot::new(info).certified_bucket_usage("known", id), None);
info.buckets_usage
.get_mut("known")
.expect("fixture bucket")
.bucket_incarnation = Some(id.to_string());
let certified = UsageSnapshot::new(info.clone(), false);
assert_eq!(certified.bucket_usage_certification("known", id), Certified(42));
assert_eq!(certified.bucket_usage_certification("missing", id), Pending(MissingBucketProof));
assert_eq!(
certified.bucket_usage_certification("known", uuid::Uuid::from_u128(8)),
Pending(PreviousIncarnation)
);
assert_eq!(
certified.bucket_usage_certification("known", uuid::Uuid::nil()),
Unavailable(InvalidBucketIncarnation)
);
for (proof, expected) in [
(None, Pending(MissingBucketProof)),
(Some("corrupt".into()), Unavailable(InvalidBucketIncarnation)),
(Some(uuid::Uuid::nil().to_string()), Unavailable(InvalidBucketIncarnation)),
] {
let mut sample = info.clone();
sample
.buckets_usage
.get_mut("known")
.expect("fixture bucket")
.bucket_incarnation = proof;
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
}
for (names, count, expected) in [
(vec!["other"], 1, Certified(42)),
(vec!["known"], 1, Pending(BucketPending)),
(vec!["known"], 0, Unavailable(InvalidSnapshotProof)),
(vec!["z", "a"], 2, Unavailable(InvalidSnapshotProof)),
(vec!["other", "other"], 2, Unavailable(InvalidSnapshotProof)),
(vec![], 0, Unavailable(InvalidSnapshotProof)),
] {
let mut sample = info.clone();
sample.usage_snapshot_converged = Some(false);
sample.usage_snapshot_pending_buckets = names.into_iter().map(str::to_owned).collect();
sample.usage_snapshot_pending_bucket_count = count;
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
}
for sample in [
DataUsageInfo {
usage_snapshot_partial: true,
..info.clone()
},
DataUsageInfo {
scanner_epoch: None,
usage_snapshot_converged: Some(false),
usage_snapshot_pending_buckets: vec!["known".into()],
..info.clone()
},
] {
assert_eq!(
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
Unavailable(InvalidSnapshotProof)
);
}
let bootstrap = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH),
scanner_epoch: Some(1),
usage_snapshot_converged: Some(false),
usage_snapshot_bootstrap_pending: true,
..Default::default()
};
for sample in [
DataUsageInfo::default(),
bootstrap,
DataUsageInfo {
usage_snapshot_observational: true,
..info.clone()
},
DataUsageInfo {
scanner_epoch: None,
..info.clone()
},
DataUsageInfo {
usage_snapshot_converged: None,
..info
},
] {
assert_eq!(
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
Pending(SnapshotNotReady)
);
}
}
#[tokio::test]
@@ -296,12 +366,55 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
.expect("persist malformed certification evidence");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_from_backend_cached(store.clone(), "known", incarnation)
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("read snapshot without accepting malformed certification"),
None
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
assert_eq!(persisted_bucket_usage(store.clone(), "known").await, Some(84));
info.scanner_cycle = Some(3);
info.usage_snapshot_converged = Some(true);
info.usage_snapshot_pending_bucket_count = 0;
info.usage_snapshot_pending_buckets.clear();
info.buckets_count += 1;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&info).expect("encode invalid bucket count"),
)
.await
.expect("persist malformed completeness claim");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("classify demoted completeness claim"),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
let raw = load_data_usage_from_backend_cached(store.clone())
.await
.expect("read normalized usage");
assert!(!raw.usage_snapshot_complete);
assert!(raw.buckets_usage.is_empty());
info.scanner_cycle = Some(4);
info.buckets_count -= 1;
info.usage_snapshot_observational = true;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&info).expect("encode observational sample in primary slot"),
)
.await
.expect("persist wrong snapshot kind");
invalidate_data_usage_snapshot_cache().await;
assert_eq!(
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
.await
.expect("classify wrong snapshot kind"),
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
);
invalidate_data_usage_snapshot_cache().await;
if let Some(cancel) = store.ctx.background_cancel_token() {
cancel.cancel();
+3 -3
View File
@@ -645,7 +645,7 @@ impl LocalDiskWrapper {
get_max_timeout_duration()
};
let observed = run_owned_mutation(external_guard, move || async move {
let mut preflight_rejection = None;
let mut rejected_before_publication = false;
let result = operation
.track_disk_health_mutation(
"rename_data",
@@ -661,7 +661,7 @@ impl LocalDiskWrapper {
namespace_owner,
))
.await;
preflight_rejection = observed.preflight_rejection;
rejected_before_publication = observed.rejected_before_publication();
observed.result
},
timeout_duration,
@@ -670,7 +670,7 @@ impl LocalDiskWrapper {
// Health tracking must observe the real disk error, not an Ok tuple.
Ok(super::RenameDataObservation {
result,
preflight_rejection,
rejected_before_publication,
})
})
.await;
+42 -6
View File
@@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub(in crate::disk) use self::commit::LocalRenamePreflightRejection;
#[cfg(test)]
#[path = "local/read_path_tests.rs"]
mod read_path_tests;
@@ -978,7 +977,7 @@ fn restore_part_transaction_file(current: &Path, backup: &Path, absent: &Path, r
}
}
#[cfg(test)]
#[cfg(all(test, not(windows)))]
async fn write_metadata_rollback_backup(object_dir: &Path, rollback_dir: Uuid, data: &[u8]) -> Result<()> {
write_delete_rollback_file(
object_dir.parent().unwrap_or(object_dir),
@@ -9324,10 +9323,29 @@ impl LocalDisk {
}
let path = trash.join(name);
let result = async {
if entry.file_type().await?.is_dir() {
fs::remove_dir_all(&path).await
} else {
fs::remove_file(&path).await
let is_dir = entry.file_type().await?.is_dir();
#[cfg(windows)]
{
// Competing recursive deletions can deny each other's directory
// handles. Keep ownership until the blocking operation returns.
let lease = os::acquire_namespace_mutation_lease_with_owner(&path, None).await;
let path = path.clone();
os::run_blocking_namespace_operation(lease, move || {
if is_dir {
std::fs::remove_dir_all(path)
} else {
std::fs::remove_file(path)
}
})
.await
}
#[cfg(not(windows))]
{
if is_dir {
fs::remove_dir_all(&path).await
} else {
fs::remove_file(&path).await
}
}
}
.await;
@@ -22915,6 +22933,22 @@ mod test {
.expect("new tmp data should be written");
let dst_meta_parent = dir.path().join(bucket).join(object);
os::fsync_dir_recorder::set_grouped_failure(&dst_meta_parent, io::ErrorKind::PermissionDenied);
let disk_permits = Arc::clone(&disk.file_sync_permits);
let initial_permits = disk_permits.available_permits();
let (permit_probe_tx, mut permit_probe_rx) = tokio::sync::oneshot::channel();
let canonical_parent = dir
.path()
.canonicalize()
.expect("canonical fixture directory")
.join(bucket)
.join(object);
let _probe = os::prepared_publication_test_hooks::install_at(
os::prepared_publication_test_hooks::Stage::DirFsync,
&canonical_parent,
move || {
let _ = permit_probe_tx.send(disk_permits.available_permits());
},
);
let new_fi = test_file_info(object, version_id, Some(new_data_dir), None);
let err = disk
@@ -22923,6 +22957,8 @@ mod test {
.expect_err("grouped dst dir fsync failure must fail the fresh PUT");
assert_eq!(err, DiskError::FileAccessDenied);
assert_eq!(permit_probe_rx.try_recv().expect("observe the grouped syscall"), initial_permits - 1);
assert_eq!(disk.file_sync_permits.available_permits(), initial_permits);
assert!(
!dst_meta_parent.join(STORAGE_FORMAT_FILE).exists(),
"fresh PUT rollback must remove the committed xl.meta after grouped dst dir fsync failure"
+13 -5
View File
@@ -540,7 +540,7 @@ async fn prepare_rename_commit_and_destination_metadata(
/// Proof produced only when the local rename returns at an existing access
/// preflight, before metadata, backups, or object data can be published.
#[derive(Debug)]
pub(in crate::disk) struct LocalRenamePreflightRejection(());
struct LocalRenamePreflightRejection(());
#[derive(Default)]
pub(super) struct RenameDataState {
@@ -2152,9 +2152,17 @@ impl LocalDisk {
&& let Some(parent) = dst_file_path.parent()
{
let fsync_started = rustfs_io_metrics::put_stage_timer();
if let Err(err) =
os::fsync_commit_directory(parent, &commit.directory_guard, commit.mutation_lease.clone(), None).await
{
let fsync_result = async {
let admission = if dst_dir_group_commit {
Some(os::acquire_file_sync_admission(self.file_sync_permits.clone()).await?)
} else {
None
};
os::fsync_commit_directory(parent, &commit.directory_guard, commit.mutation_lease.clone(), admission.as_ref())
.await
}
.await;
if let Err(err) = fsync_result {
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_DST_DIR_FSYNC,
fsync_started,
@@ -2939,7 +2947,7 @@ impl LocalDisk {
.await;
super::super::RenameDataObservation {
result,
preflight_rejection: state.preflight_rejection,
rejected_before_publication: state.preflight_rejection.is_some(),
}
}
}
@@ -2599,6 +2599,7 @@ mod tests {
assert!(!disk.root.join(RUSTFS_META_TMP_BUCKET).join(raw_path).exists());
}
#[cfg(unix)]
async fn assert_cold_recovery_after_present_head_failure(
fixture: &mut Fixture,
publication: &PublicationIdentity,
@@ -755,7 +755,7 @@ impl SourceStore {
.await?;
Ok(state)
}
#[cfg(test)]
#[cfg(all(test, unix))]
pub async fn write_owned_backup(&self, owner: Uuid, target: bool, bytes: &[u8]) -> Result<()> {
if owner.is_nil() {
return Err(DiskError::FileCorrupt);
+13 -16
View File
@@ -130,24 +130,28 @@ pub(crate) struct RenameDataGuards {
pub(crate) scanner_publication_lease_token: Option<Uuid>,
pub(crate) external_guard: Option<Arc<dyn Send + Sync>>,
pub(crate) namespace_owner: Option<Arc<dyn Send + Sync>>,
pub(crate) dispatch_deadline: Option<RenameDispatchDeadline>,
}
/// Local preflight evidence stays outside DiskAPI and the RPC response format.
/// The fanout publishes this deadline once enough disks have committed.
pub(crate) type RenameDispatchDeadline = tokio::sync::watch::Receiver<Option<tokio::time::Instant>>;
/// Pre-dispatch evidence stays outside DiskAPI and the RPC response format.
pub(crate) struct RenameDataObservation {
pub(crate) result: Result<RenameDataResp>,
preflight_rejection: Option<local::LocalRenamePreflightRejection>,
pub(crate) rejected_before_publication: bool,
}
impl RenameDataObservation {
fn unknown(result: Result<RenameDataResp>) -> Self {
pub(crate) fn unknown(result: Result<RenameDataResp>) -> Self {
Self {
result,
preflight_rejection: None,
rejected_before_publication: false,
}
}
pub(crate) fn rejected_before_publication(&self) -> bool {
self.result.is_err() && self.preflight_rejection.is_some()
self.result.is_err() && self.rejected_before_publication
}
}
@@ -1388,18 +1392,11 @@ impl Disk {
.rename_data_observed_with_guards(src_volume, src_path, fi, dst_volume, dst_path, guards)
.await
}
Disk::Remote(remote_disk) => RenameDataObservation::unknown(
Disk::Remote(remote_disk) => {
remote_disk
.rename_data_borrowed_with_fence(
src_volume,
src_path,
fi,
dst_volume,
dst_path,
guards.scanner_publication_lease_token,
)
.await,
),
.rename_data_observed(src_volume, src_path, fi, dst_volume, dst_path, guards)
.await
}
}
}
+131 -47
View File
@@ -1007,14 +1007,15 @@ impl OpenedDstDirFsyncGroup {
}
struct DstDirFsyncWaiter {
namespace_owner: Option<Arc<dyn Send + Sync>>,
resource_unit: Option<super::io_admission::ResourceIoUnit>,
owner: DstDirFsyncOwner,
result_tx: oneshot::Sender<SharedDstDirFsyncResult>,
}
#[derive(Default)]
struct DstDirFsyncOwner {
_namespace: Option<Arc<dyn Send + Sync>>,
_resource: Option<super::io_admission::ResourceIoUnit>,
disk_permit: Option<Arc<OwnedSemaphorePermit>>,
}
#[derive(Clone)]
@@ -1073,6 +1074,7 @@ impl DstDirFsyncGroupCommit {
&self,
opened: OpenedDstDirFsyncGroup,
namespace_owner: Option<Arc<dyn Send + Sync>>,
admission: Option<&FileSyncAdmission>,
) -> io::Result<(oneshot::Receiver<SharedDstDirFsyncResult>, Option<Arc<DstDirFsyncGroup>>)> {
let (result_tx, result_rx) = oneshot::channel();
let mut registry = self.inner.lock();
@@ -1105,8 +1107,11 @@ impl DstDirFsyncGroupCommit {
let mut group_state = group.inner.lock();
group_state.pending.push_back(DstDirFsyncWaiter {
result_tx,
namespace_owner,
resource_unit: super::io_admission::current_resource_unit(),
owner: DstDirFsyncOwner {
_namespace: namespace_owner,
_resource: super::io_admission::current_resource_unit(),
disk_permit: admission.map(|admission| Arc::clone(&admission.disk_permit)),
},
});
let start_worker = !group_state.worker_running;
if start_worker {
@@ -1158,7 +1163,7 @@ impl DstDirFsyncGroupCommit {
&self,
dir: &Path,
) -> io::Result<(oneshot::Receiver<SharedDstDirFsyncResult>, Option<Arc<DstDirFsyncGroup>>)> {
self.enqueue_opened(OpenedDstDirFsyncGroup::open(dir)?, None)
self.enqueue_opened(OpenedDstDirFsyncGroup::open(dir)?, None, None)
}
}
@@ -1224,7 +1229,10 @@ impl Drop for DstDirFsyncWorkerGuard {
}
}
fn run_dst_dir_fsync_group_worker(group: Arc<DstDirFsyncGroup>) -> impl std::future::Future<Output = ()> {
fn run_dst_dir_fsync_group_worker(
group: Arc<DstDirFsyncGroup>,
global_permits: &Semaphore,
) -> impl std::future::Future<Output = ()> + '_ {
// Capture before spawning: shutdown may drop the future without polling it.
let worker_guard = DstDirFsyncWorkerGuard {
group: group.clone(),
@@ -1253,20 +1261,25 @@ fn run_dst_dir_fsync_group_worker(group: Arc<DstDirFsyncGroup>) -> impl std::fut
#[cfg(test)]
fsync_dir_recorder::record_grouped(&group.dir, batch.len());
let namespace_owners = batch
let owners: Vec<_> = batch
.iter_mut()
.filter_map(|waiter| {
let namespace = waiter.namespace_owner.take();
let resource = waiter.resource_unit.take();
(namespace.is_some() || resource.is_some()).then_some(DstDirFsyncOwner {
_namespace: namespace,
_resource: resource,
})
let owner = std::mem::take(&mut waiter.owner);
(owner._namespace.is_some() || owner._resource.is_some() || owner.disk_permit.is_some()).then_some(owner)
})
.collect();
let result = fsync_open_dst_dir_group(&group, namespace_owners)
.await
.map_err(SharedDstDirFsyncError::from_error);
let result = async {
// The waiters already hold their disk admission. Reserve one global slot
// per physical sync, keeping it with the worker so shutdown can release it.
let _global_permit = if owners.iter().any(|owner| owner.disk_permit.is_some()) {
Some(acquire_global_file_sync_permit(global_permits).await?)
} else {
None
};
fsync_open_dst_dir_group(&group, owners).await
}
.await
.map_err(SharedDstDirFsyncError::from_error);
let batch_len = batch.len();
DST_DIR_FSYNC_GROUP_COMMIT.complete_batch(batch_len);
worker_guard.in_flight = 0;
@@ -1300,7 +1313,7 @@ async fn fsync_dst_dir_group_commit_with_enabled(
enabled: bool,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> io::Result<()> {
fsync_dst_dir_group_commit_opened(dir.as_ref(), enabled, namespace_owner, None).await
fsync_dst_dir_group_commit_opened(dir.as_ref(), enabled, namespace_owner, None, None).await
}
async fn fsync_dst_dir_group_commit_opened(
@@ -1308,6 +1321,7 @@ async fn fsync_dst_dir_group_commit_opened(
enabled: bool,
namespace_owner: Option<Arc<dyn Send + Sync>>,
opened: Option<Arc<std::fs::File>>,
admission: Option<&FileSyncAdmission>,
) -> io::Result<()> {
if !enabled {
if let Some(file) = opened {
@@ -1333,9 +1347,9 @@ async fn fsync_dst_dir_group_commit_opened(
})
.await
.map_err(|err| io::Error::other(format!("blocking dst dir group open failed: {err}")))??;
let (result_rx, worker) = DST_DIR_FSYNC_GROUP_COMMIT.enqueue_opened(opened, namespace_owner)?;
let (result_rx, worker) = DST_DIR_FSYNC_GROUP_COMMIT.enqueue_opened(opened, namespace_owner, admission)?;
if let Some(group) = worker {
tokio::spawn(run_dst_dir_fsync_group_worker(group));
tokio::spawn(run_dst_dir_fsync_group_worker(group, &FILE_SYNC_PERMITS));
}
match result_rx.await {
@@ -1415,9 +1429,8 @@ pub(crate) async fn fsync_commit_directory(
.ok_or_else(|| io::Error::other("commit directory was not published"))?
.file
.clone();
if !dst_dir_fsync_group_commit_enabled()
&& let Some(admission) = admission
{
let grouped = dst_dir_fsync_group_commit_enabled();
if !grouped && let Some(admission) = admission {
let dir = dir.to_path_buf();
return run_blocking_namespace_file_sync_operation(lease, admission, move || {
#[cfg(test)]
@@ -1426,7 +1439,7 @@ pub(crate) async fn fsync_commit_directory(
})
.await;
}
fsync_dst_dir_group_commit_opened(dir, dst_dir_fsync_group_commit_enabled(), Some(lease), Some(file)).await
fsync_dst_dir_group_commit_opened(dir, grouped, Some(lease), Some(file), admission).await
}
#[cfg(not(target_os = "linux"))]
{
@@ -1453,7 +1466,7 @@ pub(crate) async fn fsync_dst_dir_group_commit_or_namespace_file_sync_limit(
admission: &FileSyncAdmission,
) -> io::Result<()> {
if dst_dir_fsync_group_commit_enabled() {
fsync_dst_dir_group_commit_with_enabled(dir, true, Some(lease)).await
fsync_dst_dir_group_commit_opened(dir.as_ref(), true, Some(lease), None, Some(admission)).await
} else {
fsync_dir_with_namespace_file_sync_limit(dir, lease, admission).await
}
@@ -2328,9 +2341,10 @@ static FSYNC_RUNTIME: LazyLock<Option<tokio::runtime::Runtime>> = LazyLock::new(
if threads <= 1 {
return None;
}
let workers = crate::runtime::detect_worker_parallelism().get().min(8);
let mut builder = tokio::runtime::Builder::new_multi_thread();
builder
.worker_threads(num_cpus::get().min(8))
.worker_threads(workers)
.max_blocking_threads(threads)
.thread_name("rustfs-fsync")
.thread_stack_size(512 * 1024)
@@ -2666,7 +2680,7 @@ fn default_global_file_sync_limit(cpu_count: usize, max_blocking_threads: usize)
fn global_file_sync_limit() -> usize {
let max_blocking_threads =
rustfs_utils::get_env_usize(rustfs_config::ENV_MAX_BLOCKING_THREADS, rustfs_config::DEFAULT_MAX_BLOCKING_THREADS);
default_global_file_sync_limit(num_cpus::get(), max_blocking_threads)
default_global_file_sync_limit(crate::runtime::detect_worker_parallelism().get(), max_blocking_threads)
}
#[cfg(test)]
@@ -2737,7 +2751,7 @@ impl DiskBlockingLane {
#[derive(Default)]
struct DiskBlockingQueueState {
jobs: VecDeque<Box<dyn FnOnce() + Send>>,
#[cfg(test)]
#[cfg(all(test, unix))]
submitted_jobs: usize,
active_workers: usize,
idle_workers: usize,
@@ -2865,7 +2879,7 @@ impl DiskBlockingQueue {
let should_spawn = {
let mut state = self.lane(lane).state.lock();
state.jobs.push_back(job);
#[cfg(test)]
#[cfg(all(test, unix))]
{
state.submitted_jobs += 1;
}
@@ -2883,7 +2897,7 @@ impl DiskBlockingQueue {
}
}
#[cfg(test)]
#[cfg(all(test, unix))]
pub(crate) fn submitted_jobs_for_test(&self) -> usize {
self.lanes.iter().map(|lane| lane.state.lock().submitted_jobs).sum()
}
@@ -3312,8 +3326,8 @@ static DISK_METADATA_MUTATION_LOCKS: LazyLock<ShardedPathLockRegistry<NamespaceM
#[derive(Clone)]
pub(crate) struct MetadataMutationLockHandle(Arc<NamespaceMutationLock>);
#[cfg(all(test, unix))]
impl MetadataMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
@@ -3323,8 +3337,8 @@ impl MetadataMutationLockHandle {
#[derive(Clone)]
pub(in crate::disk) struct NamespaceMutationLockHandle(Arc<NamespaceMutationLock>);
#[cfg(all(test, unix))]
impl NamespaceMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
@@ -5845,15 +5859,7 @@ async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: S
global_permits: &Semaphore,
operation: impl FnOnce(&dyn Fn() -> bool) -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
let wait_started = rustfs_io_metrics::put_stage_timer();
let global_permit = global_permits
.acquire()
.await
.map_err(|_| io::Error::other("global file sync concurrency limiter closed"))?;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_GLOBAL_FILE_SYNC_PERMIT_WAIT,
wait_started,
);
let global_permit = acquire_global_file_sync_permit(global_permits).await?;
let disk_permit = admission.disk_permit.clone();
let queue = Arc::clone(&lease.blocking_queue);
let result = queue
@@ -5867,6 +5873,19 @@ async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: S
result
}
async fn acquire_global_file_sync_permit(global_permits: &Semaphore) -> io::Result<SemaphorePermit<'_>> {
let wait_started = rustfs_io_metrics::put_stage_timer();
let permit = global_permits
.acquire()
.await
.map_err(|_| io::Error::other("global file sync concurrency limiter closed"))?;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_GLOBAL_FILE_SYNC_PERMIT_WAIT,
wait_started,
);
Ok(permit)
}
pub(crate) async fn fsync_dir_with_namespace_file_sync_limit(
dir: impl AsRef<Path>,
lease: Arc<NamespaceMutationLease>,
@@ -12306,11 +12325,20 @@ mod tests {
let second_owner = second_ctx.begin_namespace_commit();
let first_probe = Arc::downgrade(&first_owner);
let second_probe = Arc::downgrade(&second_owner);
let disk_permits = Arc::new(Semaphore::new(2));
let first_admission = acquire_file_sync_admission(disk_permits.clone())
.await
.expect("first disk slot");
let second_admission = acquire_file_sync_admission(disk_permits.clone())
.await
.expect("second disk slot");
let global_permits = Arc::new(Semaphore::new(1));
let (first_rx, group) = with_background_resource_unit(resources[0].acquire().await, async {
DST_DIR_FSYNC_GROUP_COMMIT
.enqueue_opened(
OpenedDstDirFsyncGroup::open(&dir).expect("open first waiter directory"),
Some(first_owner),
Some(&first_admission),
)
.expect("queue first real waiter")
})
@@ -12321,6 +12349,7 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(&dir).expect("open second waiter directory"),
Some(second_owner),
Some(&second_admission),
)
.expect("queue second real waiter")
})
@@ -12334,12 +12363,18 @@ mod tests {
let _ = entered_tx.send(());
let _ = release_rx.recv();
});
let worker = tokio::spawn(run_dst_dir_fsync_group_worker(group.clone()));
drop((first_admission, second_admission));
let worker = tokio::spawn({
let group = group.clone();
let global_permits = global_permits.clone();
async move { run_dst_dir_fsync_group_worker(group, &global_permits).await }
});
tokio::time::timeout(Duration::from_secs(5), entered_rx)
.await
.expect("batch must reach its physical fsync")
.expect("physical fsync entry");
assert_eq!(fsync_dir_recorder::grouped_batch_sizes(&dir), vec![2]);
assert_eq!(global_permits.available_permits(), 0, "one physical sync must reserve the global slot");
assert!(
group.inner.lock().pending.is_empty(),
"both waiters were transferred into the physical batch"
@@ -12353,6 +12388,7 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(&dir).expect("open queued waiter directory"),
Some(queued_owner),
None,
)
.expect("queue a waiter after the physical batch was frozen")
})
@@ -12372,6 +12408,8 @@ mod tests {
let first_pending = first_ctx.namespace_commits_pending() && first_probe.upgrade().is_some();
let second_pending = second_ctx.namespace_commits_pending() && second_probe.upgrade().is_some();
let retained_resources = resources.each_ref().map(|gate| gate.snapshot().active);
let retained_disk_permits = disk_permits.available_permits();
let released_global_permits = global_permits.available_permits();
let generations = (first_ctx.namespace_commit_generation(), second_ctx.namespace_commit_generation());
drop(release_tx);
tokio::time::timeout(Duration::from_secs(5), async {
@@ -12401,6 +12439,38 @@ mod tests {
assert!(!second_ctx.namespace_commits_pending());
assert!(first_ctx.namespace_commit_generation() > generations.0);
assert!(second_ctx.namespace_commit_generation() > generations.1);
assert_eq!(retained_disk_permits, 0, "both disk slots must survive abort while the syscall runs");
assert_eq!(released_global_permits, 1, "abort must restore capacity for other disks");
assert_eq!(disk_permits.available_permits(), 2, "both disk slots return after fsync");
}
#[cfg(unix)]
#[tokio::test]
#[serial_test::serial(dst_dir_fsync_group_commit)]
async fn grouped_fsync_propagates_closed_global_limit_without_syncing() {
let directory = tempdir().expect("fixture directory");
let disk_permits = Arc::new(Semaphore::new(1));
let admission = acquire_file_sync_admission(disk_permits.clone()).await.expect("disk slot");
let (result, worker) = DST_DIR_FSYNC_GROUP_COMMIT
.enqueue_opened(
OpenedDstDirFsyncGroup::open(directory.path()).expect("open fixture"),
None,
Some(&admission),
)
.expect("enqueue waiter");
drop(admission);
let global_permits = Semaphore::new(0);
global_permits.close();
run_dst_dir_fsync_group_worker(worker.expect("first waiter starts worker"), &global_permits).await;
let error = result
.await
.expect("worker reports completion")
.expect_err("closed limiter must reject fsync");
assert_eq!(&*error.message, "global file sync concurrency limiter closed");
assert!(!fsync_dir_recorder::was_fsynced(directory.path()));
assert_eq!(disk_permits.available_permits(), 1);
assert_eq!(DST_DIR_FSYNC_GROUP_COMMIT.counts_for_test(), (0, 0));
}
#[cfg(unix)]
@@ -12416,10 +12486,11 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(temp_dir.path()).expect("open queued waiter directory"),
Some(owner),
None,
)
.expect("queue a real waiter");
let group = group.expect("first waiter starts the group");
let worker = run_dst_dir_fsync_group_worker(group.clone());
let worker = run_dst_dir_fsync_group_worker(group.clone(), &FILE_SYNC_PERMITS);
assert!(ctx.namespace_commits_pending());
drop(worker);
assert!(rx.await.is_err(), "shutdown before first poll must release the waiter");
@@ -12496,9 +12567,12 @@ mod tests {
.enqueue_for_test(temp_dir.path())
.expect("enqueue old group");
let old_group = old_worker.expect("old group starts a worker");
tokio::time::timeout(Duration::from_secs(5), run_dst_dir_fsync_group_worker(old_group.clone()))
.await
.expect("old worker must finish its actual fsync");
tokio::time::timeout(
Duration::from_secs(5),
run_dst_dir_fsync_group_worker(old_group.clone(), &FILE_SYNC_PERMITS),
)
.await
.expect("old worker must finish its actual fsync");
assert!(old_rx.await.expect("old worker reports completion").is_ok());
assert!(fsync_dir_recorder::was_fsynced(temp_dir.path()));
assert_eq!(fsync_dir_recorder::grouped_batch_sizes(temp_dir.path()), vec![1]);
@@ -12512,11 +12586,12 @@ mod tests {
.enqueue_opened(
OpenedDstDirFsyncGroup::open(temp_dir.path()).expect("open successor directory"),
Some(owner),
None,
)
.expect("enqueue successor owner");
let successor = successor_worker.expect("successor starts a new group");
assert!(!Arc::ptr_eq(&old_group, &successor));
let worker = run_dst_dir_fsync_group_worker(successor.clone());
let worker = run_dst_dir_fsync_group_worker(successor.clone(), &FILE_SYNC_PERMITS);
// The stale Arc represents W1 resuming after another worker removed G.
DST_DIR_FSYNC_GROUP_COMMIT.remove_idle_group(&old_group);
assert!(ctx.namespace_commits_pending());
@@ -14665,8 +14740,17 @@ mod tests {
q_fsync
.run_fsync_cancellable(|is_cancelled| {
assert!(!is_cancelled());
if FSYNC_RUNTIME.is_some() {
let blocking_threads = rustfs_utils::get_env_usize(
rustfs_config::ENV_FSYNC_BLOCKING_THREADS,
rustfs_config::DEFAULT_FSYNC_BLOCKING_THREADS,
);
if blocking_threads > 1 {
let runtime = FSYNC_RUNTIME.as_ref().expect("configured dedicated fsync runtime");
assert_eq!(std::thread::current().name(), Some("rustfs-fsync"));
let expected = std::thread::available_parallelism().map_or(1, usize::from).min(8);
assert_eq!(runtime.metrics().num_workers(), expected);
} else {
assert!(FSYNC_RUNTIME.is_none());
}
Ok(())
})
+9 -38
View File
@@ -110,29 +110,24 @@ pub fn compression_index_storage_bytes(index: &Index) -> Bytes {
}
}
/// Decodes one complete stored compression index for Range GET planning.
pub fn decode_compression_index_bytes(bytes: &Bytes) -> Option<Index> {
#[cfg(feature = "rio-v2")]
{
if let Some(decoded) = decode_minio_index_bytes(bytes) {
return Some(decoded);
}
}
// Check the legacy frame before attempting to restore a headerless S2
// index. Metadata contains exactly one index, so reject partial parses.
let mut decoded = Index::new();
if decoded.load(bytes.as_ref()).is_ok() {
if decoded.load(bytes.as_ref()).is_ok_and(|remaining| remaining.is_empty()) {
return Some(decoded);
}
#[cfg(feature = "rio-v2")]
{
let restored = restore_legacy_index_headers(bytes.as_ref());
let mut decoded = Index::new();
if decoded.load(&restored).is_ok() {
return Some(decoded);
}
decode_minio_index_bytes(bytes)
}
None
#[cfg(not(feature = "rio-v2"))]
{
None
}
}
pub fn compression_reader<R>(reader: R, algorithm: CompressionAlgorithm, encrypted: bool) -> CompressReader<R>
@@ -298,30 +293,6 @@ where
}
}
#[cfg(feature = "rio-v2")]
fn restore_legacy_index_headers(bytes: &[u8]) -> Vec<u8> {
if bytes.is_empty() {
return Vec::new();
}
const S2_INDEX_HEADER: &[u8] = b"s2idx\x00";
const S2_INDEX_TRAILER: &[u8] = b"\x00xdi2s";
let mut restored = Vec::with_capacity(4 + S2_INDEX_HEADER.len() + bytes.len() + 4 + S2_INDEX_TRAILER.len());
restored.extend_from_slice(&[0x99, 0x2A, 0x4D, 0x18]);
restored.extend_from_slice(S2_INDEX_HEADER);
restored.extend_from_slice(bytes);
let total_size = (restored.len() + 4 + S2_INDEX_TRAILER.len()) as u32;
restored.extend_from_slice(&total_size.to_le_bytes());
restored.extend_from_slice(S2_INDEX_TRAILER);
let chunk_len = restored.len() - 4;
restored[1] = chunk_len as u8;
restored[2] = (chunk_len >> 8) as u8;
restored[3] = (chunk_len >> 16) as u8;
restored
}
#[derive(Debug, Clone, Copy)]
pub struct WriteEncryption {
key_bytes: [u8; 32],
+10 -3
View File
@@ -73,6 +73,8 @@ impl TryFrom<&str> for Endpoint {
/// Performs the conversion.
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
const INVALID_URL_PORT: &str = "invalid URL endpoint format: port number must be between 1 to 65535";
// check whether given path is not empty.
if ["", "/", "\\"].iter().any(|&v| v.eq(value)) {
return Err(Error::other("empty or root endpoint is not supported"));
@@ -80,6 +82,7 @@ impl TryFrom<&str> for Endpoint {
let mut is_local = false;
let url = match Url::parse(value) {
Ok(url) if url.port() == Some(0) => return Err(Error::other(INVALID_URL_PORT)),
#[allow(unused_mut)]
Ok(mut url) if url.has_host() => {
// URL style of endpoint.
@@ -139,9 +142,7 @@ impl TryFrom<&str> for Endpoint {
url_parse_from_file_path(value)?
}
Err(e) => match e {
ParseError::InvalidPort => {
return Err(Error::other("invalid URL endpoint format: port number must be between 1 to 65535"));
}
ParseError::InvalidPort => return Err(Error::other(INVALID_URL_PORT)),
ParseError::EmptyHost => return Err(Error::other("invalid URL endpoint format: empty host name")),
ParseError::RelativeUrlWithoutBase => {
// like /foo
@@ -450,6 +451,12 @@ mod test {
expected_type: Some(EndpointType::Url),
expected_err: None,
},
TestCase {
arg: "http://127.0.0.1:0/path",
expected_endpoint: None,
expected_type: None,
expected_err: Some(Error::other("invalid URL endpoint format: port number must be between 1 to 65535")),
},
TestCase {
arg: "https://93.184.216.34:808080/path",
expected_endpoint: None,
+262 -246
View File
@@ -21,20 +21,25 @@ use rustfs_config::{
ENV_KUBERNETES_SERVICE_HOST, ENV_LOCAL_ENDPOINT_HOST, ENV_MINIO_CI, ENV_STARTUP_TOPOLOGY_RETRY_MAX_DELAY,
ENV_STARTUP_TOPOLOGY_WAIT_MODE, ENV_STARTUP_TOPOLOGY_WAIT_TIMEOUT, ENV_UNSAFE_BYPASS_DISK_CHECK,
};
use rustfs_utils::{XHost, check_local_server_addr, get_env_opt_str, get_host_ip, is_local_host};
use rustfs_utils::{XHost, check_local_server_addr, get_env_opt_str, is_local_ip};
#[cfg(test)]
use std::sync::{LazyLock, Mutex};
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet, HashMap, HashSet, hash_map::Entry},
future::Future,
io::{Error, ErrorKind, Result},
net::IpAddr,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::time::sleep as async_sleep;
use tokio::time::{Instant as TokioInstant, sleep as async_sleep, sleep_until};
use tracing::{error, info, instrument, warn};
use url::Host;
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_ENDPOINT_TOPOLOGY: &str = "endpoint_topology";
const EVENT_STARTUP_ENDPOINT_DNS_FAILED: &str = "startup_endpoint_dns_failed";
/// enum for setup type.
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum SetupType {
@@ -196,18 +201,17 @@ struct PoolEndpointList {
setup_type: SetupType,
}
struct ResolvedStartupHost {
addresses: HashSet<IpAddr>,
is_local: bool,
}
impl AsRef<Vec<Endpoints>> for PoolEndpointList {
fn as_ref(&self) -> &Vec<Endpoints> {
&self.inner
}
}
impl AsMut<Vec<Endpoints>> for PoolEndpointList {
fn as_mut(&mut self) -> &mut Vec<Endpoints> {
&mut self.inner
}
}
impl PoolEndpointList {
/// Creates a list of endpoints per pool, resolves their relevant hostnames
/// and discovers whether those are local or remote.
@@ -322,76 +326,41 @@ impl PoolEndpointList {
let convergence_started = Instant::now();
let dns_retry_deadline = DnsRetryDeadline::new(policy.wait_timeout, policy.retry_max_delay);
if let Some(local_endpoint_host) = local_endpoint_host {
let resolved_hosts = if let Some(local_endpoint_host) = local_endpoint_host {
pool_endpoint_list.update_is_local_from_explicit_host(disks_layout, server_addr.port(), local_endpoint_host)?;
HashMap::new()
} else {
pool_endpoint_list
.update_is_local(server_addr.port(), &dns_retry_deadline)
.await?;
// Collapse divergent local/remote verdicts for the same host:port that
// orchestrated DNS churn can produce during startup, before any check
// relies on the local flag.
normalize_same_host_local_state(pool_endpoint_list.as_mut());
}
.resolve_startup_hosts(server_addr.port(), &dns_retry_deadline, lookup_startup_host_ips)
.await?
};
let mut total_endpoints = 0;
let mut local_endpoints = 0;
for endpoints in pool_endpoint_list.inner.iter_mut() {
// Check whether same path is not used in endpoints of a host on different port.
// This relies on resolving every host to its IP set, which can flap while a
// Kubernetes headless service is still publishing records; defer it in
// orchestrated mode and re-run the DNS-independent checks below.
if !policy.is_orchestrated() {
let mut path_ip_map: HashMap<String, HashSet<IpAddr>> = HashMap::new();
let mut host_ip_cache: HashMap<Host<&str>, HashSet<IpAddr>> = HashMap::new();
let mut path_ip_map: HashMap<String, Cow<'_, HashSet<IpAddr>>> = HashMap::new();
for ep in endpoints.as_ref() {
let Some(host) = ep.url.host() else {
let Some(host) = ep.url.host_str().and_then(|host| resolved_hosts.get(host)) else {
continue;
};
let host_ip_set = if let Some(set) = host_ip_cache.get(&host) {
info!(
target: "rustfs::ecstore::endpoints",
host = %host,
endpoint = %ep.to_string(),
from = "cache",
"Create pool endpoints host '{}' found in cache for endpoint '{}'", host, ep.to_string()
);
set.clone()
} else {
let ips = match resolve_host_ips_with_retry(host.clone(), &ep.to_string(), &dns_retry_deadline).await {
Ok(ips) => ips,
Err(e) => {
error!("Create pool endpoints host {} not found, error:{}", host, e);
return Err(e);
}
};
info!(
target: "rustfs::ecstore::endpoints",
host = %host,
endpoint = %ep.to_string(),
from = "get_host_ip",
"Create pool endpoints host '{}' resolved to ips {:?} for endpoint '{}'",
host,
ips,
ep.to_string()
);
host_ip_cache.insert(host.clone(), ips.clone());
ips
};
let path = ep.get_file_path();
match path_ip_map.entry(path) {
Entry::Occupied(mut e) => {
if e.get().intersection(&host_ip_set).count() > 0 {
let path_key = e.key().clone();
if !e.get().is_disjoint(&host.addresses) {
return Err(Error::other(format!(
"same path '{path_key}' can not be served by different port on same address"
"same path '{}' can not be served by different port on same address",
e.key()
)));
}
e.get_mut().extend(host_ip_set.iter());
e.get_mut().to_mut().extend(&host.addresses);
}
Entry::Vacant(e) => {
e.insert(host_ip_set);
e.insert(Cow::Borrowed(&host.addresses));
}
}
}
@@ -414,13 +383,11 @@ impl PoolEndpointList {
}
// Here all endpoints are URL style.
let mut ep_path_set = HashSet::new();
let mut local_server_host_set = HashSet::new();
let mut local_port_set = HashSet::new();
let mut local_endpoint_count = 0;
for ep in endpoints.as_ref() {
ep_path_set.insert(ep.get_file_path());
if ep.is_local && ep.url.has_host() {
local_server_host_set.insert(ep.url.host());
local_port_set.insert(ep.url.port());
@@ -438,30 +405,20 @@ impl PoolEndpointList {
}
// Add missing port in all endpoints.
total_endpoints += endpoints.as_ref().len();
for ep in endpoints.as_mut() {
local_endpoints += usize::from(ep.is_local);
if !ep.url.has_host() {
unique_args.insert(format!("localhost:{}", server_addr.port()));
continue;
}
match ep.url.port() {
None => {
if local_endpoint_host.is_none() {
let _ = ep.url.set_port(Some(server_addr.port()));
}
}
Some(port) => {
// If endpoint is local, but port is different than serverAddrPort, then make it as remote.
if ep.is_local && server_addr.port() != port {
ep.is_local = false;
}
}
if ep.url.port().is_none() && local_endpoint_host.is_none() {
let _ = ep.url.set_port(Some(server_addr.port()));
}
unique_args.insert(ep.host_port());
}
}
validate_local_physical_disk_independence(pool_endpoint_list.as_ref())?;
let setup_type = match pool_endpoint_list.as_ref()[0].as_ref()[0].get_type() {
EndpointType::Path => SetupType::Erasure,
EndpointType::Url => match unique_args.len() {
@@ -470,15 +427,25 @@ impl PoolEndpointList {
},
};
pool_endpoint_list.setup_type = setup_type;
// A storage member can belong to just one pool, but it must own a slot somewhere in the topology.
if local_endpoints == 0 {
let local_port = server_addr.port();
if local_endpoint_host.is_some() {
return Err(Error::other(format!(
"{ENV_LOCAL_ENDPOINT_HOST} does not match any distributed endpoint on the local server port {local_port}"
)));
}
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"no local storage endpoints on the local server port {local_port}; \
check that a host in RUSTFS_VOLUMES resolves to a local interface and uses the RUSTFS_ADDRESS port"
),
));
}
let total_endpoints: usize = pool_endpoint_list.inner.iter().map(|eps| eps.as_ref().len()).sum();
let local_endpoints = pool_endpoint_list
.inner
.iter()
.flat_map(|eps| eps.as_ref())
.filter(|ep| ep.is_local)
.count();
validate_local_physical_disk_independence(pool_endpoint_list.as_ref())?;
pool_endpoint_list.setup_type = setup_type;
info!(
target: "rustfs::ecstore::endpoints",
mode = ?policy.mode,
@@ -492,34 +459,33 @@ impl PoolEndpointList {
Ok(pool_endpoint_list)
}
/// resolves all hosts and discovers which are local
async fn update_is_local(&mut self, local_port: u16, dns_retry_deadline: &DnsRetryDeadline) -> Result<()> {
self._update_is_local(local_port, dns_retry_deadline).await
}
/// resolves all hosts and discovers which are local
async fn _update_is_local(&mut self, local_port: u16, dns_retry_deadline: &DnsRetryDeadline) -> Result<()> {
// Keep each successful answer for the whole startup so all drives and path checks agree.
async fn resolve_startup_hosts(
&mut self,
local_port: u16,
dns_retry_deadline: &DnsRetryDeadline,
resolve: impl for<'a> AsyncFn(Host<&'a str>) -> Result<HashSet<IpAddr>>,
) -> Result<HashMap<String, ResolvedStartupHost>> {
let mut resolved_hosts: HashMap<String, ResolvedStartupHost> = HashMap::new();
for endpoints in self.inner.iter_mut() {
for ep in endpoints.as_mut() {
match ep.url.host() {
None => {
ep.is_local = true;
}
Some(host) => {
ep.is_local = resolve_local_host_with_retry(
host,
ep.url.port().unwrap_or_default(),
local_port,
&ep.to_string(),
dns_retry_deadline,
)
.await?;
}
}
let (Some(host_name), Some(host)) = (ep.url.host_str(), ep.url.host()) else {
ep.is_local = true;
continue;
};
let is_local = if let Some(resolved) = resolved_hosts.get(host_name) {
resolved.is_local
} else {
let addresses = resolve_startup_host_with_retry(host, &ep.to_string(), dns_retry_deadline, &resolve).await?;
let is_local = addresses.iter().any(is_local_ip);
resolved_hosts.insert(host_name.to_owned(), ResolvedStartupHost { addresses, is_local });
is_local
};
ep.is_local = is_local && ep.url.port().is_none_or(|port| port == local_port);
}
}
Ok(())
Ok(resolved_hosts)
}
fn update_is_local_from_explicit_host(
@@ -529,7 +495,6 @@ impl PoolEndpointList {
raw_local_host: &str,
) -> Result<()> {
let local_host = parse_explicit_local_endpoint_host(raw_local_host)?;
let mut local_endpoint_found = false;
let mut host_path_ports = HashMap::new();
debug_assert_eq!(self.inner.len(), disks_layout.pools.len());
@@ -575,17 +540,9 @@ impl PoolEndpointList {
entry.insert(endpoint_port);
}
}
local_endpoint_found |= endpoint.is_local;
}
}
if !local_endpoint_found {
return Err(Error::other(format!(
"{ENV_LOCAL_ENDPOINT_HOST} does not match any distributed endpoint on the local server port {local_port}"
)));
}
Ok(())
}
}
@@ -686,17 +643,21 @@ fn kernel_hostname_for_endpoint_identity() -> Result<String> {
.map_err(|_| Error::new(ErrorKind::InvalidData, "kernel hostname is not valid UTF-8"))
}
fn endpoint_is_local_host(host: Host<&str>, port: u16, local_port: u16) -> Result<bool> {
async fn lookup_startup_host_ips(host: Host<&str>) -> Result<HashSet<IpAddr>> {
#[cfg(test)]
if local_host_resolution_timeout_forced(&host) {
return Err(Error::new(ErrorKind::TimedOut, "resolver timeout"));
}
is_local_host(host, port, local_port)
match host {
Host::Domain(domain) => Ok(tokio::net::lookup_host((domain, 0)).await?.map(|addr| addr.ip()).collect()),
Host::Ipv4(ip) => Ok(HashSet::from([IpAddr::V4(ip)])),
Host::Ipv6(ip) => Ok(HashSet::from([IpAddr::V6(ip)])),
}
}
struct DnsRetryDeadline {
started: Instant,
started: TokioInstant,
timeout: Duration,
max_delay: Duration,
}
@@ -704,7 +665,7 @@ struct DnsRetryDeadline {
impl DnsRetryDeadline {
fn new(timeout: Duration, max_delay: Duration) -> Self {
Self {
started: Instant::now(),
started: TokioInstant::now(),
timeout,
max_delay,
}
@@ -718,6 +679,14 @@ impl DnsRetryDeadline {
self.started.elapsed()
}
fn expires_at(&self) -> Option<TokioInstant> {
// Zero means one lookup with no retries. MAX is the unbounded orchestrated policy.
if matches!(self.timeout, Duration::ZERO | Duration::MAX) {
return None;
}
self.started.checked_add(self.timeout)
}
fn bounded_delay(&self, delay: Duration) -> Option<Duration> {
let remaining = self.timeout.saturating_sub(self.started.elapsed());
if remaining.is_zero() {
@@ -746,17 +715,16 @@ where
RetryLog: FnMut(u32, Duration, Duration, &Error),
{
let mut attempts: u32 = 0;
let mut last_warn: Option<Instant> = None;
loop {
match resolve().await {
Ok(value) => return Ok(value),
Err(err) => {
if !is_retryable_dns_error(&err) {
return Err(permanent_error(err));
}
let result = {
let retry = async {
let mut last_warn: Option<Instant> = None;
loop {
attempts += 1;
let err = match resolve().await {
Ok(value) => return Ok(value),
Err(err) if is_retryable_dns_error(&err) => err,
Err(err) => return Err(permanent_error(err)),
};
let Some(delay) = dns_retry_deadline.bounded_delay(dns_retry_delay(attempts, dns_retry_deadline.max_delay))
else {
return Err(timeout_error(attempts, dns_retry_deadline.timeout(), err));
@@ -770,8 +738,25 @@ where
}
sleep(delay).await;
}
};
match dns_retry_deadline.expires_at() {
Some(expires_at) if expires_at <= TokioInstant::now() => None,
Some(expires_at) => tokio::select! {
biased;
() = sleep_until(expires_at) => None,
result = retry => Some(result),
},
None => Some(retry.await),
}
}
};
result.unwrap_or_else(|| {
Err(timeout_error(
attempts,
dns_retry_deadline.timeout(),
Error::new(ErrorKind::TimedOut, "startup DNS deadline elapsed"),
))
})
}
/// Action-oriented tail shared by topology convergence timeout errors so a
@@ -781,26 +766,30 @@ const TOPOLOGY_TIMEOUT_HINT: &str = "check DNS and /etc/hosts resolution, the ht
and that all peer nodes have started; on Kubernetes/orchestrated deployments set \
RUSTFS_STARTUP_TOPOLOGY_WAIT_MODE=orchestrated to keep waiting instead of exiting";
async fn resolve_local_host_with_retry(
async fn resolve_startup_host_with_retry(
host: Host<&str>,
port: u16,
local_port: u16,
context: &str,
dns_retry_deadline: &DnsRetryDeadline,
) -> Result<bool> {
resolve: &impl for<'a> AsyncFn(Host<&'a str>) -> Result<HashSet<IpAddr>>,
) -> Result<HashSet<IpAddr>> {
retry_dns_operation(
|| {
let host = host.clone();
async move { endpoint_is_local_host(host, port, local_port) }
},
|| resolve(host.clone()),
async_sleep,
dns_retry_deadline,
|err| Error::other(format!("endpoint '{context}' local-host detection failed for host '{host}': {err}")),
|attempts, timeout, err| {
Error::other(format!(
"endpoint '{context}' local-host detection did not converge for host '{host}' after {attempts} attempts \
let kind = if timeout.is_zero() {
ErrorKind::Other
} else {
ErrorKind::TimedOut
};
Error::new(
kind,
format!(
"endpoint '{context}' local-host detection did not converge for host '{host}' after {attempts} attempts \
over {timeout:?} (stage=local_host_detection): {err}. {TOPOLOGY_TIMEOUT_HINT}"
))
),
)
},
|attempts, delay, elapsed, err| {
warn!(
@@ -817,42 +806,18 @@ over {timeout:?} (stage=local_host_detection): {err}. {TOPOLOGY_TIMEOUT_HINT}"
},
)
.await
}
async fn resolve_host_ips_with_retry(
host: Host<&str>,
context: &str,
dns_retry_deadline: &DnsRetryDeadline,
) -> Result<HashSet<IpAddr>> {
retry_dns_operation(
|| {
let host = host.clone();
async move { get_host_ip(host).await }
},
async_sleep,
dns_retry_deadline,
|err| Error::other(format!("endpoint '{context}' host '{host}' cannot resolve: {err}")),
|attempts, timeout, err| {
Error::other(format!(
"endpoint '{context}' host '{host}' DNS resolution did not converge after {attempts} attempts over \
{timeout:?} (stage=host_ip_resolution): {err}. {TOPOLOGY_TIMEOUT_HINT}"
))
},
|attempts, delay, elapsed, err| {
warn!(
target = "rustfs::ecstore::endpoints",
stage = "host_ip_resolution",
context = %context,
host = %host,
attempt = attempts,
delay_ms = delay.as_millis(),
elapsed_ms = elapsed.as_millis(),
error = %err,
"retrying endpoint DNS resolution after temporary error"
);
},
)
.await
.inspect_err(|err| {
error!(
target: "rustfs::ecstore::endpoints",
event = EVENT_STARTUP_ENDPOINT_DNS_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_ENDPOINT_TOPOLOGY,
state = "failed",
host = %host,
error_kind = ?err.kind(),
"Startup endpoint DNS resolution failed"
);
})
}
fn is_retryable_dns_error(err: &Error) -> bool {
@@ -936,6 +901,26 @@ fn explicit_url_port(raw: &str) -> Result<Option<u16>> {
port.parse().map(Some).map_err(|_| invalid())
}
fn is_url_topology_with_non_literal_hosts(disks_layout: &DisksLayout) -> Result<bool> {
let mut endpoints = disks_layout
.pools
.iter()
.flat_map(|pool| pool.iter().flatten())
.map(|endpoint| Endpoint::try_from(endpoint.as_str()));
let Some(first) = endpoints.next().transpose()? else {
return Ok(false);
};
if first.get_type() != EndpointType::Url {
return Ok(false);
}
for endpoint in std::iter::once(Ok(first)).chain(endpoints) {
if !matches!(endpoint?.url.host(), Some(Host::Ipv4(_) | Host::Ipv6(_))) {
return Ok(true);
}
}
Ok(false)
}
fn infer_kubernetes_local_endpoint_host(
disks_layout: &DisksLayout,
local_port: u16,
@@ -1189,34 +1174,6 @@ fn parse_wait_duration(raw: &str) -> Option<Duration> {
}
}
/// Collapses divergent local/remote verdicts for endpoints that share the same
/// `host:port`. A `host:port` is a single network identity, so if any endpoint
/// of the group resolved as local, all of them are local. This absorbs the
/// transient inconsistency that orchestrated DNS churn can produce across the
/// several drives exported by one host.
fn normalize_same_host_local_state(pools: &mut [Endpoints]) {
let mut local_hosts: HashSet<String> = HashSet::new();
for endpoints in pools.iter() {
for ep in endpoints.as_ref() {
if ep.is_local && ep.url.has_host() {
local_hosts.insert(ep.host_port());
}
}
}
if local_hosts.is_empty() {
return;
}
for endpoints in pools.iter_mut() {
for ep in endpoints.as_mut() {
if !ep.is_local && ep.url.has_host() && local_hosts.contains(&ep.host_port()) {
ep.is_local = true;
}
}
}
}
/// represent endpoints in a given pool
/// along with its setCount and setDriveCount.
#[derive(Debug, Clone)]
@@ -1280,32 +1237,11 @@ impl EndpointServerPools {
) -> Result<(EndpointServerPools, SetupType)> {
let mut local_endpoint_host = get_env_opt_str(ENV_LOCAL_ENDPOINT_HOST);
let mut policy_override = None;
let first_endpoint = disks_layout
.pools
.iter()
.flat_map(|pool| pool.iter().flatten())
.next()
.map(|endpoint| Endpoint::try_from(endpoint.as_str()))
.transpose()?;
let distributed = first_endpoint
.as_ref()
.is_some_and(|endpoint| endpoint.get_type() == EndpointType::Url);
let mut all_distributed_hosts_are_ip_literals = distributed;
if distributed {
for raw_endpoint in disks_layout.pools.iter().flat_map(|pool| pool.iter().flatten()) {
let endpoint = Endpoint::try_from(raw_endpoint.as_str())?;
if !matches!(endpoint.url.host(), Some(Host::Ipv4(_) | Host::Ipv6(_))) {
all_distributed_hosts_are_ip_literals = false;
break;
}
}
}
let wait_mode = get_env_opt_str(ENV_STARTUP_TOPOLOGY_WAIT_MODE).map(|value| value.trim().to_ascii_lowercase());
let infer_kubernetes_host = local_endpoint_host.is_none()
&& distributed
&& !all_distributed_hosts_are_ip_literals
&& std::env::var_os(ENV_KUBERNETES_SERVICE_HOST).is_some()
&& matches!(wait_mode.as_deref(), None | Some("") | Some("auto") | Some("orchestrated"));
&& matches!(wait_mode.as_deref(), None | Some("") | Some("auto") | Some("orchestrated"))
&& is_url_topology_with_non_literal_hosts(disks_layout)?;
if infer_kubernetes_host {
let kernel_hostname = kernel_hostname_for_endpoint_identity()?;
let local_port = check_local_server_addr(server_addr)?.port();
@@ -1317,7 +1253,7 @@ impl EndpointServerPools {
policy_override = Some(StartupTopologyPolicy::resolve_from(
Some("bounded"),
true,
distributed,
true,
get_env_opt_str(ENV_STARTUP_TOPOLOGY_WAIT_TIMEOUT).as_deref(),
get_env_opt_str(ENV_STARTUP_TOPOLOGY_RETRY_MAX_DELAY).as_deref(),
false,
@@ -1788,7 +1724,7 @@ mod test {
#[tokio::test]
async fn system_resolver_negative_result_reaches_the_dns_allowlist() {
let Err(err) = get_host_ip(Host::Domain("rustfs-startup-negative.invalid")).await else {
let Err(err) = lookup_startup_host_ips(Host::Domain("rustfs-startup-negative.invalid")).await else {
// Some corporate and ISP resolvers synthesize an address for
// unknown names, including the reserved .invalid suffix.
return;
@@ -1959,22 +1895,48 @@ mod test {
);
}
#[test]
fn normalize_same_host_local_state_unifies_divergent_verdicts() {
let mut d1 = Endpoint::try_from("http://node1:9000/d1").unwrap();
let mut d2 = Endpoint::try_from("http://node1:9000/d2").unwrap();
d1.is_local = true;
d2.is_local = false; // divergent verdict for the same host:port
let mut remote = Endpoint::try_from("http://node2:9000/d1").unwrap();
remote.is_local = false;
#[tokio::test]
async fn startup_reuses_one_dns_answer_per_host_across_ports_and_pools() {
let mut pools = PoolEndpointList {
inner: vec![
Endpoints::try_from(["http://node1:9000/d1", "http://node1:9000/d2", "http://node2:9000/d1"].as_slice())
.expect("first pool endpoints should parse"),
Endpoints::try_from(["http://node1:9000/d3", "http://node1:9001/d4"].as_slice())
.expect("second pool endpoints should parse"),
],
setup_type: SetupType::Unknown,
};
let deadline = DnsRetryDeadline::new(Duration::ZERO, DNS_RETRY_MAX_DELAY);
let node1_lookups = std::cell::Cell::new(0);
let local_ip = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
let stale_ip = IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 10));
let resolve = async |host: Host<&str>| match host {
Host::Domain("node1") => {
let lookups = node1_lookups.get();
node1_lookups.set(lookups + 1);
Ok(HashSet::from([if lookups == 0 { stale_ip } else { local_ip }]))
}
Host::Domain("node2") => Ok(HashSet::from([stale_ip])),
_ => panic!("unexpected hostname in test: {host}"),
};
let mut pools = vec![Endpoints::from(vec![d1, d2, remote])];
normalize_same_host_local_state(&mut pools);
let first_start = pools
.resolve_startup_hosts(9000, &deadline, resolve)
.await
.expect("first lookup");
assert_eq!(node1_lookups.get(), 1);
assert_eq!(first_start["node1"].addresses, HashSet::from([stale_ip]));
assert_eq!(local_flags(&pools.inner[0]), [false, false, false]);
assert_eq!(local_flags(&pools.inner[1]), [false, false]);
let eps = pools[0].as_ref();
assert!(eps[0].is_local);
assert!(eps[1].is_local, "same host:port must inherit the local verdict");
assert!(!eps[2].is_local, "a genuinely remote host must stay remote");
let restart = pools
.resolve_startup_hosts(9000, &deadline, resolve)
.await
.expect("fresh lookup");
assert_eq!(node1_lookups.get(), 2);
assert_eq!(restart["node1"].addresses, HashSet::from([local_ip]));
assert_eq!(local_flags(&pools.inner[0]), [true, true, false]);
assert_eq!(local_flags(&pools.inner[1]), [true, false]);
}
#[test]
@@ -2020,11 +1982,11 @@ mod test {
// trip the DNS-IP cross-port check in bounded mode but must be deferred
// (allowed) in orchestrated mode, where headless-service records can
// still be flapping.
let args = vec![
let args = [
"http://192.0.2.10:9000/export",
"http://192.0.2.10:9001/export",
"http://192.0.2.11:9000/export",
"http://192.0.2.12:9000/export",
"http://127.0.0.1:9000/export",
];
let layout = DisksLayout::from_volumes(args.as_slice()).unwrap();
@@ -2046,6 +2008,24 @@ mod test {
assert_eq!(resolved.setup_type, SetupType::DistErasure);
}
#[tokio::test]
async fn rejects_startup_when_no_endpoint_is_local() {
for volumes in [
["http://192.0.2.10:9000/data", "http://192.0.2.11:9000/data"],
["http://192.0.2.10:9000/data", "http://127.0.0.1:9001/data"],
["http://192.0.2.10:9000/data1", "http://192.0.2.10:9000/data2"],
] {
let layout = DisksLayout::from_volumes(&volumes).expect("URL topology should parse");
for policy in [bounded_test_policy(), orchestrated_test_policy()] {
let err = EndpointServerPools::create_server_endpoints_with("0.0.0.0:9000", &layout, Some(policy), None)
.await
.expect_err("startup must reject a topology with no local endpoints");
assert_eq!(err.kind(), ErrorKind::InvalidInput);
assert!(err.to_string().contains("no local storage endpoints"), "{err}");
}
}
}
#[test]
fn explicit_local_endpoint_host_accepts_only_a_canonical_host() {
assert_eq!(
@@ -2274,7 +2254,7 @@ mod test {
#[serial]
#[tokio::test]
async fn create_server_endpoints_infers_kubernetes_pod_host_without_peer_dns() {
async fn create_server_endpoints_infers_kubernetes_host_after_literal_peer_without_dns() {
let _kernel_hostname = force_kernel_hostname_for_test("rustfs-0");
let local_host = "rustfs-0.rustfs-headless.ns.svc.cluster.local";
@@ -2288,14 +2268,16 @@ mod test {
let (pools, setup_type) = EndpointServerPools::from_volumes(
"0.0.0.0:9000",
vec![
"http://192.0.2.10:9000/data2".to_string(),
format!("http://{local_host}:9000/data0"),
"http://permanently-missing.invalid:9000/data1".to_string(),
"http://192.0.2.11:9000/data3".to_string(),
],
)
.await
.expect("kernel hostname inference should avoid resolving the missing peer");
assert_eq!(local_flags(&pools.0[0].endpoints), vec![true, false]);
assert_eq!(local_flags(&pools.0[0].endpoints), vec![false, true, false, false]);
assert_eq!(setup_type, SetupType::DistErasure);
},
)
@@ -2815,6 +2797,40 @@ mod test {
assert!(err.to_string().contains("timed out after 1 attempts"));
}
#[tokio::test(start_paused = true)]
async fn startup_dns_deadline_stops_pending_and_later_lookups() {
let timeout = Duration::from_secs(3);
let deadline = DnsRetryDeadline::new(timeout, DNS_RETRY_MAX_DELAY);
let lookups = std::cell::Cell::new(0);
let resolve = async |_host: Host<&str>| {
lookups.set(lookups.get() + 1);
std::future::pending::<Result<HashSet<IpAddr>>>().await
};
let err = tokio::time::timeout(
timeout * 2,
resolve_startup_host_with_retry(Host::Domain("node1"), "first endpoint", &deadline, &resolve),
)
.await
.expect("a pending lookup must complete before the test deadline")
.expect_err("a pending lookup must stop at the startup deadline");
assert_eq!(err.kind(), ErrorKind::TimedOut);
assert!(err.to_string().contains("first endpoint"));
assert!(err.to_string().contains("startup DNS deadline elapsed"));
assert_eq!(deadline.elapsed(), timeout);
assert_eq!(lookups.get(), 1);
let err = tokio::time::timeout(
timeout * 2,
resolve_startup_host_with_retry(Host::Domain("node2"), "second endpoint", &deadline, &resolve),
)
.await
.expect("a later lookup must complete before the test deadline")
.expect_err("an exhausted startup budget must prevent a new lookup");
assert!(err.to_string().contains("second endpoint"));
assert_eq!(lookups.get(), 1);
}
#[test]
fn test_new_endpoints() {
let test_cases = [
+338 -300
View File
@@ -14,8 +14,9 @@
use super::*;
#[cfg(test)]
use crate::io_support::rio::Index;
use std::mem::MaybeUninit;
use std::{mem::MaybeUninit, task::ready};
#[cfg(feature = "rio-v2")]
const DARE_PAYLOAD_SIZE: i64 = 64 * 1024;
@@ -41,11 +42,8 @@ pub(crate) fn restore_request_active(opts: &ObjectOptions) -> bool {
restore.type_.is_some() || restore.days.is_some() || restore.output_location.is_some() || restore.select_parameters.is_some()
}
fn decode_compression_index(index: Option<&Bytes>) -> Option<Index> {
crate::io_support::rio::decode_compression_index_bytes(index?)
}
fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
#[cfg(feature = "rio-v2")]
fn get_encrypted_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
let mut skip_length = 0_i64;
let mut cumulative_actual_size = 0_i64;
let mut first_part_idx = 0_usize;
@@ -63,30 +61,20 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
}
let mut part_skip = offset - skip_length;
#[cfg(feature = "rio-v2")]
let (mut decrypt_skip, mut seq_num) = (0_i64, 0_u64);
#[cfg(not(feature = "rio-v2"))]
let (decrypt_skip, seq_num) = (0_i64, 0_u64);
if part_skip > 0
&& let Some(part) = oi.parts.get(first_part_idx)
&& let Some(index) = decode_compression_index(part.index.as_ref())
&& let Some(index) = part
.index
.as_ref()
.and_then(crate::io_support::rio::decode_compression_index_bytes)
&& let Ok((comp_off, uncomp_off)) = index.find(part_skip)
&& comp_off > 0
{
#[cfg(feature = "rio-v2")]
if oi.is_encrypted() {
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
} else {
compressed_offset += comp_off;
}
#[cfg(not(feature = "rio-v2"))]
{
compressed_offset += comp_off;
}
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
part_skip -= uncomp_off;
}
@@ -94,6 +82,68 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
(compressed_offset, part_skip, first_part_idx, decrypt_skip, seq_num)
}
// Plan a window of complete compression blocks in stored coordinates. The
// index can omit the final block or record a stale total. Part metadata owns
// the actual bounds, and missing checkpoints widen only the covering parts.
fn compressed_storage_window(oi: &ObjectInfo, offset: usize, length: i64) -> Option<(usize, i64, usize)> {
let start = i64::try_from(offset).ok()?;
let end = start.checked_add(length)?;
if start >= end {
return None;
}
let (mut plaintext_offset, mut stored_offset) = (0_i64, 0_i64);
let mut window_start = None;
for part in oi.parts.iter() {
let stored_size = i64::try_from(part.size).ok()?;
let stored_end = stored_offset.checked_add(stored_size)?;
if stored_end > oi.size || part.actual_size < 0 || (part.actual_size == 0) != (stored_size == 0) {
return None;
}
let plaintext_end = plaintext_offset.checked_add(part.actual_size)?;
let starts_here = window_start.is_none() && start < plaintext_end;
let ends_here = end <= plaintext_end;
if starts_here || ends_here {
let index = part
.index
.as_ref()
.filter(|_| (starts_here && start > plaintext_offset) || (ends_here && end < plaintext_end))
.and_then(crate::io_support::rio::decode_compression_index_bytes);
if starts_here {
let relative_start = start - plaintext_offset;
let (stored, plaintext) = index
.as_ref()
.filter(|_| relative_start > 0)
.and_then(|index| index.checkpoint_at_or_before(relative_start))
.filter(|&(stored, plaintext)| {
(1..stored_size).contains(&stored) && (0..=relative_start).contains(&plaintext)
})
.unwrap_or((0, 0));
window_start = Some((stored_offset + stored, relative_start - plaintext));
}
if ends_here {
let (window_start, skip) = window_start?;
let relative_end = end - plaintext_offset;
let window_end = index
.filter(|_| relative_end < part.actual_size)
.as_ref()
.and_then(|index| index.checkpoint_at_or_after(relative_end))
.filter(|&(stored, plaintext)| {
(1..=stored_size).contains(&stored) && (relative_end..=part.actual_size).contains(&plaintext)
})
.map_or(stored_end, |(stored, _)| stored_offset + stored);
return (window_end > window_start).then_some((
usize::try_from(window_start).ok()?,
window_end - window_start,
usize::try_from(skip).ok()?,
));
}
}
plaintext_offset = plaintext_end;
stored_offset = stored_end;
}
None
}
#[cfg(feature = "rio-v2")]
fn get_encrypted_offsets(oi: &ObjectInfo, offset: i64) -> Result<(i64, usize, usize, u32, i64)> {
if oi.parts.is_empty() {
@@ -713,10 +763,12 @@ impl ReadPlan {
let actual_size = oi.get_actual_size()?;
let (storage_offset, storage_length, decompressed_offset, decompressed_length) = if let Some(rs) = rs {
let (req_off, req_length) = rs.get_offset_length(actual_size)?;
let (physical_off, decompressed_skip, _, _, _) = get_compressed_offsets(oi, req_off as i64);
let storage_offset = usize::try_from(physical_off)
.map_err(|_| Error::other(format!("invalid compressed offset {physical_off}")))?;
(storage_offset, oi.size - physical_off, decompressed_skip as usize, req_length)
let (storage_offset, storage_length, skip) = if req_length < actual_size {
compressed_storage_window(oi, req_off, req_length).unwrap_or((0, oi.size, req_off))
} else {
(0, oi.size, req_off)
};
(storage_offset, storage_length, skip, req_length)
} else {
(0, oi.size, 0, actual_size)
};
@@ -794,7 +846,7 @@ impl ReadPlan {
)?
} else if is_compressed {
let (physical_off, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
get_compressed_offsets(oi, requested_offset as i64);
get_encrypted_compressed_offsets(oi, requested_offset as i64);
(
usize::try_from(physical_off)
.map_err(|_| Error::other(format!("invalid encrypted compressed offset {physical_off}")))?,
@@ -910,40 +962,14 @@ impl ReadPlan {
decompressed_length,
total_plaintext_size,
} => {
let dec_reader = crate::io_support::rio::decompression_reader(reader, algorithm, backend);
#[cfg(feature = "rio-v2")]
let dec_reader = StreamConsumer::new(dec_reader);
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if decompressed_offset > 0
|| decompressed_length != total_plaintext_size as i64
{
#[cfg(feature = "rio-v2")]
let ranged_result = RangedDecompressReader::new_draining(
dec_reader,
decompressed_offset,
decompressed_length,
total_plaintext_size,
);
#[cfg(not(feature = "rio-v2"))]
let ranged_result =
RangedDecompressReader::new(dec_reader, decompressed_offset, decompressed_length, total_plaintext_size);
match ranged_result {
Ok(ranged_reader) => {
tracing::debug!(
"Successfully created RangedDecompressReader for offset={}, length={}",
decompressed_offset,
decompressed_length
);
Box::new(ranged_reader)
}
Err(e) => {
tracing::error!("RangedDecompressReader failed with invalid range parameters: {}", e);
return Err(e);
}
}
} else {
Box::new(HardLimitReader::new(dec_reader, decompressed_length))
};
let final_reader = compressed_object_reader(
reader,
algorithm,
backend,
decompressed_offset,
decompressed_length,
total_plaintext_size,
)?;
let mut object_info = oi.clone();
object_info.size = self.object_size;
@@ -1019,29 +1045,14 @@ impl ReadPlan {
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> =
if let Some((algo, compression_backend)) = compression {
let decompressed_reader =
crate::io_support::rio::decompression_reader(decrypted_reader, algo, compression_backend);
#[cfg(feature = "rio-v2")]
let decompressed_reader = StreamConsumer::new(decompressed_reader);
if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
#[cfg(feature = "rio-v2")]
let ranged_reader = RangedDecompressReader::new_draining(
decompressed_reader,
plaintext_offset,
plaintext_length,
total_plaintext_size,
)?;
#[cfg(not(feature = "rio-v2"))]
let ranged_reader = RangedDecompressReader::new(
decompressed_reader,
plaintext_offset,
plaintext_length,
total_plaintext_size,
)?;
Box::new(ranged_reader)
} else {
Box::new(HardLimitReader::new(decompressed_reader, total_plaintext_size_i64))
}
compressed_object_reader(
decrypted_reader,
algo,
compression_backend,
plaintext_offset,
plaintext_length,
total_plaintext_size,
)?
} else if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
Box::new(RangedDecompressReader::new(
decrypted_reader,
@@ -1118,294 +1129,201 @@ impl AsyncRead for GetObjectReader {
}
}
fn compressed_object_reader(
source: Box<dyn AsyncRead + Unpin + Send + Sync>,
algorithm: CompressionAlgorithm,
backend: crate::io_support::rio::ReadCompressionBackend,
offset: usize,
length: i64,
total_size: usize,
) -> Result<Box<dyn AsyncRead + Unpin + Send + Sync>> {
let decoded = crate::io_support::rio::decompression_reader(source, algorithm, backend);
if offset != 0 || usize::try_from(length).ok() != Some(total_size) {
// A partial response needs the blocks covering its bytes. Dropping the
// source closes the producer instead of draining unrelated blocks.
return Ok(Box::new(RangedDecompressReader::new(decoded, offset, length, total_size)?));
}
#[cfg(feature = "rio-v2")]
let decoded = StreamConsumer::new(decoded);
Ok(Box::new(HardLimitReader::new(decoded, length)))
}
#[derive(Debug)]
struct SkipReader<R> {
inner: R,
bytes_to_skip: usize,
bytes_skipped: usize,
scratch: Box<[MaybeUninit<u8>]>,
remaining_skip: usize,
scratch: Option<Box<[MaybeUninit<u8>]>>,
}
impl<R: AsyncRead + Unpin + Send + Sync> SkipReader<R> {
impl<R: AsyncRead + Unpin> SkipReader<R> {
fn new(inner: R, bytes_to_skip: usize) -> Self {
Self {
inner,
bytes_to_skip,
bytes_skipped: 0,
scratch: Box::<[u8]>::new_uninit_slice(8192),
remaining_skip: bytes_to_skip,
scratch: None,
}
}
}
impl<R: AsyncRead + Unpin + Send + Sync> AsyncRead for SkipReader<R> {
impl<R: AsyncRead + Unpin> AsyncRead for SkipReader<R> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
let this = self.as_mut().get_mut();
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
while this.bytes_skipped < this.bytes_to_skip {
let remaining = this.bytes_to_skip - this.bytes_skipped;
let scratch_len = remaining.min(this.scratch.len());
let mut scratch_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
match Pin::new(&mut this.inner).poll_read(cx, &mut scratch_buf) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
Poll::Ready(Ok(())) => {
let n = scratch_buf.filled().len();
if n == 0 {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!("unexpected EOF while skipping {} bytes from decrypted stream", this.bytes_to_skip),
)));
}
this.bytes_skipped += n;
if this.remaining_skip != 0 {
let scratch_len = this.remaining_skip.min(8192);
let scratch = this.scratch.get_or_insert_with(|| Box::<[u8]>::new_uninit_slice(scratch_len));
while this.remaining_skip > 0 {
// An unindexed range can skip many decoded blocks without the source yielding.
let budget = ready!(tokio::task::coop::poll_proceed(cx));
let len = this.remaining_skip.min(scratch.len());
let mut discard = ReadBuf::uninit(&mut scratch[..len]);
ready!(Pin::new(&mut this.inner).poll_read(cx, &mut discard))?;
let n = discard.filled().len();
if n == 0 {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"object stream ended before reaching the range start",
)));
}
this.remaining_skip -= n;
budget.made_progress();
}
this.scratch = None;
}
Pin::new(&mut this.inner).poll_read(cx, buf)
}
}
/// A streaming decompression reader that supports range requests by skipping data in the decompressed stream.
/// This implementation acknowledges that compressed streams (like LZ4) must be decompressed sequentially
/// from the beginning, so it streams and discards data until reaching the target offset.
/// Reads a bounded plaintext range from a stream positioned at or before its start.
/// The source is released when the range completes. An early source EOF is an error.
#[derive(Debug)]
pub struct RangedDecompressReader<R: AsyncRead + Unpin + Send + Sync + 'static> {
inner: Option<R>,
target_offset: usize,
target_length: usize,
current_offset: usize,
bytes_returned: usize,
scratch: Box<[MaybeUninit<u8>]>,
inner: Option<tokio::io::Take<SkipReader<R>>>,
drain_on_done: bool,
drain_task: Option<tokio::task::JoinHandle<()>>,
}
impl<R: AsyncRead + Unpin + Send + Sync + 'static> RangedDecompressReader<R> {
/// Skips `offset` bytes and yields up to `length` bytes, capped by `total_size`.
///
/// # Errors
/// Returns an invalid range error if the offset is outside the stream or the length is negative.
pub fn new(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
Self::new_with_drain(inner, offset, length, total_size, false)
}
/// Reads like [Self::new] and drains any remainder in the background once the range completes.
///
/// # Errors
/// Returns the same range validation errors as [Self::new].
pub fn new_draining(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
Self::new_with_drain(inner, offset, length, total_size, true)
}
fn new_with_drain(inner: R, offset: usize, length: i64, total_size: usize, drain_on_done: bool) -> Result<Self> {
// Validate the range request
if offset >= total_size {
tracing::debug!("Range offset {} exceeds total size {}", offset, total_size);
return Err(Error::InvalidRangeSpec("Range offset exceeds file size".to_string()));
}
// Adjust length if it extends beyond file end
let actual_length = std::cmp::min(length as usize, total_size - offset);
tracing::debug!(
"Creating RangedDecompressReader: offset={}, length={}, total_size={}, actual_length={}",
offset,
length,
total_size,
actual_length
);
let length =
u64::try_from(length).map_err(|_| Error::InvalidRangeSpec("Range length must be nonnegative".to_string()))?;
let length = length.min((total_size - offset) as u64);
Ok(Self {
inner: Some(inner),
target_offset: offset,
target_length: actual_length,
current_offset: 0,
bytes_returned: 0,
scratch: Box::<[u8]>::new_uninit_slice(8192),
inner: Some(SkipReader::new(inner, offset).take(length)),
drain_on_done,
drain_task: None,
})
}
fn start_drain(&mut self) {
if !self.drain_on_done || self.drain_task.is_some() {
return;
fn finish(&mut self) {
if let Some(inner) = self.inner.take()
&& self.drain_on_done
{
drain_stream(inner.into_inner().inner);
}
let Some(mut inner) = self.inner.take() else {
return;
};
self.drain_task = Some(tokio::spawn(async move {
let mut buf = [0u8; 8192];
loop {
match inner.read(&mut buf).await {
Ok(0) => break,
Ok(_) => continue,
Err(_) => break,
}
}
}));
}
}
impl<R: AsyncRead + Unpin + Send + Sync + 'static> AsyncRead for RangedDecompressReader<R> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
use std::pin::Pin;
use std::task::Poll;
use tokio::io::ReadBuf;
let this = self.as_mut().get_mut();
loop {
// If we've returned all the bytes we need, return EOF
if this.bytes_returned >= this.target_length {
this.start_drain();
return Poll::Ready(Ok(()));
}
// Read from the inner stream
let buf_capacity = buf.remaining();
if buf_capacity == 0 {
return Poll::Ready(Ok(()));
}
let scratch_len = std::cmp::min(this.scratch.len(), std::cmp::max(buf_capacity, 1));
let mut temp_read_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
let Some(inner) = this.inner.as_mut() else {
return Poll::Ready(Ok(()));
};
match Pin::new(inner).poll_read(cx, &mut temp_read_buf) {
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Ready(Ok(())) => {
let n = temp_read_buf.filled().len();
if n == 0 {
// EOF from inner stream
if this.current_offset < this.target_offset {
// We haven't reached the target offset yet - this is an error
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
format!(
"Unexpected EOF: only read {} bytes, target offset is {}",
this.current_offset, this.target_offset
),
)));
}
// Normal EOF after reaching target
return Poll::Ready(Ok(()));
}
// Update current position
let old_offset = this.current_offset;
this.current_offset += n;
// Check if we're still in the skip phase
if old_offset < this.target_offset {
// We're still skipping data
let skip_end = std::cmp::min(this.current_offset, this.target_offset);
let bytes_to_skip_in_this_read = skip_end - old_offset;
if this.current_offset <= this.target_offset {
// All data in this read should be skipped
tracing::trace!("Skipping {} bytes at offset {}", n, old_offset);
// Continue reading in the loop instead of recursive call
continue;
} else {
// Partial skip: some data should be returned
let data_start_in_buffer = bytes_to_skip_in_this_read;
let available_data = n - data_start_in_buffer;
let bytes_to_return = std::cmp::min(
available_data,
std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned),
);
if bytes_to_return > 0 {
let data_slice =
&temp_read_buf.filled()[data_start_in_buffer..data_start_in_buffer + bytes_to_return];
buf.put_slice(data_slice);
this.bytes_returned += bytes_to_return;
tracing::trace!(
"Skipped {} bytes, returned {} bytes at offset {}",
bytes_to_skip_in_this_read,
bytes_to_return,
old_offset
);
}
return Poll::Ready(Ok(()));
}
} else {
// We're in the data return phase
let bytes_to_return =
std::cmp::min(n, std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned));
if bytes_to_return > 0 {
buf.put_slice(&temp_read_buf.filled()[..bytes_to_return]);
this.bytes_returned += bytes_to_return;
tracing::trace!("Returned {} bytes at offset {}", bytes_to_return, old_offset);
}
return Poll::Ready(Ok(()));
}
}
}
let Some(inner) = this.inner.as_mut() else {
return Poll::Ready(Ok(()));
};
if inner.limit() == 0 {
this.finish();
return Poll::Ready(Ok(()));
}
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
let before = buf.filled().len();
ready!(Pin::new(&mut *inner).poll_read(cx, buf))?;
if before == buf.filled().len() {
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"decompressed stream ended before the requested range was complete",
)));
}
if inner.limit() == 0 {
this.finish();
}
Poll::Ready(Ok(()))
}
}
impl<R: AsyncRead + Unpin + Send + Sync + 'static> Drop for RangedDecompressReader<R> {
fn drop(&mut self) {
if self.bytes_returned >= self.target_length {
self.start_drain();
if self.inner.as_ref().is_some_and(|inner| inner.limit() == 0) {
self.finish();
}
}
}
/// A wrapper that ensures the inner stream is fully consumed even if the outer reader stops early.
/// This prevents broken pipe errors in erasure coding scenarios where the writer expects
/// the full stream to be consumed.
fn drain_stream<R: AsyncRead + Unpin + Send + 'static>(mut stream: R) {
drop(tokio::spawn(async move {
let mut buf = [0u8; 8192];
while matches!(stream.read(&mut buf).await, Ok(n) if n > 0) {}
}));
}
/// Drains the source in the background if dropped before observing its EOF.
pub struct StreamConsumer<R: AsyncRead + Unpin + Send + 'static> {
inner: Option<R>,
consumer_task: Option<tokio::task::JoinHandle<()>>,
}
impl<R: AsyncRead + Unpin + Send + 'static> StreamConsumer<R> {
pub fn new(inner: R) -> Self {
Self {
inner: Some(inner),
consumer_task: None,
}
}
fn ensure_consumer_started(&mut self) {
if self.consumer_task.is_none() && self.inner.is_some() {
let mut inner = self.inner.take().unwrap();
let task = tokio::spawn(async move {
let mut buf = [0u8; 8192];
loop {
match inner.read(&mut buf).await {
Ok(0) => break, // EOF
Ok(_) => continue, // Keep consuming
Err(_) => break, // Error, stop consuming
}
}
});
self.consumer_task = Some(task);
}
Self { inner: Some(inner) }
}
}
impl<R: AsyncRead + Unpin + Send + 'static> AsyncRead for StreamConsumer<R> {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
use std::pin::Pin;
use std::task::Poll;
if let Some(ref mut inner) = self.inner {
Pin::new(inner).poll_read(cx, buf)
} else {
Poll::Ready(Ok(())) // EOF
let Some(inner) = self.inner.as_mut() else {
return Poll::Ready(Ok(()));
};
if buf.remaining() == 0 {
return Poll::Ready(Ok(()));
}
let before = buf.filled().len();
ready!(Pin::new(inner).poll_read(cx, buf))?;
if before == buf.filled().len() {
self.inner = None;
}
Poll::Ready(Ok(()))
}
}
impl<R: AsyncRead + Unpin + Send + 'static> Drop for StreamConsumer<R> {
fn drop(&mut self) {
self.ensure_consumer_started();
if let Some(inner) = self.inner.take() {
drain_stream(inner);
}
}
}
@@ -1666,6 +1584,129 @@ mod tests {
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
}
#[tokio::test]
async fn ranged_reader_fills_large_buffers_without_overreading() {
let data = vec![0x32; 128 * 1024];
let length = 64 * 1024;
let mut reader = RangedDecompressReader::new(Cursor::new(data.clone()), 0, length as i64, data.len()).unwrap();
let mut output = vec![0xa5; data.len()];
assert_eq!(reader.read(&mut output).await.unwrap(), length);
assert_eq!(&output[..length], &data[..length]);
assert!(output[length..].iter().all(|&byte| byte == 0xa5));
assert_eq!(reader.read(&mut output).await.unwrap(), 0);
}
#[tokio::test]
async fn ranged_reader_skips_in_bulk_with_a_small_response_buffer() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct CountReads {
cursor: Cursor<Vec<u8>>,
calls: Arc<AtomicUsize>,
}
impl AsyncRead for CountReads {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
self.calls.fetch_add(1, Ordering::Relaxed);
Pin::new(&mut self.cursor).poll_read(cx, buf)
}
}
let skip = 512 * 1024;
let mut data = vec![0xa5; skip];
data.extend_from_slice(b"wanted bytes here");
let total = data.len();
let calls = Arc::new(AtomicUsize::new(0));
let inner = CountReads {
cursor: Cursor::new(data),
calls: Arc::clone(&calls),
};
let mut reader = RangedDecompressReader::new(inner, skip, 16, total).unwrap();
let mut output = [0; 16];
reader.read_exact(&mut output).await.unwrap();
assert_eq!(&output, b"wanted bytes her");
assert_eq!(calls.load(Ordering::Relaxed), 65, "64 discards and one response read");
}
#[tokio::test]
async fn ranged_reader_yields_while_skipping_an_unindexed_prefix() {
let skip = 2 * 1024 * 1024;
let data = vec![0x36; skip + 1];
let total = data.len();
let mut reader = RangedDecompressReader::new(Cursor::new(data), skip, 1, total).unwrap();
let mut output = [0; 1];
let mut buf = ReadBuf::new(&mut output);
let mut yielded = false;
std::future::poll_fn(|cx| {
let poll = Pin::new(&mut reader).poll_read(cx, &mut buf);
yielded |= poll.is_pending();
poll
})
.await
.unwrap();
assert!(yielded, "a long discard must yield even when the source stays ready");
assert_eq!(buf.filled(), &[0x36]);
}
#[tokio::test]
async fn ranged_reader_releases_the_source_when_the_range_completes() {
use tokio::io::AsyncWriteExt;
let (source, mut producer) = tokio::io::duplex(16);
producer.write_all(b"abcxyz").await.unwrap();
let mut reader = RangedDecompressReader::new(source, 0, 3, 6).unwrap();
let mut body = [0; 3];
reader.read_exact(&mut body).await.unwrap();
assert_eq!(&body, b"abc");
let error = producer
.write_all(b"!")
.await
.expect_err("completed range must release the pipe");
assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);
assert_eq!(reader.read(&mut body).await.unwrap(), 0);
}
#[tokio::test]
async fn ranged_reader_drains_the_source_when_requested() {
use tokio::io::AsyncWriteExt;
let (source, mut producer) = tokio::io::duplex(8);
producer.write_all(b"abc").await.unwrap();
let mut reader = RangedDecompressReader::new_draining(source, 0, 3, 19).unwrap();
let mut body = [0; 3];
reader.read_exact(&mut body).await.unwrap();
assert_eq!(&body, b"abc");
tokio::time::timeout(std::time::Duration::from_secs(2), producer.write_all(b"0123456789abcdef"))
.await
.expect("completed range must start draining the source")
.expect("draining must keep the pipe open");
}
#[tokio::test]
async fn stream_consumer_observes_eof_only_with_a_nonempty_buffer() {
let mut reader = StreamConsumer::new(Cursor::new(b"body"));
assert_eq!(reader.read(&mut []).await.unwrap(), 0);
let mut output = Vec::new();
reader.read_to_end(&mut output).await.unwrap();
assert_eq!(output, b"body");
assert!(reader.inner.is_none(), "observed EOF needs no background drain");
}
#[tokio::test]
async fn ranged_decompress_reader_rejects_eof_inside_the_requested_range() {
let mut reader = RangedDecompressReader::new(Cursor::new(b"abc"), 1, 3, 4).unwrap();
let mut output = Vec::new();
let error = reader.read_to_end(&mut output).await.expect_err("short range must fail");
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
assert_eq!(output, b"bc");
}
#[tokio::test]
async fn test_ranged_decompress_reader_from_start() {
let original_data = b"Hello, World! This is a test.";
@@ -2688,10 +2729,6 @@ mod tests {
let (compressed_offset, uncompressed_offset) = decoded.find(2_097_152).expect("seek into decoded index");
assert!(compressed_offset > 0);
assert_eq!(uncompressed_offset, 2_097_152);
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, 2_097_152);
assert!(physical_offset > 0);
assert_eq!(decompressed_skip, 0);
let range = HTTPRangeSpec {
is_suffix_length: false,
start: 2_097_152,
@@ -2830,7 +2867,8 @@ mod tests {
assert!(compressed_offset > 0);
assert_eq!(uncompressed_offset, range.start);
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, range.start);
let (physical_offset, _, decompressed_skip) =
compressed_storage_window(&object_info, range.start as usize, 10).expect("indexed range");
assert!(physical_offset > 0);
assert_eq!(decompressed_skip, 0);
@@ -2838,14 +2876,14 @@ mod tests {
.await
.expect("MinIO headerless compression index should be decoded");
assert_eq!(plan.storage_offset as i64, physical_offset);
assert_eq!(plan.storage_offset, physical_offset);
assert_eq!(plan.storage_length, object_info.size - plan.storage_offset as i64);
assert_eq!(plan.object_size, 10);
}
#[cfg(feature = "rio-v2")]
#[test]
fn test_get_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
fn test_get_encrypted_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
let mut index = Index::new();
index.add(0, 0).unwrap();
index.add(200_000, 2_097_152).unwrap();
@@ -2879,7 +2917,7 @@ mod tests {
};
let (physical_offset, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
get_compressed_offsets(&object_info, 2_097_152);
get_encrypted_compressed_offsets(&object_info, 2_097_152);
assert_eq!(first_part_idx, 0);
assert_eq!(physical_offset, (expected_comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE);
@@ -12,7 +12,6 @@ const HISTORICAL_INDEX: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/compression-index/pre-zigzag-index.bin"
));
#[cfg(not(feature = "rio-v2"))]
const CURRENT_INDEX: &[u8] =
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/compression-index/zigzag-index.bin"));
const PLAINTEXT_LEN: usize = 3 * 1024 * 1024 + 123;
@@ -161,6 +160,16 @@ async fn truncated_index_falls_back_without_truncating_the_range() {
assert_eq!(actual, fixture_plaintext()[start..start + 97]);
}
#[test]
fn compression_metadata_requires_one_complete_index() {
use crate::io_support::rio::decode_compression_index_bytes;
let index = Bytes::from_static(CURRENT_INDEX);
assert!(decode_compression_index_bytes(&index).is_some());
let trailing = Bytes::from([CURRENT_INDEX, b"trailing bytes"].concat());
assert!(decode_compression_index_bytes(&trailing).is_none());
}
#[tokio::test]
async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
let info = fixture_info(HISTORICAL_INDEX);
@@ -183,3 +192,105 @@ async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
assert!(actual.len() < PLAINTEXT_LEN);
}
#[tokio::test]
async fn compressed_ranges_bound_storage_for_large_index_and_unsampled_tail() {
use crate::io_support::rio::compression_index_storage_bytes;
use rustfs_rio::{CompressReader, TryGetIndex};
const BLOCK: usize = 1024 * 1024;
const BLOCKS: usize = 203;
const TAIL: usize = 32 * 1024;
const LENGTH: usize = 16 * 1024;
let len = BLOCK * BLOCKS + TAIL;
let mut compressor = CompressReader::new(
tokio::io::repeat(b'a')
.take((len - TAIL) as u64)
.chain(tokio::io::repeat(b'z').take(TAIL as u64)),
CompressionAlgorithm::Lz4,
);
let mut stored = Vec::new();
compressor.read_to_end(&mut stored).await.expect("compress fixture");
let index = compressor.try_get_index().expect("legacy writer has an index");
assert!(index.len() > 200);
assert_eq!(index.total_uncompressed, (len - TAIL) as i64, "short final block is not indexed");
let index = compression_index_storage_bytes(index);
let mut info = fixture_info(&index);
info.size = stored.len() as i64;
info.actual_size = len as i64;
let part = &mut Arc::make_mut(&mut info.parts)[0];
part.size = stored.len();
part.actual_size = len as i64;
for start in [1000, 9999, BLOCK - 7, len - LENGTH] {
let range = if start == len - LENGTH {
HTTPRangeSpec {
is_suffix_length: true,
start: -(LENGTH as i64),
end: -1,
}
} else {
HTTPRangeSpec {
is_suffix_length: false,
start: start as i64,
end: (start + LENGTH - 1) as i64,
}
};
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
.await
.expect("plan valid range");
let physical_start = plan.storage_offset;
let physical_end = physical_start + usize::try_from(plan.storage_length).expect("positive storage window");
let mut output = Vec::new();
let (mut reader, _, _) = plan
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
.expect("valid plaintext range has a reader");
reader.read_to_end(&mut output).await.expect("decode from planned window");
let expected_byte = if start == len - LENGTH { b'z' } else { b'a' };
assert_eq!(output, vec![expected_byte; LENGTH], "range starting at {start}");
assert!(
physical_end - physical_start < stored.len() / 20,
"range at {start} reads too much compressed data"
);
if start == len - LENGTH {
assert!(physical_start > stored.len() * 9 / 10, "suffix must seek within the final part");
}
}
}
#[tokio::test]
async fn compressed_multipart_window_stops_at_the_last_covering_part() {
let mut info = fixture_info(CURRENT_INDEX);
let parts = Arc::make_mut(&mut info.parts);
parts.push(ObjectPartInfo {
number: 2,
..parts[0].clone()
});
parts.push(ObjectPartInfo {
number: 3,
..parts[0].clone()
});
info.size *= 3;
info.actual_size = (PLAINTEXT_LEN * 3) as i64;
let range = HTTPRangeSpec {
is_suffix_length: false,
start: PLAINTEXT_LEN as i64 - 16,
end: PLAINTEXT_LEN as i64 + 15,
};
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
.await
.expect("valid range across parts");
let physical_start = plan.storage_offset;
let physical_end = physical_start + plan.storage_length as usize;
assert!(physical_end > STREAM.len(), "range crosses the stored part boundary");
assert!(physical_end < STREAM.len() * 2, "range should stop at the first checkpoint in part two");
let stored = STREAM.repeat(3);
let (mut reader, _, _) = plan
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
.expect("create multipart range reader");
let mut output = Vec::new();
reader.read_to_end(&mut output).await.expect("decode part boundary");
let plaintext = fixture_plaintext();
assert_eq!(output, [&plaintext[PLAINTEXT_LEN - 16..], &plaintext[..16]].concat());
}
+8
View File
@@ -54,6 +54,7 @@ use crate::store::delete_recovery_runtime::DeleteRecoveryHints;
use rustfs_lock::{GlobalLockManager, get_global_lock_manager};
use rustfs_s3_types::Region;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroUsize;
use std::sync::{
Arc, OnceLock,
atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
@@ -234,6 +235,8 @@ pub struct InstanceContext {
/// drift out of sync). Stored as one value so the three predicates can
/// never observe a torn intermediate state.
erasure_kind: RwLock<SetupType>,
/// Snapshot of the creating thread's affinity and CPU quota for instance workers.
worker_parallelism: NonZeroUsize,
list_read_budget: OnceLock<ListReadBudget>,
#[cfg(feature = "internode-transport")]
internode_data_transport: OnceLock<Arc<dyn crate::api::rpc::InternodeDataTransport>>,
@@ -464,6 +467,7 @@ impl InstanceContext {
fn with_lock_manager(lock_manager: Arc<GlobalLockManager>) -> Self {
Self {
erasure_kind: RwLock::new(SetupType::Unknown),
worker_parallelism: super::detect_worker_parallelism(),
list_read_budget: OnceLock::new(),
#[cfg(feature = "internode-transport")]
internode_data_transport: OnceLock::new(),
@@ -515,6 +519,10 @@ impl InstanceContext {
Self::with_lock_manager(lock_manager)
}
pub(crate) fn worker_parallelism(&self) -> NonZeroUsize {
self.worker_parallelism
}
/// This instance's namespace lock manager.
pub fn lock_manager(&self) -> Arc<GlobalLockManager> {
self.lock_manager.clone()
+4
View File
@@ -18,3 +18,7 @@ pub(crate) mod global;
pub(crate) mod instance;
pub(crate) mod sources;
pub(crate) mod usage_watch;
pub(crate) fn detect_worker_parallelism() -> std::num::NonZeroUsize {
std::thread::available_parallelism().unwrap_or(std::num::NonZeroUsize::MIN)
}
@@ -2443,6 +2443,197 @@ mod tests {
});
}
/// A stopped run left a multipart version committed on the target pool
/// and still present on the source. Its metadata reads back from two of
/// the four target drives, but a copy held only there is one drive loss
/// from unreadable: while the target set is below write quorum the retry
/// must keep the source. Once the drives are back it settles on the
/// committed copy without writing it again.
#[test]
#[serial_test::serial]
fn real_rebalance_retry_keeps_the_source_while_the_committed_target_is_below_write_quorum() {
run_large_stack_async_test("rebalance-degraded-equivalent-target", || async {
const REBALANCE_ID: &str = "rebalance-degraded-equivalent-target";
let (_temp_dirs, store, _peer) = super::super::test_pool_stores_with_contexts(None, true, 2, 4).await;
let bucket = "rebalance-degraded-target";
let object = "multipart.bin";
Box::pin(store.make_bucket(
bucket,
&MakeBucketOptions {
versioning_enabled: true,
..Default::default()
},
))
.await
.expect("create bucket");
prepare_rebalance_test_volumes(&store).await;
let incarnation = store.bucket_incarnation_id(bucket).await.expect("bucket incarnation");
let rebalance_meta = active_rebalance_meta(REBALANCE_ID);
rebalance_meta
.save(Arc::clone(&store.pools[0]))
.await
.expect("persist the active rebalance run");
*store.rebalance_meta.write().await = Some(rebalance_meta);
let source_set = store.pools[0].get_disks_by_key(object);
let target_set = store.pools[1].get_disks_by_key(object);
// Four drives per set written as 2+2: read quorum 2, write quorum 3.
let storage_class = crate::config::storageclass::lookup_config_for_pools_without_env(
&rustfs_config::server_config::KVS::new(),
&[4, 4],
)
.expect("the automatic storage class resolves for both pools");
source_set.set_test_storage_class_config(storage_class.clone());
target_set.set_test_storage_class_config(storage_class);
let write_opts = ObjectOptions {
versioned: true,
..Default::default()
};
let upload = Box::pin(source_set.new_multipart_upload(bucket, object, &write_opts))
.await
.expect("create the source multipart upload");
let parts = [vec![0x5a; 5 << 20], vec![0xa5; 1024]];
let mut completed = Vec::with_capacity(parts.len());
for (index, bytes) in parts.iter().enumerate() {
let part = Box::pin(source_set.put_object_part(
bucket,
object,
&upload.upload_id,
index + 1,
&mut PutObjReader::from_vec(bytes.clone()),
&write_opts,
))
.await
.expect("write a source part");
completed.push(CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
});
}
let written = Box::pin(Arc::clone(&source_set).complete_multipart_upload(
bucket,
object,
&upload.upload_id,
completed,
&write_opts,
))
.await
.expect("complete the source multipart upload");
assert!(written.is_multipart(), "the migration must use its multipart path");
let version_id = written.version_id.expect("the source version id");
let source_versions = || async {
source_set
.load_file_info_versions_exact(bucket, object)
.await
.expect("read source versions")
};
let version = source_versions().await.expect("the source version").versions.remove(0);
assert_eq!(version.version_id, Some(version_id));
// The stopped run: the copy commits on the target and the source
// cleanup never runs.
let read_opts = super::super::migration::rebalance_object_migration_read_opts(&version);
let reader = Box::pin(source_set.get_object_reader(bucket, object, None, HeaderMap::new(), &read_opts))
.await
.expect("read the source version");
let copied = Box::pin(Arc::clone(&store).rebalance_object(0, bucket.to_owned(), reader, Some(incarnation), None))
.await
.expect("commit the copy on the target pool");
assert_eq!(copied, data_movement::DataMovementCopy::Committed);
let committed = target_set
.get_object_info(bucket, object, &read_opts)
.await
.expect("the target holds the committed copy");
assert!(committed.data_dir.is_some());
assert_eq!((committed.data_blocks, committed.parity_blocks), (2, 2), "the target copy must be 2+2");
assert!(source_versions().await.is_some(), "the stopped run left the source in place");
let run_entry = || async {
let entry = metacache_entry_from_source(&source_set, bucket, object).await;
tokio::time::timeout(
StdDuration::from_secs(60),
Box::pin(Arc::clone(&store).rebalance_entry(
RebalanceEntryTarget {
bucket: bucket.to_owned(),
pool_index: 0,
},
entry,
Arc::clone(&source_set),
Arc::new(RebalanceBucketConfigs {
bucket_incarnation_id: Some(incarnation),
..Default::default()
}),
Arc::from(REBALANCE_ID),
CancellationToken::new(),
)),
)
.await
.expect("the entry must finish within the test deadline")
};
let offline = {
let mut disks = target_set.disks.write().await;
[disks[0].take(), disks[1].take()]
};
assert!(offline.iter().all(Option::is_some), "the fixture drives must have been online");
let degraded = target_set
.get_object_info(bucket, object, &read_opts)
.await
.expect("two drives still serve the committed copy's metadata");
assert_eq!(degraded.data_dir, committed.data_dir);
let outcome = run_entry().await;
assert!(
!matches!(outcome, Ok(RebalanceEntryOutcome::Completed)),
"the entry must not complete on a target below write quorum: {outcome:?}"
);
let kept = source_versions()
.await
.expect("the source must survive a target below write quorum");
assert_eq!(kept.versions.len(), 1, "{:?}", kept.versions);
assert_eq!(kept.versions[0].version_id, Some(version_id));
let mut source_reader = Box::pin(source_set.get_object_reader(bucket, object, None, HeaderMap::new(), &read_opts))
.await
.expect("the source version must stay readable");
let mut source_bytes = Vec::new();
source_reader
.stream
.read_to_end(&mut source_bytes)
.await
.expect("drain the source version");
assert_eq!(source_bytes, parts.concat());
{
let mut disks = target_set.disks.write().await;
let [first, second] = offline;
disks[0] = first;
disks[1] = second;
}
let outcome = run_entry().await.expect("rebalance entry on a healthy target");
assert_eq!(outcome, RebalanceEntryOutcome::Completed);
assert!(
source_versions().await.is_none(),
"the source is removed once the target holds the version on write quorum"
);
let settled = target_set
.get_object_info(bucket, object, &read_opts)
.await
.expect("the target still holds the committed copy");
assert_eq!(settled.data_dir, committed.data_dir, "the retry must not rewrite the committed copy");
let mut target_reader = Box::pin(target_set.get_object_reader(bucket, object, None, HeaderMap::new(), &read_opts))
.await
.expect("the committed copy must be readable");
let mut target_bytes = Vec::new();
target_reader
.stream
.read_to_end(&mut target_bytes)
.await
.expect("drain the committed copy");
assert_eq!(target_bytes, parts.concat());
});
}
const TRANSITIONED_REBALANCE_ID: &str = "rebalance-transitioned-source-cleanup";
/// One transitioned source version on pool 0 of a two-pool store with an
+145 -65
View File
@@ -149,7 +149,7 @@ use std::{
time::{Duration, Instant},
};
use tokio::io::{AsyncRead, ReadBuf};
use tokio::sync::{RwLock, mpsc, oneshot};
use tokio::sync::{RwLock, mpsc, oneshot, watch};
use tokio::task::JoinSet;
pub(in crate::set_disk) const EVENT_SET_DISK_READ: &str = "set_disk_read";
@@ -3279,6 +3279,7 @@ fn rename_tail_cleanup_queue() -> &'static RenameTailCleanupQueue {
}
const EVENT_SET_DISK_RENAME_ROLLBACK: &str = "set_disk_rename_rollback";
const PUT_RENAME_POST_QUORUM_DISPATCH_GRACE: Duration = Duration::from_secs(1);
#[derive(Clone, Copy)]
enum RenameDispatchState {
@@ -3305,12 +3306,22 @@ struct RenameBatchGroup {
slots: Vec<usize>,
}
#[derive(Clone)]
struct RenameSlotPaths {
src_bucket: Arc<String>,
src_object: Arc<String>,
dst_bucket: Arc<String>,
dst_object: Arc<String>,
src_bucket: String,
src_object: String,
dst_bucket: String,
dst_object: String,
}
impl RenameSlotPaths {
fn new(src_bucket: &str, src_object: &str, dst_bucket: &str, dst_object: &str) -> Self {
Self {
src_bucket: src_bucket.to_owned(),
src_object: src_object.to_owned(),
dst_bucket: dst_bucket.to_owned(),
dst_object: dst_object.to_owned(),
}
}
}
struct RenameSlotContext {
@@ -3320,20 +3331,22 @@ struct RenameSlotContext {
scanner_token: Option<Uuid>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
publication_scope: Option<crate::object_api::ScannerPublicationCommitScope>,
paths: RenameSlotPaths,
paths: Arc<RenameSlotPaths>,
successful_completion_rank: Option<Arc<AtomicUsize>>,
write_quorum: usize,
dispatch_deadline: Option<disk::RenameDispatchDeadline>,
}
struct RenameOutcomeProducerArgs {
disks: Arc<Vec<Option<DiskStore>>>,
file_infos: Arc<Vec<FileInfo>>,
fence_tokens: Arc<Vec<Option<Uuid>>>,
paths: RenameSlotPaths,
paths: Arc<RenameSlotPaths>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
publication_scope: Option<crate::object_api::ScannerPublicationCommitScope>,
write_quorum: usize,
allow_batch: bool,
dispatch_deadline: Option<disk::RenameDispatchDeadline>,
}
struct RenameOutcomeProducers {
@@ -3827,6 +3840,7 @@ pub(in crate::set_disk) struct RenameDataFenceOptions<'a> {
rollback_receipt: Option<RenameRollbackReceipt>,
multipart_proof_authority: Option<crate::disk::multipart_source::ProofVerificationContext>,
multipart_commit_owner: Option<Arc<MultipartLogicalGuards>>,
bound_dispatch_after_quorum: bool,
}
impl<'a> RenameDataFenceOptions<'a> {
@@ -3842,9 +3856,15 @@ impl<'a> RenameDataFenceOptions<'a> {
rollback_receipt: None,
multipart_proof_authority: None,
multipart_commit_owner: None,
bound_dispatch_after_quorum: false,
}
}
pub(in crate::set_disk) fn with_quorum_bounded_dispatch(mut self, enabled: bool) -> Self {
self.bound_dispatch_after_quorum = enabled;
self
}
pub(in crate::set_disk) fn with_multipart_commit_owner(mut self, owner: Arc<MultipartLogicalGuards>) -> Self {
self.multipart_commit_owner = Some(owner);
self
@@ -4426,6 +4446,7 @@ impl SetDisks {
disk::RenameDataGuards {
scanner_publication_lease_token: context.scanner_token,
namespace_owner: context.namespace_owner.clone(),
dispatch_deadline: context.dispatch_deadline.clone(),
..Default::default()
},
)
@@ -4602,6 +4623,7 @@ impl SetDisks {
publication_scope,
write_quorum,
allow_batch,
dispatch_deadline,
} = args;
debug_assert!(!allow_batch || publication_scope.is_none());
let disk_count = disks.len();
@@ -4626,6 +4648,10 @@ impl SetDisks {
continue;
}
let outcome_tx = outcome_tx.clone();
let dispatch_deadline = dispatch_deadline
.as_ref()
.filter(|_| disk.as_ref().is_some_and(|disk| !disk.is_local()))
.cloned();
let context = RenameSlotContext {
slot,
disk,
@@ -4636,6 +4662,7 @@ impl SetDisks {
paths: paths.clone(),
successful_completion_rank: successful_completion_rank.clone(),
write_quorum,
dispatch_deadline,
};
let resource_unit = resource_unit.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
@@ -4653,6 +4680,7 @@ impl SetDisks {
let group_disks = disks.clone();
let group_tokens = fence_tokens.clone();
let resource_unit = resource_unit.clone();
let dispatch_deadline = dispatch_deadline.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
let prepared = join_all(group.slots.into_iter().map(|slot| {
let context = RenameSlotContext {
@@ -4665,6 +4693,7 @@ impl SetDisks {
paths: paths.clone(),
successful_completion_rank: successful_completion_rank.clone(),
write_quorum,
dispatch_deadline: dispatch_deadline.clone(),
};
async move { (slot, Self::prepare_and_admit_rename_slot(context).await) }
}))
@@ -4736,6 +4765,7 @@ impl SetDisks {
&paths.dst_bucket,
&paths.dst_object,
items,
dispatch_deadline,
)
.await
}
@@ -4844,6 +4874,7 @@ impl SetDisks {
rollback_receipt,
multipart_proof_authority: _,
multipart_commit_owner: _,
bound_dispatch_after_quorum: _,
} = fence_options;
if let Some(file_info) = disks
.iter()
@@ -4864,19 +4895,13 @@ impl SetDisks {
Arc::new(Self::scanner_publication_lease_tokens_for_disks(disks, scanner_publication_lease_tokens)?);
Self::record_rename_batch_candidates(disks, &file_infos, &fanout_fence_tokens, src_bucket, dst_bucket, dst_object);
let coordinator_disks = fanout_disks.clone();
let src_bucket = Arc::new(src_bucket.to_string());
let src_object = Arc::new(src_object.to_string());
let dst_bucket = Arc::new(dst_bucket.to_string());
let dst_object = Arc::new(dst_object.to_string());
let paths = Arc::new(RenameSlotPaths::new(src_bucket, src_object, dst_bucket, dst_object));
let (commit_tx, commit_rx) = oneshot::channel();
let coordinator_failure_receipt = rollback_receipt.clone();
let early_ack_spawn_to_quorum_wait_started = rustfs_io_metrics::put_stage_timer();
let tail_drain = tokio::spawn(crate::disk::with_detached_disk_io_context({
let fanout_src_bucket = src_bucket.clone();
let fanout_src_object = src_object.clone();
let fanout_dst_bucket = dst_bucket.clone();
let fanout_dst_object = dst_object.clone();
let paths = paths.clone();
async move {
let allow_batch = scanner_publication_commit_scope.is_none();
let RenameOutcomeProducers {
@@ -4886,16 +4911,12 @@ impl SetDisks {
disks: fanout_disks.clone(),
file_infos: file_infos.clone(),
fence_tokens: fanout_fence_tokens.clone(),
paths: RenameSlotPaths {
src_bucket: fanout_src_bucket.clone(),
src_object: fanout_src_object.clone(),
dst_bucket: fanout_dst_bucket.clone(),
dst_object: fanout_dst_object.clone(),
},
paths: paths.clone(),
namespace_owner: namespace_commit_guard.clone().map(|owner| owner as Arc<dyn Send + Sync>),
publication_scope: scanner_publication_commit_scope,
write_quorum,
allow_batch,
dispatch_deadline: None,
});
let mut commit_tx = Some(commit_tx);
@@ -4980,7 +5001,7 @@ impl SetDisks {
}
if let Some(commit_tx) = commit_tx.take() {
#[cfg(test)]
rename_fanout_barrier::wait_for_armed_rename_before_early_ack(&fanout_dst_object).await;
rename_fanout_barrier::wait_for_armed_rename_before_early_ack(&paths.dst_object).await;
let _ = commit_tx.send(snapshot_commit);
}
sent_commit = true;
@@ -4998,7 +5019,7 @@ impl SetDisks {
);
#[cfg(test)]
rollback_fault_injection::after_fanout(&fanout_dst_object);
rollback_fault_injection::after_fanout(&paths.dst_object);
if rustfs_io_metrics::put_stage_metrics_enabled() {
let fanout_success = errs.iter().filter(|err| err.is_none()).count();
let fanout_error = errs.len().saturating_sub(fanout_success + fanout_panic);
@@ -5021,7 +5042,7 @@ impl SetDisks {
&errs,
&dispatch_states,
&data_dirs,
(&fanout_dst_bucket, &fanout_dst_object),
(&paths.dst_bucket, &paths.dst_object),
RenameRollbackOwnership {
receipt: rollback_receipt,
namespace_commit_guard,
@@ -5068,11 +5089,10 @@ impl SetDisks {
let Some(disk) = disk.clone() else {
continue;
};
let dst_bucket = fanout_dst_bucket.clone();
let dst_object = fanout_dst_object.clone();
let paths = paths.clone();
backup_reclaims.push(tokio::spawn(async move {
let backup_path = format!("{dst_object}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
disk.delete(&dst_bucket, &backup_path, DeleteOptions::default()).await
let backup_path = format!("{}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}", paths.dst_object);
disk.delete(&paths.dst_bucket, &backup_path, DeleteOptions::default()).await
}));
}
for result in join_all(backup_reclaims).await {
@@ -5081,16 +5101,16 @@ impl SetDisks {
Ok(Err(DiskError::FileNotFound | DiskError::VolumeNotFound)) => {}
Ok(Err(err)) => {
warn!(
dst_bucket = %fanout_dst_bucket,
dst_object = %fanout_dst_object,
dst_bucket = %paths.dst_bucket,
dst_object = %paths.dst_object,
error = %err,
"rollback backup reclamation failed after committed rename"
);
}
Err(join_err) => {
warn!(
dst_bucket = %fanout_dst_bucket,
dst_object = %fanout_dst_object,
dst_bucket = %paths.dst_bucket,
dst_object = %paths.dst_object,
error = %join_err,
"rollback backup reclamation task failed after committed rename"
);
@@ -5136,7 +5156,7 @@ impl SetDisks {
let commit = match commit_rx.await {
Ok(commit) => commit,
Err(_) => {
record_indeterminate_rename(disks, (&dst_bucket, &dst_object), coordinator_failure_receipt).await;
record_indeterminate_rename(disks, (dst_bucket, dst_object), coordinator_failure_receipt).await;
return Err(DiskError::Unexpected);
}
};
@@ -5216,6 +5236,7 @@ impl SetDisks {
rollback_receipt,
multipart_proof_authority,
multipart_commit_owner,
bound_dispatch_after_quorum,
} = fence_options;
if let Some(file_info) = disks
.iter()
@@ -5239,28 +5260,15 @@ impl SetDisks {
};
let mut errs = vec![Some(DiskError::Unexpected); disks.len()];
let src_bucket = Arc::new(src_bucket.to_string());
let src_object = Arc::new(src_object.to_string());
let dst_bucket = Arc::new(dst_bucket.to_string());
let dst_object = Arc::new(dst_object.to_string());
let paths = Arc::new(RenameSlotPaths::new(src_bucket, src_object, dst_bucket, dst_object));
let disk_count = disks.len();
let fanout_disks = Arc::new(disks.to_vec());
let fanout_file_infos = Arc::new(file_infos);
let fanout_fence_tokens =
Arc::new(Self::scanner_publication_lease_tokens_for_disks(disks, scanner_publication_lease_tokens)?);
Self::record_rename_batch_candidates(
disks,
&fanout_file_infos,
&fanout_fence_tokens,
src_bucket.as_str(),
dst_bucket.as_str(),
dst_object.as_str(),
);
let fanout_src_bucket = src_bucket.clone();
let fanout_src_object = src_object.clone();
let fanout_dst_bucket = dst_bucket.clone();
let fanout_dst_object = dst_object.clone();
Self::record_rename_batch_candidates(disks, &fanout_file_infos, &fanout_fence_tokens, src_bucket, dst_bucket, dst_object);
let fanout_paths = paths.clone();
let fanout_publication_scope = scanner_publication_commit_scope.clone();
let logical_guards = multipart_commit_owner;
let multipart_commit_owner = logical_guards
@@ -5278,13 +5286,16 @@ impl SetDisks {
// fan-out owner, even if the caller future is cancelled.
let _fanout_publication_scope = fanout_publication_scope;
let _namespace_commit_guard = fanout_namespace_commit_guard.clone();
let paths = RenameSlotPaths {
src_bucket: fanout_src_bucket,
src_object: fanout_src_object,
dst_bucket: fanout_dst_bucket,
dst_object: fanout_dst_object.clone(),
};
let allow_batch = !protected_multipart && scanner_publication_commit_scope.is_none();
let (dispatch_deadline_tx, dispatch_deadline) = if bound_dispatch_after_quorum
&& fanout_disks.iter().flatten().count() > write_quorum
&& fanout_disks.iter().flatten().any(|disk| !disk.is_local())
{
let (tx, rx) = watch::channel(None);
(Some(tx), Some(rx))
} else {
(None, None)
};
let RenameOutcomeProducers {
outcomes: mut outcome_rx,
mut tasks,
@@ -5292,19 +5303,29 @@ impl SetDisks {
disks: fanout_disks,
file_infos: fanout_file_infos.clone(),
fence_tokens: fanout_fence_tokens,
paths,
paths: fanout_paths.clone(),
namespace_owner: fanout_namespace_owner,
publication_scope: scanner_publication_commit_scope,
write_quorum,
allow_batch,
dispatch_deadline,
});
let mut results = Vec::with_capacity(disk_count);
let mut successful = 0;
while let Some(outcome) = outcome_rx.recv().await {
if let Some(tx) = dispatch_deadline_tx.as_ref()
&& matches!(&outcome.completion, Ok(Ok(_)))
{
successful += 1;
if successful == write_quorum {
tx.send_replace(Some(tokio::time::Instant::now() + PUT_RENAME_POST_QUORUM_DISPATCH_GRACE));
}
}
results.push(outcome);
}
while tasks.join_next().await.is_some() {}
#[cfg(test)]
rollback_fault_injection::after_fanout(&fanout_dst_object);
rollback_fault_injection::after_fanout(&fanout_paths.dst_object);
(results, fanout_file_infos)
};
let fanout_future = crate::disk::with_detached_disk_io_context(fanout_future);
@@ -5338,7 +5359,7 @@ impl SetDisks {
let (results, file_infos) = match fanout_result {
Ok(result) => result,
Err(_) => {
record_indeterminate_rename(disks, (&dst_bucket, &dst_object), rollback_receipt).await;
record_indeterminate_rename(disks, (dst_bucket, dst_object), rollback_receipt).await;
return Err(DiskError::Unexpected);
}
};
@@ -5471,7 +5492,7 @@ impl SetDisks {
// Destination-only Undo cannot restore a consumed MPU head.
// Only this failed owner can spend the original native caps.
owner
.failed_owned(disks, &file_infos, &src_object, (&dst_bucket, &dst_object), namespace_commit_guard)
.failed_owned(disks, &file_infos, src_object, (dst_bucket, dst_object), namespace_commit_guard)
.await;
} else {
rollback_failed_rename(
@@ -5480,7 +5501,7 @@ impl SetDisks {
&errs,
&dispatch_states,
&data_dirs,
(&dst_bucket, &dst_object),
(dst_bucket, dst_object),
RenameRollbackOwnership {
receipt: rollback_receipt,
namespace_commit_guard,
@@ -5526,11 +5547,10 @@ impl SetDisks {
let Some(disk) = disk.clone() else {
continue;
};
let dst_bucket = dst_bucket.clone();
let dst_object = dst_object.clone();
let paths = paths.clone();
backup_reclaims.push(tokio::spawn(async move {
let backup_path = format!("{dst_object}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
disk.delete(&dst_bucket, &backup_path, DeleteOptions::default()).await
let backup_path = format!("{}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}", paths.dst_object);
disk.delete(&paths.dst_bucket, &backup_path, DeleteOptions::default()).await
}));
}
for result in join_all(backup_reclaims).await {
@@ -12818,6 +12838,66 @@ mod tests {
}
}
#[tokio::test]
#[serial_test::serial(capacity_dirty_scope)]
async fn rename_data_bounds_cold_connect_after_durable_quorum() {
const DISKS: usize = 4;
let bucket = "rename-connect-tail-bucket";
let object = "rename-connect-tail-object";
let (dirs, mut disks) = call_counter_local_disks(bucket, DISKS).await;
prepare_rename_source_dirs(&dirs, &disks, "source").await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind cold peer");
// The TCP socket remains open, but there is no TLS server to finish the dial.
let endpoint = crate::disk::endpoint::Endpoint {
url: url::Url::parse(&format!("https://{}/data/rustfs0", listener.local_addr().expect("cold peer address")))
.expect("cold peer URL"),
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx: 3,
};
disks[DISKS - 1] = Some(
crate::disk::new_disk(
&endpoint,
&crate::disk::DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.expect("construct remote disk"),
);
let file_infos = rename_commit_fileinfos(object, DISKS, "bounded-connect-etag");
let commit = temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CONNECT_TIMEOUT_SECS, Some("15"))], async {
tokio::time::timeout(
Duration::from_secs(5),
SetDisks::rename_data_owned_with_fence(
&disks,
(RUSTFS_META_TMP_BUCKET, "source"),
file_infos,
(bucket, object),
false,
RenameDataFenceOptions::new(3, None).with_quorum_bounded_dispatch(true),
),
)
.await
.expect("durable quorum must finish before the silent peer's dial deadline")
.expect("three durable renames must satisfy write quorum")
})
.await;
assert_eq!(commit.convergence, RenameConvergence::PartialCommit);
assert!(commit.needs_immediate_heal());
assert!(commit.tail_drain.is_none());
for dir in dirs.iter().take(3) {
let reopened = reopen_local_disk(dir).await;
let stored = reopened
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("quorum metadata survives reopening");
assert_eq!(stored.metadata.get("etag").map(String::as_str), Some("bounded-connect-etag"));
}
}
#[tokio::test]
#[serial_test::serial(capacity_dirty_scope)]
async fn rename_data_without_tail_handoff_waits_after_write_quorum() {
+35
View File
@@ -7207,6 +7207,41 @@ impl SetDisks {
.any(|copy| FileMeta::load(&copy.buf).is_ok_and(|meta| meta.find_version(Some(version_id)).is_ok()))
}
/// Whether a write quorum of this set's drives hold `version_id` of the
/// key as the committed copy in `data_dir`. An object read answers from
/// read quorum, which on a data = parity set is one drive loss away from
/// unreadable; a data-movement caller that removes the source on this
/// answer needs the drives a new copy would have been written to. Every
/// drive is asked in one fanout, and a drive counts only for the shard
/// its own slot is assigned.
pub(crate) async fn holds_version_on_write_quorum(
&self,
bucket: &str,
object: &str,
version_id: Uuid,
data_dir: Option<Uuid>,
) -> Result<bool> {
let disks = self.disk_inventory().await;
let (copies, _) =
Self::read_all_fileinfo(&disks, "", bucket, object, &version_id.to_string(), false, false, false).await?;
let mut holders: HashMap<[u8; 32], (usize, usize)> = HashMap::new();
for (slot, copy) in copies.iter().enumerate() {
if !file_info_is_valid_for_metadata(copy)
|| copy.deleted
|| copy.version_id.unwrap_or_else(Uuid::nil) != version_id
|| copy.data_dir != data_dir
|| !copy.has_valid_erasure_geometry()
|| copy.erasure.distribution.len() != copies.len()
|| copy.erasure.distribution.get(slot) != Some(&copy.erasure.index)
{
continue;
}
let required = copy.write_quorum(self.default_write_quorum());
holders.entry(Self::file_info_quorum_hash(copy)).or_insert((0, required)).0 += 1;
}
Ok(holders.into_values().any(|(drives, required)| drives >= required))
}
/// Publish an internal tier free-version record without changing its
/// delete-marker shape or remote-tier identity. The caller holds the
/// source and target object locks; a write quorum is required before the
+98 -26
View File
@@ -25,7 +25,8 @@ use super::super::{
reduce_write_quorum_errs,
};
use crate::api::bucket::metadata_sys;
use crate::disk::DiskAPI;
use crate::disk::{DiskAPI, DiskStore, VolumeInfo};
use futures::{Stream, StreamExt, stream::FuturesUnordered};
#[derive(Clone, Copy)]
pub(crate) enum BucketInfoQuorum {
@@ -34,6 +35,39 @@ pub(crate) enum BucketInfoQuorum {
HealCandidates,
}
async fn stat_bucket_volume(disk: Option<DiskStore>, bucket: &str) -> crate::disk::error::Result<VolumeInfo> {
match disk {
Some(disk) => disk.stat_volume(bucket).await,
None => Err(DiskError::DiskNotFound),
}
}
async fn collect_bucket_presence(
mut probes: impl Stream<Item = crate::disk::error::Result<()>> + Unpin,
disk_count: usize,
) -> Result<()> {
let required = disk_count.div_ceil(2).max(1);
let mut successes = 0;
let mut errors = Vec::new();
while let Some(result) = probes.next().await {
match result {
Ok(()) => {
successes += 1;
// The reducer favors success on ties, so the remaining disks
// cannot change this decision. Presence doesn't use timestamps.
if successes == required {
return Ok(());
}
}
Err(err) => errors.push(Some(err)),
}
}
errors.resize_with(errors.len() + successes, || None);
Err(reduce_read_quorum_errs(&errors, BUCKET_OP_IGNORED_ERRS, required)
.unwrap_or(DiskError::ErasureReadQuorum)
.into())
}
impl SetDisks {
/// Require proof from every configured disk before retiring a bucket
/// generation whose visible volume was removed outside the storage API.
@@ -43,12 +77,9 @@ impl SetDisks {
return Err(Error::ErasureReadQuorum);
}
let futures = disks.into_iter().map(|disk| async move {
match disk {
Some(disk) => disk.stat_volume(bucket).await.map(|_| ()),
None => Err(DiskError::DiskNotFound),
}
});
let futures = disks
.into_iter()
.map(|disk| async move { stat_bucket_volume(disk, bucket).await.map(|_| ()) });
let results = join_all(futures).await;
let mut volume_present = false;
let mut first_unknown = None;
@@ -70,31 +101,32 @@ impl SetDisks {
Ok(())
}
pub(crate) async fn check_bucket_presence_at_read_quorum(&self, bucket: &str) -> Result<()> {
let disks = self.disk_inventory().await;
let disk_count = disks.len();
let probes = disks
.into_iter()
.map(|disk| async move { stat_bucket_volume(disk, bucket).await.map(|_| ()) })
.collect::<FuturesUnordered<_>>();
collect_bucket_presence(probes, disk_count).await
}
pub(crate) async fn stat_bucket_with_quorum(&self, bucket: &str, quorum: BucketInfoQuorum) -> Result<BucketInfo> {
let disks = self.disk_inventory().await;
let disk_count = disks.len();
let mut futures = Vec::with_capacity(disk_count);
for disk in disks {
let bucket = bucket.to_string();
futures.push(async move {
match disk {
Some(disk) => disk.stat_volume(&bucket).await,
None => Err(DiskError::DiskNotFound),
}
});
}
let results = join_all(futures).await;
let mut infos = Vec::with_capacity(results.len());
let probes = disks.into_iter().map(|disk| stat_bucket_volume(disk, bucket));
let results = join_all(probes).await;
let mut first_info = None;
let mut errs = Vec::with_capacity(results.len());
for result in results {
match result {
Ok(info) => {
infos.push(Some(info));
if first_info.is_none() {
first_info = Some(info);
}
errs.push(None);
}
Err(err) => {
infos.push(None);
errs.push(Some(err));
}
}
@@ -113,10 +145,7 @@ impl SetDisks {
return Err(err.into());
}
infos
.into_iter()
.flatten()
.next()
first_info
.map(|info| BucketInfo {
name: info.name,
created: info.created,
@@ -341,3 +370,46 @@ impl BucketOperations for SetDisks {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::{FutureExt, stream};
#[test]
fn bucket_presence_returns_with_a_silent_peer() {
let probes = stream::iter([Err(DiskError::VolumeNotFound), Ok(()), Ok(())]).chain(stream::pending());
collect_bucket_presence(probes, 4)
.now_or_never()
.expect("read quorum must return before the fourth probe replies")
.expect("two successes win even if both other disks report a missing volume");
}
#[tokio::test]
async fn bucket_presence_preserves_absence_and_read_quorum_errors() {
let probes = stream::iter([Ok(()), Err(DiskError::VolumeNotFound), Err(DiskError::DiskNotFound)]);
assert!(
collect_bucket_presence(probes.chain(stream::pending()), 4)
.now_or_never()
.is_none(),
"the last disk can still prove either presence or absence"
);
let missing = stream::iter([
Ok(()),
Err(DiskError::VolumeNotFound),
Err(DiskError::DiskNotFound),
Err(DiskError::VolumeNotFound),
]);
assert!(matches!(collect_bucket_presence(missing, 4).await, Err(Error::VolumeNotFound)));
let unavailable = stream::iter([
Ok(()),
Err(DiskError::VolumeNotFound),
Err(DiskError::DiskNotFound),
Err(DiskError::DiskNotFound),
]);
assert!(matches!(collect_bucket_presence(unavailable, 4).await, Err(Error::ErasureReadQuorum)));
}
}
@@ -5927,6 +5927,14 @@ impl SetDisks {
|| commit_decommission_object_lock_guard.is_some()
|| commit_publication_guard.is_some();
let commit_write_completion = opts.write_completion;
let bound_rename_dispatch = commit_write_completion == crate::object_api::WriteCompletion::TailDrained
&& commit_object_lock_guard.is_some()
&& !is_meta_bucketname(bucket)
&& !opts.data_movement
&& !opts.replication_request
&& !quota_mutation_fence
&& commit_scanner_publication_scope.is_none()
&& scanner_publication_lease_tokens.is_none();
let commit_allows_early_ack = write_context.allows_early_ack(commit_write_completion)
&& !(opts.data_movement && opts.has_decommission_capacity_reservation())
&& commit_owns_namespace_guard
@@ -6254,6 +6262,7 @@ impl SetDisks {
commit_scanner_publication_lease_tokens.as_ref(),
)
.with_publication_scope(commit_scanner_publication_scope.clone())
.with_quorum_bounded_dispatch(bound_rename_dispatch)
.with_rollback_receipt(commit_rollback_receipt.clone())
.with_namespace_commit_guard(
(!is_meta_bucketname(&commit_bucket))
+24 -14
View File
@@ -5035,27 +5035,37 @@ mod metadata_cache_tests {
disk.make_volume(bucket).await.expect("bucket volume should be created");
}
let mut reader = PutObjReader::from_vec(vec![7u8; 1024]);
set.put_object(bucket, object, &mut reader, &ObjectOptions::default())
.await
.expect("test object should be written");
// A quorum-acknowledged PUT can leave a rename running on a healthy
// disk. This test needs an error-free fanout to reach cache publication.
set.put_object(
bucket,
object,
&mut reader,
&ObjectOptions {
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("the fixture PUT should drain its commit fanout");
let barrier = MetadataCachePublishBarrier::install(bucket, object);
let stale_generation = set
.get_object_metadata_cache_generation(bucket, object)
.expect("metadata cache generation should be active");
let reader_set = Arc::clone(&set);
let read = tokio::spawn(async move {
reader_set
.get_object_fileinfo(bucket, object, &ObjectOptions::default(), true, false)
.await
});
barrier.wait_until_paused().await;
let opts = ObjectOptions::default();
let read = set.get_object_fileinfo(bucket, object, &opts, true, false);
tokio::pin!(read);
tokio::select! {
() = barrier.wait_until_paused() => {}
result = &mut read => match result {
Ok(_) => panic!("metadata read returned without reaching cache publication"),
Err(err) => panic!("metadata read failed before cache publication: {err}"),
},
}
set.invalidate_get_object_metadata_cache(bucket, object).await;
barrier.release();
let snapshot = read
.await
.expect("metadata read task should not panic")
.expect("metadata fanout should still return its selected FileInfo");
let snapshot = read.await.expect("metadata fanout should still return its selected FileInfo");
assert!(snapshot.owned.is_some());
assert!(snapshot.has_valid_representation());
+15 -33
View File
@@ -24,7 +24,7 @@ use crate::disk::{
};
use crate::error::is_err_bucket_not_found;
use crate::runtime::sources as runtime_sources;
use crate::set_disk::{BucketInfoQuorum, get_lock_acquire_timeout};
use crate::set_disk::{BucketInfoQuorum, SetDisks, get_lock_acquire_timeout};
use crate::storage_api_contracts::admin::DiskSetSelector;
use crate::storage_api_contracts::bucket::{BUCKET_LIFECYCLE_LOCK_OBJECT, SRBucketDeleteOp};
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
@@ -1702,65 +1702,47 @@ impl ECStore {
#[instrument(skip(self))]
pub(crate) async fn get_bucket_info_from_sets(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
self.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Write)
self.probe_bucket_sets(|set| async move { set.get_bucket_info(bucket, opts).await })
.await
}
pub(crate) async fn get_bucket_info_from_sets_at_read_quorum(
&self,
bucket: &str,
opts: &BucketOptions,
) -> Result<BucketInfo> {
self.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Read)
pub(crate) async fn check_bucket_presence_at_read_quorum(&self, bucket: &str) -> Result<()> {
self.probe_bucket_sets(|set| async move { set.check_bucket_presence_at_read_quorum(bucket).await })
.await
}
async fn get_bucket_info_from_sets_with_quorum(
&self,
bucket: &str,
opts: &BucketOptions,
quorum: BucketInfoQuorum,
) -> Result<BucketInfo> {
async fn probe_bucket_sets<T, F: Future<Output = Result<T>>>(&self, probe: impl Fn(Arc<SetDisks>) -> F) -> Result<T> {
// One host may participate in several pools after expansion. Resolve the
// namespace against each erasure set so disks from different pools can
// never be combined into one bucket quorum.
// Bucket validation is request-path IO. Keep the previous peer fanout's
// latency shape by probing every set concurrently; scanner listings use
// a separate bounded path below because they run continuously.
let mut scoped_results = futures::future::join_all(self.bucket_sets().map(|(pool_index, set_index, set)| async move {
let result = match quorum {
BucketInfoQuorum::Read => set.stat_bucket_with_quorum(bucket, quorum).await,
BucketInfoQuorum::Write | BucketInfoQuorum::HealCandidates => set.get_bucket_info(bucket, opts).await,
};
(pool_index, set_index, result)
let mut scoped_results = futures::future::join_all(self.bucket_sets().map(|(pool_index, set_index, set)| {
let result = probe(set);
async move { (pool_index, set_index, result.await) }
}))
.await;
scoped_results.sort_unstable_by_key(|(pool_index, set_index, _)| (*pool_index, *set_index));
let mut first_info = None;
let mut first_error = None;
let mut first_success = None;
for (_, _, result) in scoped_results {
match result {
Ok(info) if first_info.is_none() => first_info = Some(info),
Ok(value) if first_success.is_none() => first_success = Some(value),
Ok(_) => {}
Err(err) if is_err_strict_volume_not_found(&err) => {}
Err(err) if first_error.is_none() => first_error = Some(err),
Err(_) => {}
Err(err) => return Err(err),
}
}
if let Some(err) = first_error {
return Err(err);
}
first_info.ok_or(Error::VolumeNotFound)
first_success.ok_or(Error::VolumeNotFound)
}
#[instrument(skip(self))]
pub(super) async fn handle_get_bucket_info(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
let mut info = match self.get_bucket_info_from_sets(bucket, opts).await {
Ok(info) => info,
Err(Error::ErasureWriteQuorum) => return self.get_bucket_info_at_read_quorum(bucket, opts).await,
Err(Error::ErasureWriteQuorum) => return self.get_bucket_info_at_read_quorum(bucket).await,
Err(err) => return Err(err),
};
@@ -1775,14 +1757,14 @@ impl ECStore {
Ok(info)
}
async fn get_bucket_info_at_read_quorum(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
async fn get_bucket_info_at_read_quorum(&self, bucket: &str) -> Result<BucketInfo> {
// Lock order: bucket lifecycle -> internal metadata object read locks.
// Keep create/delete from changing the namespace while a read quorum
// confirms both physical presence and persisted bucket metadata.
let guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
await_bucket_namespace_operation(Some(&guard), bucket, "bucket read quorum validation", async {
let mut info = self
.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Read)
.probe_bucket_sets(|set| async move { set.stat_bucket_with_quorum(bucket, BucketInfoQuorum::Read).await })
.await?;
let (metadata, persisted) = metadata_sys::get_config_from_disk_with_presence_in(&self.ctx, bucket).await?;
if !persisted {
+249 -12
View File
@@ -6451,8 +6451,14 @@ mod tests {
};
if let Some(split) = multipart_split {
assert!(split > 0 && split < body.len(), "multipart source split must create two non-empty parts");
// Upload initiation belongs to the current bucket generation. The
// historical object timestamp is assigned at completion.
let init_opts = ObjectOptions {
mod_time: None,
..write_opts.clone()
};
let upload = pool
.new_multipart_upload(bucket, object, &write_opts)
.new_multipart_upload(bucket, object, &init_opts)
.await
.expect("create physical data-movement source upload");
let mut completed_parts = Vec::with_capacity(2);
@@ -7609,7 +7615,7 @@ mod tests {
..versioned.clone()
};
let upload = store.pools[0]
.new_multipart_upload(&bucket, object, &native_opts)
.new_multipart_upload(&bucket, object, &versioned)
.await
.expect("real pool-zero Init");
let part = store.pools[0]
@@ -8445,6 +8451,133 @@ mod tests {
.expect("join data movement test thread");
}
/// Fails the migration if it reads the source body.
struct SourceBodyMustNotBeRead;
impl tokio::io::AsyncRead for SourceBodyMustNotBeRead {
fn poll_read(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
_buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Err(std::io::Error::other("the source body must not be read again")))
}
}
/// A rebalance that stops after the target commit and before the source
/// cleanup leaves the version in both pools. The next attempt must settle
/// on the committed copy instead of uploading every part again.
#[test]
#[serial_test::serial(storage_class_env)]
fn rebalance_multipart_retry_skips_the_copy_the_target_already_holds() {
std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.spawn(|| {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()
.expect("build data movement test runtime");
runtime.block_on(async move {
let temp_dir = tempfile::tempdir().expect("create data movement store dir");
let (_ctx, store, _shutdown) = without_storage_class_env(build_isolated_test_store(
temp_dir.path(),
"data-movement-equivalent-target",
&[4, 4],
))
.await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("data-movement-equivalent-{}", uuid::Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create data movement bucket");
*store.rebalance_meta.write().await = Some(active_rebalance_meta_for_pool(store.pools.len(), 0));
assert!(store.is_pool_rebalancing(0).await);
let object = "multipart-object";
let version_id = Uuid::new_v4();
let first_part_size = 5 * 1024 * 1024;
let mut body = vec![b'a'; first_part_size];
body.push(b'b');
let source_reader = seed_data_movement_source_reader(
&store,
&bucket,
object,
DataMovementSourceSeed {
pool_idx: 0,
version_id: Some(version_id),
body,
multipart_split: Some(first_part_size),
mod_time: OffsetDateTime::UNIX_EPOCH + time::Duration::SECOND,
user_defined: HashMap::new(),
},
)
.await;
assert!(source_reader.object_info.is_multipart());
let committed = crate::data_movement::migrate_object(
store.clone(),
0,
bucket.clone(),
source_reader,
None,
"test_data_movement",
)
.await
.expect("the first attempt commits the target copy");
assert_eq!(committed, crate::data_movement::DataMovementCopy::Committed);
let read_opts = ObjectOptions {
versioned: true,
version_id: Some(version_id.to_string()),
include_part_checksums: true,
..Default::default()
};
let target = store.pools[1]
.get_object_info(&bucket, object, &read_opts)
.await
.expect("the target holds the committed copy");
// The run stopped here: the source is still on its pool.
let mut retry_reader = store.pools[0]
.get_object_reader(
&bucket,
object,
None,
HeaderMap::new(),
&ObjectOptions {
raw_data_movement_read: true,
..read_opts.clone()
},
)
.await
.expect("the source version is still present");
retry_reader.stream = Box::new(SourceBodyMustNotBeRead);
let retried = crate::data_movement::migrate_object(
store.clone(),
0,
bucket.clone(),
retry_reader,
None,
"test_data_movement",
)
.await
.expect("an equivalent target settles the retry without another copy");
assert_eq!(retried, crate::data_movement::DataMovementCopy::Committed);
let after = store.pools[1]
.get_object_info(&bucket, object, &read_opts)
.await
.expect("the committed copy is still on the target");
assert_eq!(after.data_dir, target.data_dir, "the retry must not rewrite the committed copy");
});
})
.expect("spawn data movement test thread")
.join()
.expect("join data movement test thread");
}
#[test]
#[serial_test::serial(storage_class_env)]
fn data_movement_multipart_replaces_only_unlocked_owned_generation() {
@@ -8801,9 +8934,9 @@ mod tests {
let retain_until = (OffsetDateTime::now_utc() + time::Duration::days(1))
.format(&time::format_description::well_known::Rfc3339)
.expect("retain-until date should format");
for (object, replacement_source, mode) in [
("compliance-target.bin", "compliance-target-replacement.bin", "COMPLIANCE"),
("governance-target.bin", "governance-target-replacement.bin", "GOVERNANCE"),
for (object, mode) in [
("compliance-target.bin", "COMPLIANCE"),
("governance-target.bin", "GOVERNANCE"),
] {
let retained_metadata = HashMap::from([
(rustfs_filemeta::metadata_keys::OBJECT_LOCK_MODE.to_string(), mode.to_string()),
@@ -8816,26 +8949,44 @@ mod tests {
store.clone(),
0,
bucket.clone(),
source_reader(object, old_body.clone(), old_time, retained_metadata.clone()).await,
source_reader(object, old_body.clone(), old_time, HashMap::new()).await,
None,
"test_retained_target_seed",
)
.await
.expect("seed retained migrated target");
let mut replacement_source_reader =
source_reader(replacement_source, new_body.clone(), new_time, retained_metadata).await;
replacement_source_reader.object_info.name = object.to_string();
.expect("seed migrated target");
// Model retention already present on the target independently of the source.
// Preserve the migration ownership markers so WORM is the rejecting check.
for disk in store.pools[1].disk_set[0].disk_inventory().await {
disk.expect("target disk should be online")
.update_metadata(
&bucket,
object,
rustfs_filemeta::FileInfo {
version_id: Some(version_id),
metadata: retained_metadata.clone(),
..Default::default()
},
&crate::disk::UpdateMetadataOpts::default(),
)
.await
.expect("seed retention on the exact target version");
}
let err = crate::data_movement::migrate_object(
store.clone(),
0,
bucket.clone(),
replacement_source_reader,
source_reader(object, new_body.clone(), new_time, HashMap::new()).await,
None,
"test_retained_target_replace",
)
.await
.expect_err("active retention must block stale target replacement");
assert!(err.to_string().contains("complete_multipart_upload"), "unexpected retention error: {err}");
assert!(
crate::data_movement::data_movement_error_is_stage(&err, "complete_multipart_upload")
&& err.to_string().contains("Prefix access is denied"),
"unexpected retention error: {err}"
);
let mut retained_reader = store.pools[1]
.get_object_reader(
@@ -22005,6 +22156,92 @@ mod tests {
assert_eq!(body, original_body);
}
#[tokio::test]
#[serial_test::serial]
async fn single_put_records_object_lock_snapshot_stages() {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use rustfs_io_metrics::{
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ, PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK, put_stage_metrics_enabled, set_put_stage_metrics_enabled,
};
struct RestorePutStageFlag(bool);
impl Drop for RestorePutStageFlag {
fn drop(&mut self) {
set_put_stage_metrics_enabled(self.0);
}
}
let temp = tempfile::tempdir().expect("create snapshot test store dir");
let (ctx, store, _shutdown) =
without_storage_class_env(build_isolated_test_store(temp.path(), "put-snapshot-stages", &[4])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
let bucket = format!("snapshot-stages-{}", uuid::Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create snapshot bucket");
let opts = ObjectOptions {
expected_bucket_incarnation_id: Some(store.bucket_incarnation_id(&bucket).await.expect("load bucket incarnation")),
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
};
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let _recorder = metrics::set_default_local_recorder(&recorder);
let _flag = RestorePutStageFlag(put_stage_metrics_enabled());
let take_stage_counts = || {
let stages = [
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
];
let mut counts = [0; 3];
for (key, _, _, value) in snapshotter.snapshot().into_vec() {
let key = key.key();
if key.name() != "rustfs_s3_put_object_stage_duration_ms" {
continue;
}
if let Some(index) = stages
.iter()
.position(|stage| key.labels().any(|label| label.key() == "stage" && label.value() == *stage))
{
assert_eq!(key.labels().count(), 1, "snapshot timings must have only a static stage label");
let DebugValue::Histogram(samples) = value else {
panic!("snapshot timing must be recorded as a histogram");
};
counts[index] += samples.len();
}
}
counts
};
set_put_stage_metrics_enabled(false);
store
.put_object(&bucket, "metrics-off", &mut PutObjReader::from_vec(vec![1]), &opts)
.await
.expect("ordinary PUT with metrics disabled");
assert_eq!(take_stage_counts(), [0, 0, 0]);
set_put_stage_metrics_enabled(true);
store
.put_object(&bucket, "metrics-on", &mut PutObjReader::from_vec(vec![1]), &opts)
.await
.expect("ordinary PUT with metrics enabled");
assert_eq!(take_stage_counts(), [1, 1, 1]);
crate::bucket::metadata_sys::inject_object_lock_disk_read_error_in(&ctx, &bucket)
.await
.expect("inject authority read error");
let error = store
.put_object(&bucket, "read-failed", &mut PutObjReader::from_vec(vec![1]), &opts)
.await
.expect_err("authority failure must still reject the PUT");
assert!(error.to_string().contains("injected Object Lock metadata disk read failure"));
assert_eq!(take_stage_counts(), [1, 1, 1], "each stage records once even when the final read fails");
}
#[cfg(feature = "test-util")]
#[tokio::test]
#[serial_test::serial(storage_class_env)]
@@ -100,12 +100,15 @@ mod multipart_copy_heal_tests {
.collect::<Vec<_>>();
let options = ObjectOptions {
versioned: true,
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixed native C timestamp")),
write_completion: WriteCompletion::TailDrained,
..Default::default()
};
let init_opts = ObjectOptions {
mod_time: None,
..options.clone()
};
let upload = store.pools[0]
.new_multipart_upload(&bucket, &object, &options)
.new_multipart_upload(&bucket, &object, &init_opts)
.await
.expect("actual native C Init");
let part = store.pools[0]
@@ -130,7 +133,11 @@ mod multipart_copy_heal_tests {
etag: part.etag,
..Default::default()
}],
&options,
&ObjectOptions {
// Pin the committed timestamp without backdating the staged upload.
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixed native C timestamp")),
..options
},
)
.await
.expect("actual native C quorum publication");
+252 -142
View File
@@ -2110,8 +2110,22 @@ fn batch_delete_action_key(object: &ObjectToDelete) -> (&str, Option<Uuid>) {
(object.object_name.as_str(), object.version_id)
}
fn batch_delete_targets_pool(creates_latest_marker: bool, marker_target_pool_idx: Option<usize>, pool_idx: usize) -> bool {
!creates_latest_marker || marker_target_pool_idx == Some(pool_idx)
#[derive(Clone, Copy)]
enum BatchDeleteRoute {
Inactive,
AllPools,
PendingMarker,
Marker(usize),
}
impl BatchDeleteRoute {
fn targets(self, pool_idx: usize) -> bool {
match self {
Self::Inactive | Self::PendingMarker => false,
Self::AllPools => true,
Self::Marker(target) => target == pool_idx,
}
}
}
#[cfg(test)]
@@ -2197,52 +2211,33 @@ fn inject_batch_delete_pool_errors(
}
}
fn resolve_batch_delete_pool_results<'a>(
initial_error: Option<Error>,
pool_results: impl IntoIterator<Item = (&'a DeletedObject, &'a Option<Error>)>,
) -> (Option<DeletedObject>, Option<Error>, bool) {
let mut failure = initial_error.map(|err| (None, err));
let mut deleted = None;
let mut fallback: Option<(DeletedObject, Option<Error>)> = None;
let mut attempted = false;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum BatchDeleteOutcome {
SilentMiss,
Missing,
Deleted,
Failed,
}
for (pool_delete, pool_error) in pool_results {
attempted = true;
match pool_error {
Some(err) if is_err_object_not_found(err) || is_err_version_not_found(err) => {
if fallback.as_ref().is_none_or(|(_, error)| error.is_none()) {
fallback = Some(((*pool_delete).clone(), Some(err.clone())));
}
}
Some(err) => {
if failure.is_none() {
failure = Some((Some((*pool_delete).clone()), err.clone()));
}
}
None if pool_delete.found => {
if deleted.is_none() {
deleted = Some((*pool_delete).clone());
}
}
None => {
if fallback.is_none() {
fallback = Some(((*pool_delete).clone(), None));
}
}
}
fn apply_batch_delete_pool_result(
selected: &mut Option<BatchDeleteOutcome>,
deleted: &mut DeletedObject,
error: &mut Option<Error>,
pool_delete: DeletedObject,
pool_error: Option<Error>,
) {
let outcome = match &pool_error {
Some(err) if is_err_object_not_found(err) || is_err_version_not_found(err) => BatchDeleteOutcome::Missing,
Some(_) => BatchDeleteOutcome::Failed,
None if pool_delete.found => BatchDeleteOutcome::Deleted,
None => BatchDeleteOutcome::SilentMiss,
};
// Results arrive in pool order. Equal priorities keep the first result.
if selected.is_none_or(|current| outcome > current) {
*selected = Some(outcome);
*deleted = pool_delete;
*error = pool_error;
}
if let Some((failed_delete, err)) = failure {
return (failed_delete, Some(err), attempted);
}
if let Some(deleted) = deleted {
return (Some(deleted), None, attempted);
}
if let Some((deleted, err)) = fallback {
return (Some(deleted), err, attempted);
}
(None, None, attempted)
}
fn transition_restore_pool_opts(opts: &ObjectOptions) -> ObjectOptions {
@@ -2774,6 +2769,7 @@ async fn await_conditional_capability_set_probe_gate(bucket: &str) -> Result<()>
}
struct BatchDeletePhasePlan<'a> {
/// Unique input positions in request order.
indices: &'a [usize],
pool_generations: HashMap<usize, HashMap<String, CurrentDeleteGeneration>>,
marker_targets: &'a HashMap<String, usize>,
@@ -3308,15 +3304,34 @@ impl ECStore {
pub(crate) async fn object_lock_config_snapshot_for_single_put(&self, bucket: &str) -> Result<Arc<ObjectLockConfigSnapshot>> {
check_valid_bucket_name(bucket)?;
let lifecycle_guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
let lifecycle_lock_started = rustfs_io_metrics::put_stage_timer();
let lifecycle_guard = self.acquire_bucket_lifecycle_read_lock(bucket).await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
lifecycle_lock_started,
);
let lifecycle_guard = lifecycle_guard?;
let metadata_lock_started = rustfs_io_metrics::put_stage_timer();
let metadata_guard = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_read_lock_in_for_purpose(
&self.ctx,
bucket,
"object_lock_snapshot_metadata_read",
)
.await?;
let (state, bucket_incarnation_id, config_revision, quota_res) =
get_object_lock_and_quota_config_from_disk_with_guard_in(&self.ctx, bucket, Some(&lifecycle_guard)).await?;
.await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
metadata_lock_started,
);
let metadata_guard = metadata_guard?;
let authority_read_started = rustfs_io_metrics::put_stage_timer();
let authority = get_object_lock_and_quota_config_from_disk_with_guard_in(&self.ctx, bucket, Some(&lifecycle_guard)).await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
authority_read_started,
);
let (state, bucket_incarnation_id, config_revision, quota_res) = authority?;
if lifecycle_guard.is_lock_lost() || metadata_guard.is_lock_lost() {
return Err(Error::other("bucket lifecycle lock was lost while loading the Object Lock snapshot"));
}
@@ -6204,10 +6219,7 @@ impl ECStore {
mut pool_generations,
marker_targets: conditional_marker_targets,
} = plan;
let mut active = vec![false; objects.len()];
for idx in indices {
active[*idx] = true;
}
debug_assert!(indices.windows(2).all(|pair| pair[0] < pair[1]));
let mut del_objects = vec![DeletedObject::default(); objects.len()];
let mut del_errs = vec![None; objects.len()];
let mut accounting = vec![None; objects.len()];
@@ -6215,46 +6227,55 @@ impl ECStore {
.delete_replication_config_snapshot
.as_deref()
.expect("batch delete replication config snapshot should be loaded");
let latest_marker_objects = objects
.iter()
.enumerate()
.map(|(idx, object)| {
active[idx] && del_errs[idx].is_none() && batch_delete_creates_latest_marker(object, delete_config_snapshot)
})
.collect::<Vec<_>>();
let marker_target_results = join_all(objects.iter().zip(&latest_marker_objects).map(|(object, creates_marker)| {
let admitted_target = conditional_marker_targets.get(&object.object_name).copied();
async move {
if *creates_marker {
// Routing is part of condition admission. A rebalance
// start cannot replace the validated current owner.
Some(match admitted_target {
Some(pool_idx) => Ok(pool_idx),
None => self.get_pool_idx_no_lock(bucket, &object.object_name, 0).await,
})
} else {
None
}
let mut routes = vec![BatchDeleteRoute::Inactive; objects.len()];
let mut has_markers = false;
let mut pending_markers = 0;
for &idx in indices {
let object = &objects[idx];
if !batch_delete_creates_latest_marker(object, delete_config_snapshot) {
routes[idx] = BatchDeleteRoute::AllPools;
continue;
}
}))
.await;
let mut marker_target_pool_indices = Vec::with_capacity(objects.len());
for (idx, target_result) in marker_target_results.into_iter().enumerate() {
match target_result {
Some(Ok(pool_idx)) => marker_target_pool_indices.push(Some(pool_idx)),
Some(Err(err)) => {
del_errs[idx] = Some(err);
marker_target_pool_indices.push(None);
}
None => marker_target_pool_indices.push(None),
has_markers = true;
// Rebalancing cannot replace the owner used to admit a conditional delete.
if let Some(&pool_idx) = conditional_marker_targets.get(&object.object_name) {
routes[idx] = BatchDeleteRoute::Marker(pool_idx);
} else {
routes[idx] = BatchDeleteRoute::PendingMarker;
pending_markers += 1;
}
}
if pending_markers != 0 {
let lookups = indices
.iter()
.copied()
.filter(|&idx| matches!(routes[idx], BatchDeleteRoute::PendingMarker))
// Bound join_all's size hint by the unresolved markers.
.take(pending_markers)
.map(|idx| async move { (idx, self.get_pool_idx_no_lock(bucket, &objects[idx].object_name, 0).await) });
let lookup_results = join_all(lookups).await;
for (idx, result) in lookup_results {
routes[idx] = match result {
Ok(pool_idx) => BatchDeleteRoute::Marker(pool_idx),
Err(err) => {
del_errs[idx] = Some(err);
BatchDeleteRoute::Inactive
}
};
}
}
let _capacity_fence = if !self.single_pool() && latest_marker_objects.iter().any(|creates_marker| *creates_marker) {
let _capacity_fence = if !self.single_pool() && has_markers {
// Only marker destinations can grow. Other pools participate in
// exact deletion under the same metadata read fence and must not
// be treated as publication targets merely because they retire.
let mut target_pool_indices = marker_target_pool_indices.iter().flatten().copied().collect::<Vec<_>>();
let mut target_pool_indices = indices
.iter()
.filter_map(|&idx| match routes[idx] {
BatchDeleteRoute::Marker(pool_idx) => Some(pool_idx),
_ => None,
})
.collect::<Vec<_>>();
target_pool_indices.sort_unstable();
target_pool_indices.dedup();
match self
@@ -6282,16 +6303,15 @@ impl ECStore {
continue;
}
let (object_indices, pool_objects): (Vec<_>, Vec<_>) = objects
let (object_indices, pool_objects): (Vec<_>, Vec<_>) = indices
.iter()
.enumerate()
.map(|&idx| (idx, &objects[idx]))
.filter(|(idx, object)| {
active[*idx] && del_errs[*idx].is_none()
routes[*idx].targets(pool.pool_idx)
// A newly rebalancing pool still owes every admitted
// conditional key its guarded mutation. Ordinary keys
// retain the existing rebalance skip behavior.
&& (!rebalancing || guarded_generations.is_some_and(|generations| generations.contains_key(&object.object_name)))
&& batch_delete_targets_pool(latest_marker_objects[*idx], marker_target_pool_indices[*idx], pool.pool_idx)
})
.map(|(idx, object)| (idx, object.clone()))
.unzip();
@@ -6319,20 +6339,23 @@ impl ECStore {
});
}
let results = join_all(futures).await;
for idx in 0..del_objects.len() {
let pool_results = results.iter().filter_map(|(object_indices, (dels, errs, _))| {
let pool_object_idx = object_indices.binary_search(&idx).ok()?;
Some((&dels[pool_object_idx], &errs[pool_object_idx]))
});
let (deleted, error, attempted) = resolve_batch_delete_pool_results(del_errs[idx].take(), pool_results);
if let Some(deleted) = deleted {
del_objects[idx] = deleted;
let mut selected: Vec<_> = del_errs
.iter()
.map(|error| error.as_ref().map(|_| BatchDeleteOutcome::Failed))
.collect();
for (object_indices, (pool_deleted, pool_errors, pool_accounting)) in join_all(futures).await {
debug_assert_eq!(object_indices.len(), pool_deleted.len());
debug_assert_eq!(object_indices.len(), pool_errors.len());
let mut pool_accounting = pool_accounting.into_iter();
for (idx, (deleted, error)) in object_indices.into_iter().zip(pool_deleted.into_iter().zip(pool_errors)) {
apply_batch_delete_pool_result(&mut selected[idx], &mut del_objects[idx], &mut del_errs[idx], deleted, error);
// Accounting follows the last pool that attempted this index.
accounting[idx] = pool_accounting.next().flatten();
}
del_errs[idx] = error;
}
if !attempted && del_errs[idx].is_none() && latest_marker_objects[idx] {
for &idx in indices {
if matches!(routes[idx], BatchDeleteRoute::Marker(_)) && selected[idx].is_none() {
del_objects[idx] = DeletedObject {
object_name: objects[idx].object_name.clone(),
version_id: objects[idx].version_id,
@@ -6342,12 +6365,6 @@ impl ECStore {
}
}
for (object_indices, (_, _, pool_accounting)) in &results {
for (pool_object_idx, object_idx) in object_indices.iter().enumerate() {
accounting[*object_idx] = pool_accounting.get(pool_object_idx).cloned().flatten();
}
}
(del_objects, del_errs, accounting)
}
@@ -6360,9 +6377,8 @@ impl ECStore {
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
// encode object name
let objects: Vec<ObjectToDelete> = objects
.iter()
.map(|v| {
let mut v = v.clone();
.into_iter()
.map(|mut v| {
v.object_name = encode_dir_object(v.object_name.as_str());
v
})
@@ -6595,7 +6611,7 @@ impl ECStore {
// the phase only runs for the keys this batch actually holds, and
// only its outcomes replace the outer per-key state.
let indices = (0..objects.len()).filter(|idx| del_errs[*idx].is_none()).collect::<Vec<_>>();
let (phase_deleted, mut phase_errors, mut phase_accounting) = self
let (mut phase_deleted, mut phase_errors, mut phase_accounting) = self
.run_batch_delete_phase(
bucket,
&objects,
@@ -6608,7 +6624,7 @@ impl ECStore {
)
.await;
for idx in indices {
del_objects[idx] = phase_deleted[idx].clone();
del_objects[idx] = std::mem::take(&mut phase_deleted[idx]);
del_errs[idx] = phase_errors[idx].take();
accounting[idx] = phase_accounting[idx].take();
}
@@ -6625,7 +6641,7 @@ impl ECStore {
}
}
if !conditional_indices.is_empty() {
let (deleted, mut errors, mut receipts) = self
let (mut deleted, mut errors, mut receipts) = self
.run_batch_delete_phase(
bucket,
&objects,
@@ -6638,7 +6654,7 @@ impl ECStore {
)
.await;
for idx in &conditional_indices {
del_objects[*idx] = deleted[*idx].clone();
del_objects[*idx] = std::mem::take(&mut deleted[*idx]);
del_errs[*idx] = errors[*idx].take();
accounting[*idx] = receipts[*idx].take();
}
@@ -6671,7 +6687,7 @@ impl ECStore {
if !ordinary_indices.is_empty() {
// The guarded phase has finished all rollback/receipt work.
// These actions receive neither its CAS nor its transaction.
let (deleted, mut errors, mut receipts) = self
let (mut deleted, mut errors, mut receipts) = self
.run_batch_delete_phase(
bucket,
&objects,
@@ -6684,7 +6700,7 @@ impl ECStore {
)
.await;
for idx in ordinary_indices {
del_objects[idx] = deleted[idx].clone();
del_objects[idx] = std::mem::take(&mut deleted[idx]);
del_errs[idx] = errors[idx].take();
accounting[idx] = receipts[idx].take();
}
@@ -9762,9 +9778,11 @@ mod tests {
..Default::default()
};
assert!(batch_delete_creates_latest_marker(&latest, &versioned));
assert!(!batch_delete_targets_pool(true, Some(1), 0));
assert!(batch_delete_targets_pool(true, Some(1), 1));
assert!(!batch_delete_targets_pool(true, Some(1), 2));
assert!(!BatchDeleteRoute::Marker(1).targets(0));
assert!(BatchDeleteRoute::Marker(1).targets(1));
assert!(!BatchDeleteRoute::Marker(1).targets(2));
assert!(!BatchDeleteRoute::Inactive.targets(0));
assert!(!BatchDeleteRoute::PendingMarker.targets(0));
let explicit = ObjectToDelete {
object_name: "explicit".to_string(),
@@ -9772,11 +9790,23 @@ mod tests {
..Default::default()
};
assert!(!batch_delete_creates_latest_marker(&explicit, &versioned));
assert!(batch_delete_targets_pool(false, Some(1), 0));
assert!(BatchDeleteRoute::AllPools.targets(0));
let unversioned = DeleteReplicationConfigSnapshot::default();
assert!(!batch_delete_creates_latest_marker(&latest, &unversioned));
assert!(batch_delete_targets_pool(false, None, 0));
assert!(BatchDeleteRoute::AllPools.targets(1));
}
fn reduce_test_pool_results(
mut error: Option<Error>,
pool_results: impl IntoIterator<Item = (DeletedObject, Option<Error>)>,
) -> (DeletedObject, Option<Error>, Option<BatchDeleteOutcome>) {
let mut selected = error.as_ref().map(|_| BatchDeleteOutcome::Failed);
let mut deleted = DeletedObject::default();
for (pool_delete, pool_error) in pool_results {
apply_batch_delete_pool_result(&mut selected, &mut deleted, &mut error, pool_delete, pool_error);
}
(deleted, error, selected)
}
#[test]
@@ -9802,15 +9832,14 @@ mod tests {
let failed = (DeletedObject::default(), Some(source_error.clone()));
let succeeded = (success.clone(), None);
let pool_results = if source_first {
vec![failed, succeeded]
[failed, succeeded]
} else {
vec![succeeded, failed]
[succeeded, failed]
};
let (_, error, attempted) =
resolve_batch_delete_pool_results(None, pool_results.iter().map(|(deleted, error)| (deleted, error)));
let (_, error, selected) = reduce_test_pool_results(None, pool_results);
assert!(attempted);
assert!(matches!(selected, Some(BatchDeleteOutcome::Failed)));
assert_eq!(error, Some(source_error.clone()));
}
}
@@ -9833,34 +9862,54 @@ mod tests {
for missing_first in [true, false] {
let succeeded = (success.clone(), None);
let pool_results = if missing_first {
vec![missing.clone(), succeeded]
[missing.clone(), succeeded]
} else {
vec![succeeded, missing.clone()]
[succeeded, missing.clone()]
};
let (deleted, error, attempted) =
resolve_batch_delete_pool_results(None, pool_results.iter().map(|(deleted, error)| (deleted, error)));
let (deleted, error, selected) = reduce_test_pool_results(None, pool_results);
assert!(attempted);
let deleted = deleted.expect("successful pool result should be retained");
assert!(matches!(selected, Some(BatchDeleteOutcome::Deleted)));
assert!(deleted.found);
assert_eq!(deleted.object_name, success.object_name.as_str());
assert!(error.is_none());
}
let missing_only = [missing];
let (_, error, attempted) =
resolve_batch_delete_pool_results(None, missing_only.iter().map(|(deleted, error)| (deleted, error)));
assert!(attempted);
let (_, error, selected) = reduce_test_pool_results(None, [missing]);
assert!(matches!(selected, Some(BatchDeleteOutcome::Missing)));
assert_eq!(error, Some(missing_error));
}
let silent_missing = [(DeletedObject::default(), None)];
let (_, error, attempted) =
resolve_batch_delete_pool_results(None, silent_missing.iter().map(|(deleted, error)| (deleted, error)));
assert!(attempted);
let (_, error, selected) = reduce_test_pool_results(None, [(DeletedObject::default(), None)]);
assert!(matches!(selected, Some(BatchDeleteOutcome::SilentMiss)));
assert!(error.is_none());
}
#[test]
fn batch_delete_pool_reduction_keeps_the_first_equal_outcome_and_preflight_error() {
let miss = |name: &str| {
(
DeletedObject {
object_name: name.to_owned(),
..Default::default()
},
Some(StorageError::ObjectNotFound("bucket".to_owned(), name.to_owned())),
)
};
let silent = (DeletedObject::default(), None);
let (deleted, error, selected) = reduce_test_pool_results(None, [silent, miss("first"), miss("second")]);
assert!(matches!(selected, Some(BatchDeleteOutcome::Missing)));
assert_eq!(deleted.object_name, "first");
assert_eq!(error, miss("first").1);
let (deleted, error, _) = reduce_test_pool_results(
Some(StorageError::PreconditionFailed),
[(miss("pool").0, Some(StorageError::ErasureWriteQuorum))],
);
assert!(deleted.object_name.is_empty());
assert_eq!(error, Some(StorageError::PreconditionFailed));
assert!(reduce_test_pool_results(None, []).2.is_none());
}
#[tokio::test]
async fn lifecycle_null_version_cas_distinguishes_absent_and_replacement_pools() {
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration as VersioningConfiguration;
@@ -13116,6 +13165,67 @@ mod tests {
));
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn batch_delete_preserves_results_and_accounting_across_sets() {
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
ctx.update_erasure_type(SetupType::Erasure).await;
let (_temp_dirs, sets) = make_local_two_set_sets_with_ctx(Arc::clone(&ctx)).await;
let store = Arc::new(new_prepared_reader_test_store_from_pools(
vec![Arc::clone(&sets)],
vec![sets.endpoints.clone()],
ctx,
));
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
let bucket = format!("batch-delete-{}", Uuid::new_v4().simple());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket on both sets");
let keys: Vec<_> = [1, 0, 1]
.into_iter()
.enumerate()
.map(|(index, set)| {
(0..100)
.map(|suffix| format!("{index}-{suffix}"))
.find(|key| Arc::ptr_eq(&sets.get_disks_by_key(key), &sets.disk_set[set]))
.expect("fixture key routed to the selected set")
})
.collect();
for indices in [&[0, 1, 2][..], &[0, 2, 1], &[0, 2], &[1]] {
for &index in indices {
let mut data = PutObjReader::from_vec(vec![0; index + 1]);
sets.put_object(&bucket, &keys[index], &mut data, &ObjectOptions::default())
.await
.expect("seed an object with a distinct size");
}
let batch = indices
.iter()
.map(|&index| ObjectToDelete {
object_name: keys[index].clone(),
..Default::default()
})
.collect();
let (deleted, errors, accounting) = sets
.delete_objects_with_accounting(&bucket, batch, ObjectOptions::default())
.await;
assert_eq!(errors.len(), indices.len());
assert!(errors.iter().all(Option::is_none), "{errors:?}");
assert_eq!(
deleted.iter().map(|object| object.object_name.as_str()).collect::<Vec<_>>(),
indices.iter().map(|&index| keys[index].as_str()).collect::<Vec<_>>()
);
assert_eq!(
accounting
.into_iter()
.map(|receipt| receipt.and_then(|receipt| receipt.size))
.collect::<Vec<_>>(),
indices.iter().map(|&index| u64::try_from(index + 1).ok()).collect::<Vec<_>>()
);
}
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn select_snapshot_allows_store_delete_for_object_in_nonzero_set() {
+1 -1
View File
@@ -288,7 +288,7 @@ impl ECStore {
RenameDataGuards {
scanner_publication_lease_token: scanner_token,
external_guard,
namespace_owner: None,
..Default::default()
},
);
if scanner_token.is_some() {
+49 -14
View File
@@ -74,7 +74,7 @@ static GET_STAGE_LOCAL_SUMMARY_SEQUENCE: AtomicU64 = AtomicU64::new(0);
type GetStageLocalSummaryKey = (&'static str, &'static str, &'static str, &'static str);
/// Sampled local aggregate for one bounded GetObject stage label set.
/// Sampled local aggregate for one bounded stage label set.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GetStageLocalSummary {
pub path: &'static str,
@@ -85,7 +85,21 @@ pub struct GetStageLocalSummary {
pub duration_nanoseconds: u64,
}
static GET_STAGE_LOCAL_SUMMARY: LazyLock<Mutex<HashMap<GetStageLocalSummaryKey, GetStageLocalSummary>>> =
impl GetStageLocalSummary {
fn key(&self) -> GetStageLocalSummaryKey {
(self.path, self.stage, self.object_class, self.size_bucket)
}
}
/// A local summary row with its peak in the same sampling window.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GetStageLocalSummaryWithMax {
pub summary: GetStageLocalSummary,
/// Largest sampled duration since the previous drain.
pub max_duration_nanoseconds: u64,
}
static GET_STAGE_LOCAL_SUMMARY: LazyLock<Mutex<HashMap<GetStageLocalSummaryKey, GetStageLocalSummaryWithMax>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
/// Global switch for all remaining (non GET/PUT-stage) metric emission in this
@@ -130,12 +144,23 @@ pub fn get_stage_local_summary_sample_rate() -> u64 {
}
pub fn take_get_stage_local_summary() -> Vec<GetStageLocalSummary> {
let mut rows = drain_get_stage_local_summary(|row| row.summary);
rows.sort_unstable_by_key(GetStageLocalSummary::key);
rows
}
/// Drain the same sampling window as [`take_get_stage_local_summary`] and include each sorted row's maximum.
pub fn take_get_stage_local_summary_with_max() -> Vec<GetStageLocalSummaryWithMax> {
let mut rows = drain_get_stage_local_summary(std::convert::identity);
rows.sort_unstable_by_key(|row| row.summary.key());
rows
}
fn drain_get_stage_local_summary<T>(mut project: impl FnMut(GetStageLocalSummaryWithMax) -> T) -> Vec<T> {
let Ok(mut summary) = GET_STAGE_LOCAL_SUMMARY.lock() else {
return Vec::new();
};
let mut rows = summary.drain().map(|(_, row)| row).collect::<Vec<_>>();
rows.sort_unstable_by_key(|row| (row.path, row.stage, row.object_class, row.size_bucket));
rows
summary.drain().map(|(_, row)| project(row)).collect()
}
fn record_get_stage_local_summary(
@@ -165,16 +190,20 @@ fn record_get_stage_local_summary(
let Ok(mut summary) = GET_STAGE_LOCAL_SUMMARY.lock() else {
return;
};
let row = summary.entry(key).or_insert_with(|| GetStageLocalSummary {
path,
stage,
object_class,
size_bucket,
sampled_count: 0,
duration_nanoseconds: 0,
let row = summary.entry(key).or_insert_with(|| GetStageLocalSummaryWithMax {
summary: GetStageLocalSummary {
path,
stage,
object_class,
size_bucket,
sampled_count: 0,
duration_nanoseconds: 0,
},
max_duration_nanoseconds: 0,
});
row.sampled_count = row.sampled_count.saturating_add(1);
row.duration_nanoseconds = row.duration_nanoseconds.saturating_add(duration_nanoseconds);
row.summary.sampled_count = row.summary.sampled_count.saturating_add(1);
row.summary.duration_nanoseconds = row.summary.duration_nanoseconds.saturating_add(duration_nanoseconds);
row.max_duration_nanoseconds = row.max_duration_nanoseconds.max(duration_nanoseconds);
}
/// Enable or disable general (non GET/PUT-stage) metric emission.
@@ -232,6 +261,9 @@ pub const PUT_STAGE_PUT_OBJECT_OPERATION_AWAIT_TOTAL: &str = "put_object_operati
pub const PUT_STAGE_PUT_OBJECT_OPERATION_BODY_TO_COMMIT_SUBMIT: &str = "put_object_operation_body_to_commit_submit";
pub const PUT_STAGE_PUT_OBJECT_OPERATION_RESULT_RETURN: &str = "put_object_operation_result_return";
pub const PUT_STAGE_PUT_OBJECT_OPERATION_FIRST_POLL_DELAY: &str = "put_object_operation_first_poll_delay";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK: &str = "put_object_commit_ready_snapshot_lifecycle_lock";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK: &str = "put_object_commit_ready_snapshot_metadata_lock";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ: &str = "put_object_commit_ready_snapshot_authority_read";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_ACQUIRED_TO_COMMIT_READY: &str =
"put_object_commit_namespace_lock_acquired_to_commit_ready";
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_PRECONDITION_AND_TIMESTAMP: &str =
@@ -4547,6 +4579,9 @@ mod tests {
PUT_STAGE_PUT_OBJECT_OPERATION_BODY_TO_COMMIT_SUBMIT,
PUT_STAGE_PUT_OBJECT_OPERATION_RESULT_RETURN,
PUT_STAGE_PUT_OBJECT_OPERATION_FIRST_POLL_DELAY,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_ACQUIRED_TO_COMMIT_READY,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_PRECONDITION_AND_TIMESTAMP,
PUT_STAGE_PUT_OBJECT_COMMIT_READY_EXPECTED_VERSION_LOOKUP,
+63 -6
View File
@@ -212,13 +212,19 @@ impl KeystoneAuthProvider {
claims.insert("keystone_roles".to_string(), json!(token.roles));
claims.insert("auth_source".to_string(), json!("keystone"));
// Keep `parent_user` in the `keystone:` namespace (matching `access_key`) so an external
// Keystone username can never collide with a local IAM user or the root access key in
// service-account ownership or admin checks. The username remains available in `name`
// and `claims["keystone_username"]`.
let access_key = format!("keystone:{}", token.user_id);
Credentials {
access_key: format!("keystone:{}", token.user_id),
access_key: access_key.clone(),
secret_key: String::new(), // Not used for token auth
session_token: token.token.clone(),
expiration: Some(token.expires_at),
status: "active".to_string(),
parent_user: token.username.clone(),
parent_user: access_key,
groups,
claims: Some(claims),
name: Some(token.username.clone()),
@@ -303,13 +309,64 @@ mod tests {
let cred = provider.keystone_token_to_credentials(&token);
assert_eq!(cred.access_key, "keystone:user123");
assert_eq!(cred.parent_user, "testuser");
assert_eq!(cred.parent_user, "keystone:user123");
assert_eq!(cred.name.as_deref(), Some("testuser"));
assert_eq!(cred.groups, Some(vec!["Member".to_string(), "admin".to_string()]));
assert!(cred.claims.is_some());
let claims = cred.claims.unwrap();
assert_eq!(claims.get("keystone_user_id").unwrap().as_str().unwrap(), "user123");
assert_eq!(claims.get("keystone_project_id").unwrap().as_str().unwrap(), "proj456");
let claims = cred.claims.expect("keystone claims must be populated");
assert_eq!(claims.get("keystone_user_id").and_then(|v| v.as_str()), Some("user123"));
assert_eq!(claims.get("keystone_username").and_then(|v| v.as_str()), Some("testuser"));
assert_eq!(claims.get("keystone_project_id").and_then(|v| v.as_str()), Some("proj456"));
}
#[test]
fn test_keystone_parent_user_uses_namespaced_identity_not_username() {
let client = KeystoneClient::new(
"http://localhost:5000".to_string(),
crate::KeystoneVersion::V3,
None,
None,
None,
"Default".to_string(),
true,
Duration::from_secs(30),
);
let provider = KeystoneAuthProvider::new(client, 100, Duration::from_secs(60), true);
for (user_id, colliding_username) in [("uid-alice", "alice"), ("uid-root-lookalike", "rustfsadmin")] {
let token = KeystoneToken {
token: "test-token".to_string(),
user_id: user_id.to_string(),
username: colliding_username.to_string(),
project_id: None,
project_name: None,
domain_id: Some("default".to_string()),
domain_name: Some("Default".to_string()),
roles: vec!["member".to_string()],
expires_at: time::OffsetDateTime::now_utc() + time::Duration::hours(1),
issued_at: time::OffsetDateTime::now_utc(),
};
let cred = provider.keystone_token_to_credentials(&token);
let expected_identity = format!("keystone:{user_id}");
assert_eq!(cred.access_key, expected_identity);
assert_eq!(cred.parent_user, expected_identity);
assert_ne!(
cred.parent_user, colliding_username,
"parent_user must never carry the bare Keystone username"
);
assert_eq!(cred.name.as_deref(), Some(colliding_username));
assert_eq!(
cred.claims
.as_ref()
.and_then(|claims| claims.get("keystone_username"))
.and_then(|value| value.as_str()),
Some(colliding_username)
);
}
}
#[test]
@@ -21,13 +21,17 @@ pub(super) fn rules() -> Vec<Rule> {
vec![
Rule {
evidence_fields: strings(["host"]),
anchors: strings(["Create pool endpoints host"]),
anchors: strings(["startup_endpoint_dns_failed", "Startup endpoint DNS resolution failed"]),
..base(
"endpoint-resolve-failed",
P1Unavailable,
"startup",
"启动期端点主机名解析失败",
all([contains("Create pool endpoints host"), contains("not found")]),
any([
field("event", "startup_endpoint_dns_failed"),
contains("Startup endpoint DNS resolution failed"),
all([contains("Create pool endpoints host"), contains("not found")]),
]),
"启动期端点主机名解析失败(DNS 未就绪/拼写错误/hosts 缺失)。",
"容器/K8s 场景确认 DNS 就绪顺序;核对 volumes 参数拼写。",
)
@@ -453,6 +453,15 @@ fn smoke_samples_hit_exact_rule_sets() {
&["unknown-access-key"],
);
exact(&msg("HTTP transport failed: BrokenPipe while streaming response body"), &[]);
exact(
&Sample {
fields: &[("event", "startup_endpoint_dns_failed"), ("host", "node5")],
..msg("DNS deadline exhausted")
},
&["endpoint-resolve-failed"],
);
exact(&msg("Startup endpoint DNS resolution failed"), &["endpoint-resolve-failed"]);
exact(&msg("retrying endpoint local-host detection after temporary DNS error"), &[]);
// Internode auth failures legitimately hit both the internode rule and
// the generic client signature rule.
exact(
+24 -1
View File
@@ -85,12 +85,25 @@ impl ActionSet {
/// `NotAction` always uses plain wildcard matching, so `NotAction: "s3:*"`
/// still excludes force-delete. An Allow grants force-delete only when its
/// `Action` list names it: an Allow built from `NotAction` alone never does.
///
/// An Allow built from `NotAction` stays within the action families named in
/// `not_actions`: excluding S3 actions never implies `admin:*`, `sts:*`, or
/// `kms:*` grants even when the statement carries a wildcard resource, while
/// an explicit admin `NotAction` keeps covering sibling admin actions. A Deny
/// keeps its full reach across every action family.
pub fn statement_covers(&self, not_actions: &ActionSet, action: &Action, deny: bool) -> bool {
if not_actions.is_match_for_effect(action, true) {
return false;
}
if self.is_empty() {
return deny || !action_requires_explicit_grant(action);
if not_actions.is_empty() {
return false;
}
if deny {
return true;
}
return !action_requires_explicit_grant(action)
&& not_actions.iter().any(|excluded| same_action_family(excluded, action));
}
self.is_match_for_effect(action, deny)
}
@@ -217,6 +230,16 @@ fn action_requires_explicit_grant(action: &Action) -> bool {
)
}
fn same_action_family(left: &Action, right: &Action) -> bool {
matches!(
(left, right),
(Action::S3Action(_), Action::S3Action(_))
| (Action::AdminAction(_), Action::AdminAction(_))
| (Action::StsAction(_), Action::StsAction(_))
| (Action::KmsAction(_), Action::KmsAction(_))
)
}
impl From<&Action> for &str {
fn from(value: &Action) -> &'static str {
match value {
+189
View File
@@ -1466,6 +1466,100 @@ mod test {
Ok(())
}
#[tokio::test]
async fn test_aws_userid_policy_variable_is_issuer_scoped_for_federated_sessions() -> Result<()> {
let resource_policy = Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::homes/${aws:userid}/*"]
}
]
}"#,
)?;
let condition_policy = Policy::parse_config(
br#"{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::homes"],
"Condition": {
"StringLike": {
"s3:prefix": ["${aws:userid}/*"]
}
}
}
]
}"#,
)?;
let empty_conditions = HashMap::new();
// Two federated issuers can emit the same (or wildcard) `sub`; `parent` separates them.
for sub in ["1001", "*"] {
let mut claims = HashMap::new();
claims.insert("sub".to_string(), Value::String(sub.to_string()));
claims.insert("parent".to_string(), Value::String("partner-parent".to_string()));
let get_args = |object| Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::GetObjectAction),
bucket: "homes",
conditions: &empty_conditions,
is_owner: false,
object,
claims: &claims,
deny_only: false,
};
assert!(resource_policy.is_allowed(&get_args("partner-parent/file")).await);
assert!(!resource_policy.is_allowed(&get_args("corporate-parent/file")).await);
assert!(!resource_policy.is_allowed(&get_args("1001/file")).await);
for (prefix, expected) in [
("partner-parent/file", true),
("corporate-parent/file", false),
("1001/file", false),
] {
let conditions = HashMap::from([("prefix".to_string(), vec![prefix.to_string()])]);
let list_args = Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::ListBucketAction),
bucket: "homes",
conditions: &conditions,
is_owner: false,
object: "",
claims: &claims,
deny_only: false,
};
assert_eq!(condition_policy.is_allowed(&list_args).await, expected, "sub={sub} prefix={prefix}");
}
}
// When `parent` is absent, `${aws:userid}` still falls back to `sub`.
let sub_only_claims = HashMap::from([("sub".to_string(), Value::String("legacy-sub".to_string()))]);
let fallback_args = Args {
account: "sts-access-key",
groups: &None,
action: Action::S3Action(crate::policy::action::S3Action::GetObjectAction),
bucket: "homes",
conditions: &empty_conditions,
is_owner: false,
object: "legacy-sub/file",
claims: &sub_only_claims,
deny_only: false,
};
assert!(resource_policy.is_allowed(&fallback_args).await);
Ok(())
}
#[tokio::test]
async fn test_aws_policy_variables_concatenation() -> Result<()> {
let data = r#"
@@ -4337,6 +4431,101 @@ mod test {
assert!(!allows(&deny_all_but("s3:GetObject"), "s3:ForceDeleteObject").await);
}
#[tokio::test]
async fn not_action_allow_does_not_grant_cross_family_actions() {
async fn eval(policy: &Policy, action: &str, bucket: &str, object: &str) -> bool {
let conditions = HashMap::new();
let claims = HashMap::new();
let groups = None;
let args = Args {
account: "user",
groups: &groups,
action: Action::try_from(action).expect("action parses"),
bucket,
conditions: &conditions,
is_owner: false,
object,
claims: &claims,
deny_only: false,
};
policy.is_allowed(&args).await
}
// Admin/STS/KMS requests often pass an empty bucket/object (which resolves to
// "/") or a warehouse bucket; an S3 NotAction Allow must never cross into them.
for (resource_clause, bucket, object) in [
(r#""Resource":["arn:aws:s3:::*"]"#, "", ""),
(r#""Resource":["arn:aws:s3:::*/*"]"#, "", ""),
(r#""Resource":["*"]"#, "", ""),
(r#""NotResource":["arn:aws:s3:::secret/*"]"#, "", ""),
(r#""Resource":["arn:aws:s3:::warehouse","arn:aws:s3:::warehouse/*"]"#, "warehouse", ""),
] {
for not_action in ["s3:DeleteObject", "s3:*"] {
let iam = Policy::parse_config(
format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","NotAction":["{not_action}"],{resource_clause}}}]}}"#
)
.as_bytes(),
)
.expect("NotAction policy parses");
for action in [
"admin:CreateUser",
"admin:AttachUserOrGroupPolicy",
"admin:ListUsers",
"admin:GetTableBucket",
"sts:AssumeRole",
"kms:ListKeys",
"kms:Decrypt",
] {
assert!(
!eval(&iam, action, bucket, object).await,
"IAM NotAction {not_action} with {resource_clause} must not grant {action}"
);
}
}
}
// The same statement still grants non-excluded S3 actions (except force-delete).
let s3_not_delete = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","NotAction":["s3:DeleteObject"],"Resource":["arn:aws:s3:::*"]}]}"#,
)
.expect("S3 NotAction policy parses");
assert!(allows(&s3_not_delete, "s3:GetObject").await);
assert!(!allows(&s3_not_delete, "s3:DeleteObject").await);
assert!(!allows(&s3_not_delete, "s3:ForceDeleteObject").await);
// An explicit admin NotAction stays confined to admin actions.
let admin_not_delete = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","NotAction":["admin:DeleteUser"],"Resource":["*"]}]}"#,
)
.expect("admin NotAction policy parses");
assert!(eval(&admin_not_delete, "admin:CreateUser", "", "").await);
assert!(!eval(&admin_not_delete, "admin:DeleteUser", "", "").await);
assert!(!allows(&admin_not_delete, "s3:GetObject").await);
assert!(!eval(&admin_not_delete, "kms:ListKeys", "", "").await);
assert!(!eval(&admin_not_delete, "sts:AssumeRole", "", "").await);
// Deny + NotAction keeps covering every non-excluded action family.
let deny = Policy::parse_config(
br#"{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["admin:*"]},
{"Effect":"Allow","Action":["kms:*"]},
{"Effect":"Allow","Action":["sts:*"]},
{"Effect":"Deny","NotAction":["s3:GetObject"],"Resource":["arn:aws:s3:::*"]}
]}"#,
)
.expect("deny NotAction policy parses");
assert!(!eval(&deny, "admin:CreateUser", "", "").await);
assert!(!eval(&deny, "kms:ListKeys", "", "").await);
assert!(!eval(&deny, "sts:AssumeRole", "", "").await);
// An empty ActionSet paired with an empty NotAction fails closed.
let empty = crate::policy::ActionSet::default();
assert!(!empty.statement_covers(&empty, &Action::S3Action(S3Action::GetObjectAction), false));
assert!(!empty.statement_covers(&empty, &Action::S3Action(S3Action::GetObjectAction), true));
}
async fn bucket_allows(policy: &BucketPolicy, action: &str) -> bool {
let conditions = HashMap::new();
policy
+29
View File
@@ -133,6 +133,13 @@ impl Principal {
}
false
}
/// Returns `true` when the principal admits callers it does not name, matching
/// either the wildcard account `"*"` or the empty account `""` used to evaluate
/// unauthenticated requests.
pub fn is_public(&self) -> bool {
self.is_match("*") || self.is_match("")
}
}
impl Validator for Principal {
@@ -236,4 +243,26 @@ mod test {
assert!(!principal.is_match("logging.s3.amazonaws.com"));
assert!(!principal.is_match("other-principal"));
}
#[test_case(r#""*""#, true ; "wildcard_string")]
#[test_case(r#"{"AWS": ["*"]}"#, true ; "aws_wildcard")]
#[test_case(r#"{"AWS": "**"}"#, true ; "aws_double_wildcard")]
#[test_case(r#"{"AWS": "?"}"#, true ; "aws_single_char_wildcard")]
#[test_case(r#"{"AWS": [""]}"#, true ; "aws_empty_array")]
#[test_case(r#"{"AWS": ""}"#, true ; "aws_empty_string")]
#[test_case(r#"{"AWS": ["alice", ""]}"#, true ; "aws_named_and_empty")]
#[test_case(r#"{"AWS": ["?nobody"]}"#, true ; "aws_leading_question_mark")]
#[test_case(r#"{"AWS": ["*?nobody"]}"#, true ; "aws_star_question_mark")]
#[test_case(r#"{"AWS": ["alice"]}"#, false ; "aws_named")]
#[test_case(r#"{"AWS": ["alice*"]}"#, false ; "aws_named_prefix")]
#[test_case(r#"{"AWS": ["arn:aws:iam::123456789012:root"]}"#, false ; "aws_arn")]
#[test_case(r#"{"Service": ""}"#, false ; "service_empty")]
#[test_case(r#"{"Service": "logging.s3.amazonaws.com"}"#, false ; "service_named")]
fn test_principal_is_public(json: &str, expected: bool) {
let principal: Principal = serde_json::from_str(json).expect("Should parse");
assert_eq!(principal.is_public(), expected, "input: {json}");
// Unauthenticated requests are evaluated under the empty account; any principal
// matching it must be classified as public.
assert!(!principal.is_match("") || principal.is_public(), "input: {json}");
}
}
+177 -14
View File
@@ -72,38 +72,201 @@ fn inner_match(pattern: impl AsRef<str>, name: impl AsRef<str>, simple: bool) ->
}
fn deep_match(mut pattern: &[u8], mut name: &[u8], simple: bool) -> bool {
while !pattern.is_empty() {
match pattern[0] {
// Fast path: match literal and `?` prefix without heap allocation.
while let Some(&p) = pattern.first() {
match p {
b'*' => break,
b'?' => {
if name.is_empty() {
return simple;
}
name = &name[1..];
pattern = &pattern[1..];
}
b'*' => {
return pattern.len() == 1
|| deep_match(&pattern[1..], name, simple)
|| (!name.is_empty() && deep_match(pattern, &name[1..], simple));
}
_ => {
if name.is_empty() || name[0] != pattern[0] {
if name.first() != Some(&p) {
return false;
}
name = &name[1..];
pattern = &pattern[1..];
}
}
}
if pattern.is_empty() {
return name.is_empty();
}
// Collapse consecutive leading `*` tokens; a trailing run matches everything.
while pattern.first() == Some(&b'*') {
pattern = &pattern[1..];
}
if pattern.is_empty() {
return true;
}
// Allocation-free fast paths when no further `*` remains in the pattern.
if !pattern.contains(&b'*') {
if !pattern.contains(&b'?') {
return name.ends_with(pattern);
}
if !simple {
return name.len() >= pattern.len()
&& pattern
.iter()
.zip(&name[name.len() - pattern.len()..])
.all(|(&p, &c)| p == b'?' || p == c);
}
}
star_match(pattern, name, simple)
}
/// Iteratively matches the remainder of a pattern immediately following a `*`.
///
/// Maintains reachable positions in `name` (`O(name.len())` space independent of
/// `pattern.len()`) and collapses consecutive `*` tokens in `O(1)` each, avoiding
/// both exponential backtracking and recursion stack growth.
fn star_match(pattern: &[u8], name: &[u8], simple: bool) -> bool {
let n = name.len();
// dp[j]: the pattern prefix processed so far (starting from the leading `*`)
// matches `name[..j]`.
let mut dp = vec![true; n + 1];
let mut prev_was_star = true;
for &p in pattern {
match p {
b'*' => {
if prev_was_star {
continue;
}
prev_was_star = true;
let Some(first) = dp.iter().position(|&matched| matched) else {
return false;
};
dp[first..].fill(true);
}
b'?' => {
prev_was_star = false;
// In simple mode, reaching `?` when `name` is exhausted accepts
// whatever follows in `pattern`.
if simple && dp[n] {
return true;
}
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1];
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
literal => {
prev_was_star = false;
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1] && name[j - 1] == literal;
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
}
name = &name[1..];
pattern = &pattern[1..];
}
name.is_empty() && pattern.is_empty()
dp[n]
}
#[cfg(test)]
mod tests {
use super::{is_match, is_match_as_pattern_prefix, is_simple_match};
#[test]
fn many_wildcards_match_without_backtracking() {
let name = format!("vault/{}", "a".repeat(1000));
let pattern = format!("vault/{}", "*a".repeat(100));
assert!(is_match(&pattern, &name));
assert!(is_simple_match(&pattern, &name));
assert!(!is_match(format!("{pattern}*b"), &name));
assert!(!is_simple_match(format!("{pattern}*b"), &name));
let repeated = format!("{}*b", "a*".repeat(80));
let aaa = "a".repeat(800);
assert!(!is_match(&repeated, &aaa));
assert!(!is_simple_match(&repeated, &aaa));
}
#[test]
fn deep_star_runs_do_not_overflow_stack() {
let stars = "*".repeat(200_000);
assert!(is_match(&stars, "tenant-bkt/report.txt"));
assert!(is_simple_match(&stars, "tenant-bkt/report.txt"));
let stars_suffix = format!("{stars}x");
let long_name = "a".repeat(1024);
assert!(!is_match(&stars_suffix, &long_name));
assert!(!is_simple_match(&stars_suffix, &long_name));
assert!(is_match(&stars_suffix, format!("{long_name}x")));
let middle_stars = format!("a{}b{}c", "*".repeat(50_000), "*".repeat(50_000));
assert!(is_match(&middle_stars, format!("a{}b{}c", "x".repeat(200), "y".repeat(200))));
assert!(!is_match(&middle_stars, format!("a{}c", "x".repeat(200))));
}
#[test]
fn utf8_multibyte_patterns_and_names_match() {
assert!(is_match("桶/目录/*文档*", "桶/目录/2026年文档.txt"));
assert!(!is_match("桶/目录/*文档*", "桶/目录/2026年表格.txt"));
assert!(is_match("café*naïve", "café-et-naïve"));
assert!(!is_match("café*naïve", "café-et-naive"));
assert!(is_simple_match("*🎉*🚀", "prefix🎉mid🚀"));
assert!(!is_simple_match("*🎉*🚀", "prefix🎉mid"));
}
/// Reference backtracking definition used only for small exhaustive equivalence checks.
fn backtracking_match(pattern: &[u8], name: &[u8], simple: bool) -> bool {
match pattern.split_first() {
None => name.is_empty(),
Some((b'*', rest)) => {
backtracking_match(rest, name, simple) || (!name.is_empty() && backtracking_match(pattern, &name[1..], simple))
}
Some((b'?', _)) if name.is_empty() => simple,
Some((&p, rest)) => !name.is_empty() && (p == b'?' || p == name[0]) && backtracking_match(rest, &name[1..], simple),
}
}
fn strings(alphabet: &str, max_len: usize) -> Vec<String> {
let mut all = vec![String::new()];
let mut longest = all.clone();
for _ in 0..max_len {
longest = longest
.iter()
.flat_map(|s| alphabet.chars().map(move |c| format!("{s}{c}")))
.collect();
all.extend_from_slice(&longest);
}
all
}
#[test]
fn agrees_with_backtracking_match() {
let names = strings("ab", 5);
for pattern in strings("ab*?", 5) {
for name in &names {
let expected = |simple| backtracking_match(pattern.as_bytes(), name.as_bytes(), simple);
assert_eq!(is_match(&pattern, name), expected(false), "is_match({pattern:?}, {name:?})");
assert_eq!(is_simple_match(&pattern, name), expected(true), "is_simple_match({pattern:?}, {name:?})");
}
}
}
#[test_case::test_case("*", "s3:GetObject" => true ; "1")]
#[test_case::test_case("", "s3:GetObject" => false ; "2")]
#[test_case::test_case("", "" => true; "3")]
+36 -6
View File
@@ -158,10 +158,16 @@ impl VariableResolver {
self.context.username.clone()
}
/// `parent` is the issuer-scoped identity RustFS authorizes and exposes through the
/// `aws:userid` condition key. A raw federated `sub` is unique only within its issuer,
/// so it must never shadow `parent`.
fn resolve_userid_values(&self) -> Option<Vec<String>> {
self.get_claim_as_strings("parent")
.or_else(|| self.get_claim_as_strings("sub"))
}
fn resolve_userid(&self) -> Option<String> {
self.get_claim_as_strings("sub")
.or_else(|| self.get_claim_as_strings("parent"))
.and_then(|mut vec| vec.pop())
self.resolve_userid_values().and_then(|mut vec| vec.pop())
}
fn resolve_principal_type(&self) -> String {
@@ -238,9 +244,7 @@ impl PolicyVariableResolver for VariableResolver {
match variable_name {
"aws:username" => self.resolve_username().map(|s| vec![s]),
"aws:userid" => self
.get_claim_as_strings("sub")
.or_else(|| self.get_claim_as_strings("parent")),
"aws:userid" => self.resolve_userid_values(),
_ => self.resolve(variable_name).await.map(|s| vec![s]),
}
@@ -481,6 +485,32 @@ mod tests {
assert_eq!(result, vec!["AIDACKCEVSQ6C2EXAMPLE-bucket".to_string()]);
}
#[tokio::test]
async fn test_resolve_aws_variables_userid_prefers_parent_over_sub() {
let mut claims = HashMap::new();
claims.insert("sub".to_string(), Value::String("1001".to_string()));
claims.insert("parent".to_string(), Value::String("issuer-scoped-parent".to_string()));
let mut context = VariableContext::new();
context.claims = Some(claims);
let resolver = VariableResolver::new(context.clone());
assert_eq!(resolver.resolve("aws:userid").await, Some("issuer-scoped-parent".to_string()));
assert_eq!(
resolver.resolve_multiple("aws:userid").await,
Some(vec!["issuer-scoped-parent".to_string()])
);
let result = resolve_aws_variables("homes/${aws:userid}/*", &resolver).await;
assert_eq!(result, vec!["homes/issuer-scoped-parent/*".to_string()]);
let cached = CachedAwsVariableResolver::new(context);
assert_eq!(cached.resolve("aws:userid").await, Some("issuer-scoped-parent".to_string()));
assert_eq!(
resolve_aws_variables("homes/${aws:userid}/*", &cached).await,
vec!["homes/issuer-scoped-parent/*".to_string()]
);
}
#[tokio::test]
async fn test_resolve_aws_variables_with_multiple_variables() {
let mut claims = HashMap::new();
+40 -71
View File
@@ -65,10 +65,17 @@ pub fn minio_index_storage_bytes(index: &Index) -> Bytes {
.unwrap_or(encoded)
}
/// Decodes a complete framed S2 index or its headerless metadata payload.
pub fn decode_minio_index_bytes(bytes: &Bytes) -> Option<Index> {
let decoded = S2Index::load(bytes.as_ref())
.or_else(|_| S2Index::load(&restore_index_headers(bytes.as_ref())))
.ok()?;
let bytes = bytes.as_ref();
// An unframed index starts with a nonnegative signed varint. Its
// low bit is clear, so it cannot start with the odd frame marker.
let body = if bytes.first() == Some(&CHUNK_TYPE_INDEX) {
remove_index_headers(bytes)?
} else {
bytes
};
let decoded = S2Index::load_body(body).ok()?;
let mut index = Index::new();
for info in decoded.info {
@@ -165,26 +172,7 @@ impl S2Index {
false
}
fn load(mut bytes: &[u8]) -> io::Result<Self> {
if bytes.len() <= SKIPPABLE_FRAME_HEADER + S2_INDEX_HEADER.len() + S2_INDEX_TRAILER.len() {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
}
if bytes[0] != CHUNK_TYPE_INDEX {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index chunk type"));
}
let chunk_len = (bytes[1] as usize) | ((bytes[2] as usize) << 8) | ((bytes[3] as usize) << 16);
bytes = &bytes[SKIPPABLE_FRAME_HEADER..];
if bytes.len() < chunk_len {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
}
bytes = &bytes[..chunk_len];
if !bytes.starts_with(S2_INDEX_HEADER) {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index header"));
}
bytes = &bytes[S2_INDEX_HEADER.len()..];
fn load_body(mut bytes: &[u8]) -> io::Result<Self> {
let (total_uncompressed, used) = read_varint(bytes)?;
if total_uncompressed < 0 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid uncompressed size"));
@@ -234,7 +222,10 @@ impl S2Index {
if idx > 0 {
let prev = info[idx - 1].uncompressed_offset;
uncompressed_offset += prev + est_block_uncompressed;
uncompressed_offset = prev
.checked_add(est_block_uncompressed)
.and_then(|base| base.checked_add(uncompressed_offset))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "uncompressed index offset overflow"))?;
if uncompressed_offset <= prev {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid uncompressed offset"));
}
@@ -251,9 +242,14 @@ impl S2Index {
bytes = &bytes[used..];
if idx > 0 {
let next_compressed_predict = compressed_predict + compressed_offset / 2;
let next_compressed_predict = compressed_predict
.checked_add(compressed_offset / 2)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index prediction overflow"))?;
let prev = info[idx - 1].compressed_offset;
compressed_offset += prev + compressed_predict;
compressed_offset = prev
.checked_add(compressed_predict)
.and_then(|base| base.checked_add(compressed_offset))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index offset overflow"))?;
if compressed_offset <= prev {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid compressed offset"));
}
@@ -265,12 +261,8 @@ impl S2Index {
info[idx].compressed_offset = compressed_offset;
}
if bytes.len() < 4 + S2_INDEX_TRAILER.len() {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
}
bytes = &bytes[4..];
if !bytes.starts_with(S2_INDEX_TRAILER) {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index trailer"));
if !bytes.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidData, "trailing bytes in index body"));
}
Ok(Self {
@@ -290,10 +282,9 @@ fn remove_index_headers(bytes: &[u8]) -> Option<&[u8]> {
let chunk_len = (bytes[1] as usize) | ((bytes[2] as usize) << 8) | ((bytes[3] as usize) << 16);
let bytes = &bytes[SKIPPABLE_FRAME_HEADER..];
if bytes.len() < chunk_len {
if bytes.len() != chunk_len {
return None;
}
let bytes = &bytes[..chunk_len];
let bytes = bytes.strip_prefix(S2_INDEX_HEADER)?;
let bytes = bytes.strip_suffix(S2_INDEX_TRAILER)?;
@@ -303,25 +294,6 @@ fn remove_index_headers(bytes: &[u8]) -> Option<&[u8]> {
Some(&bytes[..bytes.len() - 4])
}
fn restore_index_headers(input: &[u8]) -> Vec<u8> {
if input.is_empty() {
return Vec::new();
}
let mut bytes = Vec::with_capacity(SKIPPABLE_FRAME_HEADER + S2_INDEX_HEADER.len() + input.len() + 4 + S2_INDEX_TRAILER.len());
bytes.extend_from_slice(&[CHUNK_TYPE_INDEX, 0, 0, 0]);
bytes.extend_from_slice(S2_INDEX_HEADER);
bytes.extend_from_slice(input);
bytes.extend_from_slice(&((bytes.len() + 4 + S2_INDEX_TRAILER.len()) as u32).to_le_bytes());
bytes.extend_from_slice(S2_INDEX_TRAILER);
let chunk_len = bytes.len() - SKIPPABLE_FRAME_HEADER;
bytes[1] = chunk_len as u8;
bytes[2] = (chunk_len >> 8) as u8;
bytes[3] = (chunk_len >> 16) as u8;
bytes
}
fn write_varint(out: &mut Vec<u8>, value: i64) {
let mut unsigned = ((value as u64) << 1) ^ ((value >> 63) as u64);
while unsigned >= 0x80 {
@@ -342,10 +314,10 @@ fn read_uvarint(bytes: &[u8]) -> io::Result<(u64, usize)> {
let mut shift = 0_u32;
for (idx, byte) in bytes.iter().copied().enumerate() {
if idx == 9 && byte > 1 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "varint overflow"));
}
if byte < 0x80 {
if idx > 9 || (idx == 9 && byte > 1) {
return Err(io::Error::new(io::ErrorKind::InvalidData, "varint overflow"));
}
return Ok((value | ((byte as u64) << shift), idx + 1));
}
@@ -388,15 +360,7 @@ mod tests {
source.total_compressed = 3_000_000;
let stored = minio_index_storage_bytes(&source);
assert!(!stored.starts_with(&[CHUNK_TYPE_INDEX, 0x2a, 0x4d, 0x18]));
assert_eq!(
S2Index::load(&restore_index_headers(&stored))
.expect("restore full index")
.info
.len(),
2
);
assert_ne!(stored.first(), Some(&CHUNK_TYPE_INDEX));
let decoded = decode_minio_index_bytes(&stored).expect("decode headerless MinIO index");
assert_eq!(decoded.total_uncompressed, source.total_uncompressed);
assert_eq!(decoded.total_compressed, source.total_compressed);
@@ -423,12 +387,17 @@ mod tests {
let full = index.into_full_bytes();
assert_eq!(full[0], CHUNK_TYPE_INDEX);
let headerless = Bytes::copy_from_slice(remove_index_headers(full.as_ref()).expect("strip index headers"));
let restored = restore_index_headers(&headerless);
assert_eq!(restored[0], CHUNK_TYPE_INDEX);
for bytes in [&full, &headerless] {
let decoded = decode_minio_index_bytes(bytes).expect("decode index with unknown compressed total");
assert_eq!(decoded.total_uncompressed, 4_194_304);
assert_eq!(decoded.total_compressed, -1);
assert_eq!(decoded.find(2_097_152).unwrap(), (1_048_576, 2_097_152));
let decoded = decode_minio_index_bytes(&headerless).expect("decode index with unknown compressed total");
assert_eq!(decoded.total_uncompressed, 4_194_304);
assert_eq!(decoded.total_compressed, -1);
assert_eq!(decoded.find(2_097_152).unwrap(), (1_048_576, 2_097_152));
let truncated = bytes.slice(..bytes.len() - 1);
assert!(decode_minio_index_bytes(&truncated).is_none());
let mut trailing = bytes.to_vec();
trailing.push(0);
assert!(decode_minio_index_bytes(&Bytes::from(trailing)).is_none());
}
}
}
+27 -30
View File
@@ -115,7 +115,7 @@ impl Index {
));
}
if latest.uncompressed_offset + MIN_INDEX_DIST > uncompressed_offset {
if uncompressed_offset.saturating_sub(latest.uncompressed_offset) < MIN_INDEX_DIST {
return Ok(());
}
@@ -150,34 +150,23 @@ impl Index {
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "empty index"));
}
if self.info.len() > 200 {
let n = self
.info
.binary_search_by(|info| {
if info.uncompressed_offset > offset {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Less
}
})
.unwrap_or_else(|i| i);
Ok(self.checkpoint_at_or_before(offset).unwrap_or((0, 0)))
}
if n == 0 {
return Ok((self.info[0].compressed_offset, self.info[0].uncompressed_offset));
}
return Ok((self.info[n - 1].compressed_offset, self.info[n - 1].uncompressed_offset));
}
/// Returns the last recorded (stored, plaintext) offset at or before `offset`.
/// Index totals can be stale, so the caller must check the actual part bounds.
pub fn checkpoint_at_or_before(&self, offset: i64) -> Option<(i64, i64)> {
let next = self.info.partition_point(|entry| entry.uncompressed_offset <= offset);
let entry = self.info.get(next.checked_sub(1)?)?;
Some((entry.compressed_offset, entry.uncompressed_offset))
}
let mut compressed_off = 0;
let mut uncompressed_off = 0;
for info in &self.info {
if info.uncompressed_offset > offset {
break;
}
compressed_off = info.compressed_offset;
uncompressed_off = info.uncompressed_offset;
}
Ok((compressed_off, uncompressed_off))
/// Returns the first recorded (stored, plaintext) offset at or after `offset`.
/// Index totals can be stale, so the caller must check the actual part bounds.
pub fn checkpoint_at_or_after(&self, offset: i64) -> Option<(i64, i64)> {
let next = self.info.partition_point(|entry| entry.uncompressed_offset < offset);
let entry = self.info.get(next)?;
Some((entry.compressed_offset, entry.uncompressed_offset))
}
fn reduce(&mut self) {
@@ -366,7 +355,10 @@ impl Index {
if idx > 0 {
let prev = self.info[idx - 1].uncompressed_offset;
u_off += prev + self.est_block_uncomp;
u_off = prev
.checked_add(self.est_block_uncomp)
.and_then(|base| base.checked_add(u_off))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "uncompressed index offset overflow"))?;
if u_off <= prev {
return Err(io::Error::other("invalid offset"));
}
@@ -385,9 +377,14 @@ impl Index {
b = &b[n..];
if idx > 0 {
let next_c_predict = c_predict + c_off / 2;
let next_c_predict = c_predict
.checked_add(c_off / 2)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index prediction overflow"))?;
let prev = self.info[idx - 1].compressed_offset;
c_off += prev + c_predict;
c_off = prev
.checked_add(c_predict)
.and_then(|base| base.checked_add(c_off))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index offset overflow"))?;
if c_off <= prev {
return Err(io::Error::other("invalid offset"));
}
+94 -91
View File
@@ -14,7 +14,7 @@
use crate::compress_index::{Index, TryGetIndex};
use pin_project_lite::pin_project;
use rustfs_utils::compress::{CompressionAlgorithm, compress_block, decompress_block_with_limit};
use rustfs_utils::compress::{CompressionAlgorithm, compress_block, decompress_block_into};
use rustfs_utils::{put_uvarint, uvarint};
use std::cmp::min;
use std::io::{self};
@@ -177,7 +177,7 @@ where
delegate_reader_capabilities_generic_no_index!(CompressReader<R>, inner);
pin_project! {
/// A reader wrapper that decompresses data on the fly using DEFLATE algorithm.
/// Streams legacy compressed blocks after verifying their decoded length and checksum.
/// Header format:
/// - First byte: compression type (00 = compressed, 01 = uncompressed, FF = end)
/// - Bytes 1-3: length of compressed data (little-endian)
@@ -347,97 +347,19 @@ where
}
}
let typ = this.header_buf[0];
let crc = (this.header_buf[4] as u32)
| ((this.header_buf[5] as u32) << 8)
| ((this.header_buf[6] as u32) << 16)
| ((this.header_buf[7] as u32) << 24);
let compressed_buf = &this.compressed_buf[..*this.compressed_len];
// `compressed_buf`'s length comes from the untrusted 24-bit header length field, so it
// can be shorter than 16 bytes. `uvarint` is safe on any slice length (reads at most 10
// bytes and stops at the terminator), so pass the whole slice instead of a fixed
// `[0..16]` index that panics on corrupted/truncated blocks shorter than 16 bytes.
let (uncompress_len, uvarint) = uvarint(compressed_buf);
// Reject a length prefix that could not be decoded: `uvarint <= 0` means the varint was
// empty/unterminated (0) or overflowed (negative — as usize it would index far past the
// buffer and panic the slice below). The `> len` bound is belt-and-suspenders (uvarint's
// positive return is always <= buf.len()) but keeps the slice panic-free regardless.
if uvarint <= 0 || uvarint as usize > compressed_buf.len() {
*this.compressed_read = 0;
*this.compressed_len = 0;
*this.poisoned = true;
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid compressed block length prefix")));
}
// Bound the untrusted declared plaintext length up front and enforce it
// inside the decoder so a small block cannot expand into GiB before the
// post-decode length check runs.
if uncompress_len > MAX_BLOCK_PLAINTEXT_LEN {
*this.compressed_read = 0;
*this.compressed_len = 0;
*this.poisoned = true;
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::InvalidData,
"Compressed block declares an oversized length",
)));
}
let Ok(uncompress_len_usize) = usize::try_from(uncompress_len) else {
*this.compressed_read = 0;
*this.compressed_len = 0;
*this.poisoned = true;
return Poll::Ready(Err(io::Error::new(
io::ErrorKind::InvalidData,
"Compressed block declares an oversized length",
)));
};
let compressed_data = &compressed_buf[uvarint as usize..];
let decompressed = if typ == COMPRESS_TYPE_COMPRESSED {
match decompress_block_with_limit(compressed_data, *this.compression_algorithm, uncompress_len_usize) {
Ok(out) => out,
Err(e) => {
// error!("DecompressReader decompress_block error: {e}");
*this.compressed_read = 0;
*this.compressed_len = 0;
*this.poisoned = true;
return Poll::Ready(Err(e));
}
}
} else {
// The header phase already rejected every type other than
// COMPRESS_TYPE_COMPRESSED / COMPRESS_TYPE_UNCOMPRESSED.
compressed_data.to_vec()
};
if decompressed.is_empty() {
// The writer never emits zero-length plaintext blocks; an empty
// decode surfacing as Ready(Ok) with no bytes would read as EOF and
// silently truncate the stream.
*this.poisoned = true;
*this.compressed_read = 0;
*this.compressed_len = 0;
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Empty compressed block")));
}
if decompressed.len() != uncompress_len_usize {
// error!("DecompressReader decompressed length mismatch: {} != {}", decompressed.len(), uncompress_len);
*this.compressed_read = 0;
*this.compressed_len = 0;
*this.poisoned = true;
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Decompressed length mismatch")));
}
let actual_crc = {
let mut hasher = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
hasher.update(&decompressed);
hasher.finalize() as u32
};
if actual_crc != crc {
// error!("DecompressReader CRC32 mismatch: actual {actual_crc} != expected {crc}");
*this.compressed_read = 0;
*this.compressed_len = 0;
*this.poisoned = true;
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "CRC32 mismatch")));
}
*this.buffer = decompressed;
*this.buffer_pos = 0;
let result = decode_block(
this.header_buf,
&this.compressed_buf[..*this.compressed_len],
*this.compression_algorithm,
this.buffer,
);
*this.compressed_read = 0;
*this.compressed_len = 0;
if let Err(error) = result {
this.buffer.clear();
*this.poisoned = true;
return Poll::Ready(Err(error));
}
let to_copy = min(buf.remaining(), this.buffer.len());
buf.put_slice(&this.buffer[..to_copy]);
*this.buffer_pos += to_copy;
@@ -451,6 +373,50 @@ where
delegate_reader_capabilities_generic_no_index!(DecompressReader<R>, inner);
fn decode_block(
header: &[u8; HEADER_LEN],
payload: &[u8],
algorithm: CompressionAlgorithm,
output: &mut Vec<u8>,
) -> io::Result<()> {
let (declared_len, prefix_len) = uvarint(payload);
let data = usize::try_from(prefix_len)
.ok()
.filter(|len| *len != 0)
.and_then(|len| payload.get(len..))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Invalid compressed block length prefix"))?;
let declared_len = usize::try_from(declared_len)
.ok()
.filter(|_| declared_len <= MAX_BLOCK_PLAINTEXT_LEN)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Compressed block declares an oversized length"))?;
let compressed = header[0] == COMPRESS_TYPE_COMPRESSED;
let plaintext = if compressed {
decompress_block_into(data, algorithm, declared_len, output)?;
output.as_slice()
} else {
data
};
if plaintext.is_empty() {
return Err(io::Error::new(io::ErrorKind::InvalidData, "Empty compressed block"));
}
if plaintext.len() != declared_len {
return Err(io::Error::new(io::ErrorKind::InvalidData, "Decompressed length mismatch"));
}
let expected_crc = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
let mut hasher = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
hasher.update(plaintext);
if hasher.finalize() as u32 != expected_crc {
return Err(io::Error::new(io::ErrorKind::InvalidData, "CRC32 mismatch"));
}
if !compressed {
output.clear();
output.extend_from_slice(data);
}
Ok(())
}
/// Build compressed block with header + uvarint + compressed data
fn build_compressed_block(uncompressed_data: &[u8], compression_algorithm: CompressionAlgorithm) -> Vec<u8> {
let crc = {
@@ -503,6 +469,43 @@ mod tests {
assert_eq!(&decompressed, data);
}
#[tokio::test]
async fn decompress_reader_reuses_the_verified_plaintext_buffer() {
let algorithm = CompressionAlgorithm::Lz4;
let len = 128 * 1024;
let first = vec![0x23; len];
let second = vec![0x45; len];
let mut stored = build_compressed_block(&first, algorithm);
stored.extend_from_slice(&build_compressed_block(&second, algorithm));
let mut bad_crc = build_compressed_block(&first, algorithm);
bad_crc[4] ^= 1;
stored.extend_from_slice(&bad_crc);
let mut reader = DecompressReader::new(Cursor::new(stored), algorithm);
let mut output = vec![0; len];
reader.read_exact(&mut output).await.unwrap();
assert_eq!(output, first);
let allocation = reader.buffer.as_ptr();
reader.read_exact(&mut output).await.unwrap();
assert_eq!(output, second);
assert_eq!(
reader.buffer.as_ptr(),
allocation,
"equal-sized blocks should reuse the output allocation"
);
let mut probe = [0xa5; 16];
for _ in 0..2 {
let error = reader
.read(&mut probe)
.await
.expect_err("a rejected block must never be readable");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(probe, [0xa5; 16]);
}
}
#[tokio::test]
async fn test_compress_reader_basic_deflate() {
let data = b"hello world, hello world, hello world!";
+149 -68
View File
@@ -20,8 +20,9 @@ use async_compression::tokio::bufread::BzDecoder;
use bytes::{Buf as _, Bytes};
use datafusion::object_store::{Error as ObjectStoreError, Result as ObjectStoreResult};
use flate2::bufread::GzDecoder;
use futures::{StreamExt, stream};
use futures::{Stream, StreamExt, TryStreamExt as _, stream};
use futures_core::stream::BoxStream;
use memchr::{memchr, memchr2};
use std::{
error::Error as StdError,
io::{self, BufRead as _, Read as _},
@@ -356,7 +357,8 @@ impl io::Read for BlockingChannelReader {
}
}
pub(crate) fn compressed_input_stream(
#[cfg(test)]
fn compressed_input_stream(
reader: SelectInputReader,
compressed_size: u64,
format: CompressionFormat,
@@ -366,22 +368,58 @@ pub(crate) fn compressed_input_stream(
query_guard: Option<QueryExecutionGuard>,
) -> ObjectStoreResult<BoxStream<'static, ObjectStoreResult<Bytes>>> {
let record_size = RecordSizeTracker::new(record_delimiter).map_err(select_object_store_error)?;
compressed_input_stream_with_tracker(
reader,
compressed_size,
format,
input_metrics,
record_size,
max_processed_bytes,
query_guard,
)
}
pub(crate) fn compressed_input_stream_with_tracker(
reader: SelectInputReader,
compressed_size: u64,
format: CompressionFormat,
input_metrics: Arc<SelectInputMetrics>,
record_size: RecordSizeTracker,
max_processed_bytes: u64,
query_guard: Option<QueryExecutionGuard>,
) -> ObjectStoreResult<BoxStream<'static, ObjectStoreResult<Bytes>>> {
let reader = compressed_input_reader(reader, compressed_size, format, input_metrics, max_processed_bytes, query_guard);
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES);
Ok(stream::try_unfold((stream, record_size), |(mut stream, mut record_size)| async move {
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES).map_err(input_io_error);
Ok(record_size_limited_stream(stream, record_size, select_object_store_error))
}
/// Fails the stream with `OverMaxRecordSize` once a record exceeds
/// `MAX_SELECT_RECORD_BYTES`. The `ScanRange` splitter and the Arrow decoders
/// buffer whole records, so every CSV and JSON Lines input path applies it,
/// compressed or uncompressed.
pub(crate) fn record_size_limited_stream<S, E>(
stream: S,
record_size: RecordSizeTracker,
map_error: fn(SelectError) -> E,
) -> BoxStream<'static, Result<Bytes, E>>
where
S: Stream<Item = Result<Bytes, E>> + Send + 'static,
E: Send + 'static,
{
stream::try_unfold((stream.boxed(), record_size), move |(mut stream, mut record_size)| async move {
match stream.next().await {
Some(Ok(bytes)) => {
record_size.observe(&bytes).map_err(select_object_store_error)?;
record_size.observe(&bytes).map_err(map_error)?;
Ok(Some((bytes, (stream, record_size))))
}
Some(Err(error)) => Err(input_io_error(error)),
Some(Err(error)) => Err(error),
None => {
record_size.finish().map_err(select_object_store_error)?;
record_size.finish().map_err(map_error)?;
Ok(None)
}
}
})
.boxed())
.boxed()
}
pub(crate) fn input_io_error(source: io::Error) -> ObjectStoreError {
@@ -395,7 +433,7 @@ pub(crate) fn input_io_error(source: io::Error) -> ObjectStoreError {
}
}
fn select_object_store_error(source: SelectError) -> ObjectStoreError {
pub(crate) fn select_object_store_error(source: SelectError) -> ObjectStoreError {
ObjectStoreError::Generic {
store: "EcObjectStore",
source: Box::new(source),
@@ -657,84 +695,127 @@ pub(crate) fn find_error_source<'a, T: StdError + 'static>(error: &'a (dyn StdEr
None
}
struct RecordSizeTracker {
delimiter: Vec<u8>,
prefix: Vec<usize>,
enum RecordDelimiterMatcher {
/// Default CSV line endings (`\r`, `\n`, or `\r\n`) when no custom `RecordDelimiter` is configured.
DefaultCsvLineEnding,
SingleByte(u8),
MultiByte {
delimiter: Vec<u8>,
prefix: Vec<usize>,
matched: usize,
},
}
pub(crate) struct RecordSizeTracker {
matcher: RecordDelimiterMatcher,
record_bytes: usize,
matched: usize,
}
impl RecordSizeTracker {
fn new(delimiter: Vec<u8>) -> Result<Self, SelectError> {
pub(crate) fn default_csv() -> Self {
Self {
matcher: RecordDelimiterMatcher::DefaultCsvLineEnding,
record_bytes: 0,
}
}
pub(crate) fn new(delimiter: Vec<u8>) -> Result<Self, SelectError> {
if delimiter.is_empty() {
return Err(SelectError::InvalidDataSource);
}
let mut prefix = vec![0; delimiter.len()];
let mut matched = 0;
for index in 1..delimiter.len() {
while matched > 0 && delimiter[index] != delimiter[matched] {
matched = prefix[matched - 1];
let matcher = if delimiter.len() == 1 {
RecordDelimiterMatcher::SingleByte(delimiter[0])
} else {
let mut prefix = vec![0; delimiter.len()];
let mut matched = 0;
for index in 1..delimiter.len() {
while matched > 0 && delimiter[index] != delimiter[matched] {
matched = prefix[matched - 1];
}
if delimiter[index] == delimiter[matched] {
matched += 1;
}
prefix[index] = matched;
}
if delimiter[index] == delimiter[matched] {
matched += 1;
RecordDelimiterMatcher::MultiByte {
delimiter,
prefix,
matched: 0,
}
prefix[index] = matched;
}
};
Ok(Self {
delimiter,
prefix,
matcher,
record_bytes: 0,
matched: 0,
})
}
fn observe(&mut self, bytes: &[u8]) -> Result<(), SelectError> {
if self.delimiter.len() == 1 {
return self.observe_single_byte_delimiter(bytes);
}
for &byte in bytes {
self.record_bytes = self.record_bytes.checked_add(1).ok_or(SelectError::OverMaxRecordSize)?;
while self.matched > 0 && byte != self.delimiter[self.matched] {
self.matched = self.prefix[self.matched - 1];
}
if byte == self.delimiter[self.matched] {
self.matched += 1;
}
if self.matched == self.delimiter.len() {
let payload_bytes = self.record_bytes - self.delimiter.len();
if payload_bytes > MAX_SELECT_RECORD_BYTES {
fn observe(&mut self, mut bytes: &[u8]) -> Result<(), SelectError> {
match &mut self.matcher {
RecordDelimiterMatcher::DefaultCsvLineEnding => {
while let Some(index) = memchr2(b'\r', b'\n', bytes) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
self.matched = 0;
} else if self.record_bytes - self.matched > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
Ok(())
}
RecordDelimiterMatcher::SingleByte(delimiter) => {
let delimiter = *delimiter;
while let Some(index) = memchr(delimiter, bytes) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
Ok(())
}
RecordDelimiterMatcher::MultiByte {
delimiter,
prefix,
matched,
} => {
for &byte in bytes {
self.record_bytes = self.record_bytes.checked_add(1).ok_or(SelectError::OverMaxRecordSize)?;
while *matched > 0 && byte != delimiter[*matched] {
*matched = prefix[*matched - 1];
}
if byte == delimiter[*matched] {
*matched += 1;
}
if *matched == delimiter.len() {
let payload_bytes = self.record_bytes - delimiter.len();
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
*matched = 0;
} else if self.record_bytes - *matched > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
}
Ok(())
}
}
Ok(())
}
fn observe_single_byte_delimiter(&mut self, mut bytes: &[u8]) -> Result<(), SelectError> {
let delimiter = self.delimiter[0];
while let Some(index) = bytes.iter().position(|byte| *byte == delimiter) {
let payload_bytes = self.record_bytes.checked_add(index).ok_or(SelectError::OverMaxRecordSize)?;
if payload_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
self.record_bytes = 0;
bytes = &bytes[index + 1..];
}
self.record_bytes = self
.record_bytes
.checked_add(bytes.len())
.ok_or(SelectError::OverMaxRecordSize)?;
if self.record_bytes > MAX_SELECT_RECORD_BYTES {
return Err(SelectError::OverMaxRecordSize);
}
Ok(())
}
fn finish(&self) -> Result<(), SelectError> {
+227 -25
View File
@@ -22,12 +22,13 @@ use crate::{
SelectInputMetrics, SelectObjectOptions, SelectObjectSnapshot, SelectObjectSnapshotReadError, SelectStorageError,
SelectStore, SnapshotConsistencyError,
input_stream::{
CompressionFormat, SELECT_DECODE_CHUNK_BYTES, compressed_input_reader, compressed_input_stream, input_io_error,
processed_bytes_limit,
CompressionFormat, MAX_SELECT_RECORD_BYTES, RecordSizeTracker, SELECT_DECODE_CHUNK_BYTES, compressed_input_reader,
compressed_input_stream_with_tracker, input_io_error, processed_bytes_limit, record_size_limited_stream,
select_object_store_error,
},
query::{
ast::{JsonPathSegment, JsonSource},
parser::RustFsDialect,
parser::{BoundedRustFsDialect, validate_set_operator_budget},
session::QueryExecutionTracker,
},
resolve_select_object_store_handle, select_is_err_bucket_not_found, select_is_err_object_not_found,
@@ -47,6 +48,7 @@ use datafusion::{
sqlparser::{
ast::{Expr, Ident, JsonPathElem, ObjectNamePart, SetExpr, Statement, TableFactor},
parser::Parser as SqlParser,
tokenizer::Tokenizer,
},
},
};
@@ -345,6 +347,37 @@ impl EcObjectStore {
.unwrap_or_else(|| b"\n".to_vec())
}
fn record_size_tracker(&self) -> Result<RecordSizeTracker> {
if let Some(csv) = self.input.request.input_serialization.csv.as_ref() {
if csv.record_delimiter.is_none() {
return Ok(RecordSizeTracker::default_csv());
}
return RecordSizeTracker::new(self.record_delimiter()).map_err(select_object_store_error);
}
RecordSizeTracker::new(b"\n".to_vec()).map_err(select_object_store_error)
}
/// Applies the 1 MiB record size limit to uncompressed CSV and JSON Lines input,
/// matching compressed input enforcement.
fn limit_record_size<S>(&self, stream: S) -> Result<BoxStream<'static, Result<Bytes>>>
where
S: Stream<Item = Result<Bytes>> + Send + 'static,
{
if self
.input
.request
.input_serialization
.csv
.as_ref()
.is_some_and(|csv| csv.allow_quoted_record_delimiter.unwrap_or(false))
{
// The CSV normalizer owns logical-record limits.
return Ok(stream.boxed());
}
let record_size = self.record_size_tracker()?;
Ok(record_size_limited_stream(stream, record_size, select_object_store_error))
}
fn record_delimiter_for_conversion(&self) -> Option<Vec<u8>> {
let delimiter = self.record_delimiter();
(self.need_convert || (delimiter.len() == 2 && delimiter != NORMALIZED_RECORD_DELIMITER)).then_some(delimiter)
@@ -467,16 +500,22 @@ impl EcObjectStore {
return Ok(Bytes::new());
}
let mut end = select_default_read_buffer_size_u64().min(object_size);
let max_probe = u64::try_from(MAX_SELECT_RECORD_BYTES.saturating_add(delimiter.len())).unwrap_or(u64::MAX);
let mut end = select_default_read_buffer_size_u64().min(object_size).min(max_probe);
loop {
let bytes = self.read_raw_range(0..end).await?;
if let Some(pos) = find_delimiter(&bytes, delimiter) {
let header_end = find_delimiter(&bytes, delimiter);
// Stop widening the read once the header cannot fit the 1 MiB record limit.
if header_end.unwrap_or(bytes.len()) > MAX_SELECT_RECORD_BYTES {
return Err(select_object_store_error(SelectError::OverMaxRecordSize));
}
if let Some(pos) = header_end {
return Ok(bytes.slice(0..pos + delimiter.len()));
}
if end == object_size {
return Ok(bytes);
}
end = end.saturating_mul(2).min(object_size);
end = end.saturating_mul(2).min(object_size).min(max_probe);
}
}
@@ -515,10 +554,19 @@ pub(crate) fn is_json_document_input(input: &SelectObjectContentInput) -> bool {
/// Preserves the pre-typed-path single-key behavior of public legacy constructors.
pub(crate) fn legacy_json_source_from_input(input: &SelectObjectContentInput) -> JsonSource {
if !is_json_document_input(input) {
const MAX_LEGACY_EXPRESSION_BYTES: usize = 256 * 1024;
if !is_json_document_input(input) || input.request.expression.len() > MAX_LEGACY_EXPRESSION_BYTES {
return JsonSource::default();
}
let Ok(mut statements) = SqlParser::parse_sql(&RustFsDialect, &input.request.expression) else {
let dialect = BoundedRustFsDialect::default();
let Ok(tokens) = Tokenizer::new(&dialect, &input.request.expression).tokenize() else {
return JsonSource::default();
};
if validate_set_operator_budget(&tokens).is_err() {
return JsonSource::default();
}
let Ok(mut statements) = SqlParser::new(&dialect).with_tokens(tokens).parse_statements() else {
return JsonSource::default();
};
if statements.len() != 1 {
@@ -963,17 +1011,13 @@ impl ObjectStore for EcObjectStore {
let stream = ReaderStream::with_capacity(reader, SELECT_DECODE_CHUNK_BYTES).map_err(input_io_error);
GetResultPayload::Stream(self.convert_csv_stream(stream))
} else {
let input_record_delimiter = if self.input.request.input_serialization.csv.is_some() {
self.record_delimiter()
} else {
b"\n".to_vec()
};
let stream = compressed_input_stream(
let record_size = self.record_size_tracker()?;
let stream = compressed_input_stream_with_tracker(
reader.stream,
original_size,
compression,
Arc::clone(&self.input_metrics),
input_record_delimiter,
record_size,
max_processed_bytes,
query_guard,
)?;
@@ -1013,10 +1057,17 @@ impl ObjectStore for EcObjectStore {
} else {
None
};
// The ScanRange splitter buffers each record up to its delimiter, so the
// record size limit has to come first.
let record_size = RecordSizeTracker::new(delimiter.clone()).map_err(select_object_store_error)?;
let stream = scan_range_stream(
meter_uncompressed_input_stream(
ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE),
Arc::clone(&self.input_metrics),
record_size_limited_stream(
meter_uncompressed_input_stream(
ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE),
Arc::clone(&self.input_metrics),
),
record_size,
|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error),
),
delimiter,
scan_range,
@@ -1040,6 +1091,7 @@ impl ObjectStore for EcObjectStore {
let stream = bytes_stream(ReaderStream::with_capacity(reader.stream, SELECT_DEFAULT_READ_BUFFER_SIZE), stream_size);
if meter_input {
let stream = meter_uncompressed_input_stream(stream, Arc::clone(&self.input_metrics));
let stream = self.limit_record_size(stream)?;
let stream = self.convert_csv_stream(stream);
GetResultPayload::Stream(stream)
} else {
@@ -1263,13 +1315,7 @@ where
Some(Ok(bytes)) => state.push_chunk(&bytes),
Some(Err(err)) => {
state.done = true;
return Some((
Err(o_Error::Generic {
store: "EcObjectStore",
source: Box::new(err),
}),
state,
));
return Some((Err(input_io_error(err)), state));
}
None => {
if state.offset < state.expected_end {
@@ -1639,6 +1685,23 @@ mod test {
assert_eq!(legacy_json_source_from_input(&quoted_key).scalar_column(), Some("LongKey"));
}
#[test]
fn legacy_source_adapter_bounds_operator_and_set_chains_on_small_stack() {
let plus_chain = format!("SELECT {} FROM S3Object.employees", vec!["1"; 64 * 1024].join("+"));
let trailing_err = format!("SELECT {}+) FROM S3Object.employees", vec!["1"; 64 * 1024].join("+"));
let union_chain = vec!["SELECT 1"; 16 * 1024].join(" UNION ");
for expression in [plus_chain, trailing_err, union_chain] {
let input = json_document_input("bucket", "input.json", &expression);
let source = std::thread::Builder::new()
.stack_size(1024 * 1024)
.spawn(move || legacy_json_source_from_input(&input))
.expect("spawn bounded-stack worker")
.join()
.expect("bounded parser must not overflow worker stack");
assert_eq!(source, JsonSource::default());
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial]
async fn legacy_public_constructors_preserve_single_key_json_source() {
@@ -3235,6 +3298,145 @@ mod test {
}
}
#[tokio::test]
async fn uncompressed_input_enforces_the_record_size_limit() {
const BUCKET: &str = "select-uncompressed-record-limit";
let env = crate::storage_api::select_test_ecstore_env().await;
env.make_bucket(BUCKET, false).await;
// (JSON Lines, ScanRange, ScanRange starting after CSV header)
let cases = [
(false, false, false),
(false, true, false),
(false, true, true),
(true, false, false),
(true, true, false),
];
for (json, scan_range, after_header) in cases {
for size in [MAX_SELECT_RECORD_BYTES, MAX_SELECT_RECORD_BYTES + 1] {
let mut data = if json {
let mut record = br#"{"v":""#.to_vec();
record.resize(size - 2, b'a');
record.extend_from_slice(b"\"}");
record
} else {
vec![b'a'; size]
};
data.push(b'\n');
if after_header {
data.extend_from_slice(b"1\n");
}
let object = format!("{json}-{scan_range}-{after_header}-{size}");
let mut reader = SelectPutObjReader::from_vec(data.clone());
env.ecstore
.put_object(BUCKET, &object, &mut reader, &Default::default())
.await
.expect("write record limit fixture");
let mut input = if json {
(*json_input(BUCKET, &object, JsonType::LINES)).clone()
} else {
(*csv_input(BUCKET, &object)).clone()
};
if after_header {
let csv = input.request.input_serialization.csv.as_mut().expect("CSV input");
csv.file_header_info = Some(FileHeaderInfo::USE);
}
if scan_range {
let start = if after_header { size + 1 } else { 0 };
input.request.scan_range = Some(ScanRange {
start: Some(i64::try_from(start).expect("fixture offset")),
end: Some(i64::try_from(start + 1).expect("fixture offset")),
});
}
let store = EcObjectStore::build_with_snapshot(
Arc::new(input),
Arc::new(GreedyMemoryPool::new(4 * MAX_SELECT_RECORD_BYTES)),
None,
Arc::new(SelectInputMetrics::default()),
prepare_test_snapshot(BUCKET, &object).await,
JsonSource::default(),
)
.expect("record limit store");
let output = match store.get_opts(&Path::from(object.as_str()), GetOptions::default()).await {
Ok(result) => {
let GetResultPayload::Stream(stream) = result.payload else { panic!("uncompressed stream") };
stream.try_collect::<Vec<_>>().await
}
Err(error) => Err(error),
};
if size > MAX_SELECT_RECORD_BYTES {
let error = output.expect_err("uncompressed records over 1 MiB must fail like compressed ones");
assert_eq!(
QueryError::from(DataFusionError::from(error)).select_error(),
SelectError::OverMaxRecordSize,
"object={object}"
);
} else {
assert_eq!(output.expect("records within the limit must pass").concat(), data, "object={object}");
}
}
}
}
#[tokio::test]
async fn default_csv_record_limit_handles_cr_only_line_endings() {
const BUCKET: &str = "select-cr-only-csv-limit";
let env = crate::storage_api::select_test_ecstore_env().await;
env.make_bucket(BUCKET, false).await;
let valid_cr_csv = format!("a,b\r{}", format!("{},val\r", "x".repeat(95)).repeat(15_000)).into_bytes();
assert!(
valid_cr_csv.len() > MAX_SELECT_RECORD_BYTES,
"fixture must span more than 1 MiB across CR-only records"
);
let mut oversized_cr_csv = vec![b'a'; MAX_SELECT_RECORD_BYTES + 1];
oversized_cr_csv.push(b'\r');
for compression in [None, Some(CompressionFormat::Gzip)] {
for (name, raw, should_fail) in [("valid-cr", &valid_cr_csv, false), ("oversized-cr", &oversized_cr_csv, true)] {
let bytes = match compression {
Some(format) => encode_compressed_fixture(format, raw).await,
None => raw.clone(),
};
let object = format!("{name}-{compression:?}");
let mut reader = SelectPutObjReader::from_vec(bytes);
env.ecstore
.put_object(BUCKET, &object, &mut reader, &Default::default())
.await
.expect("write CR CSV fixture");
let mut input = (*csv_input(BUCKET, &object)).clone();
input.request.input_serialization.compression_type = compression.map(|format| match format {
CompressionFormat::Gzip => CompressionType::GZIP,
CompressionFormat::Bzip2 => CompressionType::BZIP2,
});
let store = EcObjectStore::build_with_snapshot(
Arc::new(input),
Arc::new(GreedyMemoryPool::new(4 * MAX_SELECT_RECORD_BYTES)),
None,
Arc::new(SelectInputMetrics::default()),
prepare_test_snapshot(BUCKET, &object).await,
JsonSource::default(),
)
.expect("CR CSV store");
let result = store
.get_opts(&Path::from(object.as_str()), GetOptions::default())
.await
.expect("open CR CSV stream");
let GetResultPayload::Stream(stream) = result.payload else { panic!("CSV stream") };
let output = stream.try_collect::<Vec<_>>().await;
if should_fail {
let error = output.expect_err("oversized CR-only record must fail");
assert_eq!(
QueryError::from(DataFusionError::from(error)).select_error(),
SelectError::OverMaxRecordSize,
"object={object}"
);
} else {
assert_eq!(output.expect("valid CR-only CSV over 1 MiB must pass").concat(), *raw, "object={object}");
}
}
}
}
#[tokio::test]
async fn quoted_record_delimiters_preserve_compressed_crlf_size_boundaries() {
use crate::input_stream::MAX_SELECT_RECORD_BYTES;
+85 -2
View File
@@ -12,13 +12,41 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::VecDeque;
use std::{
collections::VecDeque,
sync::atomic::{AtomicUsize, Ordering},
};
use datafusion::sql::sqlparser::dialect::Dialect;
use datafusion::sql::sqlparser::{
ast::Expr,
dialect::Dialect,
keywords::Keyword,
parser::{Parser as SqlParser, ParserError},
tokenizer::Token,
};
use super::ast::ExtStatement;
use crate::QueryResult;
/// Maximum number of infix and postfix operators in one S3 Select expression.
///
/// sqlparser's recursion limit only guards nested sub-expressions. Operator chains
/// (`1+1+...+1`, `a OR b OR ...`, `x IS NULL IS NULL ...`) are parsed in a loop where
/// each operator nests the expression built so far one level deeper. The resulting
/// AST is later cloned, dropped, and planned recursively on a worker-thread stack,
/// so operator count must be bounded during parsing.
pub const MAX_SELECT_OPERATORS: usize = 256;
/// Maximum number of SQL set-operation keywords (`UNION`, `EXCEPT`, `INTERSECT`,
/// `MINUS`) allowed before parsing. sqlparser builds `SetExpr::SetOperation` chains
/// in a loop without touching `Dialect::parse_infix`, so unbounded chains would
/// overflow the stack on drop even though S3 Select rejects set operations.
pub const MAX_SELECT_SET_OPERATORS: usize = 16;
/// Maximum nested field-access segments (`a.b.c...` or `a[0][1]...`) in one expression,
/// bounding `CoreFunctionPlanner::plan_compound_identifier` recursion depth.
pub const MAX_SELECT_FIELD_ACCESS_DEPTH: usize = 64;
#[derive(Debug, Default)]
pub struct RustFsDialect;
@@ -40,6 +68,61 @@ impl Dialect for RustFsDialect {
}
}
/// [`RustFsDialect`] that rejects expressions with more than [`MAX_SELECT_OPERATORS`]
/// infix or postfix operators. The budget is per instance, so construct a fresh
/// dialect for every parse.
#[derive(Debug, Default)]
pub struct BoundedRustFsDialect {
operators: AtomicUsize,
}
impl Dialect for BoundedRustFsDialect {
fn is_identifier_start(&self, ch: char) -> bool {
RustFsDialect.is_identifier_start(ch)
}
fn is_identifier_part(&self, ch: char) -> bool {
RustFsDialect.is_identifier_part(ch)
}
fn supports_group_by_expr(&self) -> bool {
RustFsDialect.supports_group_by_expr()
}
fn supports_partiql(&self) -> bool {
RustFsDialect.supports_partiql()
}
/// Called by sqlparser before every infix or postfix operator.
fn parse_infix(&self, _parser: &mut SqlParser, _expr: &Expr, _precedence: u8) -> Option<Result<Expr, ParserError>> {
if self.operators.load(Ordering::Relaxed) >= MAX_SELECT_OPERATORS {
// `RecursionLimitExceeded` is the only error sqlparser's speculative
// `maybe_parse` does not swallow, and matches nested-parenthesis errors.
return Some(Err(ParserError::RecursionLimitExceeded));
}
self.operators.fetch_add(1, Ordering::Relaxed);
// `None` hands the operator back to sqlparser's standard infix parsing.
None
}
}
/// Rejects token streams with more than [`MAX_SELECT_SET_OPERATORS`] set-operation
/// keywords before sqlparser constructs a deeply nested `SetExpr::SetOperation` tree.
pub fn validate_set_operator_budget(tokens: &[Token]) -> Result<(), ParserError> {
let mut set_operators = 0usize;
for token in tokens {
if let Token::Word(word) = token
&& matches!(word.keyword, Keyword::UNION | Keyword::EXCEPT | Keyword::INTERSECT | Keyword::MINUS)
{
set_operators += 1;
if set_operators > MAX_SELECT_SET_OPERATORS {
return Err(ParserError::RecursionLimitExceeded);
}
}
}
Ok(())
}
pub trait Parser {
fn parse(&self, sql: &str) -> QueryResult<VecDeque<ExtStatement>>;
}
+36 -14
View File
@@ -441,12 +441,20 @@ impl SessionCtxFactory {
};
let rt = RuntimeEnvBuilder::new().with_memory_limit(memory_limit_bytes, 1.0).build()?;
let config = SessionConfig::new().with_target_partitions(self.target_partitions);
// Arrow CSV reserves two usize offsets for every cell outside the
// DataFusion memory pool. Bound that reservation to at most 4 MiB and
// one sixteenth of the configured query budget, including narrow input.
let config = if context.input.request.input_serialization.csv.is_some() {
// Bound decoder batch rows for CSV and JSON Lines to match the configured
// query budget, and disable batch coalescing across S3 Select formats so
// downstream operators cannot re-buffer unbounded batches outside the pool.
let config = if context.input.request.input_serialization.csv.is_some()
|| (context.input.request.input_serialization.json.is_some() && !is_json_document_input(&context.input))
{
let batch_rows = (memory_limit_bytes / 16 / (MAX_SELECT_COLUMNS * 2 * size_of::<usize>())).clamp(1, 256);
config.with_batch_size(batch_rows)
let mut config = config.with_batch_size(batch_rows);
config.options_mut().execution.coalesce_batches = false;
config
} else if is_json_document_input(&context.input) {
let mut config = config;
config.options_mut().execution.coalesce_batches = false;
config
} else {
config
};
@@ -1035,12 +1043,26 @@ mod tests {
#[tokio::test]
async fn decoder_batch_budgets_keep_parquet_downstream_execution_single_row() {
let factory = SessionCtxFactory::new(true);
for (budget, expected) in [(64 * 1024 * 1024, 256), (8 * 1024 * 1024, 32), (1024, 1)] {
let session = factory
.create_session_ctx_inner(&test_context(), None, JsonSource::default(), None, None, budget)
.await
.expect("CSV session");
assert_eq!(session.inner().config().batch_size(), expected);
for json_lines in [false, true] {
let mut context = test_context();
if json_lines {
let input = Arc::make_mut(&mut context.input);
input.request.input_serialization.csv = None;
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
});
}
for (budget, expected) in [(64 * 1024 * 1024, 256), (8 * 1024 * 1024, 32), (1024, 1)] {
let session = factory
.create_session_ctx_inner(&context, None, JsonSource::default(), None, None, budget)
.await
.expect("delimited session");
assert_eq!(session.inner().config().batch_size(), expected, "json_lines={json_lines}");
assert!(
!session.inner().config().options().execution.coalesce_batches,
"coalesce_batches must be disabled for json_lines={json_lines}"
);
}
}
for parquet in [false, true] {
let mut context = test_context();
@@ -1050,16 +1072,16 @@ mod tests {
input.request.input_serialization.parquet = Some(ParquetInput::default());
} else {
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
r#type: Some(JsonType::DOCUMENT),
});
}
let session = factory.create_session_ctx(&context).await.expect("non-CSV session");
let session = factory.create_session_ctx(&context).await.expect("non-delimited session");
assert_eq!(
session.inner().config().batch_size(),
if parquet { 1 } else { SessionConfig::new().batch_size() }
);
assert!(!session.inner().config().options().execution.coalesce_batches);
if parquet {
assert!(!session.inner().config().options().execution.coalesce_batches);
assert_eq!(session.inner().config().target_partitions(), 1);
}
}
File diff suppressed because it is too large Load Diff
@@ -637,7 +637,7 @@ impl Stream for JsonDocumentBatchStream {
}
}
fn json_decoder_layout(schema: &SchemaRef, requested_batch_size: usize) -> DFResult<(usize, usize)> {
pub(super) fn json_decoder_layout(schema: &SchemaRef, requested_batch_size: usize) -> DFResult<(usize, usize)> {
let fields = schema.flattened_fields().len();
let field_slots = fields.checked_mul(2).ok_or_else(decoder_resource_error)?;
let offset_bytes_per_row = field_slots
+101 -27
View File
@@ -28,8 +28,8 @@ use datafusion::{
record_batch::RecordBatch,
},
datasource::{
file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat, json::JsonFormat},
listing::{ListingOptions, ListingTable, ListingTableConfig, ListingTableUrl},
file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat},
listing::ListingTableUrl,
},
error::{DataFusionError, Result as DFResult},
execution::{RecordBatchStream, SendableRecordBatchStream},
@@ -62,7 +62,12 @@ use tokio::{
};
use crate::{
dispatcher::{json_document_table::JsonDocumentTable, json_lines_schema, parquet_table::ParquetSelectTable},
dispatcher::{
delimited_table::{DelimitedFormat, DelimitedSelectTable},
json_document_table::JsonDocumentTable,
json_lines_schema,
parquet_table::ParquetSelectTable,
},
execution::factory::QueryExecutionFactoryRef,
instance::{DEFAULT_MAX_CONCURRENT_QUERIES, DEFAULT_QUERY_TIMEOUT_SECS},
metadata::{MetadataProvider, TableHandleProviderRef, base_table::BaseTableProvider},
@@ -75,7 +80,6 @@ use super::schema_inference::{PrefixBoundary, infer_csv_schema, read_schema_pref
static IGNORE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::IGNORE);
static NONE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::NONE);
static USE: LazyLock<FileHeaderInfo> = LazyLock::new(|| FileHeaderInfo::USE);
const EXACT_OBJECT_FILE_EXTENSION: &str = "";
#[derive(Clone)]
pub struct SimpleQueryDispatcher {
@@ -447,7 +451,7 @@ impl SimpleQueryDispatcher {
let path = format!("s3://{}/{}", self.input.bucket, self.input.key);
let table_path = ListingTableUrl::parse(path)?;
let mut csv_format = None;
let (listing_options, need_rename_volume_name, need_ignore_volume_name) =
let (format, need_rename_volume_name, need_ignore_volume_name) =
if let Some(csv) = self.input.request.input_serialization.csv.as_ref() {
let mut need_rename_volume_name = false;
let mut need_ignore_volume_name = false;
@@ -509,19 +513,11 @@ impl SimpleQueryDispatcher {
.with_comment(None)
.with_newlines_in_values(true);
}
csv_format = Some(CsvFormat::default().with_options(file_format.options().clone()));
(
ListingOptions::new(Arc::new(file_format)).with_file_extension(EXACT_OBJECT_FILE_EXTENSION),
need_rename_volume_name,
need_ignore_volume_name,
)
let options = file_format.options().clone();
csv_format = Some(CsvFormat::default().with_options(options.clone()));
(DelimitedFormat::Csv(Box::new(options)), need_rename_volume_name, need_ignore_volume_name)
} else if self.input.request.input_serialization.json.is_some() {
let file_format = JsonFormat::default();
(
ListingOptions::new(Arc::new(file_format)).with_file_extension(EXACT_OBJECT_FILE_EXTENSION),
false,
false,
)
(DelimitedFormat::JsonLines, false, false)
} else {
return Err(SelectError::InvalidDataSource.into());
};
@@ -559,7 +555,7 @@ impl SimpleQueryDispatcher {
Ok(schema)
})
.await?;
let config = if need_rename_volume_name {
let schema = if need_rename_volume_name {
let mut new_fields = Vec::new();
for (i, field) in resolve_schema.fields().iter().enumerate() {
let f_name = field.name();
@@ -574,17 +570,12 @@ impl SimpleQueryDispatcher {
new_fields.push(mut_field);
}
}
let new_schema = Arc::new(Schema::new(new_fields).with_metadata(resolve_schema.metadata().clone()));
ListingTableConfig::new(table_path)
.with_listing_options(listing_options)
.with_schema(new_schema)
Arc::new(Schema::new(new_fields).with_metadata(resolve_schema.metadata().clone()))
} else {
ListingTableConfig::new(table_path)
.with_listing_options(listing_options)
.with_schema(resolve_schema)
resolve_schema
};
// rename default
let provider = Arc::new(ListingTable::try_new(config)?);
let provider =
DelimitedSelectTable::try_new(session.inner(), table_path.object_store(), &self.input.key, schema, format).await?;
let current_session_table_provider = self.build_table_handle_provider()?;
let metadata_provider =
MetadataProvider::new(provider, current_session_table_provider, self.func_manager.clone(), session.clone());
@@ -2049,6 +2040,89 @@ mod tests {
assert_eq!(field_names(batches[0].schema().fields()), ["z", "a"]);
}
#[tokio::test]
async fn delimited_input_stays_within_tight_memory_budget_and_enforces_record_limit() {
const TIGHT_MEMORY_LIMIT_BYTES: usize = 8 * 1024 * 1024;
const RECORDS: usize = 64;
let line = "x".repeat(256 * 1024);
// 64 rows * 128 KiB = 8 MiB CSV payload processed with a WHERE filter under an 8 MiB pool.
let csv_records = format!("id,name\n{}", format!("1,{}\n", &line[..line.len() / 2]).repeat(RECORDS));
// 64 rows * 128 KiB = 8 MiB JSON Lines payload processed with a WHERE filter under an 8 MiB pool.
let json_records = format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", &line[..line.len() / 2]).repeat(RECORDS);
// Oversized single uncompressed records (> 1 MiB) must fail with OverMaxRecordSize.
let oversized_csv = format!("id,name\n1,{}\n", "x".repeat(1024 * 1024 + 1));
let oversized_json = format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", "x".repeat(1024 * 1024));
// Logical quoted CSV record spanning 64 * 256 KiB = 16 MiB must fail under the 8 MiB pool.
let oversized_quoted_csv = format!("id,name\n1,\"{}\"\n", [line.as_str(); RECORDS].join("\n"));
let cases = [
(csv_records, false, TIGHT_MEMORY_LIMIT_BYTES, Ok(RECORDS)),
(json_records, true, TIGHT_MEMORY_LIMIT_BYTES, Ok(RECORDS)),
(
oversized_csv,
false,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Err(SelectError::OverMaxRecordSize),
),
(
oversized_json,
true,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Err(SelectError::OverMaxRecordSize),
),
(oversized_quoted_csv, false, TIGHT_MEMORY_LIMIT_BYTES, Err(SelectError::ResourceExhausted)),
// Valid large JSON Lines object (120 * 70 KiB = ~8.4 MiB) must succeed under the default 64 MiB limit.
(
format!("{{\"id\":\"1\",\"name\":\"{}\"}}\n", "x".repeat(70_000)).repeat(120),
true,
DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES,
Ok(120),
),
];
let env = snapshot_test_env().await;
for (index, (data, json, memory_limit, expected)) in cases.into_iter().enumerate() {
let mut input = test_input();
input.bucket = format!("select-delimited-budget-{index}");
input.key = "records".to_owned();
if json {
input.request.input_serialization.csv = None;
input.request.input_serialization.json = Some(JsonInput {
r#type: Some(JsonType::LINES),
});
}
env.make_bucket(&input.bucket, false).await;
env.put_object_bytes(&input.bucket, &input.key, data.into_bytes()).await;
let snapshot = env.prepare_select_object_snapshot(&input.bucket, &input.key).await;
let input = Arc::new(input);
let optimizer = Arc::new(CascadeOptimizerBuilder::default().build());
let dispatcher = SimpleQueryDispatcherBuilder::default()
.with_input(Arc::clone(&input))
.with_default_table_provider(Arc::new(BaseTableProvider::default()))
.with_session_factory(Arc::new(SessionCtxFactory::new(false)))
.with_parser(Arc::new(DefaultParser::default()))
.with_query_execution_factory(Arc::new(SqlQueryExecutionFactory::new(optimizer, Arc::new(LocalScheduler {}))))
.with_func_manager(Arc::new(SimpleFunctionMetadataManager::default()))
.with_memory_limit_bytes(memory_limit)
.build()
.expect("query dispatcher should build");
// Keep every row through a FilterExec to confirm filtered batches stream without coalescing.
let sql = "SELECT s.id FROM S3Object s WHERE s.name <> ''".to_owned();
let query = Query::new_with_snapshot(QueryContext { input }, sql, snapshot);
let rows = match dispatcher.execute_query(&query).await {
Ok(output) => output
.into_record_batch_stream()
.expect("record stream")
.try_collect::<Vec<_>>()
.await
.map(|batches| batches.iter().map(RecordBatch::num_rows).sum::<usize>())
.map_err(|error| QueryError::from(error).select_error()),
Err(error) => Err(error.select_error()),
};
assert_eq!(rows, expected, "fixture={index}");
}
}
#[tokio::test(flavor = "current_thread")]
async fn blocking_select_planning_keeps_runtime_responsive_and_admission_after_cancel() {
for phase in ["SQL parse", "schema inference", "SQL plan"] {
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
mod delimited_table;
mod json_document_schema;
mod json_document_table;
mod json_lines_schema;
@@ -21,7 +21,7 @@ use datafusion::{
},
datasource::file_format::{DEFAULT_SCHEMA_INFER_MAX_RECORD, csv::CsvFormat},
error::{DataFusionError, Result},
execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation},
execution::memory_pool::{MemoryConsumer, MemoryLimit, MemoryPool, MemoryReservation},
object_store::Error as ObjectStoreError,
};
use futures::{StreamExt, stream::BoxStream};
@@ -65,7 +65,7 @@ impl PrefixBoundary {
}
}
fn consume(&mut self, input: &[u8], prefix: &[u8]) -> Result<(usize, bool)> {
fn consume(&mut self, input: &[u8], prefix: &[u8], json_sample_limit: usize) -> Result<(usize, bool)> {
match self {
Self::JsonLines { records, line_start } => {
for (index, byte) in input.iter().enumerate() {
@@ -83,7 +83,7 @@ impl PrefixBoundary {
if nonblank {
*records += 1;
}
if *records == DEFAULT_SCHEMA_INFER_MAX_RECORD {
if *records == DEFAULT_SCHEMA_INFER_MAX_RECORD || (*records > 0 && end >= json_sample_limit) {
return Ok((index + 1, true));
}
}
@@ -129,17 +129,31 @@ pub(super) async fn read_schema_prefix(
mut boundary: PrefixBoundary,
) -> Result<SchemaPrefix> {
let reservation = MemoryConsumer::new("S3 Select schema prefix").register(memory_pool);
// Keep multi-record JSON Lines inference samples within the query memory budget
// (accounting for downstream schema-inference working memory) while still allowing
// a single record to probe up to MAX_SCHEMA_PREFIX_BYTES.
let json_sample_limit = match memory_pool.memory_limit() {
MemoryLimit::Finite(limit) => MAX_SCHEMA_PREFIX_BYTES.min((limit / 32).max(1)),
MemoryLimit::Infinite | MemoryLimit::Unknown => MAX_SCHEMA_PREFIX_BYTES,
};
let mut bytes = Vec::new();
let mut parsed = 0;
while let Some(chunk) = stream.next().await.transpose()? {
let mut offset = 0;
while offset < chunk.len() {
let remaining = MAX_SCHEMA_PREFIX_BYTES - bytes.len();
let step_limit = match &boundary {
PrefixBoundary::JsonLines { records, .. } if *records > 0 => json_sample_limit,
PrefixBoundary::JsonLines { .. } if bytes.len() < json_sample_limit => json_sample_limit,
_ => MAX_SCHEMA_PREFIX_BYTES,
};
let remaining = step_limit.saturating_sub(bytes.len());
if remaining == 0 {
if let PrefixBoundary::JsonLines { records, line_start } = &boundary
&& *records > 0
{
bytes.truncate(*line_start);
bytes.shrink_to_fit();
reservation.try_resize(bytes.capacity())?;
return Ok(SchemaPrefix { bytes, reservation });
}
return Err(prefix_limit_error());
@@ -162,19 +176,21 @@ pub(super) async fn read_schema_prefix(
offset = end;
continue;
}
let (consumed, done) = boundary.consume(&bytes[parsed..], &bytes)?;
let (consumed, done) = boundary.consume(&bytes[parsed..], &bytes, json_sample_limit)?;
parsed += consumed;
bytes.truncate(parsed);
offset = end;
if done {
bytes.shrink_to_fit();
reservation.try_resize(bytes.capacity())?;
return Ok(SchemaPrefix { bytes, reservation });
}
}
}
if parsed < bytes.len() {
boundary.consume(&bytes[parsed..], &bytes)?;
boundary.consume(&bytes[parsed..], &bytes, json_sample_limit)?;
}
boundary.consume(&[], &bytes)?;
boundary.consume(&[], &bytes, json_sample_limit)?;
Ok(SchemaPrefix { bytes, reservation })
}
@@ -13,3 +13,4 @@
// limitations under the License.
pub mod simple_func_manager;
pub mod size_bound;
@@ -19,10 +19,110 @@ use datafusion::execution::SessionStateDefaults;
use datafusion::logical_expr::{AggregateUDF, ScalarUDF, WindowUDF};
use rustfs_s3select_api::query::function::FunctionMetadataManager;
use rustfs_s3select_api::{QueryError, QueryResult};
use tracing::debug;
use crate::function::size_bound::bound_result_size;
pub type SimpleFunctionMetadataManagerRef = Arc<SimpleFunctionMetadataManager>;
/// Explicit allowlist of canonical DataFusion scalar function names exposed to S3 Select SQL.
///
/// S3 Select must not expose the entire DataFusion catalog (such as `arrow_cast`,
/// `repeat`, `lpad`, `rpad`, `replace`, `levenshtein`, `version`, `uuid`, regex,
/// encoding, crypto, or nested-array builders). Aliases declared by an allowlisted
/// UDF (such as `length` / `char_length` for `character_length`, `substring` for
/// `substr`, `trim` for `btrim`, and `pow` for `power`) are registered alongside it.
const ALLOWED_SCALAR_FUNCTIONS: &[&str] = &[
// Conditional
"coalesce",
"greatest",
"least",
"nullif",
"nvl",
"nvl2",
// String
"ascii",
"bit_length",
"btrim",
"character_length",
"chr",
"concat",
"concat_ws",
"contains",
"ends_with",
"initcap",
"left",
"lower",
"ltrim",
"octet_length",
"reverse",
"right",
"rtrim",
"split_part",
"starts_with",
"strpos",
"substr",
"substr_index",
"upper",
// Math
"abs",
"acos",
"acosh",
"asin",
"asinh",
"atan",
"atan2",
"atanh",
"cbrt",
"ceil",
"cos",
"cosh",
"cot",
"degrees",
"exp",
"floor",
"isnan",
"iszero",
"ln",
"log",
"log10",
"log2",
"nanvl",
"pi",
"power",
"radians",
"round",
"signum",
"sin",
"sinh",
"sqrt",
"tan",
"tanh",
"trunc",
// Date / Time
"current_date",
"current_time",
"date_bin",
"date_part",
"date_trunc",
"from_unixtime",
"make_date",
"make_time",
"now",
"to_char",
"to_date",
"to_local_time",
"to_time",
"to_timestamp",
"to_timestamp_micros",
"to_timestamp_millis",
"to_timestamp_nanos",
"to_timestamp_seconds",
"to_unixtime",
];
/// Explicit allowlist of canonical DataFusion aggregate function names exposed to S3 Select SQL.
const ALLOWED_AGGREGATE_FUNCTIONS: &[&str] = &["avg", "count", "max", "min", "sum"];
#[derive(Debug)]
pub struct SimpleFunctionMetadataManager {
/// Scalar functions that are registered with the context
@@ -40,28 +140,19 @@ impl Default for SimpleFunctionMetadataManager {
aggregate_functions: Default::default(),
window_functions: Default::default(),
};
SessionStateDefaults::default_scalar_functions().into_iter().for_each(|udf| {
let existing_udf = func_meta_manager.register_udf(udf.clone());
if let Ok(()) = existing_udf {
debug!("Overwrote an existing UDF: {}", udf.name());
for udf in SessionStateDefaults::default_scalar_functions() {
if ALLOWED_SCALAR_FUNCTIONS.contains(&udf.name()) {
let _ = func_meta_manager.register_udf(udf);
}
});
}
SessionStateDefaults::default_aggregate_functions()
.into_iter()
.for_each(|udaf| {
let existing_udaf = func_meta_manager.register_udaf(udaf.clone());
if let Ok(()) = existing_udaf {
debug!("Overwrote an existing UDAF: {}", udaf.name());
}
});
SessionStateDefaults::default_window_functions().into_iter().for_each(|udwf| {
let existing_udwf = func_meta_manager.register_udwf(udwf.clone());
if let Ok(()) = existing_udwf {
debug!("Overwrote an existing UDWF: {}", udwf.name());
for udaf in SessionStateDefaults::default_aggregate_functions() {
if ALLOWED_AGGREGATE_FUNCTIONS.contains(&udaf.name()) {
let _ = func_meta_manager.register_udaf(udaf);
}
});
}
// S3 Select does not support window functions, so no default window UDFs are registered.
func_meta_manager
}
@@ -69,7 +160,11 @@ impl Default for SimpleFunctionMetadataManager {
impl FunctionMetadataManager for SimpleFunctionMetadataManager {
fn register_udf(&mut self, f: Arc<ScalarUDF>) -> QueryResult<()> {
self.scalar_functions.insert(f.inner().name().to_uppercase(), f);
let f = bound_result_size(f);
self.scalar_functions.insert(f.inner().name().to_uppercase(), Arc::clone(&f));
for alias in f.aliases() {
self.scalar_functions.insert(alias.to_uppercase(), Arc::clone(&f));
}
Ok(())
}
@@ -117,3 +212,86 @@ impl FunctionMetadataManager for SimpleFunctionMetadataManager {
self.window_functions.keys().cloned().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allowlist_entries_all_resolve_in_default_manager() {
let manager = SimpleFunctionMetadataManager::default();
for name in ALLOWED_SCALAR_FUNCTIONS {
assert!(manager.udf(name).is_ok(), "allowlisted scalar function '{name}' must be registered");
}
for alias in [
"length",
"char_length",
"substring",
"trim",
"pow",
"ifnull",
"position",
"instr",
] {
assert!(manager.udf(alias).is_ok(), "allowlisted alias '{alias}' must be registered");
}
for name in ALLOWED_AGGREGATE_FUNCTIONS {
assert!(manager.udaf(name).is_ok(), "allowlisted aggregate function '{name}' must be registered");
}
assert!(manager.udwfs().is_empty(), "S3 Select must not register default window functions");
}
#[test]
fn disallowed_datafusion_functions_are_not_registered() {
let manager = SimpleFunctionMetadataManager::default();
for disallowed in [
"arrow_cast",
"arrow_try_cast",
"arrow_typeof",
"arrow_field",
"arrow_metadata",
"cast_to_type",
"try_cast_to_type",
"repeat",
"lpad",
"rpad",
"replace",
"levenshtein",
"version",
"uuid",
"input_file_name",
"file_row_index",
"encode",
"decode",
"regexp_like",
"regexp_match",
"regexp_replace",
"regexp_count",
"regexp_instr",
"random",
"rand",
"factorial",
] {
assert!(
manager.udf(disallowed).is_err(),
"non-S3-Select scalar function '{disallowed}' must not be registered"
);
}
for disallowed in [
"array_agg",
"string_agg",
"median",
"percentile_cont",
"first_value",
"last_value",
] {
assert!(
manager.udaf(disallowed).is_err(),
"non-S3-Select aggregate function '{disallowed}' must not be registered"
);
}
for disallowed in ["row_number", "rank", "dense_rank", "lag", "lead"] {
assert!(manager.udwf(disallowed).is_err(), "window function '{disallowed}' must not be registered");
}
}
}
@@ -0,0 +1,478 @@
// 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.
//! Result-size guard for scalar functions whose output can expand beyond a single
//! input column (`concat`, `concat_ws`, `to_char`, and count-sized functions such
//! as `repeat`, `lpad`, and `rpad` if registered).
//!
//! Scalar results are built outside the DataFusion memory pool, so any unbounded
//! allocation can exhaust memory or abort the process via `handle_alloc_error`.
//! This wrapper checks a saturating upper bound on the bytes a call would produce
//! before invoking the inner UDF.
use std::sync::Arc;
use datafusion::arrow::array::{Array, AsArray};
use datafusion::arrow::datatypes::{DataType, FieldRef, Int32Type, Int64Type, UInt32Type, UInt64Type};
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TransformedResult as _, TreeNode as _};
use datafusion::common::{Result as DFResult, ScalarValue, exec_err};
use datafusion::logical_expr::interval_arithmetic::Interval;
use datafusion::logical_expr::preimage::PreimageResult;
use datafusion::logical_expr::simplify::{ExprSimplifyResult, SimplifyContext};
use datafusion::logical_expr::sort_properties::{ExprProperties, SortProperties};
use datafusion::logical_expr::udf_eq::UdfEq;
use datafusion::logical_expr::{
ColumnarValue, Documentation, Expr, ExpressionPlacement, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,
Signature, StructFieldMapping,
};
use rustfs_s3select_api::query::session::DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES;
/// Largest result, in bytes, a guarded scalar function may build for a single batch.
pub(crate) const MAX_SCALAR_RESULT_BYTES: usize = DEFAULT_S3SELECT_MEMORY_LIMIT_BYTES / 4;
/// Conservative expansion factor for chrono `strftime` specifiers (for example `%c`, `%B`).
const TO_CHAR_FORMAT_EXPANSION_FACTOR: usize = 20;
const TO_CHAR_PER_ROW_OVERHEAD_BYTES: usize = 64;
const UNKNOWN_SCALAR_ESTIMATE_BYTES: usize = 64;
/// How a guarded function sizes its result from its arguments.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ResultSize {
/// `repeat(string, count)`: each row builds `len(string) * count` bytes.
Repeat,
/// `lpad(string, length[, fill])` / `rpad`: each row builds `length` characters,
/// which DataFusion allocates at up to four bytes per character.
Pad,
/// `concat(arg1, ..., argN)`: each row concatenates all non-null arguments.
Concat,
/// `concat_ws(sep, arg1, ..., argN)`: each row concatenates `arg1..` with `sep`.
ConcatWs,
/// `to_char(datetime, format)`: expands strftime specifiers in `format`.
ToChar,
}
impl ResultSize {
fn for_function(name: &str) -> Option<Self> {
match name {
"repeat" => Some(Self::Repeat),
"lpad" | "rpad" => Some(Self::Pad),
"concat" => Some(Self::Concat),
"concat_ws" => Some(Self::ConcatWs),
"to_char" => Some(Self::ToChar),
_ => None,
}
}
/// Upper bound of the bytes the function builds for this batch. Arguments the
/// function would reject anyway contribute nothing so the inner function reports
/// the original type/argument error.
fn bytes(self, args: &[ColumnarValue], number_rows: usize) -> usize {
// All-scalar arguments are evaluated once, not once per row.
let rows = if args.iter().all(|arg| matches!(arg, ColumnarValue::Scalar(_))) {
1
} else {
number_rows
};
match (self, args) {
(Self::Repeat, [string, count]) => string_lengths(string, rows)
.zip(counts(count, rows))
.fold(0usize, |total, (len, count)| total.saturating_add(len.saturating_mul(count))),
(Self::Pad, [_, length, ..]) => {
counts(length, rows).fold(0usize, |total, length| total.saturating_add(length.saturating_mul(4)))
}
(Self::Concat, args) => args
.iter()
.fold(0usize, |total, arg| total.saturating_add(columnar_total_bytes(arg, rows))),
(Self::ConcatWs, [separator, rest @ ..]) => {
let values_bytes = rest
.iter()
.fold(0usize, |total, arg| total.saturating_add(columnar_total_bytes(arg, rows)));
let sep_bytes = columnar_total_bytes(separator, rows).saturating_mul(rest.len().saturating_sub(1));
values_bytes.saturating_add(sep_bytes)
}
(Self::ToChar, [_, format]) => columnar_total_bytes(format, rows)
.saturating_mul(TO_CHAR_FORMAT_EXPANSION_FACTOR)
.saturating_add(rows.saturating_mul(TO_CHAR_PER_ROW_OVERHEAD_BYTES)),
_ => 0,
}
}
fn check_literal_simplify_args(self, name: &str, args: &[Expr]) -> DFResult<()> {
let total = match self {
Self::Concat => args
.iter()
.fold(0usize, |acc, expr| acc.saturating_add(literal_expr_bytes(expr))),
Self::ConcatWs => match args {
[separator, rest @ ..] => {
let values_bytes = rest
.iter()
.fold(0usize, |acc, expr| acc.saturating_add(literal_expr_bytes(expr)));
let sep_bytes = literal_expr_bytes(separator).saturating_mul(rest.len().saturating_sub(1));
values_bytes.saturating_add(sep_bytes)
}
[] => 0,
},
Self::Repeat | Self::Pad | Self::ToChar => 0,
};
if total > MAX_SCALAR_RESULT_BYTES {
return exec_err!("string size overflow on {name}, max size is {MAX_SCALAR_RESULT_BYTES}, but got {total}");
}
Ok(())
}
}
fn literal_expr_bytes(expr: &Expr) -> usize {
let Expr::Literal(scalar, _) = expr else {
return 0;
};
scalar_byte_len(scalar)
}
fn scalar_byte_len(scalar: &ScalarValue) -> usize {
match scalar {
ScalarValue::Utf8(Some(s)) | ScalarValue::LargeUtf8(Some(s)) | ScalarValue::Utf8View(Some(s)) => s.len(),
ScalarValue::Binary(Some(b))
| ScalarValue::LargeBinary(Some(b))
| ScalarValue::BinaryView(Some(b))
| ScalarValue::FixedSizeBinary(_, Some(b)) => b.len(),
ScalarValue::Null
| ScalarValue::Utf8(None)
| ScalarValue::LargeUtf8(None)
| ScalarValue::Utf8View(None)
| ScalarValue::Binary(None)
| ScalarValue::LargeBinary(None)
| ScalarValue::BinaryView(None)
| ScalarValue::FixedSizeBinary(_, None) => 0,
_ => UNKNOWN_SCALAR_ESTIMATE_BYTES,
}
}
fn columnar_total_bytes(value: &ColumnarValue, rows: usize) -> usize {
match value {
ColumnarValue::Scalar(scalar) => scalar_byte_len(scalar).saturating_mul(rows),
ColumnarValue::Array(array) => match array.data_type() {
DataType::Utf8 => array
.as_string::<i32>()
.iter()
.fold(0usize, |acc, s| acc.saturating_add(s.map_or(0, str::len))),
DataType::LargeUtf8 => array
.as_string::<i64>()
.iter()
.fold(0usize, |acc, s| acc.saturating_add(s.map_or(0, str::len))),
DataType::Utf8View => array
.as_string_view()
.iter()
.fold(0usize, |acc, s| acc.saturating_add(s.map_or(0, str::len))),
DataType::Binary => array
.as_binary::<i32>()
.iter()
.fold(0usize, |acc, b| acc.saturating_add(b.map_or(0, <[u8]>::len))),
DataType::LargeBinary => array
.as_binary::<i64>()
.iter()
.fold(0usize, |acc, b| acc.saturating_add(b.map_or(0, <[u8]>::len))),
DataType::BinaryView => array
.as_binary_view()
.iter()
.fold(0usize, |acc, b| acc.saturating_add(b.map_or(0, <[u8]>::len))),
DataType::FixedSizeBinary(width) => usize::try_from(*width)
.unwrap_or(0)
.saturating_mul(array.len().saturating_sub(array.null_count())),
DataType::Null => 0,
_ => UNKNOWN_SCALAR_ESTIMATE_BYTES.saturating_mul(array.len().saturating_sub(array.null_count())),
},
}
}
fn string_lengths<'a>(value: &'a ColumnarValue, rows: usize) -> Box<dyn Iterator<Item = usize> + 'a> {
match value {
ColumnarValue::Scalar(scalar) => {
let len = match scalar {
ScalarValue::Utf8(Some(s)) | ScalarValue::LargeUtf8(Some(s)) | ScalarValue::Utf8View(Some(s)) => s.len(),
_ => 0,
};
Box::new(std::iter::repeat_n(len, rows))
}
ColumnarValue::Array(array) => match array.data_type() {
DataType::Utf8 => Box::new(array.as_string::<i32>().iter().map(|s| s.map_or(0, str::len))),
DataType::LargeUtf8 => Box::new(array.as_string::<i64>().iter().map(|s| s.map_or(0, str::len))),
DataType::Utf8View => Box::new(array.as_string_view().iter().map(|s| s.map_or(0, str::len))),
_ => Box::new(std::iter::repeat_n(0, rows)),
},
}
}
fn counts<'a>(value: &'a ColumnarValue, rows: usize) -> Box<dyn Iterator<Item = usize> + 'a> {
let i64_to_count = |count: Option<i64>| count.and_then(|count| usize::try_from(count).ok()).unwrap_or(0);
let i32_to_count = |count: Option<i32>| count.and_then(|count| usize::try_from(count).ok()).unwrap_or(0);
let u64_to_count = |count: Option<u64>| count.map_or(0, |count| usize::try_from(count).unwrap_or(usize::MAX));
let u32_to_count = |count: Option<u32>| count.map_or(0, |count| usize::try_from(count).unwrap_or(usize::MAX));
match value {
ColumnarValue::Scalar(ScalarValue::Int64(count)) => Box::new(std::iter::repeat_n(i64_to_count(*count), rows)),
ColumnarValue::Scalar(ScalarValue::Int32(count)) => Box::new(std::iter::repeat_n(i32_to_count(*count), rows)),
ColumnarValue::Scalar(ScalarValue::UInt64(count)) => Box::new(std::iter::repeat_n(u64_to_count(*count), rows)),
ColumnarValue::Scalar(ScalarValue::UInt32(count)) => Box::new(std::iter::repeat_n(u32_to_count(*count), rows)),
ColumnarValue::Array(array) => match array.data_type() {
DataType::Int64 => Box::new(array.as_primitive::<Int64Type>().iter().map(i64_to_count)),
DataType::Int32 => Box::new(array.as_primitive::<Int32Type>().iter().map(i32_to_count)),
DataType::UInt64 => Box::new(array.as_primitive::<UInt64Type>().iter().map(u64_to_count)),
DataType::UInt32 => Box::new(array.as_primitive::<UInt32Type>().iter().map(u32_to_count)),
_ => Box::new(std::iter::repeat_n(0, rows)),
},
_ => Box::new(std::iter::repeat_n(0, rows)),
}
}
/// Wraps `udf` so that an oversized result fails the call instead of being allocated.
/// Functions whose result is bounded by their input are returned unchanged.
pub(crate) fn bound_result_size(udf: Arc<ScalarUDF>) -> Arc<ScalarUDF> {
if (udf.inner().as_ref() as &dyn std::any::Any).is::<ResultSizeBoundedUdf>() {
return udf;
}
match ResultSize::for_function(udf.name()) {
Some(result_size) => Arc::new(ScalarUDF::new_from_impl(ResultSizeBoundedUdf {
inner: Arc::clone(udf.inner()).into(),
result_size,
})),
None => udf,
}
}
/// A [`ScalarUDF`] whose `invoke_with_args` checks the size of the result the inner
/// function would build; all other behavior delegates to the inner function.
#[derive(Debug, PartialEq, Eq, Hash)]
struct ResultSizeBoundedUdf {
inner: UdfEq<Arc<dyn ScalarUDFImpl>>,
result_size: ResultSize,
}
impl ScalarUDFImpl for ResultSizeBoundedUdf {
fn name(&self) -> &str {
self.inner.name()
}
fn schema_name(&self, args: &[Expr]) -> DFResult<String> {
self.inner.schema_name(args)
}
fn signature(&self) -> &Signature {
self.inner.signature()
}
fn return_type(&self, arg_types: &[DataType]) -> DFResult<DataType> {
self.inner.return_type(arg_types)
}
fn return_field_from_args(&self, args: ReturnFieldArgs) -> DFResult<FieldRef> {
self.inner.return_field_from_args(args)
}
fn is_strict(&self) -> bool {
self.inner.is_strict()
}
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DFResult<ColumnarValue> {
let bytes = self.result_size.bytes(&args.args, args.number_rows);
if bytes > MAX_SCALAR_RESULT_BYTES {
return exec_err!(
"string size overflow on {}, max size is {}, but got {}",
self.name(),
MAX_SCALAR_RESULT_BYTES,
bytes
);
}
self.inner.invoke_with_args(args)
}
fn with_updated_config(&self, config: &ConfigOptions) -> Option<ScalarUDF> {
self.inner.with_updated_config(config).map(|udf| {
ScalarUDF::new_from_impl(Self {
inner: Arc::clone(udf.inner()).into(),
result_size: self.result_size,
})
})
}
fn aliases(&self) -> &[String] {
self.inner.aliases()
}
fn simplify(&self, args: Vec<Expr>, info: &SimplifyContext) -> DFResult<ExprSimplifyResult> {
self.result_size.check_literal_simplify_args(self.name(), &args)?;
let simplified = self.inner.simplify(args, info)?;
match simplified {
ExprSimplifyResult::Original(args) => Ok(ExprSimplifyResult::Original(args)),
ExprSimplifyResult::Simplified(expr) => {
// Re-wrap any scalar UDF synthesized by simplification (for example
// `concat_ws('', ...)` rewriting into `concat(...)`) so the size bound
// cannot be bypassed.
let expr = expr
.transform_up(|node| match node {
Expr::ScalarFunction(mut func) => {
let bounded = bound_result_size(Arc::clone(&func.func));
if Arc::ptr_eq(&bounded, &func.func) {
Ok(Transformed::no(Expr::ScalarFunction(func)))
} else {
func.func = bounded;
Ok(Transformed::yes(Expr::ScalarFunction(func)))
}
}
other => Ok(Transformed::no(other)),
})
.data()?;
Ok(ExprSimplifyResult::Simplified(expr))
}
}
}
fn preimage(&self, args: &[Expr], lit_expr: &Expr, info: &SimplifyContext) -> DFResult<PreimageResult> {
self.inner.preimage(args, lit_expr, info)
}
fn conditional_arguments<'a>(&self, args: &'a [Expr]) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
self.inner.conditional_arguments(args)
}
fn short_circuits(&self) -> bool {
self.inner.short_circuits()
}
fn evaluate_bounds(&self, input: &[&Interval]) -> DFResult<Interval> {
self.inner.evaluate_bounds(input)
}
fn propagate_constraints(&self, interval: &Interval, inputs: &[&Interval]) -> DFResult<Option<Vec<Interval>>> {
self.inner.propagate_constraints(interval, inputs)
}
fn struct_field_mapping(&self, literal_args: &[Option<ScalarValue>]) -> Option<StructFieldMapping> {
self.inner.struct_field_mapping(literal_args)
}
fn output_ordering(&self, inputs: &[ExprProperties]) -> DFResult<SortProperties> {
self.inner.output_ordering(inputs)
}
fn preserves_lex_ordering(&self, inputs: &[ExprProperties]) -> DFResult<bool> {
self.inner.preserves_lex_ordering(inputs)
}
fn strictly_order_preserving(&self, inputs: &[ExprProperties]) -> DFResult<bool> {
self.inner.strictly_order_preserving(inputs)
}
fn coerce_types(&self, arg_types: &[DataType]) -> DFResult<Vec<DataType>> {
self.inner.coerce_types(arg_types)
}
fn documentation(&self) -> Option<&Documentation> {
self.inner.documentation()
}
fn placement(&self, args: &[ExpressionPlacement]) -> ExpressionPlacement {
self.inner.placement(args)
}
}
#[cfg(test)]
mod tests {
use super::*;
use datafusion::arrow::array::{Int64Array, StringArray};
use datafusion::execution::SessionStateDefaults;
fn scalar_args(string: ScalarValue, count: i64) -> Vec<ColumnarValue> {
vec![
ColumnarValue::Scalar(string),
ColumnarValue::Scalar(ScalarValue::Int64(Some(count))),
]
}
#[test]
fn repeat_bound_is_len_times_count_regardless_of_offset_width() {
for string in [
ScalarValue::Utf8(Some("ab".into())),
ScalarValue::LargeUtf8(Some("ab".into())),
ScalarValue::Utf8View(Some("ab".into())),
] {
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(string.clone(), 3), 8192), 6);
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(string, 1 << 62), 1), 1 << 63);
}
assert_eq!(
ResultSize::Repeat.bytes(&scalar_args(ScalarValue::Utf8(Some("abc".into())), i64::MAX), 1),
usize::MAX,
"oversized counts saturate instead of wrapping"
);
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(ScalarValue::Utf8(None), 1 << 62), 1), 0);
assert_eq!(ResultSize::Repeat.bytes(&scalar_args(ScalarValue::Utf8(Some("a".into())), -1), 1), 0);
}
#[test]
fn repeat_bound_sums_over_rows() {
let strings: ColumnarValue = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some("abc"), None, Some("d")])));
let counts = ColumnarValue::Array(Arc::new(Int64Array::from(vec![Some(2), Some(1 << 40), Some(5)])));
assert_eq!(ResultSize::Repeat.bytes(&[strings.clone(), counts], 3), 11);
let scalar_count = ColumnarValue::Scalar(ScalarValue::Int64(Some(10)));
assert_eq!(ResultSize::Repeat.bytes(&[strings, scalar_count], 3), 40);
}
#[test]
fn pad_bound_is_four_bytes_per_requested_character_per_row() {
let string = ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".into())));
let length = ColumnarValue::Scalar(ScalarValue::Int64(Some(10)));
let fill = ColumnarValue::Scalar(ScalarValue::Utf8(Some("*".into())));
assert_eq!(ResultSize::Pad.bytes(&[string.clone(), length.clone()], 8192), 40);
assert_eq!(ResultSize::Pad.bytes(&[string, length, fill], 8192), 40);
let strings = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some("a"), Some("b")])));
let length = ColumnarValue::Scalar(ScalarValue::Int64(Some(i64::from(i32::MAX))));
assert!(ResultSize::Pad.bytes(&[strings, length], 2) > MAX_SCALAR_RESULT_BYTES);
}
#[test]
fn concat_and_to_char_bounds_accumulate_across_rows() {
let chunk = "x".repeat(1024 * 1024);
let col_val = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some(chunk.as_str()); 4])));
let args = vec![col_val; 5];
assert_eq!(ResultSize::Concat.bytes(&args, 4), 20 * 1024 * 1024);
assert!(ResultSize::Concat.bytes(&args, 4) > MAX_SCALAR_RESULT_BYTES);
let sep = ColumnarValue::Scalar(ScalarValue::Utf8(Some(chunk)));
let short = ColumnarValue::Array(Arc::new(StringArray::from(vec![Some("a"); 4])));
let ws_args = vec![sep, short.clone(), short.clone(), short.clone(), short.clone(), short];
assert!(ResultSize::ConcatWs.bytes(&ws_args, 4) >= 16 * 1024 * 1024);
let fmt = ColumnarValue::Scalar(ScalarValue::Utf8(Some("%B".repeat(50_000))));
let dt = ColumnarValue::Array(Arc::new(Int64Array::from(vec![Some(0); 10])));
assert!(ResultSize::ToChar.bytes(&[dt, fmt], 10) > MAX_SCALAR_RESULT_BYTES);
}
#[test]
fn expected_expanding_functions_are_wrapped_and_idempotent() {
let mut wrapped = Vec::new();
for udf in SessionStateDefaults::default_scalar_functions() {
let name = udf.name().to_string();
let bounded = bound_result_size(Arc::clone(&udf));
if !Arc::ptr_eq(&udf, &bounded) {
assert_eq!(bounded.name(), name);
assert_eq!(bounded.aliases(), udf.aliases());
assert_eq!(bounded.signature(), udf.signature());
let double_bounded = bound_result_size(Arc::clone(&bounded));
assert!(Arc::ptr_eq(&bounded, &double_bounded), "wrapping must be idempotent");
wrapped.push(name);
}
}
wrapped.sort();
assert_eq!(wrapped, ["concat", "concat_ws", "lpad", "repeat", "rpad", "to_char"]);
}
}
+1 -4
View File
@@ -90,10 +90,7 @@ impl ContextProvider for MetadataProvider {
}
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>> {
self.func_manager
.udf(name)
.ok()
.or_else(|| self.session.inner().scalar_functions().get(name).cloned())
self.func_manager.udf(name).ok()
}
fn get_aggregate_meta(&self, name: &str) -> Option<Arc<AggregateUDF>> {
+1 -1
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub use rustfs_s3select_api::query::parser::RustFsDialect;
pub use rustfs_s3select_api::query::parser::{BoundedRustFsDialect, RustFsDialect};
#[cfg(test)]
use datafusion::sql::sqlparser::dialect::Dialect;
+66 -4
View File
@@ -22,10 +22,13 @@ use datafusion::sql::sqlparser::{
};
use rustfs_s3select_api::{
QueryError,
query::{ast::ExtStatement, parser::Parser as RustFsParser},
query::{
ast::ExtStatement,
parser::{Parser as RustFsParser, validate_set_operator_budget},
},
};
use super::dialect::RustFsDialect;
use super::dialect::BoundedRustFsDialect;
pub(crate) const MAX_SQL_EXPRESSION_BYTES: usize = 256 * 1024;
@@ -61,6 +64,7 @@ impl<'a> ExtParser<'a> {
return parser_err!("S3 Select expression exceeds 256 KiB");
}
let mut tokens = tokenizer.tokenize()?;
validate_set_operator_budget(&tokens)?;
validate_projection_width(&tokens)?;
rewrite_source_object_wildcards(&mut tokens);
Ok(ExtParser {
@@ -70,7 +74,7 @@ impl<'a> ExtParser<'a> {
/// Parse a SQL statement and produce a set of statements
pub fn parse_sql(sql: &str) -> Result<VecDeque<ExtStatement>> {
let dialect = &RustFsDialect {};
let dialect = &BoundedRustFsDialect::default();
ExtParser::parse_sql_with_dialect(sql, dialect)
}
@@ -186,7 +190,11 @@ fn ends_from_source(keyword: Keyword) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use rustfs_s3select_api::query::ast::ExtStatement;
use crate::sql::dialect::RustFsDialect;
use rustfs_s3select_api::query::{
ast::ExtStatement,
parser::{MAX_SELECT_OPERATORS, MAX_SELECT_SET_OPERATORS},
};
#[test]
fn test_default_parser_creation() {
@@ -336,6 +344,60 @@ mod tests {
assert_eq!(statements.len(), 1, "Should have exactly one statement");
}
#[test]
fn test_ext_parser_parse_sql_bounds_operator_and_set_chains() {
let plus_chain = |terms: usize| format!("SELECT {} FROM S3Object", vec!["1"; terms].join("+"));
assert!(
ExtParser::parse_sql(&plus_chain(MAX_SELECT_OPERATORS + 1)).is_ok(),
"chain with exactly MAX_SELECT_OPERATORS operators must succeed"
);
assert_eq!(
ExtParser::parse_sql(&plus_chain(MAX_SELECT_OPERATORS + 2)),
Err(ParserError::RecursionLimitExceeded)
);
let or_chain = |terms: usize| format!("SELECT * FROM S3Object s WHERE {}", vec!["s.id='1'"; terms].join(" OR "));
assert_eq!(
ExtParser::parse_sql(&or_chain(MAX_SELECT_OPERATORS + 1)),
Err(ParserError::RecursionLimitExceeded)
);
let is_null_chain = |ops: usize| format!("SELECT 1{} FROM S3Object", " IS NULL".repeat(ops));
assert!(ExtParser::parse_sql(&is_null_chain(MAX_SELECT_OPERATORS)).is_ok());
assert_eq!(
ExtParser::parse_sql(&is_null_chain(MAX_SELECT_OPERATORS + 1)),
Err(ParserError::RecursionLimitExceeded)
);
let union_chain = |unions: usize| vec!["SELECT 1"; unions + 1].join(" UNION ");
assert!(ExtParser::parse_sql(&union_chain(MAX_SELECT_SET_OPERATORS)).is_ok());
assert_eq!(
ExtParser::parse_sql(&union_chain(MAX_SELECT_SET_OPERATORS + 1)),
Err(ParserError::RecursionLimitExceeded)
);
// Long chains close to the 256 KiB expression limit, including trailing syntax
// errors that trigger `Drop` on a partially built AST, must fail cleanly without
// overflowing a release-profile 1 MiB worker stack.
for sql in [
plus_chain(120 * 1024),
format!("SELECT {}+) FROM S3Object", vec!["1"; 120 * 1024].join("+")),
or_chain(4096),
is_null_chain(4096),
union_chain(10_000),
] {
assert!(sql.len() <= MAX_SQL_EXPRESSION_BYTES, "test SQL must exercise parser, not byte cap");
let result = std::thread::Builder::new()
.stack_size(1024 * 1024)
.spawn(move || ExtParser::parse_sql(&sql).map(|_| ()))
.expect("spawn 1 MiB stack worker")
.join()
.expect("parser thread must not overflow stack");
assert_eq!(result, Err(ParserError::RecursionLimitExceeded));
}
}
#[test]
fn test_ext_parser_parse_sql_with_dialect() {
let sql = "SELECT * FROM S3Object";
@@ -15,12 +15,16 @@
use std::sync::Arc;
use async_trait::async_trait;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TransformedResult as _, TreeNode as _};
use datafusion::error::Result as DFResult;
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::LogicalPlan;
use datafusion::physical_optimizer::PhysicalOptimizerRule;
use datafusion::physical_optimizer::aggregate_statistics::AggregateStatistics;
use datafusion::physical_optimizer::join_selection::JoinSelection;
use datafusion::physical_plan::ExecutionPlan;
use datafusion::physical_plan::filter::FilterExec;
use datafusion::physical_planner::{
DefaultPhysicalPlanner as DFDefaultPhysicalPlanner, ExtensionPlanner, PhysicalPlanner as DFPhysicalPlanner,
};
@@ -55,6 +59,7 @@ impl Default for DefaultPhysicalPlanner {
// repartitioning and local sorting steps to meet distribution and ordering requirements.
// Therefore, it should run before EnforceDistribution and EnforceSorting.
Arc::new(JoinSelection::new()),
Arc::new(StreamFilterOutput),
];
Self {
@@ -91,6 +96,35 @@ impl PhysicalPlanner for DefaultPhysicalPlanner {
}
}
/// Prevents `FilterExec` from coalescing filtered rows across input batches.
///
/// DataFusion's `FilterExec` buffers surviving rows until it reaches `batch_size`
/// outside the query memory pool. S3 Select scans emit already byte-bounded batches,
/// so setting `batch_size = 1` streams every non-empty filtered batch immediately.
#[derive(Debug)]
struct StreamFilterOutput;
impl PhysicalOptimizerRule for StreamFilterOutput {
fn optimize(&self, plan: Arc<dyn ExecutionPlan>, _config: &ConfigOptions) -> DFResult<Arc<dyn ExecutionPlan>> {
plan.transform_up(|node| {
let Some(filter) = node.downcast_ref::<FilterExec>() else {
return Ok(Transformed::no(node));
};
let filter: Arc<dyn ExecutionPlan> = Arc::new(filter.with_batch_size(1)?);
Ok(Transformed::yes(filter))
})
.data()
}
fn name(&self) -> &str {
"StreamFilterOutput"
}
fn schema_check(&self) -> bool {
true
}
}
impl PhysicalOptimizer for DefaultPhysicalPlanner {
fn optimize(&self, plan: Arc<dyn ExecutionPlan>, _session: &SessionCtx) -> QueryResult<Arc<dyn ExecutionPlan>> {
Ok(plan)
@@ -100,3 +134,41 @@ impl PhysicalOptimizer for DefaultPhysicalPlanner {
self.ext_physical_optimizer_rules.push(optimizer_rule);
}
}
#[cfg(test)]
mod tests {
use super::*;
use datafusion::arrow::array::{Int64Array, RecordBatch};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::datasource::memory::MemorySourceConfig;
use datafusion::execution::TaskContext;
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{binary, col, lit};
use datafusion::physical_plan::collect;
#[tokio::test]
async fn filter_output_is_not_coalesced_across_input_batches() {
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)]));
let batches = [vec![1, 2, 3], vec![4, 5], vec![6], vec![7, 8, 9]]
.into_iter()
.map(|ids| RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(Int64Array::from(ids))]).expect("batch"))
.collect::<Vec<_>>();
let input = MemorySourceConfig::try_new_exec(&[batches], Arc::clone(&schema), None).expect("input");
let predicate = binary(col("id", &schema).expect("column"), Operator::NotEq, lit(6_i64), &schema).expect("predicate");
let filter: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(predicate, input).expect("filter"));
let rows = |batches: Vec<RecordBatch>| batches.iter().map(RecordBatch::num_rows).collect::<Vec<_>>();
let coalesced = collect(Arc::clone(&filter), Arc::new(TaskContext::default()))
.await
.expect("stock filter");
assert_eq!(rows(coalesced), [8]);
let filter = StreamFilterOutput
.optimize(filter, &ConfigOptions::default())
.expect("optimized filter");
let streamed = collect(filter, Arc::new(TaskContext::default()))
.await
.expect("streaming filter");
assert_eq!(rows(streamed), [3, 2, 3]);
}
}
+45
View File
@@ -171,6 +171,11 @@ pub(crate) fn prepare_s3_select_statement(statement: &mut Statement) -> QueryRes
return Err(unsupported_structure("subqueries are not supported"));
}
let mut field_depth = FieldAccessDepthValidator;
if Visit::visit(&*query, &mut field_depth).is_break() {
return Err(unsupported_structure("nested field access depth exceeds limit"));
}
let source = {
let SetExpr::Select(select) = query.body.as_mut() else {
return Err(unsupported_structure("set operations and nested queries are not supported"));
@@ -598,6 +603,27 @@ impl Visitor for SubqueryDetector {
}
}
struct FieldAccessDepthValidator;
impl Visitor for FieldAccessDepthValidator {
type Break = ();
fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<Self::Break> {
let max_depth = rustfs_s3select_api::query::parser::MAX_SELECT_FIELD_ACCESS_DEPTH;
let exceeds = match expr {
Expr::CompoundIdentifier(parts) => parts.len() > max_depth,
Expr::CompoundFieldAccess { access_chain, .. } => access_chain.len() > max_depth,
Expr::JsonAccess { path, .. } => path.path.len() > max_depth,
_ => false,
};
if exceeds {
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
}
}
#[cfg(test)]
mod tests {
use super::{path_projection_keys, prepare_s3_select_statement};
@@ -978,4 +1004,23 @@ mod tests {
);
}
}
#[test]
fn rejects_excessive_compound_field_access_depth() {
let max_depth = rustfs_s3select_api::query::parser::MAX_SELECT_FIELD_ACCESS_DEPTH;
let allowed_path = format!("s.items{}", "[0]".repeat(max_depth));
let allowed_statement = parse_statement(&format!("SELECT {allowed_path} FROM S3Object AS s"));
assert!(validate_s3_select_statement(&allowed_statement).is_ok());
let deep_path = format!("s.items{}", "[0]".repeat(max_depth + 1));
let deep_statement = parse_statement(&format!("SELECT {deep_path} FROM S3Object AS s"));
assert!(matches!(
validate_s3_select_statement(&deep_statement),
Err(ref err) if matches!(err.s3_select_policy_error(), Some(SelectError::UnsupportedSqlStructure { .. }))
));
// Dot chains are also bounded at parse time by sqlparser's recursion limit.
let deep_dots = vec!["a"; max_depth + 1].join(".");
assert!(ExtParser::parse_sql(&format!("SELECT {deep_dots} FROM S3Object")).is_err());
}
}
@@ -15,6 +15,7 @@
#[cfg(test)]
mod error_handling_tests {
use crate::get_global_db;
use datafusion::object_store::ObjectStoreExt as _;
use rustfs_s3select_api::request::{
CsvInput, ExpressionType, FileHeaderInfo, InputSerialization, SelectObjectContentInput, SelectObjectContentRequest,
};
@@ -174,6 +175,147 @@ mod error_handling_tests {
}
}
#[tokio::test]
async fn test_non_allowlisted_datafusion_functions_are_rejected() {
for sql in [
"SELECT length(repeat(arrow_cast('a', 'LargeUtf8'), 4611686018427387904)) FROM S3Object",
"SELECT length(repeat(arrow_cast(name, 'LargeUtf8'), 1000000000000000)) FROM S3Object",
"SELECT length(repeat('a', 1000000000)) FROM S3Object",
"SELECT length(lpad('a', 500000000)) FROM S3Object",
"SELECT length(rpad('a', 500000000)) FROM S3Object",
"SELECT levenshtein('abc', 'def') FROM S3Object",
"SELECT arrow_cast(name, 'LargeUtf8') FROM S3Object",
"SELECT version() FROM S3Object",
"SELECT uuid() FROM S3Object",
"SELECT replace(name, 'a', 'bb') FROM S3Object",
"SELECT regexp_replace(name, 'a', 'b') FROM S3Object",
"SELECT encode(name, 'hex') FROM S3Object",
"SELECT array_agg(name) FROM S3Object",
"SELECT string_agg(name, ',') FROM S3Object",
"SELECT row_number() OVER () FROM S3Object",
] {
let input = create_test_input_with_sql(sql);
let db = get_global_db(input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(Context { input: Arc::new(input) }, sql.to_string());
let error = match db.execute(&query).await {
Err(error) => error,
Ok(_) => panic!("disallowed function must be rejected during planning: {sql}"),
};
assert_eq!(
error.select_error(),
SelectError::InvalidQuery,
"disallowed function must fail with InvalidQuery for {sql}: {error:?}"
);
}
}
#[tokio::test]
async fn test_standard_s3_select_functions_continue_working() {
for sql in [
"SELECT LOWER(name), UPPER(name), LENGTH(name) AS len1, CHAR_LENGTH(name) AS len2, CHARACTER_LENGTH(name) AS len3 FROM S3Object LIMIT 2",
"SELECT LEFT(name, 2), RIGHT(name, 2), TRIM(name) AS trimmed, BTRIM(name), LTRIM(name), RTRIM(name), STRPOS(name, 'a'), STARTS_WITH(name, 'A'), ENDS_WITH(name, 'e'), CONTAINS(name, 'l') FROM S3Object LIMIT 2",
"SELECT COALESCE(name, 'n/a'), NULLIF(name, 'Alice'), CONCAT(name, '-', department), CONCAT_WS(':', name, department) FROM S3Object LIMIT 2",
"SELECT ABS(-5), ROUND(3.14159, 2), SQRT(16), CEIL(1.2), FLOOR(1.8), POWER(2, 3) AS p1, POW(2, 4) AS p2 FROM S3Object LIMIT 1",
"SELECT DATE_PART('year', TO_TIMESTAMP('2025-01-02T03:04:05Z')), CURRENT_DATE(), NOW() FROM S3Object LIMIT 1",
"SELECT COUNT(*), SUM(CAST(age AS INT)), AVG(CAST(age AS INT)), MIN(CAST(age AS INT)), MAX(CAST(age AS INT)) FROM S3Object",
] {
let input = create_test_input_with_sql(sql);
let db = get_global_db(input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(Context { input: Arc::new(input) }, sql.to_string());
let handle = db
.execute(&query)
.await
.unwrap_or_else(|error| panic!("standard S3 Select query must plan ({sql}): {error:?}"));
let batches = handle
.result()
.chunk_result()
.await
.unwrap_or_else(|error| panic!("standard S3 Select query must execute ({sql}): {error:?}"));
assert!(
batches.iter().map(|batch| batch.num_rows()).sum::<usize>() > 0,
"standard S3 Select query must return rows: {sql}"
);
}
}
#[tokio::test]
async fn test_retained_expanding_functions_respect_result_size_bound() {
// Test with a large format literal in `to_char` over the 10-row fixture (column-dependent
// timestamp prevents scalar-only folding): 10 rows * (100_000 * 20 + 64) > 16 MiB.
let huge_format = "%B".repeat(50_000);
let sql = format!("SELECT TO_CHAR(TO_TIMESTAMP(CAST(age AS BIGINT)), '{huge_format}') FROM S3Object");
let input = create_test_input_with_sql(&sql);
let db = get_global_db(input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(Context { input: Arc::new(input) }, sql);
let error = match db.execute(&query).await {
Err(error) => error,
Ok(handle) => match handle.result().chunk_result().await {
Err(error) => error,
Ok(_) => panic!("oversized to_char result must fail"),
},
};
assert_eq!(error.select_error(), SelectError::InternalError, "unexpected error: {error:?}");
// Verify `concat_ws('', ...)` simplification re-wraps `concat` and enforces the bound:
// a single 200 KiB CSV column repeated 100 times (~20 MiB > 16 MiB) fails cleanly
// even though `concat_ws('', ...)` simplifies to `concat(...)` and SQL is < 1 KiB.
let repeated_cols = std::iter::repeat_n("payload", 100).collect::<Vec<_>>().join(", ");
let concat_sql = format!("SELECT LENGTH(CONCAT_WS('', {repeated_cols})) FROM S3Object");
let mut concat_input = create_test_input_with_sql(&concat_sql);
concat_input.key = "concat_bound.csv".to_string();
let db = get_global_db(concat_input.clone(), true)
.await
.expect("test database should initialize");
let query = Query::new(
Context {
input: Arc::new(concat_input.clone()),
},
concat_sql,
);
let state_machine = db.build_query_state_machine(query).await.expect("build query state machine");
let store_url = datafusion::execution::object_store::ObjectStoreUrl::parse(format!("s3://{}", concat_input.bucket))
.expect("valid test store url");
let store = state_machine
.session
.inner()
.runtime_env()
.object_store(&store_url)
.expect("test object store");
let csv_payload = format!("payload\n{}\n", "x".repeat(200 * 1024));
store
.put(
&datafusion::object_store::path::Path::from(concat_input.key.as_str()),
csv_payload.into_bytes().into(),
)
.await
.expect("put oversized concat fixture");
let plan = db
.build_logical_plan(Arc::clone(&state_machine))
.await
.expect("plan concat_ws query")
.expect("logical plan");
let output = db
.execute_logical_plan(plan, state_machine)
.await
.expect("start concat_ws execution");
let error = output
.result()
.chunk_result()
.await
.expect_err("oversized concat_ws result must fail instead of allocating");
assert_eq!(error.select_error(), SelectError::InternalError, "unexpected error: {error:?}");
}
#[tokio::test]
async fn test_invalid_column_references() {
let invalid_column_sqls = vec![
@@ -14,6 +14,7 @@ const LEADER_EPOCH: u64 = 11;
const CHECKPOINT_OBJECTS: u64 = 1024;
const CHECKPOINT_MIN_INTERVAL: Duration = Duration::from_secs(5);
const PHASE_TIMEOUT: Duration = Duration::from_secs(60);
const FIRST_OBJECT: &str = "object-0000";
async fn checkpoint_plan(set: &Arc<SetDisks>, owner: &CancellationToken) -> ScannerBucketScanPlan {
let buckets = vec![bucket_info(BUCKET)];
@@ -55,17 +56,15 @@ async fn run_checkpoint_owner_case(lose_owner: bool) -> serde_json::Value {
.make_bucket(BUCKET, &MakeBucketOptions::default())
.await
.expect("create checkpoint owner bucket");
for object in 0..=CHECKPOINT_OBJECTS {
store
.put_object(
BUCKET,
&format!("object-{object:04}"),
&mut ScannerPutObjReader::from_vec(vec![1]),
&ScannerObjectOptions::default(),
)
.await
.expect("write real object for the periodic checkpoint threshold");
}
store
.put_object(
BUCKET,
FIRST_OBJECT,
&mut ScannerPutObjReader::from_vec(vec![1]),
&ScannerObjectOptions::default(),
)
.await
.expect("write a real object for the checkpoint fixture");
save_config(
store.clone(),
DATA_USAGE_BLOOM_NAME_PATH.as_str(),
@@ -74,10 +73,27 @@ async fn run_checkpoint_owner_case(lose_owner: bool) -> serde_json::Value {
.await
.expect("persist the real global cycle fence");
wait_for_namespace_commit_tails(store.as_ref()).await;
record_dirty_usage_bucket(BUCKET);
let dirty_before = dirty_usage_buckets_for_tests();
let set = store.pools[0].disk_set[0].clone();
let disk = scanner_set_disk_inventory(&set).await.pop().expect("checkpoint owner disk");
let first_object_dir = disk
.get_object_path_if_local(BUCKET, FIRST_OBJECT)
.expect("checkpoint owner disk is local")
.expect("first checkpoint fixture object path");
// This case exercises metadata traversal and checkpoint publication. Seed
// the other disk entries from real xl.meta without repeating the PUT path.
tokio::task::spawn_blocking(move || {
let metadata = std::fs::read(first_object_dir.join(STORAGE_FORMAT_FILE)).expect("read real fixture metadata");
let bucket_dir = first_object_dir.parent().expect("checkpoint fixture bucket directory");
for object in 1..=CHECKPOINT_OBJECTS {
let object_dir = bucket_dir.join(format!("object-{object:04}"));
std::fs::create_dir(&object_dir).expect("create checkpoint fixture object directory");
std::fs::write(object_dir.join(STORAGE_FORMAT_FILE), &metadata).expect("seed checkpoint fixture metadata");
}
})
.await
.expect("seed disk entries for the periodic checkpoint threshold");
record_dirty_usage_bucket(BUCKET);
let dirty_before = dirty_usage_buckets_for_tests();
let cache_name = path_join_buf(&[BUCKET, DATA_USAGE_CACHE_NAME]);
let revisions_before = DataUsageCache::read_revisions(set.clone(), &cache_name)
.await
@@ -93,7 +109,7 @@ async fn run_checkpoint_owner_case(lose_owner: bool) -> serde_json::Value {
let mut first_object = EcstoreLocalPublicationPause::install(
&disk,
BUCKET,
"object-0000/xl.meta",
&format!("{FIRST_OBJECT}/{STORAGE_FORMAT_FILE}"),
EcstoreLocalPublicationStage::MetadataReadAfterOpen,
)
.expect("pause the first real object read");
+37 -16
View File
@@ -141,37 +141,57 @@ pub fn decompress_block(compressed: &[u8], algorithm: CompressionAlgorithm) -> i
/// Returns [`io::ErrorKind::InvalidData`] if the decompressed output exceeds `max_len`,
/// or propagates any underlying codec initialization or decoding error.
pub fn decompress_block_with_limit(compressed: &[u8], algorithm: CompressionAlgorithm, max_len: usize) -> io::Result<Vec<u8>> {
let mut out = Vec::new();
decompress_block_into(compressed, algorithm, max_len, &mut out)?;
Ok(out)
}
/// Decodes a block into a reusable buffer. Replaces its contents and caps the output at `max_len`.
///
/// # Errors
///
/// Returns [`io::ErrorKind::InvalidData`] if the output exceeds the limit, or propagates
/// a codec error. The output is empty on error and retains its capacity for reuse.
pub fn decompress_block_into(
compressed: &[u8],
algorithm: CompressionAlgorithm,
max_len: usize,
out: &mut Vec<u8>,
) -> io::Result<()> {
out.clear();
let input = std::io::Cursor::new(compressed);
match algorithm {
CompressionAlgorithm::Gzip => read_to_end_with_limit(flate2::read::GzDecoder::new(input), max_len),
CompressionAlgorithm::Deflate => read_to_end_with_limit(flate2::read::DeflateDecoder::new(input), max_len),
let result = match algorithm {
CompressionAlgorithm::Gzip => read_to_end_with_limit(flate2::read::GzDecoder::new(input), max_len, out),
CompressionAlgorithm::Deflate => read_to_end_with_limit(flate2::read::DeflateDecoder::new(input), max_len, out),
CompressionAlgorithm::Zstd => {
let mut decoder = zstd::Decoder::new(input)?;
if max_len <= ZSTD_BOUNDED_BLOCK_LIMIT {
decoder.window_log_max(ZSTD_BLOCK_MAX_WINDOW_LOG)?;
}
read_to_end_with_limit(decoder, max_len)
read_to_end_with_limit(decoder, max_len, out)
}
CompressionAlgorithm::Lz4 => read_to_end_with_limit(lz4::Decoder::new(input)?, max_len),
CompressionAlgorithm::Brotli => read_to_end_with_limit(brotli::Decompressor::new(input, 4096), max_len),
CompressionAlgorithm::Snappy => read_to_end_with_limit(snap::read::FrameDecoder::new(input), max_len),
CompressionAlgorithm::None => Ok(Vec::new()),
CompressionAlgorithm::Lz4 => read_to_end_with_limit(lz4::Decoder::new(input)?, max_len, out),
CompressionAlgorithm::Brotli => read_to_end_with_limit(brotli::Decompressor::new(input, 4096), max_len, out),
CompressionAlgorithm::Snappy => read_to_end_with_limit(snap::read::FrameDecoder::new(input), max_len, out),
CompressionAlgorithm::None => Ok(()),
};
if result.is_err() {
out.clear();
}
result
}
fn read_to_end_with_limit(decoder: impl Read, max_len: usize) -> io::Result<Vec<u8>> {
let mut out = Vec::new();
// Read at most one byte past `max_len`: enough to distinguish an exact-length
// frame (and verify its trailer) from an over-limit expansion without unbounded allocation.
fn read_to_end_with_limit(decoder: impl Read, max_len: usize, out: &mut Vec<u8>) -> io::Result<()> {
// Probe past the limit to verify an exact-length frame's trailer and reject expansion.
let probe_len = u64::try_from(max_len).unwrap_or(u64::MAX).saturating_add(1);
decoder.take(probe_len).read_to_end(&mut out)?;
decoder.take(probe_len).read_to_end(out)?;
if out.len() > max_len {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"decompressed block exceeds its declared length",
));
}
Ok(out)
Ok(())
}
#[cfg(test)]
@@ -254,10 +274,11 @@ mod tests {
CompressionAlgorithm::Snappy,
] {
let compressed = compress_block(&data, algo);
let exact = decompress_block_with_limit(&compressed, algo, data.len()).expect("exact limit should succeed");
let mut exact = decompress_block_with_limit(&compressed, algo, data.len()).expect("exact limit should succeed");
assert_eq!(exact, data, "{algo}");
let err = decompress_block_with_limit(&compressed, algo, data.len() - 1).expect_err("limit must be enforced");
let err = decompress_block_into(&compressed, algo, data.len() - 1, &mut exact).expect_err("limit must be enforced");
assert!(exact.is_empty(), "an error must clear reused output");
assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{algo}");
assert_eq!(err.to_string(), "decompressed block exceeds its declared length", "{algo}");
+6 -14
View File
@@ -26,7 +26,7 @@ use tracing::{error, info};
use transform_stream::AsyncTryStream;
use url::{Host, Url};
static LOCAL_IPS: LazyLock<Vec<IpAddr>> = LazyLock::new(get_local_ips_with_fallback);
static LOCAL_IPS: LazyLock<HashSet<IpAddr>> = LazyLock::new(|| get_local_ips_with_fallback().into_iter().collect());
#[derive(Debug, Clone)]
struct DnsCacheEntry {
@@ -203,15 +203,10 @@ pub fn check_local_server_addr(server_addr: &str) -> std::io::Result<SocketAddr>
/// checks if the given parameter correspond to one of
/// the local IP of the current machine
pub fn is_local_host(host: Host<&str>, port: u16, local_port: u16) -> std::io::Result<bool> {
let local_set: HashSet<IpAddr> = LOCAL_IPS.iter().copied().collect();
let is_local_host = match host {
Host::Domain(domain) => {
let ips = resolve_domain(domain)?.into_iter().collect::<Vec<_>>();
ips.iter().any(|ip| is_local_ip(&local_set, ip))
}
Host::Ipv4(ip) => is_local_ip(&local_set, &IpAddr::V4(ip)),
Host::Ipv6(ip) => is_local_ip(&local_set, &IpAddr::V6(ip)),
Host::Domain(domain) => resolve_domain(domain)?.iter().any(is_local_ip),
Host::Ipv4(ip) => is_local_ip(&IpAddr::V4(ip)),
Host::Ipv6(ip) => is_local_ip(&IpAddr::V6(ip)),
};
if port > 0 {
@@ -224,11 +219,8 @@ pub fn is_local_host(host: Host<&str>, port: u16, local_port: u16) -> std::io::R
/// Whether `ip` belongs to this host: it is either configured on a local
/// interface or, where the platform routes the full loopback space, a loopback
/// address.
fn is_local_ip(local_set: &HashSet<IpAddr>, ip: &IpAddr) -> bool {
if local_set.contains(ip) {
return true;
}
is_loopback_local(ip)
pub fn is_local_ip(ip: &IpAddr) -> bool {
LOCAL_IPS.contains(ip) || is_loopback_local(ip)
}
#[cfg(not(windows))]
+205 -17
View File
@@ -172,33 +172,116 @@ pub fn has_string_suffix_in_slice(str: &str, list: &[impl AsRef<str>]) -> bool {
false
}
fn deep_match_rune(str_: &[u8], pattern: &[u8], simple: bool) -> bool {
let (mut str_, mut pattern) = (str_, pattern);
while !pattern.is_empty() {
match pattern[0] as char {
'*' => {
return if pattern.len() == 1 {
true
} else {
deep_match_rune(str_, &pattern[1..], simple)
|| (!str_.is_empty() && deep_match_rune(&str_[1..], pattern, simple))
};
}
'?' => {
fn deep_match_rune(mut str_: &[u8], mut pattern: &[u8], simple: bool) -> bool {
// Fast path: match literal and `?` prefix without heap allocation.
while let Some(&p) = pattern.first() {
match p {
b'*' => break,
b'?' => {
if str_.is_empty() {
return simple;
}
str_ = &str_[1..];
pattern = &pattern[1..];
}
_ => {
if str_.is_empty() || str_[0] != pattern[0] {
if str_.first() != Some(&p) {
return false;
}
str_ = &str_[1..];
pattern = &pattern[1..];
}
}
}
if pattern.is_empty() {
return str_.is_empty();
}
// Collapse consecutive leading `*` tokens; a trailing run matches everything.
while pattern.first() == Some(&b'*') {
pattern = &pattern[1..];
}
if pattern.is_empty() {
return true;
}
// Allocation-free fast paths when no further `*` remains in the pattern.
if !pattern.contains(&b'*') {
if !pattern.contains(&b'?') {
return str_.ends_with(pattern);
}
if !simple {
return str_.len() >= pattern.len()
&& pattern
.iter()
.zip(&str_[str_.len() - pattern.len()..])
.all(|(&p, &c)| p == b'?' || p == c);
}
}
star_match_rune(str_, pattern, simple)
}
/// Iteratively matches the remainder of a pattern immediately following a `*`.
///
/// Maintains reachable positions in `str_` (`O(str_.len())` space independent of
/// `pattern.len()`) and collapses consecutive `*` tokens in `O(1)` each, avoiding
/// both exponential backtracking and recursion stack growth.
fn star_match_rune(str_: &[u8], pattern: &[u8], simple: bool) -> bool {
let n = str_.len();
// dp[j]: the pattern prefix processed so far (starting from the leading `*`)
// matches `str_[..j]`.
let mut dp = vec![true; n + 1];
let mut prev_was_star = true;
for &p in pattern {
match p {
b'*' => {
if prev_was_star {
continue;
}
prev_was_star = true;
let Some(first) = dp.iter().position(|&matched| matched) else {
return false;
};
dp[first..].fill(true);
}
b'?' => {
prev_was_star = false;
// In simple mode, reaching `?` when `str_` is exhausted accepts
// whatever follows in `pattern`.
if simple && dp[n] {
return true;
}
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1];
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
literal => {
prev_was_star = false;
let mut any = false;
for j in (1..=n).rev() {
let matched = dp[j - 1] && str_[j - 1] == literal;
dp[j] = matched;
any |= matched;
}
dp[0] = false;
if !any {
return false;
}
}
}
str_ = &str_[1..];
pattern = &pattern[1..];
}
str_.is_empty() && pattern.is_empty()
dp[n]
}
/// Matches a pattern as a prefix against the given text.
@@ -559,6 +642,111 @@ pub fn strings_has_prefix_fold(s: &str, prefix: &str) -> bool {
mod tests {
use super::*;
#[test]
fn test_match_many_wildcards_without_backtracking() {
let name = "a".repeat(1000);
let pattern = "*a".repeat(100);
assert!(match_pattern(&pattern, &name));
assert!(match_simple(&pattern, &name));
assert!(!match_pattern(&format!("{pattern}*b"), &name));
assert!(!match_simple(&format!("{pattern}*b"), &name));
let repeated = format!("{}*b", "a*".repeat(80));
assert!(!match_pattern(&repeated, &name));
assert!(!match_simple(&repeated, &name));
}
#[test]
fn test_match_deep_star_runs_do_not_overflow_stack() {
let stars = "*".repeat(200_000);
assert!(match_pattern(&stars, "tenant-bkt/report.txt"));
assert!(match_simple(&stars, "tenant-bkt/report.txt"));
let stars_suffix = format!("{stars}x");
let long_name = "a".repeat(1024);
assert!(!match_pattern(&stars_suffix, &long_name));
assert!(!match_simple(&stars_suffix, &long_name));
assert!(match_pattern(&stars_suffix, &format!("{long_name}x")));
let middle_stars = format!("a{}b{}c", "*".repeat(50_000), "*".repeat(50_000));
assert!(match_pattern(&middle_stars, &format!("a{}b{}c", "x".repeat(200), "y".repeat(200))));
assert!(!match_pattern(&middle_stars, &format!("a{}c", "x".repeat(200))));
}
#[test]
fn test_match_utf8_multibyte() {
assert!(match_pattern("桶/目录/*文档*", "桶/目录/2026年文档.txt"));
assert!(!match_pattern("桶/目录/*文档*", "桶/目录/2026年表格.txt"));
assert!(match_simple("café*naïve", "café-et-naïve"));
assert!(!match_simple("café*naïve", "café-et-naive"));
assert!(match_simple("*🎉*🚀", "prefix🎉mid🚀"));
assert!(!match_simple("*🎉*🚀", "prefix🎉mid"));
}
#[test]
fn test_match_wildcards() {
let test_cases = [
("my-bucket/In*/Ka*/Ban", "my-bucket/India/Karnataka/Ban/Ban/Ban", true, true),
("my-bucket/In*/Ka*/Ban", "my-bucket/India/Karnataka/Bangalore", false, false),
("my-bucket/mnop*?and?", "my-bucket/mnopqanda", true, true),
("*", "", true, true),
("**", "", true, true),
("*a", "", false, false),
// Simple matching accepts a `?` reached at the end of the name, whatever follows it.
("a?", "a", false, true),
("?nobody", "", false, true),
("*?a*b", "xa", false, true),
("my-bucket/mnop*?and", "my-bucket/mnopand", false, true),
("*a?c", "aa", false, true),
("*a?*c", "aa", false, true),
];
for (pattern, name, expected, expected_simple) in test_cases {
assert_eq!(match_pattern(pattern, name), expected, "match_pattern({pattern:?}, {name:?})");
assert_eq!(match_simple(pattern, name), expected_simple, "match_simple({pattern:?}, {name:?})");
}
}
fn backtracking_match_rune(str_: &[u8], pattern: &[u8], simple: bool) -> bool {
match pattern.split_first() {
None => str_.is_empty(),
Some((b'*', rest)) => {
backtracking_match_rune(str_, rest, simple)
|| (!str_.is_empty() && backtracking_match_rune(&str_[1..], pattern, simple))
}
Some((b'?', _)) if str_.is_empty() => simple,
Some((&p, rest)) => {
!str_.is_empty() && (p == b'?' || p == str_[0]) && backtracking_match_rune(&str_[1..], rest, simple)
}
}
}
fn small_strings(alphabet: &str, max_len: usize) -> Vec<String> {
let mut all = vec![String::new()];
let mut longest = all.clone();
for _ in 0..max_len {
longest = longest
.iter()
.flat_map(|s| alphabet.chars().map(move |c| format!("{s}{c}")))
.collect();
all.extend_from_slice(&longest);
}
all
}
#[test]
fn test_match_agrees_with_backtracking_definition() {
let names = small_strings("ab", 5);
for pattern in small_strings("ab*?", 5) {
for name in &names {
let expected = |simple| backtracking_match_rune(name.as_bytes(), pattern.as_bytes(), simple);
assert_eq!(match_pattern(&pattern, name), expected(false), "match_pattern({pattern:?}, {name:?})");
assert_eq!(match_simple(&pattern, name), expected(true), "match_simple({pattern:?}, {name:?})");
}
}
}
#[test]
fn test_has_ellipses() {
// Tests for all args without ellipses.
+11 -10
View File
@@ -8,8 +8,10 @@
# - which non-crates.io sources we trust,
# - which duplicate crate versions we tolerate vs. flag.
#
# When adding an exception, include an `# owner: <github-handle> review: <yyyy-mm>`
# When adding a non-advisory exception, include an `# owner: <github-handle> review: <yyyy-mm>`
# comment so future audits know who signed off and when to revisit.
# Advisory ignores below are machine-enforced against `.config/advisory-exceptions.toml`
# by `scripts/security/check_advisories.py` (rustfs/backlog#2668); both files must match.
[graph]
all-features = true
@@ -19,24 +21,23 @@ no-default-features = false
version = 2
yanked = "deny"
ignore = [
# `rsa` Marvin timing sidechannel (RUSTSEC-2023-0071). Pulled in via
# `openidconnect` (transitive) and historically used directly. No upstream
# fix is available yet. Tracked separately for follow-up; remove this
# entry once a patched `rsa` lands in the dependency graph and any
# in-process RSA decryption oracles are removed.
# `rsa` Marvin timing sidechannel (RUSTSEC-2023-0071, patched in >= 0.10.0).
# Direct workspace consumers migrated to `rsa 0.10.0` in PR #9492; only
# transitive `rsa 0.9.10` remains via `openidconnect 4.1.0` (`rustfs-iam`).
# Machine-enforced expiry and approval metadata live in `.config/advisory-exceptions.toml`.
# owner: rustfs-maintainers review: 2026-07
{ id = "RUSTSEC-2023-0071", reason = "rsa Marvin timing sidechannel; no fixed upstream version; tracked separately" },
{ id = "RUSTSEC-2023-0071", reason = "rsa 0.9.10 Marvin timing sidechannel via openidconnect 4.1.0; tracked in .config/advisory-exceptions.toml" },
# `chrono` is retained only at compatibility boundaries while the project
# migrates its internal time model to jiff. The advisory reports no safe
# upgrade for any chrono release.
# upgrade for any chrono release. Tracked in `.config/advisory-exceptions.toml`.
# owner: rustfs-maintainers review: 2026-11
{ id = "RUSTSEC-2026-0543", reason = "chrono is unmaintained; temporary exception during jiff migration" },
# `chrono-tz` is retained by a narrow compatibility path during the same
# migration and has no safe upstream upgrade.
# migration and has no safe upstream upgrade. Tracked in `.config/advisory-exceptions.toml`.
# owner: rustfs-maintainers review: 2026-11
{ id = "RUSTSEC-2026-0555", reason = "chrono-tz is unmaintained; temporary exception during jiff migration" },
# humantime wraps chrono and is retained transitively while the chrono
# graph is being removed.
# graph is being removed. Tracked in `.config/advisory-exceptions.toml`.
# owner: rustfs-maintainers review: 2026-11
{ id = "RUSTSEC-2026-0542", reason = "humantime is unmaintained through chrono; temporary exception during jiff migration" },
]
@@ -113,10 +113,9 @@ Inventory the source first: bucket default encryption means objects can be encry
| Fact | Value |
|---|---|
| Shipping status | Ships in no default build: absent from `default` and `full` in `rustfs/Cargo.toml`; released binaries and container images never include it. Enable with `--features rio-v2`. |
| Pull-request coverage | `test-and-lint-rio-v2` in `.github/workflows/ci.yml`: clippy plus `cargo nextest` for `rustfs`, `rustfs-ecstore`, and `rustfs-sse` with `--features rio-v2`. This is the cfg-seam guard; it keeps the feature compiling and its unit suite green on every pull request. |
| Full-suite lane | `build-rustfs-debug-binary-rio-v2` and `e2e-tests-rio-v2` in `ci.yml` run only on the nightly schedule and manual dispatch (`cache-warm.yml` keeps the `ci-feat-rio` cache warm so the scheduled build fits its timeout). |
| CI coverage | `.github/workflows/ci.yml` does not compile or test `rio-v2`. The former schedule and dispatch lanes `test-and-lint-rio-v2`, `build-rustfs-debug-binary-rio-v2`, and `e2e-tests-rio-v2` are removed, as is the `cache-warm.yml` job `warm-ci-feat-rio` that warmed `ci-feat-rio` for them. The default debug binary, e2e, and S3 lanes do not enable the feature. |
| Interop evidence | `.github/workflows/minio-interop.yml` (nightly plus manual) regenerates real MinIO backend trees via `crates/rio-v2/tests/minio_fixture_lab/` and runs the `#[ignore]` reader tests in `rustfs/src/storage/minio_generated_read_test.rs` with `--features rio-v2`. Its freshness is tracked in `.github/scheduled-validations.json`. |
| Promote-or-delete condition | The variant stays dormant until one of two things happens. **Promote**: a release commits to shipping MinIO SSE migration as a supported capability; then `rio-v2` joins `default`/`full`, the scheduled lanes run on every pull request, and this section is rewritten. **Delete**: no release commits to it and the scheduled lanes are not kept green; then the feature flag, `crates/rio-v2`, the cfg seams under `crates/sse/src/`, the three `ci.yml` jobs, the `cache-warm.yml` warm step, `minio-interop.yml`, and its `scheduled-validations.json` entry are removed in one change. Either outcome must update `ARCHITECTURE.md` and the `ci.yml` job comments that cite this section. |
| Promote-or-delete condition | The variant stays dormant until one of two things happens. **Promote**: a release commits to shipping MinIO SSE migration as a supported capability; then `rio-v2` joins `default`/`full`, pull-request validation for that build is added, and this section is rewritten. **Delete**: no release commits to it; then the feature flag, `crates/rio-v2`, the cfg seams under `crates/sse/src/`, `minio-interop.yml`, and its `scheduled-validations.json` entry are removed in one change. That deletion is separate from the removed `ci.yml` lanes. Either outcome must update `ARCHITECTURE.md`. |
## Fixture Evidence
@@ -145,7 +144,7 @@ Not fixture-proven: transitioned `xl.meta`; CORS, public-access-block, and bucke
- Any change to `crates/filemeta` or `crates/ecstore/src/bucket` metadata encoding is a storage-format change and follows the migration and readiness contracts in [README.md](README.md) and the ecstore layout boundary rules.
- Do not bump a Version Anchor without a read path for the prior value; see [erasure-coding.md](erasure-coding.md) for the accept-older, reject-newer rule.
- `.github/workflows/ci.yml`, `.github/workflows/cache-warm.yml`, and `ARCHITECTURE.md` cite the [rio-v2 variant lifecycle](#rio-v2-variant-lifecycle) heading; keep it when editing this file.
- `ARCHITECTURE.md` points at this document for the `rio-v2` lifecycle. Keep this heading when editing the file.
## Independent integrity upgrade contract
@@ -178,7 +178,7 @@ requires a compatibility window and a dedicated cleanup entry.
| `.scanner-cycle.lock` | scanner runtime lock | Serializes cycle-level work. A missing lock object is not itself usage evidence. |
| `.scanner-pause-backlog.json` | scanner pause and catch-up ledger | Tracks dirty usage, discovered lifecycle work, and full-scan catch-up while authoritative publication is fenced by data movement. It never grants publication admission. |
The authoritative snapshot may include an optional `bucket_incarnation` in each bucket usage entry. The coordinator writes it only when every contributing set reports the same non-nil bucket UUID. Missing or conflicting identities leave that entry uncertified without affecting publication or quota admission. Veeam SOSAPI reports numeric `Used` only when this proof matches the current bucket incarnation. Missing usage or a snapshot without valid proof, including legacy and pending entries, yields `Used=-1`. With a hard quota, `Available` is also undefined unless live free space is zero. Failures to read authoritative bucket metadata or usage, or obtain live storage capacity, yield a retryable capacity error. The proof is additive for older snapshot readers and identifies the bucket generation without making scanner usage a real-time quota ledger.
The authoritative snapshot may include an optional `bucket_incarnation` in each bucket usage entry. The coordinator writes it only when every contributing set reports the same non-nil bucket UUID. Missing or conflicting identities leave that entry uncertified without affecting publication or quota admission. Veeam SOSAPI reports numeric `Used` only when this proof matches the current bucket incarnation. Missing usage, a readable legacy snapshot without proof, explicit pending entries, and proof for a previous bucket incarnation yield `Used=-1`. Contradictory snapshot certification metadata and malformed incarnation proofs return a retryable error. With a hard quota, `Available` is also undefined unless live free space is zero. Failures to read authoritative bucket metadata or usage, or obtain live storage capacity, yield a retryable capacity error. The proof is additive for older snapshot readers and identifies the bucket generation without making scanner usage a real-time quota ledger.
SOSAPI retains the XML and its content-derived ETag when the reported figures match the previous sample. Once Last-Modified reaches nine minutes of age, a successful refresh renews the timestamp ahead of Veeam's ten-minute limit. Refresh failures still return an error.
-2
View File
@@ -74,8 +74,6 @@ Cross-registry publication is not atomic. A channel job can fail after some veri
Finish any in-flight legacy tag release, including its downstream Docker/package/Helm jobs, before enabling this cutover on main. Existing tags and Releases retain their identities. Do not feed a legacy public preview binary into the new promotion path: it embeds a different version and was not built from the frozen-input contract.
Release branches that still publish with the tag-triggered Build and Release workflow upload zip archives, provenance, an SBOM, and checksums. They do not build deb or rpm packages. GitHub runs a `workflow_run` listener from the default branch only, so `.github/workflows/package-deb-rpm.yml` is that listener: after a successful tag push it downloads that build's Linux zip artifacts, checks each zip against `SHA256SUMS`, wraps that binary with `scripts/release/build_deb.sh` and `scripts/release/build_rpm.sh`, and uploads the eight `rustfs-linux-{x86_64,aarch64}-{gnu,musl}-v<version>.{deb,rpm}` assets. It then rewrites `SHA256SUMS` and `SHA512SUMS` so the package lines match those assets. An existing package asset with a different digest is left unchanged and fails the job. Dispatch the same workflow from `main` with the release tag to backfill a release that is missing those packages; that dispatch writes to the live release, so run it only after this workflow is on `main`. `manual-main-packages.yml` can compile the same filenames for a tag, including `1.0.7`, but it only stores workflow artifacts and does not attach them. The certification publisher above still seals and publishes the same package names when a release goes through `release-complete.yml`.
All workflow responsibilities, triggers and schedule ownership remain registered in `.github/scheduled-validations.json`. The migration does not re-enable workflows disabled in GitHub. PR checks, cache warming, nightly development builds, functional chains, lab tests and monitoring retain their distinct purposes; shared source or cache does not make different feature/platform tests redundant. The watchdog allocates a runner only for relevant unsuccessful scheduled/chained runs, while its registry still determines ownership.
Run `actionlint`, the release contract suite and the workflow registry validator after changes. The Security Audit workflow also exercises actual GitHub artifact transport, DEB/RPM package extraction, both multi-platform OCI builders, local registry promotion and archive scanning. Native packaging jobs run only for relevant changes or a manual audit. Their payloads are explicit transport fixtures, not product release acceptance. See the [release skill](../../.agents/skills/rustfs-release-publish/SKILL.md) for field acceptance, human confirmation and post-release follow-up.
+1 -1
View File
@@ -10,7 +10,7 @@ Every event class the planner serves must have at least one reviewable drill: an
|---|---|---|
| `pull_request` (ordinary code) | reverse-dependency closure + fixed core inventory; shared/unknown inputs expand to full | `Test and Lint` requires exactly the planned job results |
| `pull_request` (documentation only) | `docs` mode: no code jobs | Quick Checks and Typos run; expensive jobs are required **skipped** |
| `pull_request` (isolated E2E) | `e2e` mode: workspace + server build + E2E smoke + S3 lanes | Connect boundary, serial ILM, protocol/rio-v2, real io_uring required **skipped** |
| `pull_request` (isolated E2E) | `e2e` mode: workspace + server build + E2E smoke + S3 lanes | Connect boundary, serial ILM, protocol lanes, and real io_uring required **skipped** |
| `pull_request` (closed) | `Cancel Closed PR Runs` only | in-flight validation for that PR is cancelled; no new validation is claimed |
| `pull_request` (merged) | entry into `merge_group` | combined candidate is validated as its own SHA/tree with the full matrix |
| `push` to `main` | full | complete validation; no reuse inferred from tree equality |
+7 -7
View File
@@ -16,9 +16,9 @@ The `main` ruleset (`6436880`) requires exactly these contexts, with `strict_req
Every PR enters `ci.yml`. The `classify-changes` job uses the base revision of `scripts/ci_gate.py` to select a conservative documentation-only path: root Markdown/licenses, `AGENTS.md`, Markdown under `docs/` or `.agents/skills/`, and documentation images. Unknown paths, unavailable Git history, an empty diff, or a missing base policy select the full scope for that event. Renames include their deleted source path. Documentation-only PRs still run Quick Checks and Typos; the aggregate requires the expensive jobs to be skipped exactly as selected.
PRs changing only Rust sources under `crates/e2e_test/src/` and known E2E selection digests (optionally with those documentation paths) use the `e2e` scope. They keep workspace validation, the server build, E2E smoke, and both S3 lanes; independent workflows retain their path selection. Connect boundary, serial ILM, optional protocol/rio-v2, and real io_uring jobs are skipped because their sources and test inputs are unchanged. Manifests, fixtures, shared nextest configuration, scripts, production sources, and unknown paths still select `full`. A dependency on `e2e_test` from another workspace member or reachable local dependency disables this shortcut. All non-PR events retain their full selection. The structured planner enforces affected-package and Connect selection from the trusted base policy, retaining fixed core coverage and full validation for shared or unknown inputs. See [verification plans and artifacts](ci-verification-pipeline.md) for identity, rollout and queue-switch contracts.
PRs changing only Rust sources under `crates/e2e_test/src/` and known E2E selection digests (optionally with those documentation paths) use the `e2e` scope. They keep workspace validation, the server build, E2E smoke, and both S3 lanes; independent workflows retain their path selection. Connect boundary, serial ILM, optional protocol, and real io_uring jobs are skipped because their sources and test inputs are unchanged. Manifests, fixtures, shared nextest configuration, scripts, production sources, and unknown paths still select `full`. A dependency on `e2e_test` from another workspace member or reachable local dependency disables this shortcut. All non-PR events retain their full selection. The structured planner enforces affected-package and Connect selection from the trusted base policy, retaining fixed core coverage and full validation for shared or unknown inputs. See [verification plans and artifacts](ci-verification-pipeline.md) for identity, rollout and queue-switch contracts.
Specialized boundary, hardware and alternate-feature lanes run only on the scheduled (nightly) and manual full-validation runs: `Connect Feature Boundaries`, `io_uring Integration (real)`, and the rio-v2, Swift, SFTP and HTTP/3 feature lanes. They do not gate a merge. The nightly run reports their regressions within a day, and repeating these builds on every PR revision and merge group bought no earlier signal worth the runner occupancy (Connect alone measured 53.5 median minutes per run and occasionally set the wall). PRs, merge groups and main pushes run the default workspace and retain ILM, S3, E2E smoke, the short core contract and the debug build. The aggregate requires the specialized lanes to be skipped on pull-request, merge-group and push events and successful on scheduled and manual events. For changes to these features, dispatch `ci.yml` against the candidate branch before merging when that signal is needed. Scheduled results supplement the main baseline and do not replace it.
Specialized boundary, hardware and alternate-feature lanes run only on the scheduled (nightly) and manual full-validation runs: `Connect Feature Boundaries`, `io_uring Integration (real)`, and the Swift, SFTP and HTTP/3 feature lanes. They do not gate a merge. The nightly run reports their regressions within a day, and repeating these builds on every PR revision and merge group bought no earlier signal worth the runner occupancy (Connect alone measured 53.5 median minutes per run and occasionally set the wall). PRs, merge groups and main pushes run the default workspace and retain ILM, S3, E2E smoke, the short core contract and the debug build. The aggregate requires the specialized lanes to be skipped on pull-request, merge-group and push events and successful on scheduled and manual events. For changes to these features, dispatch `ci.yml` against the candidate branch before merging when that signal is needed. Scheduled results supplement the main baseline and do not replace it.
Workspace Clippy runs on every event with a selected workspace Rust job, pull requests included, in its own `Workspace Clippy` job. It runs beside `Workspace Lint and Build` instead of in front of it, because check-mode metadata and the linked test binaries share no compiler output; `scripts/ci_gate.py --check-workflow` rejects a workflow in which the archive producer or any archive consumer waits for the lint, or in which the lint leaves the aggregate. `Workspace Lint and Build` keeps its name as the archive producer: it creates the exact test archive and runs doctests; `Workspace tests` consumes the archive without rebuilding it. `cache-warm.yml` warms Clippy's check artifacts under `ci-dev` with the same invocation to reuse compatible dependency artifacts. `make pre-commit` does not run Clippy. Select local Clippy targets, features, and documentation exemptions from the root `AGENTS.md` verification tier; the workspace command below reproduces the CI lane and is not a universal pre-push requirement.
@@ -53,7 +53,7 @@ The four site-replication state-writer concurrency proofs reserve the available
| PR, non-doc change, and every non-PR event | `Workspace Clippy`, `Workspace Lint and Build`, `Workspace tests` | `ci.yml` `workspace-clippy` / `workspace-lint-and-build` / `workspace-tests` | Via aggregate | `cargo clippy --all-targets -- -D warnings`; `cargo nextest run --profile ci --all --exclude e2e_test`; `cargo test --all --exclude e2e_test --doc`; migration evidence check described below |
| PR, non-doc change | `Typos` | `ci.yml` `typos` | Via aggregate | `typos` |
| Full selection | `Workspace tests` (serial ILM step) | `ci.yml` `workspace-tests` | Via aggregate | exact `Run ignored ILM integration tests serially` command in the job |
| Nightly schedule, manual dispatch | `Test and Lint (rio-v2)`, `Test and Lint (swift)`, `Test and Lint (sftp)`, `Test and Lint (http3)` | `ci.yml` `test-and-lint-rio-v2`, `test-and-lint-protocols` | Via aggregate on these events; skipped on PRs, merge groups and main pushes | `cargo nextest run` with the job's `--features` |
| Nightly schedule, manual dispatch | `Test and Lint (swift)`, `Test and Lint (sftp)`, `Test and Lint (http3)` | `ci.yml` `test-and-lint-protocols` | Via aggregate on these events; skipped on PRs, merge groups and main pushes | `cargo nextest run` with the job's `--features` |
| Nightly schedule, manual dispatch, full selection | `Connect Feature Boundaries` | `ci.yml` `connect-feature-boundaries` | Via aggregate on these events; skipped on PRs, merge groups and main pushes | `cargo test -p rustfs --test connect_registration --features connect-e2e-short-credentials`; `scripts/check_connect_release_boundary.py`: `cargo check -p rustfs --release` with `connect-e2e-short-credentials` must fail at its guard; `scripts/check_offline_enrollment_e2e.sh` |
| PR, non-doc change | `Build RustFS Debug Binary` | `ci.yml` `build-rustfs-debug-binary` | Via aggregate; prerequisite for black-box jobs | `python3 scripts/e2e_binary.py build --bins --features e2e-test-hooks` (binary plus its `rustfs.e2e.json` sidecar) |
| Nightly schedule, manual dispatch, full selection | `io_uring Integration (real)` | `ci.yml` `uring-integration` | Via aggregate on these events; skipped on PRs, merge groups and main pushes | `cargo test -p rustfs-ecstore --lib uring_ -- --test-threads=1 --nocapture` |
@@ -85,8 +85,8 @@ Scheduled lanes never block a PR. Their workflow-local gate fails the run. The v
| Workflow (cadence) | Jobs | Verdict and artifacts | Registry monitor | Reproduce |
|---|---|---|---|---|
| `ci.yml` (nightly) | full matrix, including the schedule/dispatch-only rio-v2 jobs `build-rustfs-debug-binary-rio-v2` and `e2e-tests-rio-v2` | strict aggregate; the full E2E lane runs on dispatch, merge groups, and main pushes that no merge group proved | yes | dispatch `ci.yml` |
| `cache-warm.yml` (every six hours, plus main pushes that change `Cargo.lock`, `rust-toolchain.toml` or the setup action) | `warm-ci-dev`, `warm-ci-feat-rio`, `warm-ci-feat-proto`, `warm-ci-uring` | no verdict; sole writer of the `rust-cache` keys that `ci.yml` restores | yes | dispatch `cache-warm.yml` |
| `ci.yml` (nightly) | full matrix | strict aggregate; the full E2E lane runs on dispatch, merge groups, and main pushes that no merge group proved | yes | dispatch `ci.yml` |
| `cache-warm.yml` (every six hours, plus main pushes that change `Cargo.lock`, `rust-toolchain.toml` or the setup action) | `warm-ci-dev`, `warm-ci-feat-proto`, `warm-ci-uring` | no verdict; sole writer of the `rust-cache` keys that `ci.yml` restores | yes | dispatch `cache-warm.yml` |
| `build.yml` (nightly Linux, weekly desktop) | `build-rustfs` over the `prepare-platform-matrix` subset for the firing cron: four Linux targets at 01:13 UTC, and macOS aarch64 plus Windows x86_64 at Sunday 16:17 UTC | build/package integrity | yes | dispatch `build.yml` with an exact platform set |
| `e2e-replication-nightly.yml` (nightly) | `repl-nightly`, `cluster-nightly`, `protocols-nightly` | three independent gates; JUnit, membership listing, server logs | yes | `python3 scripts/e2e_binary.py build --bins`, then `python3 scripts/e2e_binary.py run -- cargo nextest run --profile e2e-repl-nightly -p e2e_test`; `--features e2e-test-hooks` on both steps with `--profile e2e-nightly`; `--features ftps,webdav,sftp` on both steps with `-j 1 --profile e2e-protocols` |
| `dual-stack-nightly.yml` (nightly) | `build`, `leg` (`e2e-smoke` and `e2e-full`) | the two profiles only `ci.yml` runs, nightly on the gateway stack (the workflow keeps its name from the both-stack period); per-profile JUnit and server logs retained 30 days. The one comparison against the last legacy record is made by hand with `scripts/junit_diff.py` | yes | dispatch `dual-stack-nightly.yml` |
@@ -127,7 +127,7 @@ The versioned plan is `.config/release-validation-plan.json` (`schema_version=1`
| Nightly Linux schedule, weekly desktop schedule, or dispatch | `build.yml` `build-rustfs` (development build of that schedule's platform subset, or the dispatch platform list) | build artifacts and the uncertified dev download channel; no release publication |
| Valid release or preview tag | `build.yml` `build-rustfs`, `release-certification`, `create-release`, `upload-release-assets`, `publish-release`, `promote-release-artifacts` | staged binaries, draft release, checksummed assets, then certified publish and promotion of the same bytes |
| Successful non-preview release-tag build (`workflow_run`) | `docker.yml` `release-certification`, `build-docker`, `scan-docker-image` | multi-architecture images staged, verified against the certification and promoted, plus vulnerability report |
| Successful release-tag build (`workflow_run`) | `package-deb-rpm.yml` `resolve`, `package`, `checksums` | eight Linux deb/rpm assets wrapped from the published zips, then SHA256SUMS and SHA512SUMS rewritten to include them |
| Successful release-tag build (`workflow_run`) | `package.yml` `release-certification`, `package`, `promote-packages` | DEB/RPM packages with wrapped-binary verification, staged then promoted with checksums |
| Successful non-preview release-tag build (`workflow_run`) | `helm-package.yml` `release-certification`, `build-helm-package`, `publish-helm-package` | versioned chart and repository index, only over a certified image promotion record |
| Final tag's release published | `build.yml` `cleanup-preview-releases` | deletes every `<target>-preview.<N>` Release for that target; the tags are kept |
@@ -140,7 +140,7 @@ Publication exits and their gate:
| `latest.json` version pointer | `build.yml` `update-latest-version` | transitively through `publish-release` |
| Image channels (Docker Hub, GHCR, Quay tags) | `docker.yml` `build-docker` promotion step | certified input digests, staged image binary identity and `verify-promotion`, then promotion of the same digest with `imagetools create` |
| Official R2 package paths `packages/release` and `packages/latest` | `package.yml` `promote-packages` | `release-certification` and wrapped-binary `verify-promotion`; the package job only stages |
| GitHub release package assets | `package-deb-rpm.yml` `package` and `checksums` | zip digest checked against the published SHA256SUMS, then deb/rpm upload without replacing a different digest; checksum files are rewritten to include the packages |
| GitHub release package assets | `package.yml` `package` | `release-certification` and wrapped-binary `verify-promotion` before upload |
| Helm chart repository (`rustfs/helm` push) | `helm-package.yml` `publish-helm-package` | `release-certification` plus the Docker workflow's image-promotion record bound to the same candidate |
Downstream workflows fail closed when the trusted certification is absent: a manual dispatch without certification fails and pushes no official tag. Only results from the trusted verification sources listed in the plan (currently the `rustfs/s3chaos` `release-gate.yml` envelope runs) carry release authority; a PR-uploaded JSON set cannot certify a release. Retries reuse the same candidate, only the staged bytes are promoted (no rebuild-after-verify), and no downstream step re-resolves a mutable `latest`.
+1 -1
View File
@@ -32,7 +32,7 @@ Periodic and manual suites use the responsibility registry and retain the existi
## Merge-queue preparation and rollback
The merge-group event plans and validates its actual combined SHA/tree with the default workspace matrix: workspace lint and tests, the short core contract, the debug build, E2E smoke, both S3 lanes and the full merge-gate E2E. The specialized boundary, hardware and alternate-feature lanes (Connect Feature Boundaries, real io_uring, rio-v2, Swift, SFTP, HTTP/3) run only in the scheduled and manual full-validation runs and are required to be skipped here. Main pushes keep complete validation; no reuse is inferred from tree equality because commit identity and build inputs can matter. CLA remains an independent queue-entry requirement.
The merge-group event plans and validates its actual combined SHA/tree with the default workspace matrix: workspace lint and tests, the short core contract, the debug build, E2E smoke, both S3 lanes and the full merge-gate E2E. The specialized boundary, hardware and alternate-feature lanes (Connect Feature Boundaries, real io_uring, Swift, SFTP, HTTP/3) run only in the scheduled and manual full-validation runs and are required to be skipped here. Main pushes keep complete validation; no reuse is inferred from tree equality because commit identity and build inputs can matter. CLA remains an independent queue-entry requirement.
`scripts/ci_merge_queue.py` prepares a bounded queue proposal from a live ruleset snapshot without calling a mutation API. It preserves all existing checks, reviews, bypass actors and branch conditions, adds an `ALLGREEN` squash queue with at most two concurrent builds/two merged entries, and produces the original rollback payload. Its timeout accommodates the existing full gate while measurements are collected. API fields follow [GitHub's ruleset contract](https://docs.github.com/en/rest/repos/rules).
@@ -1295,9 +1295,10 @@ mod tests {
bucket_policy(&store, &bucket, serde_json::json!({"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":"*","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":format!("arn:aws:s3:::{bucket}/*")}
]})).await;
let denied_object = "explicitly-denied";
let denied = rustfs_policy::policy::Policy::parse_config(
serde_json::to_string(&serde_json::json!({"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":["s3:PutObject","s3:DeleteObject"],"Resource":format!("arn:aws:s3:::{bucket}/*")}
{"Effect":"Deny","Action":["s3:PutObject","s3:DeleteObject"],"Resource":format!("arn:aws:s3:::{bucket}/{denied_object}")}
]}))
.expect("identity denial JSON")
.as_bytes(),
@@ -1307,22 +1308,24 @@ mod tests {
iam.policy_db_set(&cred.access_key, UserType::Reg, false, "permission-denial")
.await
.expect("attach denial");
for (action, expected) in [
("s3:GetObject", Decision::Allowed),
("s3:PutObject", Decision::Denied),
("s3:DeleteObject", Decision::Denied),
for (action, object, expected) in [
("s3:PutObject", "bucket-grant", Decision::Allowed),
("s3:DeleteObject", "bucket-grant", Decision::Allowed),
("s3:GetObject", denied_object, Decision::Allowed),
("s3:PutObject", denied_object, Decision::Denied),
("s3:DeleteObject", denied_object, Decision::Denied),
] {
let request = parse(serde_json::json!({"checks":[{"id":"x","action":action,"bucket":bucket,"object":"object"}]}));
let request = parse(serde_json::json!({"checks":[{"id":"x","action":action,"bucket":bucket,"object":object}]}));
let result = evaluate_check(
&envelope,
&cred,
false,
&request.checks[0],
request.validate().expect("valid denial query")[0],
request.validate().expect("valid permission query")[0],
)
.await
.expect("non-owner query");
assert_eq!(result.decision, expected, "real gate semantics for {action}");
assert_eq!(result.decision, expected, "real gate semantics for {action} on {object}");
}
});
}
+144 -2
View File
@@ -141,7 +141,7 @@ impl DefaultBucketUsecase {
let policy_public = match metadata_sys::get_bucket_policy(bucket).await {
Ok((cfg, _)) => cfg.statements.iter().any(|statement| {
matches!(statement.effect, Effect::Allow)
&& statement.principal.is_match("*")
&& statement.principal.is_public()
&& statement.conditions.is_empty()
&& statement.actions.is_match(&Action::S3Action(S3Action::ListBucketAction))
}),
@@ -197,7 +197,7 @@ impl DefaultBucketUsecase {
let is_public_policy = cfg
.statements
.iter()
.any(|statement| matches!(statement.effect, Effect::Allow) && statement.principal.is_match("*"));
.any(|statement| matches!(statement.effect, Effect::Allow) && statement.principal.is_public());
if is_public_policy {
match metadata_sys::get_public_access_block_config(bucket).await {
@@ -300,4 +300,146 @@ mod tests {
.unwrap_err();
assert_eq!(err.code(), &rustfs_s3_types::S3ErrorCode::InternalError);
}
#[test]
#[serial_test::serial]
fn block_public_policy_rejects_anonymous_matching_principals() {
use crate::app::gating_test_env::{run_large_stack_test, shared_gating_ambient};
use crate::app::runtime_sources::ServerContextSlot;
use crate::app::storage_api::owned_parity::authorize_bucket_config_mutation;
use rustfs_credentials::Credentials;
use rustfs_policy::policy::action::{Action, S3Action};
run_large_stack_test("bucket-policy-block-public-principals", || async {
let context = shared_gating_ambient().await;
let store = context.object_store();
let bucket_name = format!("block-public-policy-{}", uuid::Uuid::new_v4().simple());
store
.make_bucket(&bucket_name, &MakeBucketOptions::default())
.await
.expect("create bucket");
metadata_sys::update(
&bucket_name,
BUCKET_PUBLIC_ACCESS_BLOCK_CONFIG,
b"<PublicAccessBlockConfiguration><BlockPublicPolicy>true</BlockPublicPolicy></PublicAccessBlockConfiguration>"
.to_vec(),
)
.await
.expect("seed public access block");
let server = ServerContextSlot::new();
assert!(server.install(Arc::clone(&context)));
let usecase = DefaultBucketUsecase::with_context(Some(Arc::clone(&context)));
let authorized_put_envelope = || async {
let mut extensions = http::Extensions::new();
extensions.insert(Arc::clone(&server));
extensions.insert(ReqInfo {
cred: Some(Credentials {
access_key: "policy-test-owner".to_owned(),
..Default::default()
}),
is_owner: true,
..Default::default()
});
let mut envelope = RequestEnvelope::from_parts(
crate::app::RequestHead {
method: Method::PUT,
uri: format!("/{bucket_name}?policy").parse().expect("request URI"),
headers: http::HeaderMap::new(),
credentials: None,
region: None,
service: None,
},
extensions,
);
authorize_bucket_config_mutation(
&server,
&mut envelope,
&bucket_name,
Action::S3Action(S3Action::PutBucketPolicyAction),
)
.await
.expect("owner authorization installs incarnation snapshot");
envelope
};
for (label, principal_json) in [
("wildcard", r#"{"AWS":["*"]}"#),
("empty_array", r#"{"AWS":[""]}"#),
("empty_string", r#"{"AWS":""}"#),
("question_mark", r#"{"AWS":"?"}"#),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#),
("mixed_named_and_empty", r#"{"AWS":["alice",""]}"#),
] {
let policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{principal_json},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::{bucket_name}/*"]}}]}}"#
);
let Err(err) = usecase
.execute_put_bucket_policy(authorized_put_envelope().await, &bucket_name, &policy)
.await
else {
panic!("BlockPublicPolicy must reject {label} principal");
};
assert_eq!(
err.code(),
&rustfs_s3_types::S3ErrorCode::AccessDenied,
"expected AccessDenied for {label}"
);
}
// A named principal Allow remains accepted under BlockPublicPolicy.
let named_policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{{"AWS":["alice"]}},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::{bucket_name}/*"]}}]}}"#
);
usecase
.execute_put_bucket_policy(authorized_put_envelope().await, &bucket_name, &named_policy)
.await
.expect("named principal policy should be accepted");
// A Deny statement with an empty principal is not a public grant.
let deny_policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Deny","Principal":{{"AWS":[""]}},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::{bucket_name}/*"]}}]}}"#
);
usecase
.execute_put_bucket_policy(authorized_put_envelope().await, &bucket_name, &deny_policy)
.await
.expect("Deny statement should not be rejected as a public grant");
// GetBucketPolicyStatus also classifies empty and `?` Allow principals as public.
let status_bucket = format!("policy-status-public-{}", uuid::Uuid::new_v4().simple());
store
.make_bucket(&status_bucket, &MakeBucketOptions::default())
.await
.expect("create status bucket");
for (label, principal_json, expected_public) in [
("empty_principal", r#"{"AWS":[""]}"#, true),
("leading_question_mark", r#"{"AWS":["?nobody"]}"#, true),
("named_principal", r#"{"AWS":["alice"]}"#, false),
] {
let policy = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{principal_json},"Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::{status_bucket}"]}}]}}"#
);
metadata_sys::update(&status_bucket, BUCKET_POLICY_CONFIG, policy.into_bytes())
.await
.expect("seed bucket policy");
let output = usecase
.execute_get_bucket_policy_status(
owned_envelope(Method::GET),
gateway_dto::GetBucketPolicyStatusInput {
bucket: bucket(&status_bucket),
..Default::default()
},
)
.await
.expect("get bucket policy status");
assert_eq!(
output.policy_status.and_then(|status| status.is_public),
Some(expected_public),
"unexpected policy status for {label}"
);
}
});
}
}
+79 -1
View File
@@ -18,6 +18,11 @@ use super::*;
use crate::app::storage_api::bucket_usecase::bucket::{ObjectLockConfigExt as _, VersioningConfigExt as _};
use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
/// Maximum number of excluded prefixes accepted in a bucket versioning configuration.
const MAX_EXCLUDED_PREFIXES: usize = 100;
/// Maximum byte length of a single excluded prefix (matches the S3 object key limit).
const MAX_EXCLUDED_PREFIX_BYTES: usize = 1024;
fn versioning_configuration_has_object_lock_incompatible_settings(config: &PersistedVersioningConfiguration) -> bool {
config.suspended()
|| config.exclude_folders.unwrap_or(false)
@@ -27,7 +32,7 @@ fn versioning_configuration_has_object_lock_incompatible_settings(config: &Persi
.is_some_and(|excluded_prefixes| !excluded_prefixes.is_empty())
}
async fn validate_bucket_versioning_update(bucket: &str, config: &PersistedVersioningConfiguration) -> S3Result<()> {
fn validate_versioning_configuration_shape(config: &PersistedVersioningConfiguration) -> S3Result<()> {
if config
.status
.as_ref()
@@ -38,6 +43,29 @@ async fn validate_bucket_versioning_update(bucket: &str, config: &PersistedVersi
"bucket versioning configuration has an invalid status",
));
}
if let Some(excluded_prefixes) = config.excluded_prefixes.as_ref() {
if excluded_prefixes.len() > MAX_EXCLUDED_PREFIXES {
return Err(S3Error::with_message(
S3ErrorCode::InvalidArgument,
format!("bucket versioning configuration cannot exceed {MAX_EXCLUDED_PREFIXES} excluded prefixes"),
));
}
if excluded_prefixes
.iter()
.flatten()
.any(|prefix| prefix.len() > MAX_EXCLUDED_PREFIX_BYTES)
{
return Err(S3Error::with_message(
S3ErrorCode::InvalidArgument,
format!("bucket versioning excluded prefix cannot exceed {MAX_EXCLUDED_PREFIX_BYTES} bytes"),
));
}
}
Ok(())
}
async fn validate_bucket_versioning_update(bucket: &str, config: &PersistedVersioningConfiguration) -> S3Result<()> {
validate_versioning_configuration_shape(config)?;
match metadata_sys::get_object_lock_config(bucket).await {
Ok((object_lock_config, _)) => {
if object_lock_config.enabled() && versioning_configuration_has_object_lock_incompatible_settings(config) {
@@ -154,6 +182,56 @@ mod tests {
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
}
#[tokio::test]
async fn validate_bucket_versioning_update_rejects_excessive_excluded_prefix_count() {
let prefixes = (0..=MAX_EXCLUDED_PREFIXES)
.map(|i| Some(format!("tmp-{i}/")))
.collect::<Vec<_>>();
let config = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some(prefixes),
..Default::default()
};
let err = validate_bucket_versioning_update("unregistered-test-bucket", &config)
.await
.expect_err("excessive excluded prefix count must be rejected before persistence");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
}
#[tokio::test]
async fn validate_bucket_versioning_update_rejects_oversized_excluded_prefix() {
let config = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some(vec![Some("*".repeat(MAX_EXCLUDED_PREFIX_BYTES + 1))]),
..Default::default()
};
let err = validate_bucket_versioning_update("unregistered-test-bucket", &config)
.await
.expect_err("oversized excluded prefix must be rejected before persistence");
assert_eq!(err.code(), &S3ErrorCode::InvalidArgument);
}
#[test]
fn validate_versioning_configuration_shape_accepts_bounded_excluded_prefixes() {
let at_limit_count = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some((0..MAX_EXCLUDED_PREFIXES).map(|i| Some(format!("tmp-{i}/"))).collect()),
..Default::default()
};
validate_versioning_configuration_shape(&at_limit_count).expect("max allowed excluded prefix count should pass");
let at_limit_len = PersistedVersioningConfiguration {
status: Some("Enabled".to_owned()),
excluded_prefixes: Some(vec![Some("a".repeat(MAX_EXCLUDED_PREFIX_BYTES))]),
..Default::default()
};
validate_versioning_configuration_shape(&at_limit_len).expect("max allowed excluded prefix length should pass");
}
#[test]
fn versioning_configuration_has_object_lock_incompatible_settings_rejects_suspended() {
let config = PersistedVersioningConfiguration {
+146 -43
View File
@@ -450,31 +450,18 @@ fn is_delete_objects_not_found(error: &EcstoreError) -> bool {
/// a 1000-key batch from serializing while capping the disk fanout pressure.
const DELETE_OBJECTS_PRE_STAT_CONCURRENCY: usize = 16;
/// backlog#929 (HP-8): whether the pre-delete `get_object_info` for one entry
/// of a DeleteObjects batch can be skipped without changing behavior.
///
/// The stat result feeds four consumers, and each must be provably idle:
/// - the app-layer object-lock admission check never runs for deletes that
/// create a delete marker, and non-lock buckets cannot hold retention or
/// legal-hold metadata (`bucket_lock_enabled == false`);
/// - replication reads its authoritative source metadata later while the
/// SetDisks write lock is held, so it does not consume this advisory stat;
/// - usage accounting for delete-marker creation goes through
/// `record_bucket_delete_marker_memory` and never reads the object size
/// (`accounting_creates_delete_marker` is computed from the same versioning
/// snapshot the accounting branch uses);
/// - transitioned-object (ILM tier) cleanup journaling is a no-op for
/// delete-marker creation because no version is removed, so `ObjSweeper`
/// produces no journal entry regardless of the stat result.
///
/// Object-lock enabled buckets always keep the stat, so their delete path is
/// byte-for-byte the pre-#929 one (see PR #4297).
/// Plain deletes get authoritative metadata for accounting, retention and tier
/// cleanup under the storage write lock. An advisory read would take a second
/// namespace lock per request entry, including duplicates of a busy key.
fn can_skip_delete_objects_pre_stat(
bucket_lock_enabled: bool,
opts: &ObjectOptions,
accounting_creates_delete_marker: bool,
has_entry_condition: bool,
) -> bool {
!bucket_lock_enabled && delete_creates_delete_marker(opts) && accounting_creates_delete_marker
!bucket_lock_enabled
&& ((delete_creates_delete_marker(opts) && accounting_creates_delete_marker)
|| (!opts.versioned && opts.version_id.is_none() && opts.http_preconditions.is_none() && !has_entry_condition))
}
fn complete_delete_noop(
@@ -869,7 +856,12 @@ impl DefaultObjectUsecase {
// so evaluate it here with the same inputs to keep the stat-skip
// decision and the accounting path provably consistent.
let accounting_creates_delete_marker = object.version_id.is_none() && opts.versioned && !opts.version_suspended;
let skip_stat = can_skip_delete_objects_pre_stat(bucket_lock_enabled, &opts, accounting_creates_delete_marker);
let skip_stat = can_skip_delete_objects_pre_stat(
bucket_lock_enabled,
&opts,
accounting_creates_delete_marker,
object.delete_condition.is_some(),
);
prepared_deletes.push(PreparedDelete {
idx,
@@ -2932,6 +2924,109 @@ mod tests {
assert_eq!(err.message(), Some("Not init"));
}
#[tokio::test]
#[serial_test::serial]
async fn execute_plain_unversioned_bulk_delete_reaches_storage_for_disabled_and_suspended_buckets() {
use crate::app::storage_api::test::DeleteAfterObjectLockSnapshotBarrier;
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
let ambient = crate::app::gating_test_env::shared_gating_ambient().await;
let context = Arc::new(AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
for suspended in [false, true] {
let bucket = format!("delete-objects-contended-{}", Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create authorized bucket");
let mut reader = PutObjReader::from_vec(b"contended object".to_vec());
store
.put_object(&bucket, "object", &mut reader, &ObjectOptions::default())
.await
.expect("put contended object");
if suspended {
store
.update_bucket_metadata_config(
&bucket,
crate::app::storage_api::test::bucket::metadata::BUCKET_VERSIONING_CONFIG,
b"<VersioningConfiguration><Status>Suspended</Status></VersioningConfiguration>".to_vec(),
)
.await
.expect("suspend fixture versioning");
}
let policy_json = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{{"AWS":"*"}},"Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::{bucket}/*"]}}]}}"#
);
let mut metadata = (*store
.get_bucket_metadata(&bucket)
.await
.expect("authorized bucket metadata should be cached"))
.clone();
metadata.policy_config = Some(serde_json::from_str(&policy_json).expect("test policy should parse"));
metadata.policy_config_json = policy_json.clone().into_bytes();
crate::storage::storage_api::set_bucket_metadata(bucket.clone(), metadata)
.await
.expect("publish test bucket policy");
let writer = store
.new_ns_lock(&bucket, "object")
.await
.expect("open object namespace lock")
.get_write_lock(tokio::time::Duration::from_secs(5))
.await
.expect("hold a concurrent writer's lock");
let admission = DeleteAfterObjectLockSnapshotBarrier::install(&bucket);
let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
let input = DeleteBatchInput {
bucket: bucket.clone(),
objects: (0..16)
.map(|_| DeleteBatchEntry {
key: "object".to_owned(),
..Default::default()
})
.collect(),
quiet: None,
};
let mut req = method_only_delete_envelope(Method::POST);
req.install_req_info(crate::storage::req_info::ReqInfo::default());
let delete = tokio::spawn(async move { usecase.execute_delete_objects(req, input).await });
tokio::time::timeout(tokio::time::Duration::from_secs(5), admission.wait_until_paused())
.await
.expect("a plain batch must reach storage admission without acquiring an advisory read lock");
drop(writer);
admission.release();
let response = tokio::time::timeout(tokio::time::Duration::from_secs(10), delete)
.await
.expect("delete finishes once the writer releases the key")
.expect("delete task joins")
.expect("delete returns per-entry results");
let deleted = response.deleted.expect("non-quiet delete");
assert_eq!(deleted.len(), 16);
assert!(
deleted
.iter()
.all(|entry| entry.delete_marker.unwrap_or_default() == suspended)
);
assert!(response.errors.is_none_or(|errors| errors.is_empty()));
let read = store
.get_object_reader(&bucket, "object", None, HeaderMap::new(), &ObjectOptions::default())
.await;
assert!(matches!(read, Err(ref error) if is_err_object_not_found(error) || is_err_version_not_found(error)));
store
.delete_bucket(
&bucket,
&DeleteBucketOptions {
force: suspended,
..Default::default()
},
)
.await
.expect("remove verification bucket");
}
}
#[tokio::test]
#[serial_test::serial]
async fn execute_delete_objects_rejects_bucket_recreated_before_publication_admission() {
@@ -3896,9 +3991,6 @@ mod tests {
});
}
// backlog#929 (HP-8): the pre-delete stat may only be skipped when every
// consumer of its result is provably idle. Each guard flips one condition
// to prove the skip is fenced on all four data dependencies.
fn delete_marker_creating_opts() -> ObjectOptions {
ObjectOptions {
version_id: None,
@@ -3910,12 +4002,12 @@ mod tests {
#[test]
fn delete_objects_pre_stat_skippable_for_delete_marker_on_plain_bucket() {
assert!(can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), true));
assert!(can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), true, false));
}
#[test]
fn delete_objects_pre_stat_kept_for_object_lock_buckets() {
assert!(!can_skip_delete_objects_pre_stat(true, &delete_marker_creating_opts(), true));
assert!(!can_skip_delete_objects_pre_stat(true, &delete_marker_creating_opts(), true, false));
}
#[test]
@@ -3926,39 +4018,50 @@ mod tests {
version_suspended: false,
..Default::default()
};
assert!(!can_skip_delete_objects_pre_stat(false, &opts, true));
assert!(!can_skip_delete_objects_pre_stat(false, &opts, true, false));
}
#[test]
fn delete_objects_pre_stat_kept_for_unversioned_buckets() {
// Unversioned deletes remove the current object: usage accounting needs
// the object size and ILM tier cleanup needs the transition metadata.
let opts = ObjectOptions {
version_id: None,
versioned: false,
version_suspended: false,
fn delete_objects_pre_stat_skips_plain_unversioned_entries() {
let opts = ObjectOptions::default();
assert!(can_skip_delete_objects_pre_stat(false, &opts, false, false));
assert!(!can_skip_delete_objects_pre_stat(true, &opts, false, false));
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false, true));
}
#[test]
fn delete_objects_pre_stat_keeps_unversioned_http_conditions_and_version_ids() {
let header_condition = ObjectOptions {
http_preconditions: Some(Default::default()),
..Default::default()
};
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false));
assert!(!can_skip_delete_objects_pre_stat(false, &header_condition, false, false));
for synthetic_version_id in [false, true] {
let version_address = ObjectOptions {
version_id: Some(Uuid::nil().to_string()),
synthetic_version_id,
..Default::default()
};
assert!(!can_skip_delete_objects_pre_stat(false, &version_address, false, false));
}
}
#[test]
fn delete_objects_pre_stat_kept_for_suspended_versioning() {
fn delete_objects_pre_stat_skips_plain_suspended_entries() {
let opts = ObjectOptions {
version_id: None,
versioned: true,
version_suspended: true,
..Default::default()
};
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false));
assert!(can_skip_delete_objects_pre_stat(false, &opts, false, false));
assert!(!can_skip_delete_objects_pre_stat(true, &opts, false, false));
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false, true));
}
#[test]
fn delete_objects_pre_stat_kept_when_accounting_snapshot_disagrees() {
// If the accounting-side versioning snapshot does not also classify the
// delete as a delete-marker creation, the stat must stay so usage
// accounting keeps its size input.
assert!(!can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), false));
// Keep the existing marker-specific skip tied to the accounting decision.
assert!(!can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), false, false));
}
#[test]
+15 -7
View File
@@ -32,7 +32,9 @@ use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
use time::OffsetDateTime;
use tracing::debug;
use super::super::storage_api::object_usecase::data_usage::load_bucket_usage_from_backend_cached;
use super::super::storage_api::object_usecase::data_usage::{
BucketUsagePendingReason, BucketUsageStatus, load_bucket_usage_certification_from_backend_cached,
};
use super::super::storage_api::object_usecase::{ECStore, StorageObjectInfo as ObjectInfo, check_preconditions};
use super::HTTPRangeSpec;
use super::shared::{LOG_COMPONENT_APP, LOG_SUBSYSTEM_OBJECT};
@@ -388,12 +390,17 @@ fn capacity_unavailable() -> S3Error {
}
async fn load_capacity_inputs(store: &Arc<ECStore>, bucket: &str, incarnation: Uuid) -> S3Result<CapacityInputs> {
let used_bucket = load_bucket_usage_from_backend_cached(Arc::clone(store), bucket, incarnation)
let used_bucket = match load_bucket_usage_certification_from_backend_cached(Arc::clone(store), bucket, incarnation)
.await
.map_err(|_| capacity_unavailable())?;
if used_bucket.is_none() {
log_usage_missing_once(bucket);
}
.map_err(|_| capacity_unavailable())?
{
BucketUsageStatus::Certified(bytes) => Some(bytes),
BucketUsageStatus::Pending(reason) => {
log_usage_missing_once(bucket, reason);
None
}
BucketUsageStatus::Unavailable(_) => return Err(capacity_unavailable()),
};
let (capacity_cluster, free_cluster) = cached_cluster_capacity(store).await?;
// The authoritative quota read also fences publication of the sampled capacity to this incarnation.
let (quota, quota_incarnation, _) = store.bucket_quota_and_incarnation_from_disk(bucket).await.map_err(|_| {
@@ -533,7 +540,7 @@ fn conservative_cluster_capacity(info: &rustfs_madmin::StorageInfo) -> Option<(u
Some((total, free))
}
fn log_usage_missing_once(bucket: &str) {
fn log_usage_missing_once(bucket: &str, reason: BucketUsagePendingReason) {
if LOGGED_USAGE_MISSING
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
.is_ok()
@@ -543,6 +550,7 @@ fn log_usage_missing_once(bucket: &str) {
component = LOG_COMPONENT_APP,
subsystem = LOG_SUBSYSTEM_OBJECT,
state = "snapshot_missing",
reason = ?reason,
bucket = %bucket,
"Veeam SOSAPI is reporting undefined bucket usage"
);
+11 -3
View File
@@ -1018,15 +1018,23 @@ fn veeam_sosapi_http_contract() {
assert_eq!(stale.status(), http::StatusCode::OK);
let stale_body = BodyExt::collect(stale.into_body()).await.expect("stale capacity body").to_bytes();
assert_eq!(element_text(std::str::from_utf8(&stale_body).unwrap(), "Used"), "-1");
let recycled_key = CapacityCacheKey { store_id: store.id, bucket: recycled.clone(), incarnation: new_id };
snapshot.last_update = Some(std::time::SystemTime::now() + Duration::from_secs(5));
snapshot.buckets_usage.get_mut(&recycled).expect("recycled bucket").bucket_incarnation = Some("invalid UUID".into());
crate::app::storage_api::test::data_usage::store_data_usage_in_backend(snapshot.clone(), Arc::clone(&store))
.await.expect("seed malformed incarnation proof");
caches.current.invalidate(&recycled_key).await;
for method in [Method::GET, Method::HEAD] {
let malformed = owner.call(owner_call(method, recycled_uri.clone(), Vec::new(), Bytes::new()))
.await.expect("malformed capacity");
assert_eq!(malformed.status(), http::StatusCode::SERVICE_UNAVAILABLE);
}
snapshot.last_update = Some(std::time::SystemTime::now() + Duration::from_secs(6));
snapshot.buckets_usage.get_mut(&recycled).unwrap().bucket_incarnation = Some(new_id.to_string());
snapshot.buckets_usage.get_mut(&recycled).unwrap().size = 17;
snapshot.bucket_sizes.insert(recycled.clone(), 17);
crate::app::storage_api::test::data_usage::store_data_usage_in_backend(snapshot, Arc::clone(&store))
.await.expect("seed new incarnation snapshot");
capacity_caches().current.invalidate(&CapacityCacheKey {
store_id: store.id, bucket: recycled.clone(), incarnation: new_id,
}).await;
let fresh = owner.call(owner_call(Method::GET, recycled_uri, Vec::new(), Bytes::new())).await.expect("new capacity");
assert_eq!(fresh.status(), http::StatusCode::OK);
let fresh_body = BodyExt::collect(fresh.into_body()).await.expect("new capacity body").to_bytes();
+11 -11
View File
@@ -14,8 +14,8 @@
//! GetObjectLegalHold: the legal hold status an object's metadata stores.
//!
//! Responsible for: reading the stored status, `OFF` when none is stored, on a bucket with Object
//! Lock enabled. A stored status outside the model's set is answered as stored.
//! Responsible for: reading the stored status on a bucket with Object Lock enabled. Missing hold
//! metadata produces `NoSuchObjectLockConfiguration`. Other statuses are answered as stored.
//! Also writes lock metadata to the requested version and schedules metadata replication.
//! NOT responsible for: authorization.
//! Upstream: both edges. Downstream: the object store and the bucket's Object Lock configuration.
@@ -154,9 +154,10 @@ impl ObjectMetaUsecase {
///
/// # Errors
///
/// `MethodNotAllowed` for a Veeam SOSAPI system object; `InternalError` before the store is up
/// or when the object cannot be read; `NoSuchBucket`; the Object Lock refusal of a bucket
/// without Object Lock.
/// `MethodNotAllowed` for a Veeam SOSAPI system object or an explicitly selected delete marker.
/// `NoSuchBucket`, `NoSuchKey`, or `NoSuchVersion` for a missing resource.
/// `InvalidRequest` if Object Lock is disabled and `NoSuchObjectLockConfiguration` if no hold
/// status is stored for the object version. Storage failures can return `InternalError`.
pub async fn execute_get_object_legal_hold(
&self,
envelope: RequestEnvelope,
@@ -180,18 +181,17 @@ impl ObjectMetaUsecase {
)
.suppress_event();
let store = self.store_outside_veeam_sosapi(bucket, key).await?;
store
.get_bucket_info(bucket, &BucketOptions::default())
.await
.map_err(ApiError::from)?;
let object_info = locked_object_info(&store, &envelope, bucket, key, version_id.clone()).await?;
let status = object_info
.user_defined
.get(AMZ_OBJECT_LOCK_LEGAL_HOLD_LOWER)
.map_or(Status::OFF, |status| Status::custom(status.clone()));
.filter(|status| !status.is_empty())
.ok_or_else(|| S3Error::new(S3ErrorCode::NoSuchObjectLockConfiguration))?;
let output = GetObjectLegalHoldOutput {
legal_hold: Some(ObjectLockLegalHold { status: Some(status) }),
legal_hold: Some(ObjectLockLegalHold {
status: Some(Status::custom(status.clone())),
}),
};
let version_id = version_id.unwrap_or_else(|| Uuid::new_v4().to_string());
+35 -17
View File
@@ -32,8 +32,8 @@ use crate::app::RequestEnvelope;
use crate::app::object::shared::reject_veeam_sosapi_mutation;
use crate::app::runtime_sources::{AppContext, current_object_store_handle_for_context};
use crate::app::storage_api::object_meta_usecase::contract::ObjectOperations as _;
use crate::app::storage_api::object_meta_usecase::validate_bucket_object_lock_enabled;
use crate::app::storage_api::object_usecase::error::is_err_version_not_found;
use crate::app::storage_api::object_meta_usecase::validate_bucket_object_lock_enabled_for_read;
use crate::app::storage_api::object_usecase::error::{StorageError, is_err_object_not_found, is_err_version_not_found};
use crate::app::storage_api::object_usecase::options::get_opts;
use crate::app::storage_api::object_usecase::{ECStore, StorageObjectInfo as ObjectInfo};
use crate::error::ApiError;
@@ -72,26 +72,44 @@ async fn locked_object_info(
key: &str,
version_id: Option<String>,
) -> S3Result<ObjectInfo> {
validate_bucket_object_lock_enabled(bucket).await?;
validate_bucket_object_lock_enabled_for_read(bucket).await?;
let explicit_version = version_id.is_some();
let opts = get_opts(bucket, key, version_id, None, envelope.headers())
.await
.map_err(ApiError::from)?;
store.get_object_info(bucket, key, &opts).await.map_err(|error| {
if explicit_version && is_err_version_not_found(&error) {
return ApiError::from(error).into();
let code = match store.get_object_info(bucket, key, &opts).await {
Ok(info) if !info.delete_marker => return Ok(info),
// A single pool can return the marker snapshot, while multi-pool lookup can reject it.
Ok(_) | Err(StorageError::MethodNotAllowed) => {
if explicit_version {
S3ErrorCode::MethodNotAllowed
} else {
S3ErrorCode::NoSuchKey
}
}
error!(
component = "storage",
subsystem = "object",
event = "object_info_load_failed",
bucket = %bucket,
object = %key,
error = %error,
"Failed to load object info"
);
s3_error!(InternalError, "{}", error.to_string())
})
Err(error) if is_err_object_not_found(&error) || is_err_version_not_found(&error) => {
if explicit_version {
S3ErrorCode::NoSuchVersion
} else {
S3ErrorCode::NoSuchKey
}
}
Err(StorageError::BucketNotFound(_) | StorageError::VolumeNotFound) => S3ErrorCode::NoSuchBucket,
Err(error) => {
error!(
component = "storage",
subsystem = "object",
event = "object_info_load_failed",
bucket = %bucket,
object = %key,
error = %error,
"Failed to load object info"
);
return Err(s3_error!(InternalError, "{}", error.to_string()));
}
};
let message = ApiError::error_code_to_message(&code);
Err(S3Error::with_message(code, message))
}
#[cfg(test)]
+20 -10
View File
@@ -181,9 +181,11 @@ impl ObjectMetaUsecase {
///
/// # Errors
///
/// `MethodNotAllowed` for a Veeam SOSAPI system object; `InternalError` before the store is up,
/// when the object cannot be read, or for a stored date outside the answerable range; the
/// Object Lock refusal of a bucket without Object Lock.
/// `MethodNotAllowed` for a Veeam SOSAPI system object or an explicitly selected delete marker.
/// `NoSuchBucket`, `NoSuchKey`, or `NoSuchVersion` for an absent resource.
/// `InvalidRequest` if Object Lock is disabled and `NoSuchObjectLockConfiguration` if no
/// retention is stored for the object version. Storage failures and out-of-range dates can
/// return `InternalError`.
pub async fn execute_get_object_retention(
&self,
envelope: RequestEnvelope,
@@ -220,14 +222,22 @@ impl ObjectMetaUsecase {
}
}
/// The retention `metadata` stores. An unparseable date is answered as absent, as before.
/// Decode stored retention, preserving a legacy mode even if its date cannot be parsed.
fn stored_retention(metadata: &HashMap<String, String>) -> S3Result<ObjectLockRetention> {
let mode = metadata
.get(AMZ_OBJECT_LOCK_MODE_LOWER)
.map(|mode| Mode::custom(mode.clone()));
let retain_until_date = metadata
let mode = metadata.get(AMZ_OBJECT_LOCK_MODE_LOWER).filter(|mode| !mode.is_empty());
let retain_until = metadata
.get(AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE_LOWER)
.and_then(|value| OffsetDateTime::parse(value, &Rfc3339).ok())
.filter(|date| !date.is_empty());
// PutObjectRetention clears both fields by storing empty strings.
if mode.is_none() && retain_until.is_none() {
return Err(S3Error::new(S3ErrorCode::NoSuchObjectLockConfiguration));
}
let parsed_date = match retain_until.map(|value| OffsetDateTime::parse(value, &Rfc3339)).transpose() {
Ok(date) => date,
Err(_) if mode.is_some() => None,
Err(_) => return Err(S3Error::with_message(S3ErrorCode::InternalError, "Stored retention date is invalid")),
};
let retain_until_date = parsed_date
.map(|date| {
date.checked_to_offset(time::UtcOffset::UTC)
.filter(|date| (0..=9999).contains(&date.year()))
@@ -241,7 +251,7 @@ fn stored_retention(metadata: &HashMap<String, String>) -> S3Result<ObjectLockRe
})
.transpose()?;
Ok(ObjectLockRetention {
mode,
mode: mode.map(|mode| Mode::custom(mode.clone())),
retain_until_date,
..Default::default()
})
+15 -5
View File
@@ -89,12 +89,19 @@ pub(crate) mod data_usage {
crate::storage::storage_api::ecstore_data_usage::load_admin_data_usage_with_memory_overlay(store).await
}
pub(crate) async fn load_bucket_usage_from_backend_cached(
pub(crate) use crate::storage::storage_api::ecstore_data_usage::{BucketUsagePendingReason, BucketUsageStatus};
pub(crate) async fn load_bucket_usage_certification_from_backend_cached(
store: Arc<crate::storage::storage_api::ECStore>,
bucket: &str,
incarnation: uuid::Uuid,
) -> Result<Option<u64>, crate::storage::storage_api::StorageError> {
crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_from_backend_cached(store, bucket, incarnation).await
) -> Result<BucketUsageStatus, crate::storage::storage_api::StorageError> {
crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_certification_from_backend_cached(
store,
bucket,
incarnation,
)
.await
}
#[cfg(test)]
@@ -1728,7 +1735,8 @@ pub(crate) mod object_meta_usecase {
pub(crate) use crate::storage::storage_api::check_retention_for_modification;
pub(crate) use crate::storage::storage_api::ecfs_consumer::object_lock::{
load_bucket_object_lock_config_state, validate_bucket_object_lock_enabled, validate_bucket_object_lock_enabled_state,
load_bucket_object_lock_config_state, validate_bucket_object_lock_enabled, validate_bucket_object_lock_enabled_for_read,
validate_bucket_object_lock_enabled_state,
};
pub(crate) use crate::storage::storage_api::ecstore_bucket::metadata::validate_tag_set_entries;
pub(crate) use crate::storage::storage_api::ecstore_bucket::tagging::{
@@ -1871,7 +1879,9 @@ pub(crate) mod test {
}
pub(crate) use crate::storage::storage_api::bootstrap_instance_ctx;
pub(crate) use crate::storage::storage_api::ecstore_bucket::install_all_v6_fleet_capability_proof;
pub(crate) use crate::storage::storage_api::test_consumer::{get_global_bucket_metadata_sys, set_bucket_metadata};
pub(crate) use crate::storage::storage_api::test_consumer::{
DeleteAfterObjectLockSnapshotBarrier, get_global_bucket_metadata_sys, set_bucket_metadata,
};
pub(crate) use crate::storage::storage_api::{
ECStore, Endpoint, Endpoints, PoolEndpoints, StorageObjectInfo, StorageObjectOptions, StoragePutObjReader,
};
+283 -36
View File
@@ -302,6 +302,23 @@ struct RpcRequestTarget {
method: Method,
}
/// Set by `check_auth` once the caller's internode request HMAC has been verified.
///
/// Boot-epoch and capability response proofs are HMACs keyed with the internode RPC secret over
/// caller-known values, so `RpcRequestPathService` only emits them when this marker is raised.
#[derive(Clone, Debug, Default)]
struct RpcSignatureVerified(Arc<AtomicBool>);
impl RpcSignatureVerified {
fn mark_verified(&self) {
self.0.store(true, Ordering::Release);
}
fn is_verified(&self) -> bool {
self.0.load(Ordering::Acquire)
}
}
#[derive(Clone)]
struct RpcRequestPathService<S> {
inner: S,
@@ -434,22 +451,10 @@ where
method: req.method().clone(),
};
req.extensions_mut().insert(target);
let signature_verified = RpcSignatureVerified::default();
req.extensions_mut().insert(signature_verified.clone());
let msgpack_manifest_capability_requested = storage::tonic_msgpack_manifest_capability_requested(req.headers());
let response_headers = tonic_boot_epoch_challenge(req.headers())
.ok()
.flatten()
.and_then(|challenge| {
storage::try_current_local_node_name()
.and_then(|node| normalize_tonic_rpc_audience(&node).ok())
.and_then(|audience| {
storage::tonic_boot_epoch_response_headers_with_msgpack_capability(
&audience,
challenge,
msgpack_manifest_capability_requested,
)
.ok()
})
});
let challenge = tonic_boot_epoch_challenge(req.headers()).ok().flatten();
let future = self.inner.call(req);
Box::pin(async move {
let mut response = storage::with_remote_background_io(resource_context, async move {
@@ -463,6 +468,20 @@ where
result
})
.await?;
// Answer the challenge only after `check_auth` verified the caller's request HMAC.
// Unauthenticated, forged, or unrouted requests must never receive secret-keyed proofs.
let response_headers = challenge.filter(|_| signature_verified.is_verified()).and_then(|challenge| {
storage::try_current_local_node_name()
.and_then(|node| normalize_tonic_rpc_audience(&node).ok())
.and_then(|audience| {
storage::tonic_boot_epoch_response_headers_with_msgpack_capability(
&audience,
challenge,
msgpack_manifest_capability_requested,
)
.ok()
})
});
if let Some(headers) = response_headers {
response.headers_mut().extend(headers);
}
@@ -3636,6 +3655,34 @@ fn hyper_body_write_close_kind(debug: &str) -> Option<&'static str> {
}
}
fn mark_rpc_signature_verified(req: &Request<()>) {
if let Some(verified) = req.extensions().get::<RpcSignatureVerified>() {
verified.mark_verified();
}
}
/// Whether an error from `verify_tonic_rpc_signature_with_bootstrap` was raised only after the
/// caller's request HMAC verified.
///
/// Only post-HMAC rejections may receive secret-keyed boot-epoch and capability proofs so cluster
/// restart recovery, strict replay-scope bootstrap, and replay-cache overload retries keep working
/// without emitting secret-keyed proofs to unauthenticated callers.
fn rpc_auth_failure_verified_signature(error: &std::io::Error, failure_reason: &str) -> bool {
storage::rpc_auth_is_resource_exhausted(error)
|| matches!(
failure_reason,
"stale_boot_epoch"
| "replay_scope_required"
| "replay_detected"
| "replay_cache_capacity"
| "replay_cache_memory"
| "replay_cache_allocation"
| "replay_cache_unavailable"
| "replay_expiry_overflow"
| "timestamp_expired_after_clock_regression"
)
}
fn rpc_auth_failure_status(error: &std::io::Error) -> Status {
if storage::rpc_auth_is_resource_exhausted(error) {
crate::error::rpc_replay_admission_exhausted_status()
@@ -3697,6 +3744,9 @@ fn check_auth(req: Request<()>) -> std::result::Result<Request<()>, Status> {
.map(|addr| addr.0.to_string())
.unwrap_or_else(|| "unknown".to_string());
let failure_reason = storage::tonic_rpc_auth_failure_reason(&e);
if rpc_auth_failure_verified_signature(&e, failure_reason) {
mark_rpc_signature_verified(&req);
}
let operation = match rpc_method {
"ReadAll" => INTERNODE_OPERATION_GRPC_READ_ALL,
"ReadMultiple" => INTERNODE_OPERATION_GRPC_READ_MULTIPLE,
@@ -3753,6 +3803,7 @@ fn check_auth(req: Request<()>) -> std::result::Result<Request<()>, Status> {
rejection
}
})?;
mark_rpc_signature_verified(&req);
if storage::rpc_background_admission(req.metadata().as_ref())
.map_err(|_| Status::unauthenticated("Invalid background admission request"))?
@@ -8591,30 +8642,40 @@ mod tests {
let audience = "127.0.0.1:9000";
rustfs_common::set_global_local_node_name(audience).await;
let challenge = uuid::Uuid::new_v4();
let node = InterceptedService::new(NodeServiceServer::new(make_server()), check_auth);
let service = RpcRequestPathService::new(Routes::new(node).prepare());
let response_for = |request_capability: bool| async move {
let mut request = HttpRequest::builder()
.method(Method::POST)
.uri("/node_service.NodeService/Ping")
.body(())
.expect("capability request");
request.headers_mut().insert(
"x-rustfs-rpc-boot-epoch-challenge",
challenge.to_string().parse().expect("challenge header"),
);
if request_capability {
let response_for = |signed: bool, request_capability: bool| {
let mut service = service.clone();
async move {
let mut request = HttpRequest::builder()
.method(Method::POST)
.uri(format!("http://{audience}/node_service.NodeService/Ping"))
.header("content-type", "application/grpc")
.body(Empty::<Bytes>::new())
.expect("capability request");
if signed {
let auth = storage::gen_tonic_signature_headers(audience, "node_service.NodeService", "Ping", None)
.expect("signed capability request");
request.headers_mut().extend(auth);
}
request.headers_mut().insert(
"x-rustfs-rpc-msgpack-manifest-request",
HeaderValue::from_static("msgpack-compat-manifest-v1"),
"x-rustfs-rpc-boot-epoch-challenge",
challenge.to_string().parse().expect("challenge header"),
);
if request_capability {
request.headers_mut().insert(
"x-rustfs-rpc-msgpack-manifest-request",
HeaderValue::from_static("msgpack-compat-manifest-v1"),
);
}
service.call(request).await.expect("capability response")
}
RpcRequestPathService::new(RpcPathObserver)
.call(request)
.await
.expect("capability response")
};
let legacy = response_for(false).await;
let legacy = response_for(true, false).await;
storage::verify_tonic_boot_epoch_response(audience, challenge, legacy.headers())
.expect("signed legacy request must still receive boot-epoch proof");
assert!(!legacy.headers().contains_key("x-rustfs-rpc-msgpack-manifest-capability"));
assert!(
!legacy
@@ -8622,7 +8683,9 @@ mod tests {
.contains_key("x-rustfs-rpc-msgpack-manifest-capability-proof")
);
let capable = response_for(true).await;
let capable = response_for(true, true).await;
storage::verify_tonic_boot_epoch_response(audience, challenge, capable.headers())
.expect("signed capable request must receive boot-epoch proof");
assert_eq!(
capable
.headers()
@@ -8636,6 +8699,18 @@ mod tests {
.contains_key("x-rustfs-rpc-msgpack-manifest-capability-proof")
);
let unsigned = response_for(false, true).await;
for name in [
"x-rustfs-rpc-boot-epoch",
"x-rustfs-rpc-boot-epoch-proof",
"x-rustfs-rpc-replay-cache-capability",
"x-rustfs-rpc-replay-cache-capability-proof",
"x-rustfs-rpc-msgpack-manifest-capability",
"x-rustfs-rpc-msgpack-manifest-capability-proof",
] {
assert!(!unsigned.headers().contains_key(name), "unsigned request must not receive {name}");
}
rustfs_common::set_global_local_node_name(&previous_node_name).await;
}
@@ -9614,6 +9689,178 @@ mod tests {
);
}
#[test]
fn rpc_auth_failure_verified_signature_classifies_post_hmac_errors_only() {
for error in [
std::io::Error::new(std::io::ErrorKind::WouldBlock, storage::RpcReplayCacheAdmissionError::Capacity),
std::io::Error::new(std::io::ErrorKind::WouldBlock, storage::RpcReplayCacheAdmissionError::MemoryBudget),
std::io::Error::new(std::io::ErrorKind::OutOfMemory, "replay cache allocation failed"),
std::io::Error::other("RPC boot epoch is stale"),
std::io::Error::other("RPC replay-scoped authentication required"),
std::io::Error::other("RPC request replay detected"),
std::io::Error::other("RPC replay cache unavailable"),
std::io::Error::other("RPC request timestamp expired after clock regression"),
] {
let reason = storage::tonic_rpc_auth_failure_reason(&error);
assert!(
rpc_auth_failure_verified_signature(&error, reason),
"post-HMAC error ({reason}) must allow boot-epoch/capability proofs"
);
}
for error in [
std::io::Error::other("Missing signature header"),
std::io::Error::other("Invalid signature"),
std::io::Error::other("RPC v2 authentication required"),
std::io::Error::other("Invalid RPC v2 signature"),
std::io::Error::other("Invalid RPC replay scope signature"),
std::io::Error::other("Request timestamp expired"),
std::io::Error::other("Missing RPC boot epoch"),
std::io::Error::other("RPC background admission requires v2 authentication"),
std::io::Error::other("opaque failure"),
] {
let reason = storage::tonic_rpc_auth_failure_reason(&error);
assert!(
!rpc_auth_failure_verified_signature(&error, reason),
"pre-HMAC error ({reason}) must never receive boot-epoch/capability proofs"
);
}
}
#[tokio::test]
#[serial_test::serial]
async fn rpc_boot_epoch_proof_requires_verified_request_signature() {
let _ = rustfs_credentials::set_global_rpc_secret("rpc-http-test-secret".to_string());
let previous_node_name = rustfs_common::get_global_local_node_name().await;
let audience = "127.0.0.1:9000";
let ping = "/node_service.NodeService/Ping";
let read_all = "/node_service.NodeService/ReadAll";
rustfs_common::set_global_local_node_name(audience).await;
let node = InterceptedService::new(NodeServiceServer::new(make_server()), check_auth);
let mut service = RpcRequestPathService::new(Routes::new(node).prepare());
let epoch_probe_challenge = uuid::Uuid::new_v4();
let current_epoch = storage::verify_tonic_boot_epoch_response(
audience,
epoch_probe_challenge,
&storage::tonic_boot_epoch_response_headers(audience, epoch_probe_challenge).expect("current epoch proof"),
)
.expect("current boot epoch");
let stale_epoch = uuid::Uuid::from_u128(current_epoch.as_u128() ^ 1);
let signed_v2 = storage::gen_tonic_signature_headers(audience, "node_service.NodeService", "Ping", None)
.expect("method-bound signature");
let mut signed_v3_current = signed_v2.clone();
signed_v3_current.extend(
storage::gen_tonic_replay_scope_headers(
audience,
ping,
signed_v2["x-rustfs-timestamp"].to_str().expect("timestamp"),
signed_v2["x-rustfs-content-sha256"].to_str().expect("body digest"),
current_epoch,
)
.expect("current-epoch replay-scoped signature"),
);
let signed_v3_replay = signed_v3_current.clone();
let mut signed_v3_stale = signed_v2.clone();
signed_v3_stale.extend(
storage::gen_tonic_replay_scope_headers(
audience,
ping,
signed_v2["x-rustfs-timestamp"].to_str().expect("timestamp"),
signed_v2["x-rustfs-content-sha256"].to_str().expect("body digest"),
stale_epoch,
)
.expect("stale-epoch replay-scoped signature"),
);
let mut forged_v2 = signed_v2.clone();
forged_v2.insert("x-rustfs-rpc-signature-v2", HeaderValue::from_static("invalid"));
let mut forged_v3 = signed_v3_stale.clone();
forged_v3.insert("x-rustfs-rpc-signature-v3", HeaderValue::from_static("invalid"));
let cross_method = signed_v2.clone();
let unrouted_signed = signed_v2.clone();
for (label, path, headers, expect_proof) in [
("signed v2 ping", ping, signed_v2, true),
("signed v3 current epoch ping", ping, signed_v3_current, true),
("replayed signed v3 ping", ping, signed_v3_replay, true),
("signed v3 stale epoch ping", ping, signed_v3_stale, true),
("forged v2 ping", ping, forged_v2, false),
("forged v3 ping", ping, forged_v3, false),
("cross-method v2 read_all", read_all, cross_method, false),
("unsigned ping", ping, HeaderMap::new(), false),
("unrouted unsigned", "/unrouted.Service/Method", HeaderMap::new(), false),
("unrouted signed", "/unrouted.Service/Method", unrouted_signed, false),
] {
let challenge = uuid::Uuid::new_v4();
let mut request = HttpRequest::builder()
.method(Method::POST)
.uri(format!("http://{audience}{path}"))
.header("content-type", "application/grpc")
.header("x-rustfs-rpc-boot-epoch-challenge", challenge.to_string())
.header("x-rustfs-rpc-msgpack-manifest-request", "msgpack-compat-manifest-v1")
.body(Empty::<Bytes>::new())
.expect("request");
request.headers_mut().extend(headers);
let response = service.call(request).await.expect("response");
if expect_proof {
let verified_epoch = storage::verify_tonic_boot_epoch_response(audience, challenge, response.headers())
.unwrap_or_else(|err| panic!("{label} must receive verifiable boot-epoch proof: {err}"));
assert_eq!(verified_epoch, current_epoch, "{label} must return current boot epoch");
assert!(
response.headers().contains_key("x-rustfs-rpc-replay-cache-capability-proof"),
"{label} must receive replay-cache capability proof"
);
assert!(
response
.headers()
.contains_key("x-rustfs-rpc-msgpack-manifest-capability-proof"),
"{label} must receive requested msgpack capability proof"
);
continue;
}
for name in [
"x-rustfs-rpc-boot-epoch",
"x-rustfs-rpc-boot-epoch-proof",
"x-rustfs-rpc-replay-cache-capability",
"x-rustfs-rpc-replay-cache-capability-proof",
"x-rustfs-rpc-msgpack-manifest-capability",
"x-rustfs-rpc-msgpack-manifest-capability-proof",
] {
assert!(
!response.headers().contains_key(name),
"{label} ({path}) must not return {name} to an unverified caller"
);
}
}
// Verify that a post-HMAC ResourceExhausted rejection from background admission still
// raises `RpcSignatureVerified` so the peer does not falsely revoke capabilities.
let bg_owner = rustfs_concurrency::adaptive::NodeAdmission::new(std::num::NonZeroU16::MIN);
let bg_headers = storage::with_remote_background_io(Some(storage::RemoteBackgroundIo::new(bg_owner)), async {
storage::gen_tonic_signature_headers(audience, "node_service.NodeService", "ReadAll", None)
})
.await
.expect("signed background RPC headers");
let verified_marker = RpcSignatureVerified::default();
let mut bg_request = Request::new(());
bg_request.metadata_mut().as_mut().extend(bg_headers);
bg_request.extensions_mut().insert(RpcRequestTarget {
uri: format!("http://{audience}{read_all}").parse().expect("RPC URI"),
method: Method::POST,
});
bg_request.extensions_mut().insert(verified_marker.clone());
let bg_error = check_auth(bg_request).expect_err("background request without admission token must reject");
assert_eq!(bg_error.code(), tonic::Code::ResourceExhausted);
assert!(
verified_marker.is_verified(),
"post-HMAC ResourceExhausted rejection must still mark RpcSignatureVerified"
);
rustfs_common::set_global_local_node_name(&previous_node_name).await;
}
#[tokio::test]
#[serial_test::serial]
async fn rpc_auth_rejection_records_failure_reason_metric() {
@@ -10137,7 +10384,7 @@ mod tests {
assert_eq!(info.real_ip, peer.ip());
assert_eq!(info.forwarded_proto.as_deref(), Some("https"));
let identity = rustfs_keystone::KEYSTONE_CREDENTIALS.try_with(Clone::clone).ok().flatten().map(|credentials| credentials.parent_user).unwrap_or_else(|| "anonymous".to_owned());
if request.headers().contains_key("x-auth-token") { assert_eq!(identity, "test-user"); }
if request.headers().contains_key("x-auth-token") { assert_eq!(identity, "keystone:user-id"); }
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(Response::new(HybridBody::<EdgeBody, http_body_util::Empty<Bytes>>::Rest { rest_body: EdgeBody::from(Bytes::from(identity)) }))
});
let inner = Http3CoreService::new(inner);
@@ -10153,7 +10400,7 @@ mod tests {
assert_eq!(request(&mut client, HttpRequest::builder().uri("https://localhost/bucket/key").header("x-auth-token", "invalid-token").body(())?, Bytes::new()).await?.0, http::StatusCode::UNAUTHORIZED);
let (status, headers, body) = request(&mut client, HttpRequest::builder().uri("https://localhost/bucket/key").header("x-auth-token", "valid-token").header("x-forwarded-for", "203.0.113.1").body(())?, Bytes::new()).await?;
assert_eq!(status, http::StatusCode::OK);
assert_eq!(body, "test-user");
assert_eq!(body, "keystone:user-id");
assert!(headers.contains_key("x-amz-request-id"), "request context must survive HTTP/3 dispatch");
assert_eq!(request(&mut client, make_request()?, Bytes::new()).await?.2, "anonymous", "Keystone task-local credentials must not leak between streams");
assert_eq!(request(&mut client, make_request()?, Bytes::new()).await?.0, http::StatusCode::TOO_MANY_REQUESTS);
+53 -4
View File
@@ -25,7 +25,9 @@ use crate::{
startup_preflight::{StartupServerPreflightError, bootstrap_external_prefix_compat, init_startup_server_preflight},
startup_server::{StartupHttpServers, StartupListenContext, init_startup_http_servers, init_startup_listen_context},
startup_services::init_startup_runtime_services,
startup_storage::{StartupStorageRuntime, init_startup_storage_foundation, init_startup_storage_runtime},
startup_storage::{
StartupEndpointDiscoveryTimeout, StartupStorageRuntime, init_startup_storage_foundation, init_startup_storage_runtime,
},
storage_api::server::http::ServerContextSlot,
storage_api::startup::storage::bootstrap_instance_ctx,
};
@@ -129,12 +131,27 @@ fn run_process_on_current_thread(#[cfg(feature = "internode-transport")] build:
} else {
ExitCode::SUCCESS
};
drop(result);
// block_on has left its entered scope; the startup thread owns teardown.
drop(runtime);
shutdown_process_runtime(runtime, result);
exit_code
}
fn shutdown_process_runtime(runtime: tokio::runtime::Runtime, result: Result<()>) {
let endpoint_discovery_timed_out = result
.as_ref()
.err()
.and_then(Error::get_ref)
.is_some_and(|source| source.is::<StartupEndpointDiscoveryTimeout>());
drop(result);
// The topology timed out before publishing disks or opening listeners. A
// system DNS call may still be running on the blocking pool after cancellation.
if endpoint_discovery_timed_out {
runtime.shutdown_background();
} else {
drop(runtime);
}
}
fn format_fatal_stderr_message(context: &str, error: impl std::fmt::Display) -> String {
format!("[FATAL] {context}: {error}")
}
@@ -2186,6 +2203,38 @@ mod tests {
}
}
#[test]
fn endpoint_discovery_timeout_does_not_wait_for_a_blocking_resolver() {
std::thread::scope(|scope| {
let (started, wait_for_start) = std::sync::mpsc::channel();
let (release, wait_for_release) = std::sync::mpsc::channel::<()>();
let (stopped, wait_for_stop) = std::sync::mpsc::channel();
let (completed, wait_for_completion) = std::sync::mpsc::channel();
scope.spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("create owned startup runtime");
runtime.spawn_blocking(move || {
started.send(()).expect("report resolver start");
let _ = wait_for_release.recv();
completed.send(()).expect("report resolver completion");
});
wait_for_start.recv_timeout(Duration::from_secs(5)).expect("resolver started");
let err = Error::new(std::io::ErrorKind::TimedOut, "startup DNS deadline elapsed");
shutdown_process_runtime(runtime, Err(Error::other(StartupEndpointDiscoveryTimeout(err))));
let _ = stopped.send(());
});
let before_release = wait_for_stop.recv_timeout(Duration::from_secs(5));
drop(release);
wait_for_completion
.recv_timeout(Duration::from_secs(5))
.expect("resolver completed");
before_release.expect("startup shutdown must return while the resolver is still blocked");
});
}
#[test]
fn startup_thread_propagates_panics() {
let result = std::panic::catch_unwind(|| run_on_startup_thread(|| panic!("startup thread panic")));

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