Compare commits

...

5 Commits

Author SHA1 Message Date
Ramakrishna Chilaka d429c6f792 perf(ecstore,rio,utils): accelerate MD5 ETag hashing and SWAR disk path checks (#9110) 2026-11-02 01:02:26 +08:00
hector e494dc2b4b ci(validation): sweep the migrated canonical validation cases nightly (#9107)
* ci(validation): sweep the migrated canonical validation cases nightly

The canonical release-validation cases migrated into auto-testing by
rustfs/auto-testing#113 (66 implemented, all non-heal) currently run
only through the manual validation flow; the last fleet executions
stopped on 2026-10-27 and nothing schedules them. Add a scheduled
validation sweep that closes the gap:

- nightly at 19:30 UTC (after the functional chain settles), rotating
  windows of the implemented catalog cases so the whole catalog is
  covered roughly weekly, with a bounded batch per night
- workflow_dispatch for a single case (--case), one module (--module),
  or an explicit batch (--limit), mirroring how the lanes are testable
  standalone
- fleet admission through functional_environment enter/finish with the
  same quarantine discipline as the lanes, inter-case node cleanup,
  per-case logs + reports retained as a sweep artifact
- a markdown sweep report uploaded to rustfs/dashboard under
  functional-reports/validation/ so the cases appear next to the lane
  reports, plus an alert-on-failure job for scheduled runs
- heal.* cases stay on the interactive validation flow: many need the
  reviewed native/tool collectors built by separate validation-tools
  runs before fleet execution

The registry gains the workflow responsibility (monitor: workflow,
max-age 60h so the watchdog notices a dead sweep) and the wiring test
baseline count moves with it.

Verified locally: check_wiring, check_test_wiring, test_validation_registry
(9/9), test_functional_chain + test_functional_chain_health +
test_security_workflow (99/99).

* ci(validation): group the sweep report by catalog module

The validation cases cover distinct areas (pool lifecycle, ILM
expiration, bucket/site replication, kms, data services, identity,
s3 compatibility), so a flat case table hides the category breakdown.
Render one section per catalog module with its own case table and a
Subtotal line, and keep the single grand - Total:/- PASS:/- FAIL:
block for the dashboard overview parser. Subtotals deliberately use
a different bullet prefix so the overview regexes cannot mistake a
module subtotal for the grand total.

* ci(validation): sweep the eight planned cases whose executors exist

The planned catalog entries are not all unimplemented: all eight
(kms.sse-kms-round-trip, tiering.transition-and-restore,
events.delivery, audit.request-correlation, iam.policy-enforcement,
oidc.login-and-session, s3.basic-object-round-trip and
scanner.usage-convergence) have dedicated executors routed in
run_validation_case.sh and live PASS evidence recorded in the
migration map. Widen the sweep filter to include them: the rotating
nightly batch now covers 74 cases (66 implemented + these 8), and the
fresh evidence each sweep produces feeds their acceptance review.
heal.* procedure-ready cases remain excluded - their executors need
the reviewed native/tool collectors built by separate
validation-tools runs before fleet execution.

---------

Co-authored-by: Hauser Zhi <housemecn@gmail.com>
2026-11-01 21:53:00 +08:00
Hauser Zhi 2b7c927ee8 perf(s3): streamline conditional multipart preflight (#9099)
* perf(s3): streamline conditional multipart preflight

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

* test(e2e): isolate mc mirror fixture in full suite

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

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

* test(connect): isolate cleanup deadline fixtures

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

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

* test(ecstore): avoid lock cleanup refcount race

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

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

* fix(ecstore): defer decommission lookup lock loss

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

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

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
2026-11-01 18:59:57 +08:00
Hauser Zhi 647846956f chore(deps): update flake.lock (#9108)
Flake lock file updates:

• Updated input 'nixpkgs':
    'github:NixOS/nixpkgs/674a202' (2026-10-24)
  → 'github:NixOS/nixpkgs/a078812' (2026-10-31)
• Updated input 'rust-overlay':
    'github:oxalica/rust-overlay/5b9f119' (2026-10-24)
  → 'github:oxalica/rust-overlay/6ecf534' (2026-10-31)
2026-11-01 06:26:39 +00:00
GatewayJ 04690f7da5 fix(s3-tables): clean empty catalogs and cache registration reads (#9063)
* fix(s3-tables): clean up empty tables and parallelize catalog reads

* fix(s3-tables): bound catalog registration index reads

* fix(s3-tables): cache validated registration ownership in memory
2026-11-01 04:49:50 +00:00
43 changed files with 5342 additions and 274 deletions
+8 -2
View File
@@ -234,7 +234,7 @@ test-group = 'embedded-test-ports'
# processes cannot exhaust those budgets. Keep deadlines and assertions intact.
# The short HTTP fixtures are tracked in rustfs/backlog#2714.
[[profile.default.overrides]]
filter = 'package(rustfs) & (binary(/^connect_registration$/) | binary(connect_inventory) | binary(connect_perf_drive) | (binary(connect_perf_client) & test(=configured_proxy_and_direct_endpoint_failures_are_distinct)) | (binary(connect_perf_object) & test(/^(real_rustfs_endpoint_and_production_cli_support_bounded_get_and_put|cleanup_uses_a_budget_independent_of_the_measurement_window|oversized_response_is_rejected_without_buffering_it)$/)))'
filter = 'package(rustfs) & (binary(/^connect_registration$/) | binary(connect_inventory) | binary(connect_perf_drive) | (binary(connect_perf_client) & test(=configured_proxy_and_direct_endpoint_failures_are_distinct)) | (binary(connect_perf_object) & test(/^(real_rustfs_endpoint_and_production_cli_support_bounded_get_and_put|cleanup_uses_a_budget_independent_of_the_measurement_window|cleanup_accepts_missing_object_and_still_deletes_the_bucket|cleanup_diagnostics_identify_each_disconnected_transport_stage|cleanup_diagnostics_identify_each_failed_http_stage_without_private_context|cleanup_diagnostics_identify_timeouts_without_resetting_the_shared_deadline|oversized_response_is_rejected_without_buffering_it)$/)))'
threads-required = "num-test-threads"
# This cancellation probe hashes the serving executable before acquiring its
@@ -548,7 +548,7 @@ filter = 'package(rustfs) & (binary(/^embedded.*_test$/) | binary(admin_diagnost
test-group = 'embedded-test-ports'
[[profile.ci.overrides]]
filter = 'package(rustfs) & (binary(/^connect_registration$/) | binary(connect_inventory) | binary(connect_perf_drive) | (binary(connect_perf_client) & test(=configured_proxy_and_direct_endpoint_failures_are_distinct)) | (binary(connect_perf_object) & test(/^(real_rustfs_endpoint_and_production_cli_support_bounded_get_and_put|cleanup_uses_a_budget_independent_of_the_measurement_window|oversized_response_is_rejected_without_buffering_it)$/)))'
filter = 'package(rustfs) & (binary(/^connect_registration$/) | binary(connect_inventory) | binary(connect_perf_drive) | (binary(connect_perf_client) & test(=configured_proxy_and_direct_endpoint_failures_are_distinct)) | (binary(connect_perf_object) & test(/^(real_rustfs_endpoint_and_production_cli_support_bounded_get_and_put|cleanup_uses_a_budget_independent_of_the_measurement_window|cleanup_accepts_missing_object_and_still_deletes_the_bucket|cleanup_diagnostics_identify_each_disconnected_transport_stage|cleanup_diagnostics_identify_each_failed_http_stage_without_private_context|cleanup_diagnostics_identify_timeouts_without_resetting_the_shared_deadline|oversized_response_is_rejected_without_buffering_it)$/)))'
threads-required = "num-test-threads"
# Preserve the cancellation probe's startup budget and assertions in CI too.
@@ -976,6 +976,12 @@ test-group = 'e2e-vault'
filter = 'package(e2e_test) & (test(/^list_objects_v2_pagination_test::tests::(test_list_objects_v2_delimiter_small_page_traverses_all|test_list_objects_v2_max_keys_above_limit_returns_token|test_list_objects_v2_maxkeys_above_limit_with_delimiter)$/) | test(=reliant::tiering::test_hermetic_transition_restore_failure_expiry_and_retry))'
threads-required = "num-test-threads"
# The mc fixture uploads hundreds of objects concurrently before measuring listing.
# Reserve the runner so other server fixtures do not starve its disk operations.
[[profile.e2e-full.overrides]]
filter = 'package(e2e_test) & test(=mc_mirror_small_bucket_test::test_mc_mirror_small_bucket_completes_without_list_timeout)'
threads-required = "num-test-threads"
# Fixed, small contract for every executable server change. These existing
# scenarios exercise write/read, anonymous denial and retained bytes on restart.
[profile.core-contract]
+26
View File
@@ -296,6 +296,32 @@
"origin": "baseline",
"alert_contract": "scheduled-validation"
},
{
"workflow": ".github/workflows/rustfs-validation-sweep.yml",
"name": "RustFS Validation Sweep",
"roles": [
"periodic",
"manual"
],
"events": [
"schedule",
"workflow_dispatch"
],
"cadence": "nightly",
"timezone": "UTC",
"schedule": [
"30 19 * * *"
],
"owner": "@overtrue",
"policy": "active",
"monitor": "workflow",
"max_age_hours": 60,
"result_owner": "rustfs-validation-sweep.yml",
"disposition": "canonical validation cases executed in rotating batches",
"failure_owner": "workflow",
"origin": "baseline",
"alert_contract": "scheduled-validation"
},
{
"workflow": ".github/workflows/btf-prototype-reference.yml",
"name": "BTF prototype reference",
@@ -0,0 +1,421 @@
# 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.
name: RustFS Validation Sweep
# Executes the migrated canonical validation cases (rustfs/auto-testing#113)
# on the shared functional fleet. Everything with a lane executor is swept in
# rotating nightly batches so the whole set is covered roughly weekly; a
# single case or one module can be dispatched manually. That is the
# implemented catalog (66 today) plus the eight planned cases whose dedicated
# executors already exist and have live PASS evidence - fresh nightly
# evidence feeds their acceptance review. heal.* cases stay on the
# interactive validation flow: they require reviewed native/tool collectors
# built by separate validation-tools runs before fleet execution.
on:
schedule:
# After the nightly functional chain settles (chain starts ~16:48 UTC and
# runs for about two hours).
- cron: "30 19 * * *"
workflow_dispatch:
inputs:
case:
description: 'Single canonical validation case id (overrides module and rotation), e.g. pool.decommission'
type: string
required: false
default: ''
module:
description: 'Restrict the sweep to one catalog module, e.g. bucket-replication'
type: string
required: false
default: ''
limit:
description: 'Maximum cases per sweep (0 = run everything selected)'
type: number
required: false
default: 12
build_run_id:
description: 'Successful nightly package run; empty resolves the latest'
type: string
required: false
default: ''
build_run_attempt:
description: 'Attempt of that package run'
type: string
required: false
default: '1'
permissions:
contents: read
concurrency:
group: rustfs-validation-sweep
cancel-in-progress: false
env:
RUSTFS_NODES: ${{ secrets.RUSTFS_NODES || vars.RUSTFS_NODES || 'vm000 vm001 vm002 vm003' }}
RUSTFS_SSH_USER: ${{ secrets.RUSTFS_SSH_USER || vars.RUSTFS_SSH_USER || 'azureuser' }}
RUSTFS_ACCESS_KEY: ${{ secrets.RUSTFS_ACCESS_KEY }}
RUSTFS_SECRET_KEY: ${{ secrets.RUSTFS_SECRET_KEY }}
RUSTFS_NIGHTLY_PACKAGE_URL: ${{ vars.RUSTFS_NIGHTLY_PACKAGE_URL || 'https://dl.rustfs.com/artifacts/rustfs/packages/nightly/rustfs-nightly-latest.deb' }}
PF_TESTING_GH_TOKEN: ${{ secrets.PF_TESTING_GH_TOKEN }}
jobs:
sweep:
if: github.repository == 'rustfs/rustfs'
runs-on: smoke-testing
timeout-minutes: 150
steps:
- name: Checkout chain tooling
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- name: Resolve nightly candidate
id: candidate
env:
GH_TOKEN: ${{ secrets.PF_TESTING_GH_TOKEN }}
BUILD_RUN_ID: ${{ inputs.build_run_id }}
BUILD_RUN_ATTEMPT: ${{ inputs.build_run_attempt }}
CHAIN_OUTPUT: ${{ runner.temp }}/validation-sweep-candidate.json
run: |
set -euo pipefail
python3 scripts/resolve_functional_candidate.py
python3 - <<'PY'
import json
import os
from pathlib import Path
root = Path(os.environ["RUNNER_TEMP"]) / "validation-sweep"
root.mkdir(parents=True, exist_ok=True)
candidate = json.loads((Path(os.environ["RUNNER_TEMP"]) / "validation-sweep-candidate.json").read_text())
manifest = candidate["manifest"]
(root / "candidate.json").write_text(json.dumps({
"package_url": manifest["package_url"],
"package_sha256": manifest["package_sha256"],
"source_sha": manifest["source_sha"],
}, sort_keys=True) + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
output.write("testing_sha=" + candidate["testing_sha"] + "\n")
output.write("package_url=" + manifest["package_url"] + "\n")
output.write("source_sha=" + manifest["source_sha"] + "\n")
PY
- name: Checkout auto-testing scripts
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
repository: rustfs/auto-testing
ref: ${{ steps.candidate.outputs.testing_sha }}
token: ${{ secrets.PF_TESTING_GH_TOKEN }}
path: auto-testing
persist-credentials: false
- name: Select sweep cases
id: select
env:
SELECTED_CASE: ${{ inputs.case }}
SELECTED_MODULE: ${{ inputs.module }}
CASE_LIMIT: ${{ inputs.limit }}
SWEEP_EVENT: ${{ github.event_name }}
SWEEP_ROOT: ${{ runner.temp }}/validation-sweep
run: |
set -euo pipefail
python3 - <<'PY'
import datetime
import json
import os
from pathlib import Path
sweep_root = Path(os.environ["SWEEP_ROOT"])
catalog = json.loads(Path("auto-testing/validation-cases.json").read_text())
def sweepable(case):
status = case.get("source_status")
if status == "implemented":
return True
# The remaining planned non-heal cases route to the lane
# executors and already have live PASS evidence; sweeping them
# nightly produces fresh evidence for their acceptance review.
return status == "planned" and not case["id"].startswith("heal.")
selected = [(case["id"], module["id"]) for module in catalog["modules"]
for case in module["cases"]
if sweepable(case)]
if not selected:
raise SystemExit("catalog has no sweepable cases")
one_case = os.environ.get("SELECTED_CASE", "").strip()
module_filter = os.environ.get("SELECTED_MODULE", "").strip()
known = {case_id for case_id, _ in selected}
modules = {module_id for _, module_id in selected}
if one_case:
if one_case not in known:
raise SystemExit(f"unknown case or no lane executor for it: {one_case}")
selected = [(one_case, dict(selected)[one_case])]
elif module_filter:
if module_filter not in modules:
raise SystemExit(f"unknown module or no implemented cases: {module_filter}")
selected = [pair for pair in selected if pair[1] == module_filter]
elif os.environ.get("SWEEP_EVENT") == "schedule":
# Stateless rotation: every night take one window of the catalog
# so a full sweep needs len(selected)/limit nights and no state
# has to be carried between runs.
limit = max(1, int(os.environ.get("CASE_LIMIT") or 12))
day = datetime.datetime.now(datetime.timezone.utc).timetuple().tm_yday
start = (day * limit) % len(selected)
selected = (selected[start:] + selected[:start])[:limit]
limit = int(os.environ.get("CASE_LIMIT") or 0)
if one_case or module_filter or (not os.environ.get("SWEEP_EVENT") == "schedule"):
if limit > 0:
selected = selected[:limit]
(sweep_root / "sweep-cases.txt").write_text("".join(f"{case_id}\n" for case_id, _ in selected))
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
output.write(f"count={len(selected)}\n")
print(f"selected {len(selected)} case(s):", ", ".join(c for c, _ in selected))
PY
- name: Admit clean shared environment
id: environment
timeout-minutes: 5
env:
FUNCTIONAL_ENVIRONMENT_RECEIPT: ${{ runner.temp }}/environment-validation-sweep.json
run: python3 scripts/functional_environment.py enter --suite heal
- name: Run validation cases
id: run_cases
timeout-minutes: 120
env:
AUTO_TESTING_SHA: ${{ steps.candidate.outputs.testing_sha }}
SWEEP_ROOT: ${{ runner.temp }}/validation-sweep
run: |
set -uo pipefail
mkdir -p "${SWEEP_ROOT}/results"
: > "${SWEEP_ROOT}/results.txt"
while read -r CASE_ID; do
[ -n "${CASE_ID}" ] || continue
echo "::group::case ${CASE_ID}"
rm -rf "${SWEEP_ROOT}/run"
if ./auto-testing/scripts/run_validation_case.sh \
"${CASE_ID}" "${SWEEP_ROOT}/candidate.json" \
"${AUTO_TESTING_SHA}" "${SWEEP_ROOT}/run" \
> "${SWEEP_ROOT}/results/${CASE_ID//\//_}.log" 2>&1; then
printf '%s\tPASS\n' "${CASE_ID}" >> "${SWEEP_ROOT}/results.txt"
echo "case ${CASE_ID}: PASS"
else
printf '%s\tFAIL\n' "${CASE_ID}" >> "${SWEEP_ROOT}/results.txt"
echo "case ${CASE_ID}: FAIL (log retained in the sweep artifact)"
fi
if [ -f "${SWEEP_ROOT}/run/report.md" ]; then
cp "${SWEEP_ROOT}/run/report.md" "${SWEEP_ROOT}/results/${CASE_ID//\//_}.report.md" 2>/dev/null || true
fi
echo "::endgroup::"
# Fleet hygiene between cases: the case runners set up their own
# topology, this purge guarantees the next case starts clean even
# when the previous one died mid-run.
for node in ${RUSTFS_NODES}; do
ssh -o BatchMode=yes -o ConnectTimeout=10 "${RUSTFS_SSH_USER}@${node}" '
SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo -n"
${SUDO} systemctl stop rustfs 2>/dev/null || true
if ${SUDO} dpkg -l rustfs 2>/dev/null | grep -q "^ii"; then
${SUDO} dpkg -P rustfs
fi
for i in 1 2 3 4; do ${SUDO} rm -rf /data/rustfs${i}/mnmd; done
${SUDO} rm -f /etc/default/rustfs
' || echo "inter-case cleanup failed on ${node} (continuing)"
done
done < "${SWEEP_ROOT}/sweep-cases.txt"
echo "sweep finished: $(wc -l < "${SWEEP_ROOT}/results.txt") case(s) executed"
- name: Generate sweep report
if: ${{ always() && steps.environment.outcome == 'success' }}
env:
SWEEP_ROOT: ${{ runner.temp }}/validation-sweep
PACKAGE_URL: ${{ steps.candidate.outputs.package_url }}
SOURCE_SHA: ${{ steps.candidate.outputs.source_sha }}
run: |
set -euo pipefail
python3 - <<'PY'
import json
import os
from pathlib import Path
root = Path(os.environ["SWEEP_ROOT"])
catalog = json.loads(Path("auto-testing/validation-cases.json").read_text())
module_of = {case["id"]: module["id"] for module in catalog["modules"] for case in module["cases"]}
rows = []
for line in (root / "results.txt").read_text().splitlines():
if not line:
continue
case_id, status = line.split("\t")
rows.append((case_id, module_of.get(case_id, "?"), status))
passed = sum(1 for _, _, s in rows if s == "PASS")
failed = len(rows) - passed
run_url = (f"{os.environ.get('GITHUB_SERVER_URL', 'https://github.com')}/"
f"{os.environ.get('GITHUB_REPOSITORY', 'rustfs/rustfs')}/actions/runs/"
f"{os.environ.get('GITHUB_RUN_ID', '')}")
report = [
"# RustFS validation sweep report", "",
f"- Run: {run_url}",
f"- Attempt: {os.environ.get('GITHUB_RUN_ATTEMPT', '')}",
f"- Trigger: {os.environ.get('GITHUB_EVENT_NAME', '')}",
f"- Package: {os.environ.get('PACKAGE_URL', 'nightly (R2 latest)')}",
f"- Source SHA: {os.environ.get('SOURCE_SHA', '')}",
f"- auto-testing: {os.environ.get('AUTO_TESTING_SHA', '')}", "",
"Canonical validation cases (rustfs/auto-testing#113) executed by the sweep, grouped by catalog module.", "",
]
# Group the executed cases by catalog module (the major category:
# pool lifecycle, heal, ILM expiration, bucket/site replication, kms,
# data services, identity, s3 compatibility). Per-module subtotals
# deliberately use "- Subtotal:" so the dashboard overview regexes
# (which anchor on "- Total:") keep reading the grand totals below.
by_module = {}
module_order = []
for case_id, module, status in rows:
if module not in by_module:
by_module[module] = []
module_order.append(module)
by_module[module].append((case_id, status))
report += ["## Case Summary", ""]
for module in module_order:
cases = by_module[module]
mod_pass = sum(1 for _, st in cases if st == "PASS")
mod_fail = len(cases) - mod_pass
report += [f"### {module} ({len(cases)})", "",
"| Case | Status |", "| --- | --- |"]
report += [f"| {case_id} | {status} |" for case_id, status in cases]
report += ["", f"- Subtotal: {mod_pass} passed, {mod_fail} failed", ""]
report += [
"## Totals", "",
f"- Total: {len(rows)}",
f"- PASS: {passed}",
f"- FAIL: {failed}",
"- UNSUPPORTED: 0", "",
"Failing cases keep this workflow red only as a report; the sweep artifact",
"retains every case log and per-case report for diagnosis.", "",
]
(root / "report.md").write_text("\n".join(report))
(root / "cases.md").write_text("\n".join(f"| {c} | {m} | {s} |" for c, m, s in rows) + "\n")
PY
cat "${SWEEP_ROOT}/report.md" >> "${GITHUB_STEP_SUMMARY}"
- name: Upload functional report to dashboard
if: ${{ always() && steps.environment.outcome == 'success' }}
timeout-minutes: 2
continue-on-error: true
env:
GH_TOKEN: ${{ env.PF_TESTING_GH_TOKEN }}
REPORT_FILE: ${{ runner.temp }}/validation-sweep/report.md
SUITE: validation
run: |
set -euo pipefail
if [ -z "${GH_TOKEN:-}" ]; then
echo "PF_TESTING_GH_TOKEN is not configured; skipping dashboard upload"
exit 0
fi
DATE="$(date -u +%Y-%m-%d)"
REPORT_PATH="functional-reports/${SUITE}/${DATE}.md"
B64_FILE="$(mktemp)"
python3 -c 'import base64,sys;print(base64.b64encode(open(sys.argv[1],"rb").read()).decode())' "${REPORT_FILE}" > "${B64_FILE}"
SHA="$(gh api "repos/rustfs/dashboard/contents/${REPORT_PATH}" -q '.sha' 2>/dev/null || true)"
if [ -n "${SHA}" ]; then
jq -n --arg msg "report(${SUITE}): ${DATE}" --rawfile content "${B64_FILE}" --arg sha "${SHA}" \
'{message:$msg, content:($content|rtrimstr("\n")), sha:$sha}' \
| gh api --method PUT "repos/rustfs/dashboard/contents/${REPORT_PATH}" --input - >/dev/null
else
jq -n --arg msg "report(${SUITE}): ${DATE}" --rawfile content "${B64_FILE}" \
'{message:$msg, content:($content|rtrimstr("\n"))}' \
| gh api --method PUT "repos/rustfs/dashboard/contents/${REPORT_PATH}" --input - >/dev/null
fi
echo "dashboard updated: ${REPORT_PATH}"
- name: Retain sweep evidence
if: ${{ always() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: rustfs-validation-sweep-${{ github.run_id }}-${{ github.run_attempt }}
path: |
${{ runner.temp }}/validation-sweep/report.md
${{ runner.temp }}/validation-sweep/results.txt
${{ runner.temp }}/validation-sweep/sweep-cases.txt
${{ runner.temp }}/validation-sweep/candidate.json
${{ runner.temp }}/validation-sweep/results/
if-no-files-found: error
retention-days: 30
- name: Cleanup environment (after)
id: environment_cleanup
timeout-minutes: 5
if: ${{ always() && steps.environment.outcome == 'success' }}
run: |
set -uo pipefail
cleanup_status=0
for node in ${RUSTFS_NODES}; do
ssh -o BatchMode=yes -o ConnectTimeout=10 "${RUSTFS_SSH_USER}@${node}" '
set -euo pipefail
SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo -n"
${SUDO} systemctl stop rustfs 2>/dev/null || true
if ${SUDO} dpkg -l rustfs 2>/dev/null | grep -q "^ii"; then
${SUDO} dpkg -P rustfs
fi
for i in 1 2 3 4; do ${SUDO} rm -rf /data/rustfs${i}/mnmd; done
${SUDO} rm -f /etc/default/rustfs
' || cleanup_status=$?
done
exit "${cleanup_status}"
- name: Release environment only after successful cleanup
if: ${{ always() && steps.environment.outcome == 'success' }}
timeout-minutes: 5
env:
FUNCTIONAL_ENVIRONMENT_RECEIPT: ${{ runner.temp }}/environment-validation-sweep.json
CLEANUP_OUTCOME: ${{ steps.environment_cleanup.outcome }}
run: python3 scripts/functional_environment.py finish --suite heal --cleanup-outcome "$CLEANUP_OUTCOME"
- name: Notify on failure
if: failure()
run: echo "RustFS validation sweep failed (harness/environment breakdown); see the sweep artifact for case logs."
- name: Enforce sweep result
if: ${{ always() && steps.environment.outcome == 'success' }}
env:
SWEEP_ROOT: ${{ runner.temp }}/validation-sweep
run: |
set -euo pipefail
if grep -q $'\tFAIL$' "${SWEEP_ROOT}/results.txt"; then
echo "validation sweep has failing cases:"
grep $'\tFAIL$' "${SWEEP_ROOT}/results.txt"
exit 1
fi
alert-on-failure:
name: Alert on scheduled failure
# A scheduled sweep failure usually means a canonical validation case
# regressed or the fleet environment broke; surface it as a tracking
# issue instead of leaving it in the Actions tab.
needs: [sweep]
if: github.repository == 'rustfs/rustfs' && (always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure'))
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v5.0.0
with:
persist-credentials: false
- name: Open or update failure-tracking issue
uses: ./.github/actions/schedule-failure-issue
with:
github-token: ${{ secrets.BACKLOG_ISSUE_TOKEN }}
+57 -1
View File
@@ -683,6 +683,7 @@ pub(crate) async fn update_validated_in<F>(
bucket: &str,
config_file: &str,
data: Vec<u8>,
expected_incarnation_id: Option<Uuid>,
validate: F,
) -> Result<OffsetDateTime>
where
@@ -690,7 +691,7 @@ where
{
Box::pin(async {
let sys = require_bucket_metadata_sys_in(ctx)?;
let guard = acquire_config_write_guard(sys.clone(), bucket).await?;
let guard = acquire_config_write_guard_for_incarnation(sys.clone(), bucket, expected_incarnation_id).await?;
validate()?;
update_under_config_write_guard(sys, &guard, config_file, data, None).await
})
@@ -5209,6 +5210,61 @@ mod tests {
);
}
#[tokio::test]
#[serial]
async fn validated_config_update_rejects_a_different_bucket_incarnation() {
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "catalog-cleanup-incarnation";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
let incarnation = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("read bucket incarnation");
let called = std::sync::atomic::AtomicBool::new(false);
let result = store
.update_bucket_metadata_config_for_incarnation_validated(
bucket,
"quota.json",
br#"{"quota":1}"#.to_vec(),
Uuid::new_v4(),
|| {
called.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(())
},
)
.await;
assert!(matches!(result, Err(Error::BucketNotFound(name)) if name == bucket));
assert!(
!called.load(std::sync::atomic::Ordering::SeqCst),
"incarnation must be checked before the external fence"
);
let (metadata, _) = get_config_from_disk_with_presence_in(&store.ctx, bucket)
.await
.expect("read unchanged bucket metadata");
assert!(
metadata.quota_config_json.is_empty(),
"a stale cleanup must not modify the replacement bucket"
);
store
.update_bucket_metadata_config_for_incarnation_validated(
bucket,
"quota.json",
br#"{"quota":1}"#.to_vec(),
incarnation,
|| Ok(()),
)
.await
.expect("the current incarnation permits the validated update");
let (metadata, _) = get_config_from_disk_with_presence_in(&store.ctx, bucket)
.await
.expect("read updated bucket metadata");
assert_eq!(metadata.quota_config_json, br#"{"quota":1}"#);
}
#[tokio::test]
#[serial]
async fn quota_admission_rejects_stale_cached_no_quota() {
+154 -23
View File
@@ -3720,33 +3720,45 @@ fn is_decommission_copy_quorum_deferral(err: &Error) -> bool {
data_movement::data_movement_stage_source_as::<DecommissionCopyQuorumFailure>(err).is_some()
}
/// The storage error of a version copy that kept timing out on a namespace
/// lock through its in-place retries, kept typed so the entry failure policy
/// defers it.
/// A copy whose object namespace lock remained unavailable through its
/// in-place retries, retained as a typed deferral.
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
struct DecommissionCopyLockTimeout(#[source] Error);
struct DecommissionCopyLockUnavailable(#[source] Error);
fn is_decommission_copy_lock_timeout_error(err: &Error) -> bool {
let err = data_movement::data_movement_stage_source(err).unwrap_or(err);
matches!(err, Error::Lock(rustfs_lock::LockError::Timeout { .. }))
fn is_decommission_copy_lock_unavailable_error(err: &Error, bucket: &str, object: &str) -> bool {
let source = data_movement::data_movement_stage_source(err).unwrap_or(err);
match source {
Error::Lock(rustfs_lock::LockError::Timeout { .. }) => true,
Error::NamespaceLockQuorumUnavailable {
mode: "read",
bucket: lock_bucket,
object: lock_object,
..
} => {
data_movement::data_movement_error_is_stage(err, "prepare_put_object")
&& lock_bucket == bucket
&& lock_object == object
}
_ => false,
}
}
/// A version copy that timed out acquiring a namespace lock leaves the source
/// A version copy that could not acquire its namespace lock leaves the source
/// in place; the next attempt copies the version again or finds an equivalent
/// committed target. The lock is held by another mutation of the key or, when
/// this node restarted mid-copy, by its previous incarnation until that lock's
/// lease expires on the peers. Either clears by waiting, so the entry is
/// deferred instead of being counted as a permanent per-object failure.
fn decommission_copy_lock_timeout_deferral(stage: &str, bucket: &str, object: &str, err: Error) -> Error {
fn decommission_copy_lock_unavailable_deferral(stage: &str, bucket: &str, object: &str, err: Error) -> Error {
data_movement::data_movement_context_error(
format!("decommission {stage} timed out on a namespace lock for {bucket}/{object}: {err}"),
DecommissionCopyLockTimeout(err),
format!("decommission {stage} could not acquire a namespace lock for {bucket}/{object}: {err}"),
DecommissionCopyLockUnavailable(err),
)
}
fn is_decommission_copy_lock_timeout_deferral(err: &Error) -> bool {
data_movement::data_movement_stage_source_as::<DecommissionCopyLockTimeout>(err).is_some()
fn is_decommission_copy_lock_unavailable_deferral(err: &Error) -> bool {
data_movement::data_movement_stage_source_as::<DecommissionCopyLockUnavailable>(err).is_some()
}
/// The deferral of a version copy whose in-place retries ended on `error`, if
@@ -3756,8 +3768,8 @@ fn take_decommission_copy_deferral(stage: &str, bucket: &str, object: &str, erro
return Some(decommission_copy_quorum_deferral(stage, bucket, object, err));
}
error
.take_if(|err| is_decommission_copy_lock_timeout_error(err))
.map(|err| decommission_copy_lock_timeout_deferral(stage, bucket, object, err))
.take_if(|err| is_decommission_copy_lock_unavailable_error(err, bucket, object))
.map(|err| decommission_copy_lock_unavailable_deferral(stage, bucket, object, err))
}
fn resolve_decommission_entry_reload_result(result: Result<()>, bucket: &str, object_name: &str) -> Result<()> {
@@ -5822,13 +5834,13 @@ enum DecommissionEntryOutcome {
/// entry is done and must not be counted as a failure or escalated. A quorum
/// failure of the source cleanup is deferred too: the copied source is still
/// in place and the next attempt cleans it up again. So is a version copy that
/// lost drive quorum or timed out on a namespace lock through its in-place
/// lost drive quorum or could not acquire an object namespace lock through its in-place
/// retries: the source still holds the version and the next attempt copies it
/// again. Every other failure stays terminal.
fn resolve_decommission_entry_failure(err: Error) -> Result<DecommissionEntryOutcome> {
if is_decommission_source_cleanup_retryable_error(&err)
|| is_decommission_copy_quorum_deferral(&err)
|| is_decommission_copy_lock_timeout_deferral(&err)
|| is_decommission_copy_lock_unavailable_deferral(&err)
{
return Ok(DecommissionEntryOutcome::Deferred(err));
}
@@ -28353,7 +28365,7 @@ mod tests {
"one version must commit before the next version times out"
);
assert!(
matches!(&outcome, DecommissionEntryOutcome::Deferred(err) if is_decommission_copy_lock_timeout_deferral(err)),
matches!(&outcome, DecommissionEntryOutcome::Deferred(err) if is_decommission_copy_lock_unavailable_deferral(err)),
"{outcome:?}"
);
assert_eq!(
@@ -28387,6 +28399,88 @@ mod tests {
assert_eq!(actual, b"written after versioning was enabled");
}
/// A target lookup that loses its read-lock quorum must retain the source
/// and resume an entry after an earlier version has already committed.
#[tokio::test]
#[serial_test::serial]
async fn decommission_defers_target_lookup_read_lock_quorum_and_resumes() {
use tokio::io::AsyncReadExt as _;
let fixture = NullVersionDecommission::new(NullVersionTop::NewerVersion).await;
let object = fixture.object;
let attempted = Arc::new(AtomicUsize::new(0));
let fault = DecommissionTestFaultGuard::install_with_error(
Arc::new({
let attempted = Arc::clone(&attempted);
move |stage, _, faulted, _, success| {
stage == "before_target_commit"
&& faulted == object
&& success
&& attempted.fetch_add(1, Ordering::SeqCst) > 0
}
}),
Some(Arc::new(|_, bucket, object| {
data_movement::data_movement_stage_error_for_test(
"decommission_object",
"prepare_put_object",
bucket,
object,
Error::NamespaceLockQuorumUnavailable {
mode: "read",
bucket: bucket.to_owned(),
object: object.to_owned(),
required: 1,
achieved: 0,
},
)
})),
);
let (outcome, _) = fixture.run_entry().await;
assert!(
matches!(&outcome, DecommissionEntryOutcome::Deferred(err) if is_decommission_copy_lock_unavailable_deferral(err)),
"{outcome:?}"
);
fixture.assert_source_retained().await;
assert_eq!(
fixture
.target_versions()
.await
.expect("first version committed")
.versions
.len(),
1
);
assert_eq!(
fixture.store.pool_meta.read().await.pools[0]
.decommission
.as_ref()
.expect("active decommission")
.items_decommission_failed,
0
);
drop(fault);
let (outcome, _) = fixture.run_entry().await;
assert!(matches!(outcome, DecommissionEntryOutcome::Complete), "{outcome:?}");
fixture.assert_moved().await;
let mut reader = fixture.store.pools[1]
.get_object_reader(
fixture.bucket,
fixture.object,
None,
HeaderMap::new(),
&ObjectOptions {
version_id: Some(fixture.seeded.versions[0].version_id.expect("newer version").to_string()),
..Default::default()
},
)
.await
.expect("the newer version must remain readable");
let mut actual = Vec::new();
reader.stream.read_to_end(&mut actual).await.expect("read the newer version");
assert_eq!(actual, b"written after versioning was enabled");
}
/// A namespace lock still held on the target key, as by a copy whose node
/// was killed mid-write, makes target selection fail with a typed
/// object-lock timeout. A real held lock, not an injected error, must defer
@@ -28429,7 +28523,7 @@ mod tests {
let (outcome, _) = fixture.run_entry().await;
assert!(
matches!(&outcome, DecommissionEntryOutcome::Deferred(err) if is_decommission_copy_lock_timeout_deferral(err)),
matches!(&outcome, DecommissionEntryOutcome::Deferred(err) if is_decommission_copy_lock_unavailable_deferral(err)),
"{outcome:?}"
);
assert_eq!(
@@ -28838,17 +28932,17 @@ mod tests {
timeout(),
);
for err in [timeout(), prepare] {
assert!(is_decommission_copy_lock_timeout_error(&err), "{err}");
assert!(is_decommission_copy_lock_unavailable_error(&err, "bucket-a", "object-a"), "{err}");
assert!(!is_decommission_copy_quorum_error(&err), "{err}");
let mut error = Some(err);
let deferred = take_decommission_copy_deferral("migrate_object", "bucket-a", "object-a", &mut error)
.expect("a lock timeout copy must be deferred");
assert!(error.is_none());
assert!(is_decommission_copy_lock_timeout_deferral(&deferred));
assert!(is_decommission_copy_lock_unavailable_deferral(&deferred));
assert!(!is_decommission_copy_quorum_deferral(&deferred));
let failure = data_movement::data_movement_stage_source_as::<DecommissionCopyLockTimeout>(&deferred)
let failure = data_movement::data_movement_stage_source_as::<DecommissionCopyLockUnavailable>(&deferred)
.expect("the deferred error must keep its lock-timeout origin");
assert!(is_decommission_copy_lock_timeout_error(&failure.0));
assert!(is_decommission_copy_lock_unavailable_error(&failure.0, "bucket-a", "object-a"));
assert!(matches!(
resolve_decommission_entry_failure(deferred),
Ok(DecommissionEntryOutcome::Deferred(_))
@@ -28873,6 +28967,43 @@ mod tests {
}
}
#[test]
fn decommission_copy_defers_only_the_matching_object_read_lock_quorum() {
let quorum = |mode, bucket: &str, object: &str| Error::NamespaceLockQuorumUnavailable {
mode,
bucket: bucket.to_owned(),
object: object.to_owned(),
required: 1,
achieved: 0,
};
let wrap = |stage, err| {
data_movement::data_movement_stage_error_for_test("decommission_object", stage, "bucket-a", "object-a", err)
};
let mut error = Some(wrap("prepare_put_object", quorum("read", "bucket-a", "object-a")));
let deferred = take_decommission_copy_deferral("migrate_object", "bucket-a", "object-a", &mut error)
.expect("matching read-lock quorum must defer");
assert!(error.is_none());
assert!(matches!(
resolve_decommission_entry_failure(deferred),
Ok(DecommissionEntryOutcome::Deferred(_))
));
for err in [
quorum("read", "bucket-a", "object-a"),
wrap("source_recheck", quorum("read", "bucket-a", "object-a")),
wrap("prepare_put_object", quorum("write", "bucket-a", "object-a")),
wrap(
"prepare_put_object",
quorum("exact_delete_capacity_reconciliation", "bucket-a", "object-a"),
),
wrap("prepare_put_object", quorum("read", "other-bucket", "object-a")),
wrap("prepare_put_object", quorum("read", "bucket-a", "other-object")),
] {
let mut error = Some(err);
assert!(take_decommission_copy_deferral("migrate_object", "bucket-a", "object-a", &mut error).is_none());
assert!(error.is_some(), "unrelated lock failures must stay terminal");
}
}
#[test]
fn decommission_target_capacity_error_accepts_wrapped_capacity_errors() {
let disk_full = Error::other(format!("decommission_object: put_object failed for bucket/object: {}", Error::DiskFull));
+17 -1
View File
@@ -605,6 +605,7 @@ fn resolve_data_movement_abort_result(
#[derive(Debug)]
struct DataMovementStageError {
rendered: String,
stage: Option<String>,
source: Box<dyn std::error::Error + Send + Sync>,
}
@@ -626,6 +627,7 @@ where
{
Error::other(DataMovementStageError {
rendered,
stage: None,
source: Box::new(err),
})
}
@@ -634,7 +636,21 @@ fn data_movement_stage_error<E>(op_label: &str, stage: &str, bucket: &str, objec
where
E: std::error::Error + Send + Sync + 'static,
{
data_movement_context_error(format!("{op_label}: {stage} failed for {bucket}/{object}: {err}"), err)
Error::other(DataMovementStageError {
rendered: format!("{op_label}: {stage} failed for {bucket}/{object}: {err}"),
stage: Some(stage.to_owned()),
source: Box::new(err),
})
}
pub(crate) fn data_movement_error_is_stage(err: &Error, stage: &str) -> bool {
let Error::Io(io_err) = err else {
return false;
};
io_err
.get_ref()
.and_then(|source| source.downcast_ref::<DataMovementStageError>())
.is_some_and(|source| source.stage.as_deref() == Some(stage))
}
#[cfg(test)]
+46 -17
View File
@@ -8033,6 +8033,14 @@ impl LocalDisk {
fn io_get_object_open_path(&self, bucket: &str, key: &str) -> Result<PathBuf> {
#[cfg(target_os = "linux")]
{
if is_clean_relative_segment(bucket) && is_clean_relative_segment(key) {
let root = self.io_root();
let mut path = PathBuf::with_capacity(root.as_os_str().len() + bucket.len() + key.len() + 2);
path.push(root);
path.push(bucket);
path.push(key);
return Ok(path);
}
let (bucket_path, path) = build_local_disk_object_path(self.io_root(), bucket, key);
check_local_disk_object_path_components(self.io_root(), &bucket_path, &path)?;
Ok(path)
@@ -8047,6 +8055,11 @@ impl LocalDisk {
fn io_get_bucket_and_object_open_path(&self, bucket: &str, key: &str) -> Result<(PathBuf, PathBuf)> {
#[cfg(target_os = "linux")]
{
if is_clean_relative_segment(bucket) && is_clean_relative_segment(key) {
let bucket_path = self.io_root().join(bucket);
let path = bucket_path.join(key);
return Ok((bucket_path, path));
}
let (bucket_path, path) = build_local_disk_object_path(self.io_root(), bucket, key);
let normalized = check_local_disk_object_path_components(self.io_root(), &bucket_path, &path)?;
if matches!(normalized, std::borrow::Cow::Owned(_)) {
@@ -12027,8 +12040,7 @@ fn local_disk_object_path(root: &Path, bucket: &str, key: &str) -> Result<PathBu
#[cfg(not(windows))]
#[inline]
fn is_clean_relative_segment(s: &str) -> bool {
let b = s.as_bytes();
!matches!(b.first(), None | Some(b'/' | b'.')) && !b.ends_with(b"/") && !b.windows(2).any(|w| matches!(w, b"//" | b"/."))
!s.starts_with('/') && rustfs_utils::path::unix_is_canonical_ascii_path(s.as_bytes())
}
fn build_local_disk_object_path(root: &Path, bucket: &str, key: &str) -> (PathBuf, PathBuf) {
@@ -12075,10 +12087,26 @@ fn build_local_disk_bucket_path(root: &Path, bucket: &str) -> PathBuf {
bucket_path
}
#[inline]
fn disk_path_starts_with_normalized(path: &Path, base: &Path) -> bool {
#[cfg(not(windows))]
return rustfs_utils::path::unix_normalized_path_starts_with(path, base);
#[cfg(windows)]
path.starts_with(base)
}
#[inline]
fn disk_path_strip_prefix_normalized<'a>(path: &'a Path, base: &Path) -> Result<&'a Path> {
#[cfg(not(windows))]
return rustfs_utils::path::unix_normalized_path_strip_prefix(path, base).ok_or(DiskError::InvalidPath);
#[cfg(windows)]
path.strip_prefix(base).map_err(|_| DiskError::InvalidPath)
}
fn check_local_disk_valid_object_path(root: &Path, bucket_path: &Path, path: &Path) -> Result<()> {
let bucket_path = normalize_path_cow(bucket_path);
let path = normalize_path_cow(path);
if !bucket_path.starts_with(root) || !path.starts_with(&bucket_path) {
if !disk_path_starts_with_normalized(&bucket_path, root) || !disk_path_starts_with_normalized(&path, &bucket_path) {
return Err(DiskError::InvalidPath);
}
@@ -12087,7 +12115,7 @@ fn check_local_disk_valid_object_path(root: &Path, bucket_path: &Path, path: &Pa
fn check_local_disk_valid_path(root: &Path, path: impl AsRef<Path>) -> Result<()> {
let path = normalize_path_cow(path.as_ref());
if !path.starts_with(root) {
if !disk_path_starts_with_normalized(&path, root) {
return Err(DiskError::InvalidPath);
}
@@ -12108,7 +12136,7 @@ fn check_local_disk_object_path_components<'a>(
) -> Result<std::borrow::Cow<'a, Path>> {
let bucket_path = normalize_path_cow(bucket_path);
let path = normalize_path_cow(path);
if !bucket_path.starts_with(root) || !path.starts_with(&bucket_path) {
if !disk_path_starts_with_normalized(&bucket_path, root) || !disk_path_starts_with_normalized(&path, &bucket_path) {
return Err(DiskError::InvalidPath);
}
@@ -12118,7 +12146,7 @@ fn check_local_disk_object_path_components<'a>(
#[cfg(target_os = "linux")]
fn check_local_disk_valid_path_at(root: &Path, root_fd: &std::fs::File, path: impl AsRef<Path>) -> Result<()> {
let path = normalize_path_cow(path.as_ref());
if !path.starts_with(root) {
if !disk_path_starts_with_normalized(&path, root) {
return Err(DiskError::InvalidPath);
}
@@ -12127,7 +12155,7 @@ fn check_local_disk_valid_path_at(root: &Path, root_fd: &std::fs::File, path: im
#[cfg(target_os = "linux")]
fn reject_local_disk_symlink_components_at(root: &Path, root_fd: &std::fs::File, path: &Path) -> Result<()> {
let relative = path.strip_prefix(root).map_err(|_| DiskError::InvalidPath)?;
let relative = disk_path_strip_prefix_normalized(path, root)?;
match validate_existing_local_disk_prefix_at(root_fd, relative) {
Ok(()) => Ok(()),
Err(LocalDiskPathValidationAtError::Unsupported) => reject_local_disk_symlink_components(root, path),
@@ -12155,11 +12183,11 @@ fn validate_existing_local_disk_prefix_at(
return Ok(());
}
let mut candidate = relative.to_path_buf();
let mut candidate = relative;
loop {
match openat2(
root_fd,
&candidate,
candidate,
OFlags::PATH | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::BENEATH | ResolveFlags::NO_SYMLINKS,
@@ -12168,10 +12196,12 @@ fn validate_existing_local_disk_prefix_at(
Err(Errno::NOSYS) => return Err(LocalDiskPathValidationAtError::Unsupported),
Err(Errno::LOOP | Errno::XDEV) => return Err(LocalDiskPathValidationAtError::InvalidPath),
Err(Errno::NOENT) => {
let Some(parent) = candidate.parent().filter(|parent| !parent.as_os_str().is_empty()) else {
let Some(parent) =
rustfs_utils::path::unix_path_parent(candidate).filter(|parent| !parent.as_os_str().is_empty())
else {
return Ok(());
};
candidate = parent.to_path_buf();
candidate = parent;
}
Err(err) => return Err(LocalDiskPathValidationAtError::Io(err.into())),
}
@@ -12179,7 +12209,7 @@ fn validate_existing_local_disk_prefix_at(
}
fn reject_local_disk_symlink_components(root: &Path, path: &Path) -> Result<()> {
let relative = path.strip_prefix(root).map_err(|_| DiskError::InvalidPath)?;
let relative = disk_path_strip_prefix_normalized(path, root)?;
let mut current = root.to_path_buf();
for component in relative.components() {
@@ -12203,12 +12233,11 @@ fn reject_local_disk_symlink_components(root: &Path, path: &Path) -> Result<()>
fn normalize_path_cow(path: &Path) -> std::borrow::Cow<'_, Path> {
// Windows prefixes retain the existing PathBuf reconstruction semantics.
#[cfg(not(windows))]
if !path.as_os_str().as_encoded_bytes().contains(&b'.')
|| !path
.components()
.any(|c| matches!(c, std::path::Component::ParentDir | std::path::Component::CurDir))
{
return std::borrow::Cow::Borrowed(path);
let bytes = path.as_os_str().as_encoded_bytes();
if bytes != b"." && !bytes.starts_with(b"./") && !rustfs_utils::path::unix_path_has_dotdot_segment(bytes) {
return std::borrow::Cow::Borrowed(path);
}
}
std::borrow::Cow::Owned(normalize_path_components(path))
}
+52 -30
View File
@@ -4439,12 +4439,18 @@ fn prepare_destination_parent_with_retry(
base_dir: &Path,
publication_root: &PublicationRoot,
) -> io::Result<ExistingBaseDirectoryGuard> {
let prune_budget = parent_prune_budget(parent, base_dir);
let mut prune_budget = None;
let mut attempt = 0;
loop {
match mkdir_all_below_existing_base_std(parent, base_dir, publication_root) {
Ok(preparation) => return Ok(preparation),
Err(err) if should_retry_prepare(&err, attempt, prune_budget) => {
Err(err)
if should_retry_prepare(
&err,
attempt,
*prune_budget.get_or_insert_with(|| parent_prune_budget(parent, base_dir)),
) =>
{
attempt += 1;
}
Err(err) => return Err(err),
@@ -4936,13 +4942,9 @@ impl PublicationRoot {
#[cfg(target_os = "linux")]
{
use rustix::fs::{Mode, OFlags};
let parent = self.open_directory(
path.parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing file parent"))?,
)?;
let name = path
.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing file name"))?;
let (parent_path, name) = rustfs_utils::path::unix_split_parent_and_file_name(path)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing file parent or name"))?;
let parent = self.open_directory(parent_path)?;
let file = open_linux_relative(
&parent,
Path::new(name),
@@ -4982,9 +4984,9 @@ impl PublicationRoot {
#[cfg(target_os = "linux")]
fn relative_path<'a>(&self, path: &'a Path) -> io::Result<&'a Path> {
path.strip_prefix(self.io_path.as_path())
.or_else(|_| path.strip_prefix(self.path.as_path()))
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path must remain below its publication root"))
rustfs_utils::path::unix_normalized_path_strip_prefix(path, self.io_path.as_path())
.or_else(|| rustfs_utils::path::unix_normalized_path_strip_prefix(path, self.path.as_path()))
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path must remain below its publication root"))
}
#[cfg(windows)]
@@ -4996,6 +4998,13 @@ impl PublicationRoot {
}
}
#[cfg(target_os = "linux")]
#[inline]
fn linux_relative_path_has_invalid_component(relative: &Path) -> bool {
let bytes = relative.as_os_str().as_encoded_bytes();
bytes.starts_with(b"/") || rustfs_utils::path::unix_path_has_dotdot_segment(bytes)
}
/// Open the actual IO handle with the same containment policy as path validation.
/// Older kernels retain fd-relative traversal; only ENOSYS enables the fallback.
#[cfg(target_os = "linux")]
@@ -5006,10 +5015,7 @@ fn open_linux_relative(
mode: rustix::fs::Mode,
) -> io::Result<std::fs::File> {
use rustix::fs::{OFlags, ResolveFlags, openat2};
if relative
.components()
.any(|component| !matches!(component, Component::Normal(_) | Component::CurDir))
{
if linux_relative_path_has_invalid_component(relative) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid relative disk path"));
}
let relative = if relative.as_os_str().is_empty() {
@@ -5180,11 +5186,8 @@ impl LinuxCommitDirectories {
fn file_name<'a>(&self, path: &'a Path, source: bool) -> io::Result<&'a std::ffi::OsStr> {
let parent = if source { &self.source_path } else { &self.destination_path };
if path.parent() != Some(parent) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "file parent does not match its commit guard"));
}
path.file_name()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "missing file name"))
rustfs_utils::path::unix_direct_child_file_name(path, parent)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "file parent does not match its commit guard"))
}
fn validate(&self) -> io::Result<()> {
@@ -5196,8 +5199,8 @@ impl LinuxCommitDirectories {
return Err(io::Error::new(io::ErrorKind::InvalidData, "commit directory identity changed"));
}
let destination = self.prepare_destination()?;
if self.source_path != self.destination_path
|| (self.source.device, self.source.inode) != (destination.device, destination.inode)
if (self.source.device, self.source.inode) != (destination.device, destination.inode)
|| self.source_path.as_os_str() != self.destination_path.as_os_str()
{
let current = self.root.open_directory(&self.destination_path)?.metadata()?;
if (current.dev(), current.ino()) != (destination.device, destination.inode) {
@@ -5216,7 +5219,10 @@ impl LinuxCommitDirectories {
loop {
if let Some(prepared) = prepared {
let metadata = rustix::fs::statat(&*self.source.file, source_name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW)?;
if prepared.path != source || metadata.st_dev != prepared.device || metadata.st_ino != prepared.inode {
if (prepared.path.as_os_str() != source.as_os_str() && prepared.path != source)
|| metadata.st_dev != prepared.device
|| metadata.st_ino != prepared.inode
{
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"rename source identity changed while publication was prepared",
@@ -6354,19 +6360,35 @@ fn windows_rename_source_is_allowed(attributes: u32, reparse_tag: u32) -> bool {
}
fn existing_base_directory_suffix<'a>(dir_path: &'a Path, base_dir: &Path) -> io::Result<&'a Path> {
let relative = dir_path
.strip_prefix(base_dir)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "rename destination must remain below its base directory"))?;
for component in relative.components() {
if !matches!(component, Component::Normal(_) | Component::CurDir) {
#[cfg(target_os = "linux")]
{
let relative = rustfs_utils::path::unix_normalized_path_strip_prefix(dir_path, base_dir).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "rename destination must remain below its base directory")
})?;
if linux_relative_path_has_invalid_component(relative) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"rename destination contains an invalid path component",
));
}
Ok(relative)
}
#[cfg(not(target_os = "linux"))]
{
let relative = dir_path.strip_prefix(base_dir).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidInput, "rename destination must remain below its base directory")
})?;
for component in relative.components() {
if !matches!(component, Component::Normal(_) | Component::CurDir) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"rename destination contains an invalid path component",
));
}
}
Ok(relative)
Ok(relative)
}
}
/// Missing state never downgrades surviving native control records to legacy.
+3 -1
View File
@@ -429,6 +429,7 @@ impl WritePlan {
let checksum = reader.content_hash().clone();
let trailer = reader.get_trailer().cloned();
let delegate_inner_etag = self.compression.is_none() && reader.is_etag_reader();
let encrypted = self.encryption.is_some();
if let Some(algorithm) = self.compression {
reader = HashReader::from_reader(
@@ -448,7 +449,8 @@ impl WritePlan {
}
WriteEncryptionMode::SinglepartObjectKey | WriteEncryptionMode::MultipartObjectKey { .. } => [0u8; 12],
};
let protected_reader = rustfs_rio::EtagReader::new_encrypted(reader, encryption.key_bytes, etag_nonce)?;
let protected_reader = rustfs_rio::EtagReader::new_encrypted(reader, encryption.key_bytes, etag_nonce)?
.with_inner_etag_delegation(delegate_inner_etag);
reader = match encryption.mode {
WriteEncryptionMode::SinglepartObjectKey => HashReader::from_reader(
#[cfg(feature = "rio-v2")]
+15 -5
View File
@@ -161,7 +161,7 @@ impl SetDisks {
)
});
let mut metadata = FileMeta::new();
for parts in versions.into_values() {
for (version_id, parts) in versions {
let errors = parts
.iter()
.zip(&missing)
@@ -173,15 +173,25 @@ impl SetDisks {
}
})
.collect::<Vec<_>>();
let read_quorum = match Self::object_quorum_from_meta(&parts, &errors, default_parity) {
Ok((quorum, _)) => usize::try_from(quorum).map_err(|_| DiskError::FileCorrupt)?,
let (read_quorum, write_quorum) = match Self::object_quorum_from_meta(&parts, &errors, default_parity) {
Ok((read, write)) => (
usize::try_from(read).map_err(|_| DiskError::FileCorrupt)?,
usize::try_from(write).map_err(|_| DiskError::FileCorrupt)?,
),
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) if complete => continue,
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) => return Err(DiskError::ErasureReadQuorum),
Err(DiskError::ErasureReadQuorum) if complete => continue,
Err(error) => return Err(error),
};
let mod_time = Self::common_time(&Self::list_object_modtimes(&parts, &errors), read_quorum);
let selected = Self::pick_valid_fileinfo(&parts, mod_time, None, read_quorum)?;
let selected = if crate::bucket::utils::is_meta_bucketname(bucket) && version_id.is_none() {
// A null-version system record must carry the same commit proof
// as GET. Listing only needs the selected metadata, so no disk
// handles are retained from the shared read selector.
Self::select_committed_fileinfo(&vec![None; disk_count], &parts, &errors, "", read_quorum, write_quorum)?.1
} else {
let mod_time = Self::common_time(&Self::list_object_modtimes(&parts, &errors), read_quorum);
Self::pick_valid_fileinfo(&parts, mod_time, None, read_quorum)?
};
metadata.add_version(selected)?;
}
if metadata.versions.is_empty() {
+7 -5
View File
@@ -9038,6 +9038,13 @@ mod tests {
"constructing an object lock must not clone each client Arc"
);
// Check shared ownership before acquisition can spawn pending cleanup.
let read_lock = set
.new_ns_lock("bucket", "read-object")
.await
.expect("second namespace lock should be created");
assert_eq!(Arc::strong_count(&set.shared_lockers), clients_before + 2);
let write_error = write_lock
.get_write_lock(Duration::from_millis(500))
.await
@@ -9052,11 +9059,6 @@ mod tests {
),
"the shared client representation must preserve the exact write quorum result: {write_error}"
);
let read_lock = set
.new_ns_lock("bucket", "read-object")
.await
.expect("second namespace lock should be created");
assert_eq!(Arc::strong_count(&set.shared_lockers), clients_before + 2);
let read_guard = read_lock
.get_read_lock(Duration::from_millis(500))
.await
+223 -7
View File
@@ -978,7 +978,7 @@ async fn multipart_upload_paths_on_disk(disk: DiskStore, bucket: &str, root_pref
return Err(DiskError::DiskNotFound);
}
if !root_prefix.is_empty() {
if !root_prefix.is_empty() && root_prefix != DATA_MOVEMENT_MULTIPART_PREFIX {
let upload_dirs = match disk.list_dir(bucket, RUSTFS_META_MULTIPART_BUCKET, root_prefix, -1).await {
Ok(entries) => entries,
Err(DiskError::FileNotFound | DiskError::VolumeNotFound) => return Ok(Vec::new()),
@@ -1003,6 +1003,13 @@ async fn multipart_upload_paths_on_disk(disk: DiskStore, bucket: &str, root_pref
.into_iter()
.map(|sha_dir| sha_dir.trim_end_matches('/').to_owned())
.filter(|sha_dir| sha_dir.len() == 64 && sha_dir.bytes().all(|byte| byte.is_ascii_hexdigit()))
.map(|sha_dir| {
if root_prefix.is_empty() {
sha_dir
} else {
format!("{root_prefix}/{sha_dir}")
}
})
.collect::<Vec<_>>();
let listed_upload_dirs = stream::iter(sha_dirs)
.map(|sha_dir| {
@@ -1125,6 +1132,7 @@ impl SetDisks {
orig_bucket: &str,
error_path: &str,
root_prefix: &str,
require_all_disks: bool,
) -> Result<(Vec<Option<DiskStore>>, Vec<String>, usize, bool)> {
let disks = self.disks.read().await.clone();
if disks.is_empty() {
@@ -1166,7 +1174,8 @@ impl SetDisks {
}
}
if let Some(err) = reduce_read_quorum_errs(&discovery_errors, OBJECT_OP_IGNORED_ERRS, discovery_quorum) {
let required_discoveries = if require_all_disks { disks.len() } else { discovery_quorum };
if let Some(err) = reduce_read_quorum_errs(&discovery_errors, OBJECT_OP_IGNORED_ERRS, required_discoveries) {
return Err(to_object_err(err.into(), vec![orig_bucket, error_path]));
}
@@ -1188,7 +1197,7 @@ impl SetDisks {
pub(crate) async fn first_multipart_upload_path_for_decommission(&self, bucket: &str) -> Result<Option<String>> {
let (_, paths, _, _) = self
.discover_multipart_upload_paths(bucket, RUSTFS_META_MULTIPART_BUCKET, "")
.discover_multipart_upload_paths(bucket, RUSTFS_META_MULTIPART_BUCKET, "", false)
.await?;
Ok(paths.into_iter().next())
}
@@ -1201,8 +1210,9 @@ impl SetDisks {
upload_identity: &str,
) -> Result<Vec<String>> {
let expected_parent = format!("{DATA_MOVEMENT_MULTIPART_PREFIX}/{}", Self::get_multipart_sha_dir(bucket, object));
let (_, candidate_paths, _, has_minority_candidate) =
self.discover_multipart_upload_paths(bucket, object, &expected_parent).await?;
let (_, candidate_paths, _, has_minority_candidate) = self
.discover_multipart_upload_paths(bucket, object, &expected_parent, false)
.await?;
if has_minority_candidate {
return Err(Error::DecommissionCapacityBlocked {
message: "data movement multipart cleanup found an upload path on fewer than the discovery quorum of disks"
@@ -1751,6 +1761,54 @@ impl SetDisks {
})
}
pub(crate) async fn ensure_no_multipart_uploads(&self, bucket: &str) -> Result<()> {
// Every disk must confirm absence in both namespaces before cleanup can
// remove catalog protection from the bucket.
for root_prefix in ["", DATA_MOVEMENT_MULTIPART_PREFIX] {
let (disks, paths, _, has_minority_candidate) =
self.discover_multipart_upload_paths(bucket, "", root_prefix, true).await?;
if has_minority_candidate {
return Err(Error::ErasureReadQuorum);
}
for upload_path in paths {
let (sha_dir, _) = upload_path
.rsplit_once('/')
.filter(|(directory, upload_id)| !directory.is_empty() && !upload_id.is_empty())
.ok_or(DiskError::CorruptedFormat)?;
let (metadata, errors) =
Self::read_all_fileinfo(&disks, bucket, RUSTFS_META_MULTIPART_BUCKET, &upload_path, "", false, false, false)
.await?;
let (read_quorum, _) = Self::object_quorum_from_meta(&metadata, &errors, self.default_parity_count)?;
let read_quorum = usize::try_from(read_quorum).map_err(|_| DiskError::ErasureReadQuorum)?;
if let Some(error) = reduce_read_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, read_quorum) {
return Err(to_object_err(error.into(), vec![bucket, &upload_path]));
}
let (_, modified, etag) = Self::list_online_disks(&disks, &metadata, &errors, read_quorum);
let file = Self::pick_valid_fileinfo(&metadata, modified, etag, read_quorum)?;
let (Some(owner_bucket), Some(owner_object)) = (
file.metadata.get(RUSTFS_MULTIPART_BUCKET_KEY),
file.metadata.get(RUSTFS_MULTIPART_OBJECT_KEY),
) else {
return Err(to_object_err(DiskError::CorruptedFormat.into(), vec![bucket, &upload_path]));
};
if owner_bucket.is_empty()
|| owner_object.is_empty()
|| Self::get_multipart_sha_dir(owner_bucket, owner_object)
!= sha_dir
.strip_prefix(DATA_MOVEMENT_MULTIPART_PREFIX)
.and_then(|suffix| suffix.strip_prefix('/'))
.unwrap_or(sha_dir)
{
return Err(to_object_err(DiskError::CorruptedFormat.into(), vec![bucket, &upload_path]));
}
if owner_bucket == bucket {
return Err(Error::BucketNotEmpty(bucket.to_string()));
}
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn list_multipart_uploads_for_incarnation(
&self,
@@ -1762,7 +1820,8 @@ impl SetDisks {
max_uploads: usize,
expected_incarnation_id: Option<Uuid>,
) -> Result<ListMultipartsInfo> {
let (disks, candidate_paths, discovery_quorum, _) = self.discover_multipart_upload_paths(bucket, prefix, "").await?;
let (disks, candidate_paths, discovery_quorum, _) =
self.discover_multipart_upload_paths(bucket, prefix, "", false).await?;
let listed_uploads = stream::iter(candidate_paths)
.map(|upload_path| {
let disks = &disks;
@@ -2373,7 +2432,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let multipart_part_size = data.size();
let stream = mem::replace(
&mut data.stream,
HashReader::from_stream(Cursor::new(Vec::new()), 0, 0, None, None, false)?,
HashReader::from_stream(Cursor::new(Vec::new()), 0, 0, None, None, true)?,
);
let write_path = classify_multipart_part_write_path(multipart_part_size, fi.erasure.block_size);
@@ -11213,6 +11272,163 @@ mod tests {
assert_eq!(upload_uuid_suffix(&recovered[0]), upload_uuid_suffix(&upload.upload_id));
}
#[tokio::test]
async fn multipart_absence_inspection_distinguishes_bucket_ownership() {
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cleanup-target";
let other = "multipart-cleanup-other";
for disk in &disk_stores {
disk.make_volume(bucket).await.expect("create target bucket");
disk.make_volume(other).await.expect("create other bucket");
}
set_disks
.ensure_no_multipart_uploads(bucket)
.await
.expect("an empty upload namespace permits cleanup");
set_disks
.new_multipart_upload(other, "object.bin", &ObjectOptions::default())
.await
.expect("create upload in other bucket");
set_disks
.ensure_no_multipart_uploads(bucket)
.await
.expect("an upload owned by another bucket permits cleanup");
set_disks
.new_multipart_upload(bucket, "object.bin", &ObjectOptions::default())
.await
.expect("create upload in target bucket");
assert!(
matches!(set_disks.ensure_no_multipart_uploads(bucket).await, Err(Error::BucketNotEmpty(name)) if name == bucket)
);
}
#[tokio::test]
async fn multipart_absence_inspection_requires_every_disk_online() {
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cleanup-offline";
for disk in &disk_stores {
disk.make_volume(bucket).await.expect("create bucket");
}
set_disks.disks.write().await[3] = None;
let listed = set_disks
.list_multipart_uploads_for_incarnation(bucket, "", None, None, None, 1000, None)
.await
.expect("ordinary listing preserves its discovery quorum");
assert!(listed.uploads.is_empty());
let error = set_disks
.ensure_no_multipart_uploads(bucket)
.await
.expect_err("an offline disk must prevent confirmation of an empty multipart namespace");
assert!(
matches!(&error, Error::InsufficientReadQuorum(error_bucket, error_path) if error_bucket == bucket && error_path.is_empty()),
"the offline disk must produce a bucket-scoped read quorum error: {error:?}"
);
set_disks.disks.write().await[3] = Some(disk_stores[3].clone());
set_disks
.ensure_no_multipart_uploads(bucket)
.await
.expect("all disks can confirm the empty namespace after recovery");
}
#[tokio::test]
async fn multipart_absence_inspection_rejects_a_failed_disk_enumeration() {
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cleanup-list-error";
for disk in &disk_stores {
disk.make_volume(bucket).await.expect("create bucket");
}
let sha_dir = SetDisks::get_multipart_sha_dir(bucket, "object.bin");
let multipart_dir = temp_dirs[0].path().join(RUSTFS_META_MULTIPART_BUCKET);
tokio::fs::create_dir_all(&multipart_dir)
.await
.expect("create multipart staging directory");
tokio::fs::write(multipart_dir.join(&sha_dir), b"not a directory")
.await
.expect("replace one upload parent directory with a file");
multipart_upload_paths_on_disk(disk_stores[0].clone(), bucket, "")
.await
.expect_err("the affected disk must fail directory enumeration");
let listed = set_disks
.list_multipart_uploads_for_incarnation(bucket, "", None, None, None, 1000, None)
.await
.expect("ordinary listing still accepts the remaining discovery quorum");
assert!(listed.uploads.is_empty());
let error = set_disks
.ensure_no_multipart_uploads(bucket)
.await
.expect_err("a failed disk enumeration must prevent confirmation of an empty multipart namespace");
assert!(
matches!(&error, Error::InsufficientReadQuorum(error_bucket, error_path) if error_bucket == bucket && error_path.is_empty()),
"the failed enumeration must produce a bucket-scoped read quorum error: {error:?}"
);
tokio::fs::remove_file(temp_dirs[0].path().join(RUSTFS_META_MULTIPART_BUCKET).join(sha_dir))
.await
.expect("remove the invalid directory entry");
set_disks
.ensure_no_multipart_uploads(bucket)
.await
.expect("all disks can confirm the empty namespace after repair");
}
#[tokio::test]
async fn multipart_absence_inspection_rejects_data_movement_uploads() {
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cleanup-data-movement";
for disk in &disk_stores {
disk.make_volume(bucket).await.expect("create bucket");
}
let mut metadata = HashMap::new();
rustfs_utils::http::insert_str(
&mut metadata,
rustfs_utils::http::SUFFIX_DATA_MOVEMENT_UPLOAD,
format!("v1:{}:{}", Uuid::new_v4(), OffsetDateTime::now_utc().unix_timestamp_nanos()),
);
set_disks
.new_multipart_upload(
bucket,
"object.bin",
&ObjectOptions {
data_movement: true,
user_defined: metadata,
..Default::default()
},
)
.await
.expect("create data movement upload");
assert!(
matches!(set_disks.ensure_no_multipart_uploads(bucket).await, Err(Error::BucketNotEmpty(name)) if name == bucket)
);
}
#[tokio::test]
async fn multipart_absence_inspection_rejects_unreadable_ownership() {
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cleanup-corrupt";
for disk in &disk_stores {
disk.make_volume(bucket).await.expect("create bucket");
}
set_disks
.new_multipart_upload(bucket, "object.bin", &ObjectOptions::default())
.await
.expect("create multipart upload");
let mut corrupted = 0;
for temp_dir in &temp_dirs {
for path in multipart_meta_files_on_disk(temp_dir, "xl.meta").await {
tokio::fs::write(path, b"invalid upload metadata")
.await
.expect("corrupt upload metadata");
corrupted += 1;
}
}
assert!(corrupted > 0, "upload metadata must exist before corruption");
set_disks
.ensure_no_multipart_uploads(bucket)
.await
.expect_err("unreadable upload ownership must block cleanup");
}
/// Regression (issue #5716): a single upload directory whose `xl.meta` was
/// destroyed (crash mid-write, torn disk state) must degrade to that upload
/// alone. Failing the whole ListMultipartUploads turns one piece of stale
+1 -1
View File
@@ -4534,7 +4534,7 @@ impl SetDisks {
let stream = mem::replace(
&mut data.stream,
HashReader::from_stream(Cursor::new(Vec::new()), 0, 0, None, None, false)?,
HashReader::from_stream(Cursor::new(Vec::new()), 0, 0, None, None, true)?,
);
let small_size_hint = if matches!(write_path, SmallWritePath::Inline | SmallWritePath::SingleBlockNonInline) {
@@ -44,15 +44,16 @@ pub(crate) mod lifecycle {
pub(crate) mod list {
pub(crate) use rustfs_storage_api::{
ListObjectVersionsInfo as StorageListObjectVersionsInfo, ListObjectsInfo, ListObjectsV2Info as StorageListObjectsV2Info,
ListOperations, ObjectInfoOrErr as StorageObjectInfoOrErr, VersionMarker, WalkOptions as StorageWalkOptions,
WalkVersionsSortOrder,
AuthoritativeListOperations, ListObjectVersionsInfo as StorageListObjectVersionsInfo, ListObjectsInfo,
ListObjectsV2Info as StorageListObjectsV2Info, ListOperations, ObjectInfoOrErr as StorageObjectInfoOrErr, VersionMarker,
WalkOptions as StorageWalkOptions, WalkVersionsSortOrder,
};
}
pub(crate) mod multipart {
pub(crate) use rustfs_storage_api::{
CompletePart, ListMultipartsInfo, ListPartsInfo, MultipartInfo, MultipartOperations, MultipartUploadResult, PartInfo,
CompletePart, ListMultipartsInfo, ListPartsInfo, MultipartInfo, MultipartOperations, MultipartUploadInspection,
MultipartUploadResult, PartInfo,
};
}
+16 -1
View File
@@ -523,7 +523,22 @@ impl ECStore {
where
F: FnOnce() -> Result<()> + Send,
{
metadata_sys::update_validated_in(&self.ctx, bucket, config_file, data, validate).await
metadata_sys::update_validated_in(&self.ctx, bucket, config_file, data, None, validate).await
}
/// Validate an external fence and the bucket incarnation in one metadata transaction.
pub async fn update_bucket_metadata_config_for_incarnation_validated<F>(
&self,
bucket: &str,
config_file: &str,
data: Vec<u8>,
expected_incarnation_id: Uuid,
validate: F,
) -> Result<OffsetDateTime>
where
F: FnOnce() -> Result<()> + Send,
{
metadata_sys::update_validated_in(&self.ctx, bucket, config_file, data, Some(expected_incarnation_id), validate).await
}
pub async fn bucket_incarnation_id(&self, bucket: &str) -> Result<Uuid> {
+244 -3
View File
@@ -37,8 +37,8 @@ use crate::error::{
use crate::object_api::{ObjectInfo, ObjectOptions};
use crate::set_disk::SetDisks;
use crate::storage_api_contracts::list::{
ListObjectsInfo as StorageListObjectsInfo, StorageListObjectVersionsInfo, StorageListObjectsV2Info, StorageObjectInfoOrErr,
StorageWalkOptions, VersionMarker, WalkVersionsSortOrder,
AuthoritativeListOperations, ListObjectsInfo as StorageListObjectsInfo, StorageListObjectVersionsInfo,
StorageListObjectsV2Info, StorageObjectInfoOrErr, StorageWalkOptions, VersionMarker, WalkVersionsSortOrder,
};
use crate::store::ECStore;
use crate::store::utils::is_reserved_or_invalid_bucket;
@@ -80,6 +80,21 @@ type ListObjectVersionsInfo = StorageListObjectVersionsInfo<ObjectInfo>;
type ObjectInfoOrErr = StorageObjectInfoOrErr<ObjectInfo, Error>;
type WalkOptions = StorageWalkOptions<fn(&rustfs_filemeta::FileInfo) -> bool>;
#[async_trait::async_trait]
impl AuthoritativeListOperations for ECStore {
async fn walk_authoritative(
self: Arc<Self>,
rx: CancellationToken,
bucket: &str,
prefix: &str,
result: Sender<ObjectInfoOrErr>,
opts: WalkOptions,
) -> Result<()> {
check_list_objs_args(bucket, prefix, &None)?;
self.walk_authoritatively(rx, bucket, prefix, result, opts).await
}
}
/// Build the versioned listing options used by recursive object walks.
///
/// `list_path_result` normally derives these scan bounds before dispatching to
@@ -1550,6 +1565,57 @@ impl ECStore {
result
}
async fn walk_authoritatively(
self: Arc<Self>,
cancellation: CancellationToken,
bucket: &str,
prefix: &str,
result: Sender<ObjectInfoOrErr>,
opts: WalkOptions,
) -> Result<()> {
let cancel = cancellation.child_token();
let _cancel_on_drop = cancel.clone().drop_guard();
let mut scans = Vec::new();
let mut inputs = Vec::new();
for pool in &self.pools {
for set in &pool.disk_set {
let (sender, receiver) = mpsc::channel(1);
inputs.push(receiver);
let mut scan = recursive_walk_list_path_options(bucket.to_owned(), prefix, &opts);
// Internal absence checks must include reserved object prefixes.
scan.skip_hidden_prefix_check = true;
scans.push(set.list_versions_authoritatively(cancel.clone(), scan, sender));
}
}
if scans.is_empty() {
return Err(StorageError::ErasureReadQuorum);
}
let (sender, receiver) = mpsc::channel(100);
let forwarder = spawn_walk_entry_forwarder(cancel.clone(), receiver, result, opts, bucket.to_owned());
let merge = spawn_listing_merge(cancel.clone(), inputs, sender);
let scan_results = join_all(scans).await;
let merge_result = merge.await.map_err(Error::from)?;
let forward_result = forwarder.await.map_err(Error::from);
// An unavailable set cannot establish absence, even when another set
// completed. Only an explicitly missing directory or volume is empty.
for scan in scan_results {
match scan {
Ok(outcome) if !outcome.limit_reached => {}
Ok(_) => return Err(StorageError::ErasureReadQuorum),
Err(StorageError::FileNotFound | StorageError::VolumeNotFound) => {}
Err(err) => return Err(err),
}
}
merge_result?;
forward_result?;
if cancellation.is_cancelled() {
return Err(Error::other("authoritative object walk was cancelled"));
}
Ok(())
}
}
/// Forwards merged raw entries to a walk consumer as `ObjectInfoOrErr`,
@@ -2520,7 +2586,8 @@ impl SetDisks {
/// Version scan for set-scoped callers that act on absence: set walks
/// (tier reference proofs, tier-delete journals, pool maintenance) and the
/// recursive prefix-delete scan. Every online drive is read and each
/// version is resolved at the read quorum of its own erasure layout; a
/// version uses the read quorum of its own erasure layout. Null versions
/// in the system bucket also retain GET's commit-proof selection. A
/// version that cannot be ruled out fails the scan instead of being
/// omitted. Merged `ListObjectVersions` pages go through `list_path`.
async fn list_versions_authoritatively(
@@ -2859,6 +2926,7 @@ mod test {
use crate::error::{Result, StorageError};
use crate::object_api::{ObjectInfo, ObjectOptions, PutObjReader};
use crate::set_disk::{SetDisks, hermetic_set_disks_isolated};
use crate::storage_api_contracts::list::AuthoritativeListOperations as _;
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use crate::storage_api_contracts::object::ObjectIO as _;
use bytes::Bytes;
@@ -5719,6 +5787,126 @@ mod test {
));
}
#[test]
fn authoritative_system_bucket_scan_rejects_uncommitted_null_version_split() {
let time = time::OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid fixture time");
let old = test_unversioned_object_meta_entry("entry.json", time, "old", Uuid::from_u128(1));
for new_etag in ["new", "old"] {
let new =
test_unversioned_object_meta_entry("entry.json", time + time::Duration::seconds(1), new_etag, Uuid::from_u128(2));
let entries = MetaCacheEntries(vec![Some(old.clone()), Some(old.clone()), Some(new.clone()), Some(new)]);
assert!(matches!(
SetDisks::resolve_listed_versions(RUSTFS_META_BUCKET, entries, &[None, None, None, None], 4, 2),
Err(DiskError::ErasureReadQuorum)
));
}
}
#[test]
fn authoritative_system_bucket_scan_selects_committed_null_version() {
let time = time::OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid fixture time");
let old = test_unversioned_object_meta_entry("entry.json", time, "old", Uuid::from_u128(1));
let new = test_unversioned_object_meta_entry("entry.json", time + time::Duration::seconds(1), "new", Uuid::from_u128(2));
for (new_copies, expected) in [(1, "old"), (3, "new"), (4, "new")] {
let entries = MetaCacheEntries(
(0..4)
.map(|slot| Some(if slot < new_copies { new.clone() } else { old.clone() }))
.collect(),
);
let resolved = SetDisks::resolve_listed_versions(RUSTFS_META_BUCKET, entries, &[None, None, None, None], 4, 2)
.expect("committed generation should resolve")
.expect("committed record should be present");
let info = resolved
.to_fileinfo(RUSTFS_META_BUCKET)
.expect("resolved metadata should decode");
assert_eq!(info.metadata.get("etag").map(String::as_str), Some(expected));
}
}
#[test]
fn authoritative_system_bucket_scan_matches_degraded_null_version_reads() {
let time = time::OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid fixture time");
let old = test_unversioned_object_meta_entry("entry.json", time, "old", Uuid::from_u128(1));
let new = test_unversioned_object_meta_entry("entry.json", time + time::Duration::seconds(1), "new", Uuid::from_u128(2));
for (old_copies, new_copies, expected) in [
(2, 1, Some("old")),
(1, 2, None),
(0, 3, Some("new")),
(0, 2, Some("new")),
(0, 1, None),
] {
let entries = MetaCacheEntries(
(0..4)
.map(|slot| {
if slot < old_copies {
Some(old.clone())
} else if slot < old_copies + new_copies {
Some(new.clone())
} else {
None
}
})
.collect(),
);
let errors = (0..4)
.map(|slot| (slot >= old_copies + new_copies).then_some(DiskError::DiskNotFound))
.collect::<Vec<_>>();
let resolved = SetDisks::resolve_listed_versions(RUSTFS_META_BUCKET, entries, &errors, 4, 2);
if let Some(expected) = expected {
let info = resolved
.expect("degraded committed record should resolve")
.expect("degraded committed record should be present")
.to_fileinfo(RUSTFS_META_BUCKET)
.expect("resolved metadata should decode");
assert_eq!(info.metadata.get("etag").map(String::as_str), Some(expected));
} else {
assert!(matches!(resolved, Err(DiskError::ErasureReadQuorum)));
}
}
}
#[test]
fn authoritative_user_bucket_scan_keeps_null_version_read_quorum_selection() {
let time = time::OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid fixture time");
let old = test_unversioned_object_meta_entry("entry.json", time, "old", Uuid::from_u128(1));
let new = test_unversioned_object_meta_entry("entry.json", time + time::Duration::seconds(1), "new", Uuid::from_u128(2));
for old_copies in [1, 2] {
let entries = MetaCacheEntries(vec![
Some(new.clone()),
Some(new.clone()),
Some(old.clone()),
(old_copies == 2).then(|| old.clone()),
]);
let errors = [None, None, None, (old_copies == 1).then_some(DiskError::DiskNotFound)];
let resolved = SetDisks::resolve_listed_versions("bucket", entries, &errors, 4, 2)
.expect("user bucket read quorum should resolve")
.expect("user bucket record should be present");
let info = resolved.to_fileinfo("bucket").expect("resolved metadata should decode");
assert_eq!(info.metadata.get("etag").map(String::as_str), Some("new"));
}
}
#[test]
fn authoritative_system_bucket_scan_keeps_explicit_version_read_quorum() {
let time = time::OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid fixture time");
let entry = test_object_meta_entry_with_erasure_versions("entry.json", &[(time, "version", 2, 2)]);
let entries = MetaCacheEntries(vec![Some(entry.clone()), Some(entry), None, None]);
let errors = [None, None, Some(DiskError::DiskNotFound), Some(DiskError::DiskNotFound)];
let resolved = SetDisks::resolve_listed_versions(RUSTFS_META_BUCKET, entries, &errors, 4, 2)
.expect("explicit version read quorum should resolve")
.expect("explicit version should be present");
let info = resolved
.to_fileinfo(RUSTFS_META_BUCKET)
.expect("resolved metadata should decode");
assert_eq!(info.version_id, Some(Uuid::from_u128(1)));
assert_eq!(info.metadata.get("etag").map(String::as_str), Some("version"));
}
#[test]
fn authoritative_version_scan_tolerates_corrupt_replicas_only_with_version_quorum() {
let entry = test_object_meta_entry_with_erasure_versions(
@@ -6060,6 +6248,49 @@ mod test {
Bytes::from(meta.marshal_msg().expect("encode fixture xl.meta"))
}
#[tokio::test]
async fn authoritative_store_walk_includes_reserved_prefix_versions() {
let bucket = "catalog-cleanup-versions";
let name = ".rustfs-table/namespaces/ns/tables/table/metadata/metadata.json";
let (_dirs, store) = single_set_store(16).await;
let set = &store.pools[0].disk_set[0];
for (slot, disk) in set.disks.read().await.iter().enumerate() {
let disk = disk.as_ref().expect("fixture drive is online");
disk.make_volume(bucket).await.expect("create bucket volume");
disk.write_all(
bucket,
&format!("{name}/{STORAGE_FORMAT_FILE}"),
versioned_object_metadata(bucket, name, &[(2, 1_700_000_002), (1, 1_700_000_001)], slot),
)
.await
.expect("persist reserved metadata versions");
}
let (sender, mut receiver) = mpsc::channel(1);
let walk = store
.clone()
.walk_authoritative(CancellationToken::new(), bucket, "", sender, super::WalkOptions::default());
let collect = async {
let mut versions = Vec::new();
while let Some(item) = receiver.recv().await {
assert!(item.err.is_none(), "reserved metadata must decode: {:?}", item.err);
let item = item.item.expect("walk must return an object");
versions.push((item.name, item.version_id));
}
versions
};
let (walk, versions) = timeout(Duration::from_secs(10), async { tokio::join!(walk, collect) })
.await
.expect("authoritative reserved-prefix walk must terminate");
walk.expect("authoritative walk must succeed");
assert_eq!(
versions,
[
(name.to_string(), Some(Uuid::from_u128(1))),
(name.to_string(), Some(Uuid::from_u128(2)))
]
);
}
// A versioned DeleteObject(versionId) can reach write quorum while three
// drives are offline; they keep the deleted version after they return. A
// different drive going offline later must not turn that sub-quorum
@@ -6130,6 +6361,16 @@ mod test {
.await
.expect("set walk must terminate");
assert!(matches!(walk, Err(StorageError::ErasureReadQuorum)), "{walk:?}");
let (sender, mut receiver) = mpsc::channel(16);
let walk =
store
.clone()
.walk_authoritative(CancellationToken::new(), bucket, "", sender, super::WalkOptions::default());
let drain = async { while receiver.recv().await.is_some() {} };
let (walk, ()) = timeout(Duration::from_secs(10), async { tokio::join!(walk, drain) })
.await
.expect("authoritative store walk must terminate");
assert!(matches!(walk, Err(StorageError::ErasureReadQuorum)), "{walk:?}");
let recursive_delete_scan = set
.clone()
.inner_list_object_versions_for_recursive_delete(bucket, "", None, None, 1000)
+21 -5
View File
@@ -19,10 +19,28 @@ use crate::set_disk::get_lock_acquire_timeout;
use crate::storage_api_contracts::multipart::MultipartOperations as _;
use crate::storage_api_contracts::object::ObjectOperations as _;
use futures::{StreamExt, stream};
use rustfs_utils::path::encode_dir_object_ref;
use std::collections::HashSet;
const MULTIPART_LIST_SET_CONCURRENCY: usize = 4;
#[async_trait::async_trait]
impl crate::storage_api_contracts::multipart::MultipartUploadInspection for ECStore {
type Error = Error;
async fn ensure_no_multipart_uploads(&self, bucket: &str) -> Result<()> {
let (_, lifecycle_guard) = self
.guard_multipart_bucket_incarnation(bucket, &ObjectOptions::default())
.await?;
for pool in &self.pools {
for set in &pool.disk_set {
set.ensure_no_multipart_uploads(bucket).await?;
}
}
ensure_multipart_bucket_lifecycle_guard_held(lifecycle_guard.as_ref(), bucket, "")
}
}
#[cfg(test)]
static DATA_MOVEMENT_MULTIPART_DISCOVERY_COUNTS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<Uuid, usize>>> =
std::sync::OnceLock::new();
@@ -1168,11 +1186,9 @@ impl ECStore {
let oi = if require_all_pools {
lookup_opts.metadata_cache_safe = false;
lookup_opts.suppress_read_repair = true;
if let Err(err) = check_object_args(bucket, object) {
return Some(err);
}
let encoded_object = encode_dir_object(object);
self.get_latest_object_info_for_conditional_write(bucket, &encoded_object, &lookup_opts)
// Only completion uses this branch, after validating bucket and object.
let encoded_object = encode_dir_object_ref(object);
self.get_latest_object_info_for_conditional_write(bucket, encoded_object.as_ref(), &lookup_opts)
.await
.and_then(|(info, _)| {
lookup_opts.precondition_check(&info)?;
+6 -8
View File
@@ -1081,7 +1081,7 @@ impl ChecksumHasher for Sha512Hasher {
/// MD5 hasher for the ADDITIONAL checksum (x-amz-checksum-md5). Separate from the
/// legacy Content-MD5 / ETag machinery — this only serves the flexible-checksum path.
pub struct Md5Hasher {
hasher: md5::Md5,
hasher: rustfs_utils::FastMd5,
}
impl Default for Md5Hasher {
@@ -1092,14 +1092,14 @@ impl Default for Md5Hasher {
impl Md5Hasher {
pub fn new() -> Self {
use md5::Digest as _;
Self { hasher: md5::Md5::new() }
Self {
hasher: rustfs_utils::FastMd5::new(),
}
}
}
impl Write for Md5Hasher {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
use md5::Digest as _;
self.hasher.update(buf);
Ok(buf.len())
}
@@ -1111,13 +1111,11 @@ impl Write for Md5Hasher {
impl ChecksumHasher for Md5Hasher {
fn finalize(&mut self) -> Vec<u8> {
use md5::Digest as _;
self.hasher.clone().finalize().to_vec()
self.hasher.finalize_bytes().to_vec()
}
fn reset(&mut self) {
use md5::Digest as _;
self.hasher = md5::Md5::new();
self.hasher.reset();
}
}
+102 -28
View File
@@ -15,8 +15,8 @@
use crate::compress_index::{Index, TryGetIndex};
use crate::{BadDigest, EtagResolvable, HashReaderDetector, HashReaderMut};
use hmac::{Hmac, KeyInit, Mac};
use md5::{Digest, Md5};
use pin_project_lite::pin_project;
use rustfs_utils::FastMd5;
use sha2::Sha256;
use std::pin::Pin;
use std::task::{Context, Poll};
@@ -27,11 +27,12 @@ pin_project! {
pub struct EtagReader<R> {
#[pin]
pub inner: R,
pub md5: Md5,
pub md5: FastMd5,
pub finished: bool,
pub checksum: Option<String>,
resolved_etag: Option<String>,
encrypted_etag_mac: Option<Hmac<Sha256>>,
delegate_inner_etag: bool,
}
}
@@ -39,11 +40,12 @@ impl<R> EtagReader<R> {
pub fn new(inner: R, checksum: Option<String>) -> Self {
Self {
inner,
md5: Md5::new(),
md5: FastMd5::new(),
finished: false,
checksum,
resolved_etag: None,
encrypted_etag_mac: None,
delegate_inner_etag: false,
}
}
@@ -58,6 +60,17 @@ impl<R> EtagReader<R> {
Ok(reader)
}
/// Reuse the inner reader's plaintext ETag when deriving an encrypted ETag,
/// avoiding a redundant second MD5 pass over the same plaintext stream.
pub fn with_inner_etag_delegation(mut self, delegate: bool) -> Self
where
R: EtagResolvable,
{
self.delegate_inner_etag =
delegate && self.encrypted_etag_mac.is_some() && self.checksum.is_none() && self.inner.is_etag_reader();
self
}
/// Get the final md5 value (etag) as a hex string, only compute once.
/// Can be called multiple times, always returns the same result after finished.
pub fn get_etag(&mut self) -> String {
@@ -65,8 +78,8 @@ impl<R> EtagReader<R> {
return etag.clone();
}
let etag = self.md5.clone().finalize().to_vec();
let etag = hex_simd::encode_to_string(etag, hex_simd::AsciiCase::Lower);
let digest = self.md5.finalize_bytes();
let etag = hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower);
self.resolved_etag = Some(etag.clone());
etag
}
@@ -87,30 +100,32 @@ where
if let Poll::Ready(Ok(())) = &poll {
let filled = &buf.filled()[orig_filled..];
if !filled.is_empty() {
this.md5.update(filled);
if !*this.delegate_inner_etag {
this.md5.update(filled);
}
} else {
// EOF
*this.finished = true;
let etag = if let Some(etag) = this.resolved_etag.as_ref() {
etag.clone()
} else {
let etag = this.md5.clone().finalize().to_vec();
let etag = hex_simd::encode_to_string(etag, hex_simd::AsciiCase::Lower);
*this.resolved_etag = Some(etag.clone());
etag
};
if let Some(checksum) = this.checksum {
let etag = if let Some(etag) = this.resolved_etag.as_ref() {
etag.clone()
} else {
let digest = this.md5.finalize_bytes();
let etag = hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower);
*this.resolved_etag = Some(etag.clone());
etag
};
if let Some(checksum) = this.checksum
&& *checksum != etag
{
error!("Checksum mismatch, expected={:?}, actual={:?}", checksum, etag);
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
BadDigest {
expected_md5: checksum.clone(),
calculated_md5: etag,
},
)));
if *checksum != etag {
error!("Checksum mismatch, expected={:?}, actual={:?}", checksum, etag);
return Poll::Ready(Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
BadDigest {
expected_md5: checksum.clone(),
calculated_md5: etag,
},
)));
}
}
}
}
@@ -118,16 +133,24 @@ where
}
}
impl<R> EtagResolvable for EtagReader<R> {
impl<R> EtagResolvable for EtagReader<R>
where
R: EtagResolvable,
{
fn is_etag_reader(&self) -> bool {
true
!self.delegate_inner_etag || self.inner.is_etag_reader()
}
fn try_resolve_etag(&mut self) -> Option<String> {
if let Some(mut mac) = self.encrypted_etag_mac.clone() {
if !self.finished {
return None;
}
mac.update(self.get_etag().as_bytes());
let plaintext_etag = if self.delegate_inner_etag {
self.inner.try_resolve_etag()?
} else {
self.get_etag()
};
mac.update(plaintext_etag.as_bytes());
let protected = mac.finalize().into_bytes();
return Some(hex_simd::encode_to_string(&protected[..16], hex_simd::AsciiCase::Lower));
}
@@ -167,6 +190,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
use md5::{Digest, Md5};
use rand::RngExt;
use std::io::Cursor;
use tokio::io::{AsyncReadExt, BufReader};
@@ -340,4 +364,54 @@ mod tests {
assert_eq!(digest.expected_md5, wrong_checksum);
assert_eq!(digest.calculated_md5, calculated_md5);
}
#[tokio::test]
async fn encrypted_etag_reader_with_inner_delegation_matches_standalone() {
let data = b"delegated encrypted etag payload across multiple 64-byte MD5 blocks for verification";
let key = [0x42; 32];
let nonce = [0x24; 12];
let mut standalone =
EtagReader::new_encrypted(Cursor::new(data.as_slice()), key, nonce).expect("standalone encrypted EtagReader");
let mut out_standalone = Vec::new();
standalone.read_to_end(&mut out_standalone).await.expect("read standalone");
let expected_tag = standalone.try_resolve_etag().expect("standalone etag");
let inner =
crate::HashReader::from_stream(Cursor::new(data.as_slice()), data.len() as i64, data.len() as i64, None, None, false)
.expect("inner HashReader");
assert!(inner.is_etag_reader(), "HashReader with diskable_md5=false must report is_etag_reader");
let mut delegated = EtagReader::new_encrypted(inner, key, nonce)
.expect("delegated encrypted EtagReader")
.with_inner_etag_delegation(true);
let mut out_delegated = Vec::new();
delegated.read_to_end(&mut out_delegated).await.expect("read delegated");
assert_eq!(out_delegated, data);
assert_eq!(
delegated.try_resolve_etag().as_deref(),
Some(expected_tag.as_str()),
"delegated encrypted EtagReader must produce identical HMAC ETag without re-hashing plaintext"
);
let truncated = crate::LimitReader::new(
crate::HashReader::from_stream(Cursor::new(data.as_slice()), data.len() as i64, data.len() as i64, None, None, false)
.expect("inner HashReader for limit"),
16,
);
assert!(
!truncated.is_etag_reader(),
"truncating LimitReader must not advertise inner ETag delegation"
);
let mut non_etag_inner = EtagReader::new_encrypted(Cursor::new(data.as_slice()), key, nonce)
.expect("encrypted EtagReader over Cursor")
.with_inner_etag_delegation(true);
let mut out_cursor = Vec::new();
non_etag_inner.read_to_end(&mut out_cursor).await.expect("read cursor");
assert_eq!(
non_etag_inner.try_resolve_etag().as_deref(),
Some(expected_tag.as_str()),
"delegation request on non-EtagResolvable inner must keep outer MD5 hashing active"
);
}
}
+4
View File
@@ -630,6 +630,10 @@ impl AsyncRead for HashReader {
}
impl EtagResolvable for HashReader {
fn is_etag_reader(&self) -> bool {
!self.diskable_md5 && self.inner.is_etag_reader()
}
fn try_resolve_etag(&mut self) -> Option<String> {
if self.diskable_md5 {
return None;
+21
View File
@@ -201,10 +201,31 @@ where
boxed_reader(WarpReader::new(reader))
}
impl<T> EtagResolvable for std::io::Cursor<T> {}
impl EtagResolvable for &[u8] {}
impl<R> EtagResolvable for tokio::io::BufReader<R>
where
R: tokio::io::AsyncRead + EtagResolvable,
{
fn is_etag_reader(&self) -> bool {
self.get_ref().is_etag_reader()
}
fn try_resolve_etag(&mut self) -> Option<String> {
self.get_mut().try_resolve_etag()
}
}
impl<T> EtagResolvable for Box<T>
where
T: EtagResolvable + ?Sized,
{
fn is_etag_reader(&self) -> bool {
self.as_ref().is_etag_reader()
}
fn try_resolve_etag(&mut self) -> Option<String> {
self.as_mut().try_resolve_etag()
}
+2
View File
@@ -90,7 +90,9 @@ pub use bucket::BUCKET_LIFECYCLE_LOCK_OBJECT;
pub use bucket::{BucketInfo, BucketOperations, BucketOptions, DeleteBucketOptions, MakeBucketOptions, SRBucketDeleteOp};
pub use capability::{CapabilitySnapshotError, CapabilityState, CapabilityStatus};
pub use error::{StorageErrorCode, StorageResult};
pub use multipart::MultipartUploadInspection;
pub use multipart::{CompletePart, ListMultipartsInfo, ListPartsInfo, MultipartInfo, MultipartUploadResult, PartInfo};
pub use object::AuthoritativeListOperations;
pub use object::DeleteAccounting;
pub use object::ObjectLockDeleteOptions;
pub use object::ObjectToDeleteIdentity;
+9
View File
@@ -15,6 +15,15 @@
use std::collections::HashMap;
use time::OffsetDateTime;
/// Checks upload absence before removing a bucket's data protections.
#[async_trait::async_trait]
pub trait MultipartUploadInspection: Send + Sync {
type Error: std::error::Error + Send + Sync + 'static;
/// Unknown or unreadable upload ownership must fail this check.
async fn ensure_no_multipart_uploads(&self, bucket: &str) -> Result<(), Self::Error>;
}
#[derive(Debug, Default, Clone)]
pub struct MultipartUploadResult {
pub upload_id: String,
+23
View File
@@ -566,6 +566,29 @@ pub trait ListOperations: Send + Sync + fmt::Debug {
) -> Result<(), Self::Error>;
}
/// Quorum-backed enumeration for decisions that require proving object absence.
///
/// Consumers must drain the result stream and await successful completion before
/// trusting the scan. An error or cancellation can follow partial results and
/// leaves absence unproven. Callers coordinate concurrent mutations separately;
/// this capability does not provide a snapshot or retain a mutation lock.
#[async_trait::async_trait]
pub trait AuthoritativeListOperations: ListOperations {
/// Resolves every set at its version read quorum, including reserved prefixes.
///
/// # Errors
/// Returns an error when a set cannot establish quorum, metadata cannot be
/// resolved, or enumeration is interrupted. Retry starts a new scan.
async fn walk_authoritative(
self: Arc<Self>,
rx: Self::WalkCancellation,
bucket: &str,
prefix: &str,
result: Self::WalkResultSender,
opts: Self::WalkOptions,
) -> Result<(), Self::Error>;
}
#[async_trait::async_trait]
#[allow(clippy::too_many_arguments)]
pub trait MultipartOperations: Send + Sync + fmt::Debug {
+315 -4
View File
@@ -14,9 +14,300 @@
use blake2::Blake2b512;
use highway::{HighwayHash, HighwayHasher, Key};
use md5::Md5;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::hint::black_box;
const MD5_INITIAL_STATE: [u32; 4] = [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
const MD5_RC: [u32; 64] = [
0xd76a_a478,
0xe8c7_b756,
0x2420_70db,
0xc1bd_ceee,
0xf57c_0faf,
0x4787_c62a,
0xa830_4613,
0xfd46_9501,
0x6980_98d8,
0x8b44_f7af,
0xffff_5bb1,
0x895c_d7be,
0x6b90_1122,
0xfd98_7193,
0xa679_438e,
0x49b4_0821,
0xf61e_2562,
0xc040_b340,
0x265e_5a51,
0xe9b6_c7aa,
0xd62f_105d,
0x0244_1453,
0xd8a1_e681,
0xe7d3_fbc8,
0x21e1_cde6,
0xc337_07d6,
0xf4d5_0d87,
0x455a_14ed,
0xa9e3_e905,
0xfcef_a3f8,
0x676f_02d9,
0x8d2a_4c8a,
0xfffa_3942,
0x8771_f681,
0x6d9d_6122,
0xfde5_380c,
0xa4be_ea44,
0x4bde_cfa9,
0xf6bb_4b60,
0xbebf_bc70,
0x289b_7ec6,
0xeaa1_27fa,
0xd4ef_3085,
0x0488_1d05,
0xd9d4_d039,
0xe6db_99e5,
0x1fa2_7cf8,
0xc4ac_5665,
0xf429_2244,
0x432a_ff97,
0xab94_23a7,
0xfc93_a039,
0x655b_59c3,
0x8f0c_cc92,
0xffef_f47d,
0x8584_5dd1,
0x6fa8_7e4f,
0xfe2c_e6e0,
0xa301_4314,
0x4e08_11a1,
0xf753_7e82,
0xbd3a_f235,
0x2ad7_d2bb,
0xeb86_d391,
];
#[inline(always)]
fn md5_op_f(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 {
// Keep `w + m + c` off the `x` critical dependency path from the previous round.
let base = black_box(w.wrapping_add(m).wrapping_add(c));
let f = z ^ (x & (y ^ z));
base.wrapping_add(f).rotate_left(s).wrapping_add(x)
}
#[inline(always)]
fn md5_op_g(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 {
let base = black_box(w.wrapping_add(m).wrapping_add(c)).wrapping_add(y & !z);
base.wrapping_add(x & z).rotate_left(s).wrapping_add(x)
}
#[inline(always)]
fn md5_op_h(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 {
let base = black_box(w.wrapping_add(m).wrapping_add(c));
base.wrapping_add(x ^ (y ^ z)).rotate_left(s).wrapping_add(x)
}
#[inline(always)]
fn md5_op_i(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 {
let base = black_box(w.wrapping_add(m).wrapping_add(c));
base.wrapping_add(y ^ (x | !z)).rotate_left(s).wrapping_add(x)
}
#[inline(always)]
fn md5_word(words: &[[u8; 4]], idx: usize) -> u32 {
u32::from_le_bytes(words[idx])
}
#[inline]
pub fn compress_md5_blocks(state: &mut [u32; 4], blocks: &[[u8; 64]]) {
let [mut a, mut b, mut c, mut d] = *state;
for block in blocks {
let words = block.as_chunks::<4>().0;
let aa = a;
let bb = b;
let cc = c;
let dd = d;
a = md5_op_f(a, b, c, d, md5_word(words, 0), MD5_RC[0], 7);
d = md5_op_f(d, a, b, c, md5_word(words, 1), MD5_RC[1], 12);
c = md5_op_f(c, d, a, b, md5_word(words, 2), MD5_RC[2], 17);
b = md5_op_f(b, c, d, a, md5_word(words, 3), MD5_RC[3], 22);
a = md5_op_f(a, b, c, d, md5_word(words, 4), MD5_RC[4], 7);
d = md5_op_f(d, a, b, c, md5_word(words, 5), MD5_RC[5], 12);
c = md5_op_f(c, d, a, b, md5_word(words, 6), MD5_RC[6], 17);
b = md5_op_f(b, c, d, a, md5_word(words, 7), MD5_RC[7], 22);
a = md5_op_f(a, b, c, d, md5_word(words, 8), MD5_RC[8], 7);
d = md5_op_f(d, a, b, c, md5_word(words, 9), MD5_RC[9], 12);
c = md5_op_f(c, d, a, b, md5_word(words, 10), MD5_RC[10], 17);
b = md5_op_f(b, c, d, a, md5_word(words, 11), MD5_RC[11], 22);
a = md5_op_f(a, b, c, d, md5_word(words, 12), MD5_RC[12], 7);
d = md5_op_f(d, a, b, c, md5_word(words, 13), MD5_RC[13], 12);
c = md5_op_f(c, d, a, b, md5_word(words, 14), MD5_RC[14], 17);
b = md5_op_f(b, c, d, a, md5_word(words, 15), MD5_RC[15], 22);
a = md5_op_g(a, b, c, d, md5_word(words, 1), MD5_RC[16], 5);
d = md5_op_g(d, a, b, c, md5_word(words, 6), MD5_RC[17], 9);
c = md5_op_g(c, d, a, b, md5_word(words, 11), MD5_RC[18], 14);
b = md5_op_g(b, c, d, a, md5_word(words, 0), MD5_RC[19], 20);
a = md5_op_g(a, b, c, d, md5_word(words, 5), MD5_RC[20], 5);
d = md5_op_g(d, a, b, c, md5_word(words, 10), MD5_RC[21], 9);
c = md5_op_g(c, d, a, b, md5_word(words, 15), MD5_RC[22], 14);
b = md5_op_g(b, c, d, a, md5_word(words, 4), MD5_RC[23], 20);
a = md5_op_g(a, b, c, d, md5_word(words, 9), MD5_RC[24], 5);
d = md5_op_g(d, a, b, c, md5_word(words, 14), MD5_RC[25], 9);
c = md5_op_g(c, d, a, b, md5_word(words, 3), MD5_RC[26], 14);
b = md5_op_g(b, c, d, a, md5_word(words, 8), MD5_RC[27], 20);
a = md5_op_g(a, b, c, d, md5_word(words, 13), MD5_RC[28], 5);
d = md5_op_g(d, a, b, c, md5_word(words, 2), MD5_RC[29], 9);
c = md5_op_g(c, d, a, b, md5_word(words, 7), MD5_RC[30], 14);
b = md5_op_g(b, c, d, a, md5_word(words, 12), MD5_RC[31], 20);
a = md5_op_h(a, b, c, d, md5_word(words, 5), MD5_RC[32], 4);
d = md5_op_h(d, a, b, c, md5_word(words, 8), MD5_RC[33], 11);
c = md5_op_h(c, d, a, b, md5_word(words, 11), MD5_RC[34], 16);
b = md5_op_h(b, c, d, a, md5_word(words, 14), MD5_RC[35], 23);
a = md5_op_h(a, b, c, d, md5_word(words, 1), MD5_RC[36], 4);
d = md5_op_h(d, a, b, c, md5_word(words, 4), MD5_RC[37], 11);
c = md5_op_h(c, d, a, b, md5_word(words, 7), MD5_RC[38], 16);
b = md5_op_h(b, c, d, a, md5_word(words, 10), MD5_RC[39], 23);
a = md5_op_h(a, b, c, d, md5_word(words, 13), MD5_RC[40], 4);
d = md5_op_h(d, a, b, c, md5_word(words, 0), MD5_RC[41], 11);
c = md5_op_h(c, d, a, b, md5_word(words, 3), MD5_RC[42], 16);
b = md5_op_h(b, c, d, a, md5_word(words, 6), MD5_RC[43], 23);
a = md5_op_h(a, b, c, d, md5_word(words, 9), MD5_RC[44], 4);
d = md5_op_h(d, a, b, c, md5_word(words, 12), MD5_RC[45], 11);
c = md5_op_h(c, d, a, b, md5_word(words, 15), MD5_RC[46], 16);
b = md5_op_h(b, c, d, a, md5_word(words, 2), MD5_RC[47], 23);
a = md5_op_i(a, b, c, d, md5_word(words, 0), MD5_RC[48], 6);
d = md5_op_i(d, a, b, c, md5_word(words, 7), MD5_RC[49], 10);
c = md5_op_i(c, d, a, b, md5_word(words, 14), MD5_RC[50], 15);
b = md5_op_i(b, c, d, a, md5_word(words, 5), MD5_RC[51], 21);
a = md5_op_i(a, b, c, d, md5_word(words, 12), MD5_RC[52], 6);
d = md5_op_i(d, a, b, c, md5_word(words, 3), MD5_RC[53], 10);
c = md5_op_i(c, d, a, b, md5_word(words, 10), MD5_RC[54], 15);
b = md5_op_i(b, c, d, a, md5_word(words, 1), MD5_RC[55], 21);
a = md5_op_i(a, b, c, d, md5_word(words, 8), MD5_RC[56], 6);
d = md5_op_i(d, a, b, c, md5_word(words, 15), MD5_RC[57], 10);
c = md5_op_i(c, d, a, b, md5_word(words, 6), MD5_RC[58], 15);
b = md5_op_i(b, c, d, a, md5_word(words, 13), MD5_RC[59], 21);
a = md5_op_i(a, b, c, d, md5_word(words, 4), MD5_RC[60], 6);
d = md5_op_i(d, a, b, c, md5_word(words, 11), MD5_RC[61], 10);
c = md5_op_i(c, d, a, b, md5_word(words, 2), MD5_RC[62], 15);
b = md5_op_i(b, c, d, a, md5_word(words, 9), MD5_RC[63], 21);
a = a.wrapping_add(aa);
b = b.wrapping_add(bb);
c = c.wrapping_add(cc);
d = d.wrapping_add(dd);
}
*state = [a, b, c, d];
}
#[inline]
fn finalize_md5_state(mut state: [u32; 4], tail: &[u8], total_bytes: u64) -> [u8; 16] {
debug_assert!(tail.len() < 64);
let mut pad = [0u8; 128];
pad[..tail.len()].copy_from_slice(tail);
pad[tail.len()] = 0x80;
let bit_len = total_bytes.wrapping_mul(8).to_le_bytes();
if tail.len() < 56 {
pad[56..64].copy_from_slice(&bit_len);
compress_md5_blocks(&mut state, pad[..64].as_chunks::<64>().0);
} else {
pad[120..128].copy_from_slice(&bit_len);
compress_md5_blocks(&mut state, pad.as_chunks::<64>().0);
}
let mut out = [0u8; 16];
out[0..4].copy_from_slice(&state[0].to_le_bytes());
out[4..8].copy_from_slice(&state[1].to_le_bytes());
out[8..12].copy_from_slice(&state[2].to_le_bytes());
out[12..16].copy_from_slice(&state[3].to_le_bytes());
out
}
/// Streaming MD5 hasher using critical-path ILP reassociation and direct slice chunking.
#[derive(Clone, Debug)]
pub struct FastMd5 {
state: [u32; 4],
buf: [u8; 64],
buf_len: usize,
total_bytes: u64,
}
impl Default for FastMd5 {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl FastMd5 {
#[inline]
pub const fn new() -> Self {
Self {
state: MD5_INITIAL_STATE,
buf: [0u8; 64],
buf_len: 0,
total_bytes: 0,
}
}
#[inline]
pub fn reset(&mut self) {
self.state = MD5_INITIAL_STATE;
self.buf_len = 0;
self.total_bytes = 0;
}
#[inline]
pub fn update(&mut self, mut data: &[u8]) {
if data.is_empty() {
return;
}
self.total_bytes = self.total_bytes.wrapping_add(data.len() as u64);
if self.buf_len > 0 {
let need = 64 - self.buf_len;
if data.len() < need {
self.buf[self.buf_len..self.buf_len + data.len()].copy_from_slice(data);
self.buf_len += data.len();
return;
}
self.buf[self.buf_len..64].copy_from_slice(&data[..need]);
compress_md5_blocks(&mut self.state, std::slice::from_ref(&self.buf));
self.buf_len = 0;
data = &data[need..];
}
let (blocks, remainder) = data.as_chunks::<64>();
if !blocks.is_empty() {
compress_md5_blocks(&mut self.state, blocks);
}
if !remainder.is_empty() {
self.buf[..remainder.len()].copy_from_slice(remainder);
self.buf_len = remainder.len();
}
}
#[inline]
pub fn finalize_bytes(&self) -> [u8; 16] {
finalize_md5_state(self.state, &self.buf[..self.buf_len], self.total_bytes)
}
#[inline]
pub fn finalize(self) -> [u8; 16] {
self.finalize_bytes()
}
#[inline]
pub fn digest(data: &[u8]) -> [u8; 16] {
let mut state = MD5_INITIAL_STATE;
let (blocks, remainder) = data.as_chunks::<64>();
if !blocks.is_empty() {
compress_md5_blocks(&mut state, blocks);
}
finalize_md5_state(state, remainder, data.len() as u64)
}
}
/// Magic HH-256 key: HH-256 hash of first 100 decimals of π as utf-8 with zero key.
const MAGIC_HIGHWAY_HASH256_KEY: [u8; 32] = [
@@ -113,7 +404,7 @@ impl HashAlgorithm {
#[inline]
pub fn hash_encode(&self, data: &[u8]) -> impl AsRef<[u8]> {
match self {
HashAlgorithm::Md5 => HashEncoded::Md5(Md5::digest(data).into()),
HashAlgorithm::Md5 => HashEncoded::Md5(FastMd5::digest(data)),
HashAlgorithm::HighwayHash256 => {
let mut hasher = HighwayHasher::new(MAGIC_HIGHWAY_HASH256_PARSED_KEY);
hasher.append(data);
@@ -148,11 +439,11 @@ impl HashAlgorithm {
{
match self {
HashAlgorithm::Md5 => {
let mut hasher = Md5::new();
let mut hasher = FastMd5::new();
for slice in slices {
hasher.update(slice);
}
HashEncoded::Md5(hasher.finalize().into())
HashEncoded::Md5(hasher.finalize_bytes())
}
HashAlgorithm::HighwayHash256 => {
let mut hasher = HighwayHasher::new(MAGIC_HIGHWAY_HASH256_PARSED_KEY);
@@ -424,4 +715,24 @@ mod tests {
let blake_hash2 = HashAlgorithm::BLAKE2b512.hash_encode(data2);
assert_ne!(blake_hash1.as_ref(), blake_hash2.as_ref());
}
#[test]
fn fast_md5_matches_reference_across_boundaries_and_chunkings() {
use md5::{Digest as _, Md5};
for len in (0..=260).chain([511, 512, 513, 1024, 4096, 8193]) {
let data = generate_compat_test_data(len);
let expected: [u8; 16] = Md5::digest(&data).into();
assert_eq!(FastMd5::digest(&data), expected, "FastMd5::digest mismatch at len={len}");
for step in [1usize, 3, 7, 16, 31, 55, 56, 63, 64, 65, 128] {
let mut fast = FastMd5::new();
for chunk in data.chunks(step) {
fast.update(chunk);
}
assert_eq!(fast.finalize_bytes(), expected, "FastMd5 streaming mismatch at len={len}, step={step}");
assert_eq!(fast.finalize(), expected, "FastMd5 repeated finalize mismatch at len={len}, step={step}");
}
}
}
}
+458
View File
@@ -694,6 +694,358 @@ pub fn trim_etag(etag: &str) -> String {
etag.trim_matches('"').to_string()
}
/// Exact 64-bit SWAR byte equality mask for `b'.'` (`0x2e`) with zero cross-byte carry.
/// Bit `7 + 8 * k` is set in the returned mask iff byte `k` of `w` equals `b'.'`.
#[inline(always)]
const fn swar_exact_dot_mask(w: u64) -> u64 {
let x = w ^ 0x2e2e_2e2e_2e2e_2e2e;
let low = (x & 0x7f7f_7f7f_7f7f_7f7f).wrapping_add(0x7f7f_7f7f_7f7f_7f7f);
!(low | x) & 0x8080_8080_8080_8080
}
/// Exact 64-bit SWAR mask for `b'.'` (`0x2e`) or `b'/'` (`0x2f`) across all byte values `0x00..=0xFF`.
/// Since `0x2e` and `0x2f` differ only in bit 0, `(b & 0xfe) == 0x2e` holds iff `b` is `.` or `/`.
#[inline(always)]
const fn swar_exact_dot_or_slash_mask(w: u64) -> u64 {
swar_exact_dot_mask(w & 0xfefe_fefe_fefe_fefe)
}
#[inline(always)]
const fn is_unix_dot_or_dotdot_at(path: &[u8], dot_idx: usize) -> bool {
if dot_idx > 0 && path[dot_idx - 1] != b'/' {
return false;
}
let next = dot_idx + 1;
if next == path.len() || path[next] == b'/' {
return true;
}
path[next] == b'.' && (next + 1 == path.len() || path[next + 1] == b'/')
}
#[inline(always)]
const fn is_unix_dotdot_at(path: &[u8], dot_idx: usize) -> bool {
if dot_idx > 0 && path[dot_idx - 1] != b'/' {
return false;
}
let next = dot_idx + 1;
next < path.len() && path[next] == b'.' && (next + 1 == path.len() || path[next + 1] == b'/')
}
/// Returns `true` iff `path` (interpreted with Unix `/` separators) contains a `..` segment.
/// Scans 8 bytes at a time using carry-free 64-bit SWAR so ordinary filenames containing dots
/// (such as `xl.meta`, `part.1`, or `.rustfs.sys`) do not trigger component parsing.
#[inline]
pub const fn unix_path_has_dotdot_segment(path: &[u8]) -> bool {
let (chunks, rem) = path.as_chunks::<8>();
let mut c_idx = 0;
while c_idx < chunks.len() {
let mut mask = swar_exact_dot_mask(u64::from_le_bytes(chunks[c_idx]));
while mask != 0 {
let lane = (mask.trailing_zeros() >> 3) as usize;
if is_unix_dotdot_at(path, c_idx * 8 + lane) {
return true;
}
mask &= mask - 1;
}
c_idx += 1;
}
let base = chunks.len() * 8;
let mut r_idx = 0;
while r_idx < rem.len() {
if rem[r_idx] == b'.' && is_unix_dotdot_at(path, base + r_idx) {
return true;
}
r_idx += 1;
}
false
}
#[inline(always)]
const fn is_invalid_adjacent_dot_slash_pair(path: &[u8], idx: usize) -> bool {
let prev = path[idx - 1];
let curr = path[idx];
if prev == b'/' && curr == b'/' {
return true;
}
if prev == b'/' && curr == b'.' {
return is_unix_dot_or_dotdot_at(path, idx);
}
if prev == b'.' && curr == b'/' {
return is_unix_dot_or_dotdot_at(path, idx - 1);
}
if prev == b'.' && curr == b'.' {
return is_unix_dotdot_at(path, idx - 1);
}
false
}
/// Returns `true` when `path` is a non-empty Unix path with no repeated slashes (`//`),
/// no trailing slash (except `"/"`), and no `.` or `..` segments.
#[inline]
pub const fn unix_is_canonical_ascii_path(path: &[u8]) -> bool {
if path.is_empty() {
return false;
}
if path.len() == 1 {
return path[0] != b'.';
}
let first = path[0];
let last = path[path.len() - 1];
if last == b'/' || (first == b'.' && is_unix_dot_or_dotdot_at(path, 0)) {
return false;
}
let (chunks, rem) = path.as_chunks::<8>();
let mut c_idx = 0;
let mut prev_hi = 0u64;
while c_idx < chunks.len() {
let w = u64::from_le_bytes(chunks[c_idx]);
let m = swar_exact_dot_or_slash_mask(w);
let mut pair_mask = m & ((m << 8) | prev_hi);
while pair_mask != 0 {
let lane = (pair_mask.trailing_zeros() >> 3) as usize;
let idx = c_idx * 8 + lane;
if idx > 0 && is_invalid_adjacent_dot_slash_pair(path, idx) {
return false;
}
pair_mask &= pair_mask - 1;
}
prev_hi = m >> 56;
c_idx += 1;
}
let base = chunks.len() * 8;
let mut r_idx = 0;
while r_idx < rem.len() {
let b = rem[r_idx];
let idx = base + r_idx;
if (b == b'/' || b == b'.') && idx > 0 {
let prev = path[idx - 1];
if (prev == b'/' || prev == b'.') && is_invalid_adjacent_dot_slash_pair(path, idx) {
return false;
}
}
r_idx += 1;
}
true
}
#[inline(always)]
const fn trim_trailing_slashes_and_curdir(mut bytes: &[u8]) -> &[u8] {
while bytes.len() > 1 {
if bytes[bytes.len() - 1] == b'/' {
bytes = bytes.split_at(bytes.len() - 1).0;
} else if bytes.len() >= 2 && bytes[bytes.len() - 2] == b'/' && bytes[bytes.len() - 1] == b'.' {
if bytes.len() == 2 {
bytes = b"/";
break;
}
bytes = bytes.split_at(bytes.len() - 2).0;
} else {
break;
}
}
bytes
}
#[inline(always)]
const fn strip_leading_slashes_and_curdir(mut rem: &[u8]) -> &[u8] {
while !rem.is_empty() {
if rem[0] == b'/' {
rem = rem.split_at(1).1;
} else if rem.len() == 1 && rem[0] == b'.' {
rem = b"";
} else if rem.len() >= 2 && rem[0] == b'.' && rem[1] == b'/' {
rem = rem.split_at(2).1;
} else {
break;
}
}
rem
}
#[inline(always)]
fn unix_bytes_to_os_str(bytes: &[u8]) -> Option<&std::ffi::OsStr> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
Some(std::ffi::OsStr::from_bytes(bytes))
}
#[cfg(not(unix))]
{
std::str::from_utf8(bytes).ok().map(std::ffi::OsStr::new)
}
}
#[inline(always)]
fn unix_bytes_to_path(bytes: &[u8]) -> Option<&Path> {
unix_bytes_to_os_str(bytes).map(Path::new)
}
/// Fast Unix `Path::starts_with` when both `path` and `base` have already been normalized
/// (i.e. contain no `..` segments or leading `.`). Performs a single slice prefix comparison.
#[inline]
pub fn unix_normalized_path_starts_with(path: &Path, base: &Path) -> bool {
let p = path.as_os_str().as_encoded_bytes();
let b = trim_trailing_slashes_and_curdir(base.as_os_str().as_encoded_bytes());
if b.is_empty() {
return true;
}
if b == b"/" {
return p.starts_with(b"/");
}
if p.starts_with(b) {
return p.len() == b.len() || p[b.len()] == b'/';
}
if b.contains(&b'.') || b.windows(2).any(|w| w == b"//") {
return path.starts_with(base);
}
false
}
/// Fast Unix `Path::strip_prefix` when both `path` and `base` have already been normalized
/// (i.e. contain no `..` segments or leading `.`). Performs a single slice prefix comparison.
#[inline]
pub fn unix_normalized_path_strip_prefix<'a>(path: &'a Path, base: &Path) -> Option<&'a Path> {
let p = path.as_os_str().as_encoded_bytes();
let b = trim_trailing_slashes_and_curdir(base.as_os_str().as_encoded_bytes());
if b.is_empty() {
return Some(path);
}
if b == b"/" {
if !p.starts_with(b"/") {
return None;
}
let mut rem = strip_leading_slashes_and_curdir(&p[1..]);
if rem.ends_with(b"/") || rem.ends_with(b"/.") {
rem = trim_trailing_slashes_and_curdir(rem);
if rem == b"/" {
rem = b"";
}
}
if let Some(res) = unix_bytes_to_path(rem) {
return Some(res);
}
} else if p.starts_with(b) {
if p.len() == b.len() {
return Some(Path::new(""));
}
if p[b.len()] == b'/' {
let mut rem = strip_leading_slashes_and_curdir(&p[b.len() + 1..]);
if rem.ends_with(b"/") || rem.ends_with(b"/.") {
rem = trim_trailing_slashes_and_curdir(rem);
if rem == b"/" {
rem = b"";
}
}
if let Some(res) = unix_bytes_to_path(rem) {
return Some(res);
}
}
return None;
}
if b.contains(&b'.') || b.windows(2).any(|w| w == b"//") {
return path.strip_prefix(base).ok();
}
None
}
/// Fast Unix `Path::parent` that slices at the last `/` via SIMD `memrchr` without scanning
/// earlier path components.
#[inline]
pub fn unix_path_parent(path: &Path) -> Option<&Path> {
let p = path.as_os_str().as_encoded_bytes();
if p.is_empty() || p == b"/" {
return None;
}
if let Some(idx) = p.iter().rposition(|&b| b == b'/') {
if idx + 1 < p.len() {
let tail = &p[idx + 1..];
if tail != b"." && tail != b".." {
if idx == 0 {
return Some(Path::new("/"));
}
if !(idx == 1 && p[0] == b'.') {
let parent_bytes = trim_trailing_slashes_and_curdir(&p[..idx]);
if let Some(res) = unix_bytes_to_path(parent_bytes) {
return Some(res);
}
}
}
}
} else if p != b"." && p != b".." {
return Some(Path::new(""));
}
path.parent()
}
/// Splits a Unix `Path` into `(parent, file_name)` in a single reverse scan.
#[inline]
pub fn unix_split_parent_and_file_name(path: &Path) -> Option<(&Path, &std::ffi::OsStr)> {
let p = path.as_os_str().as_encoded_bytes();
if p.is_empty() || p == b"/" {
return None;
}
if let Some(idx) = p.iter().rposition(|&b| b == b'/') {
if idx + 1 < p.len() {
let tail = &p[idx + 1..];
if tail != b"." && tail != b".." {
if idx == 0 {
if let Some(tail_os) = unix_bytes_to_os_str(tail) {
return Some((Path::new("/"), tail_os));
}
} else if !(idx == 1 && p[0] == b'.') {
let parent_bytes = trim_trailing_slashes_and_curdir(&p[..idx]);
if let (Some(parent_p), Some(tail_os)) = (unix_bytes_to_path(parent_bytes), unix_bytes_to_os_str(tail)) {
return Some((parent_p, tail_os));
}
}
}
}
} else if p != b"."
&& p != b".."
&& let Some(tail_os) = unix_bytes_to_os_str(p)
{
return Some((Path::new(""), tail_os));
}
Some((path.parent()?, path.file_name()?))
}
/// Verifies that `path.parent() == Some(expected_parent)` and returns `path.file_name()` in one
/// slice prefix check.
#[inline]
pub fn unix_direct_child_file_name<'a>(path: &'a Path, expected_parent: &Path) -> Option<&'a std::ffi::OsStr> {
let p = path.as_os_str().as_encoded_bytes();
let b = trim_trailing_slashes_and_curdir(expected_parent.as_os_str().as_encoded_bytes());
if !b.is_empty() && b != b"." && !b.starts_with(b"./") && !unix_path_has_dotdot_segment(b) {
if b == b"/" {
if p.starts_with(b"/") {
let rem = strip_leading_slashes_and_curdir(&p[1..]);
if !rem.is_empty()
&& rem != b"."
&& rem != b".."
&& !rem.contains(&b'/')
&& let Some(res) = unix_bytes_to_os_str(rem)
{
return Some(res);
}
}
} else if p.starts_with(b) && p.len() > b.len() + 1 && p[b.len()] == b'/' {
let rem = strip_leading_slashes_and_curdir(&p[b.len() + 1..]);
if !rem.is_empty()
&& rem != b"."
&& rem != b".."
&& !rem.contains(&b'/')
&& let Some(res) = unix_bytes_to_os_str(rem)
{
return Some(res);
}
}
}
if path.parent() != Some(expected_parent) {
return None;
}
path.file_name()
}
/// Returns `true` if `path` contains a `..` component (parent directory traversal).
fn contains_parent_dir_component(path: &str) -> bool {
path.split(['/', '\\']).any(|component| component == "..")
@@ -1211,4 +1563,110 @@ mod tests {
assert!(normalize_extract_entry_key("file.txt", Some("../bad"), false).is_err());
assert!(normalize_extract_entry_key("/absolute", None, false).is_err());
}
#[test]
fn unix_swar_path_helpers_match_std_path_across_boundaries() {
for pad in 1..=20 {
let prefix = "a".repeat(pad);
let clean_cases = [
format!("/{prefix}/bucket/object/xl.meta"),
format!("/{prefix}/.rustfs.sys/tmp/uuid/part.1"),
format!("/{prefix}/dir..name/..hidden/file...ext"),
format!("{prefix}/relative/object.tar.gz"),
];
for case in &clean_cases {
let bytes = case.as_bytes();
assert!(!unix_path_has_dotdot_segment(bytes), "clean case flagged dotdot: {case}");
assert!(unix_is_canonical_ascii_path(bytes), "canonical case rejected: {case}");
}
let non_canonical_slash_cases = [
format!("//{prefix}/bucket/object/xl.meta"),
format!("/{prefix}//bucket/object/xl.meta"),
format!("/{prefix}/bucket/object/"),
];
for case in &non_canonical_slash_cases {
assert!(
!unix_is_canonical_ascii_path(case.as_bytes()),
"non-canonical slash case accepted: {case}"
);
}
let dot_cases = [
format!("/{prefix}/./xl.meta"),
format!("/{prefix}/bucket/."),
format!("./{prefix}/bucket"),
".".to_string(),
];
for case in &dot_cases {
let bytes = case.as_bytes();
assert!(!unix_path_has_dotdot_segment(bytes), "dot-only case flagged as dotdot: {case}");
assert!(!unix_is_canonical_ascii_path(bytes), "dot case accepted as canonical: {case}");
}
let dotdot_cases = [
format!("/{prefix}/../xl.meta"),
format!("/{prefix}/bucket/.."),
format!("../{prefix}/bucket"),
"..".to_string(),
];
for case in &dotdot_cases {
let bytes = case.as_bytes();
assert!(unix_path_has_dotdot_segment(bytes), "dotdot case missed by dotdot: {case}");
assert!(!unix_is_canonical_ascii_path(bytes), "dotdot case accepted as canonical: {case}");
}
}
let base = Path::new("/tmp/rustfs-disk1");
let child = Path::new("/tmp/rustfs-disk1/bucket/prefix/xl.meta");
let sibling = Path::new("/tmp/rustfs-disk10/bucket/prefix/xl.meta");
assert!(unix_normalized_path_starts_with(child, base));
assert!(!unix_normalized_path_starts_with(sibling, base));
assert_eq!(unix_normalized_path_strip_prefix(child, base), Some(Path::new("bucket/prefix/xl.meta")));
assert_eq!(unix_normalized_path_strip_prefix(base, base), Some(Path::new("")));
assert_eq!(unix_normalized_path_strip_prefix(sibling, base), None);
assert_eq!(unix_path_parent(child), Some(Path::new("/tmp/rustfs-disk1/bucket/prefix")));
assert_eq!(unix_path_parent(Path::new("/")), None);
assert_eq!(unix_path_parent(Path::new("/rootchild")), Some(Path::new("/")));
assert_eq!(unix_path_parent(Path::new("relative")), Some(Path::new("")));
assert_eq!(
unix_split_parent_and_file_name(child),
Some((Path::new("/tmp/rustfs-disk1/bucket/prefix"), std::ffi::OsStr::new("xl.meta")))
);
assert_eq!(
unix_direct_child_file_name(child, Path::new("/tmp/rustfs-disk1/bucket/prefix")),
Some(std::ffi::OsStr::new("xl.meta"))
);
assert_eq!(unix_direct_child_file_name(child, base), None);
let proc_root = Path::new("/proc/self/fd/12/.");
let proc_bucket = Path::new("/proc/self/fd/12/./bucket");
let proc_obj = Path::new("/proc/self/fd/12/./bucket/prefix/xl.meta");
assert!(unix_normalized_path_starts_with(proc_bucket, proc_root));
assert!(unix_normalized_path_starts_with(proc_obj, proc_bucket));
assert!(unix_normalized_path_starts_with(proc_obj, proc_root));
assert_eq!(
unix_normalized_path_strip_prefix(proc_obj, proc_root),
Some(Path::new("bucket/prefix/xl.meta"))
);
assert_eq!(
unix_normalized_path_strip_prefix(proc_obj, proc_bucket),
Some(Path::new("prefix/xl.meta"))
);
assert_eq!(unix_path_parent(proc_obj), Some(Path::new("/proc/self/fd/12/./bucket/prefix")));
assert_eq!(
unix_direct_child_file_name(proc_obj, Path::new("/proc/self/fd/12/./bucket/prefix")),
Some(std::ffi::OsStr::new("xl.meta"))
);
assert!(unix_is_canonical_ascii_path("bucket/对象-ключ-é/xl.meta".as_bytes()));
assert!(unix_normalized_path_starts_with(
Path::new("/data/rustfs/bucket/dir/xl.meta"),
Path::new("/data/rustfs/bucket//dir")
));
assert_eq!(
unix_normalized_path_strip_prefix(Path::new("/a/b/"), Path::new("/a")),
Some(Path::new("b"))
);
}
}
+21 -1
View File
@@ -91,6 +91,26 @@ Use `GET /iceberg/v1/buckets/{warehouse}` to check `enabled` and `disable-suppor
Review the bucket lifecycle configuration before disabling: clearing table-bucket protection allows existing object expiration rules to run again. Objects are preserved by the disable operation itself. Catalog disablement requires no namespaces, retained table/view resources, or objects under `.rustfs-table/`; an active rename or backing migration also blocks it. Clean up through supported catalog operations; do not manually delete internal metadata to bypass these checks.
The server persists an inactive catalog entry before clearing the bucket marker. If marker publication fails, retry the same DELETE; the marker retains object protections until the retry succeeds. A subsequent PUT explicitly enables the bucket again. Stale requests cannot initialize an inactive catalog entry. No table metadata or object data is deleted by either state change.
The server persists an inactive catalog entry before clearing the bucket marker. If marker publication fails, retry the same DELETE; the marker retains object protections until the retry succeeds. A subsequent PUT explicitly enables the bucket again. Stale requests cannot initialize an inactive catalog entry. A plain DELETE and a subsequent PUT preserve table metadata and object data.
### Clean Up Deleted Empty Tables
For the object-backed catalog, `DELETE /iceberg/v1/buckets/{warehouse}?cleanup=true` removes the metadata and internal records left by deleted empty tables, then disables the table catalog. Ordinary table deletion continues to preserve files. Cleanup preserves existing table record formats and can process empty tables deleted before the server upgrade.
Complete the server upgrade across all serving nodes and set the existing `RUSTFS_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED=true` setting before requesting cleanup. Delete the empty tables and their namespaces through the catalog APIs, then send the cleanup request with `admin:SetTableBucket` and `s3:GetObject`/`s3:DeleteObject` permissions for the target metadata objects. The `/_iceberg/v1` alias accepts the same option. Omitting `cleanup` or setting it to `false` keeps the ordinary disable behavior; repeated or invalid values are rejected.
Cleanup accepts only recognized empty-table metadata in the default managed warehouse. Active catalog resources, snapshots or other data references, user objects, object versions, incomplete multipart uploads, corrupt or unknown metadata, and unfinished catalog operations block cleanup. The server validates the complete cleanup plan and object permissions before deleting any object. Durable-strong catalogs retain their existing disable procedure.
If a storage operation fails during cleanup, retry the same request. The server checks the remaining objects again and keeps the bucket's table protection enabled until cleanup and catalog disablement complete. No separate cleanup task file is created. After a successful response with `enabled: false`, delete the empty bucket through the normal S3 `DeleteBucket` operation.
## Object-Backed Registration Reads
Table registration checks table ID uniqueness and warehouse directory overlap using the existing catalog and warehouse index records. Each registration obtains a complete inventory under the existing publication and migration guards. System-bucket inventory records must satisfy the same metadata commit checks as ordinary catalog reads. An incomplete or failed inventory rejects registration.
Each server keeps a bounded memory cache of validated ownership records. A record can be reused only when its object identity and ETag match the current inventory. New or changed records are read and validated again. Cache eviction and process restarts cause additional reads; catalog state continues to come from the existing persisted records. The cache is automatic and requires no additional configuration or stored objects.
Registration still enumerates the namespace and warehouse index prefixes, so enumeration work grows with catalog size. Cache hits reduce object-body reads and JSON parsing. A cache hit verifies the current metadata identity and reuses previously validated content; it does not re-read the current body to check its physical readability. Conditional writes, rollback, and lock-loss fencing continue to control publication.
Existing catalog formats and Console and Iceberg client request formats are preserved. Concurrent writers must follow the existing publication, migration, and storage fencing protocol; the memory cache does not provide synchronization for writers that bypass those guards.
Before rolling back to a server version without this endpoint, re-enable disabled catalogs with PUT while the supporting version is running. Older enable handlers do not reactivate inactive catalog entries. Complete the server upgrade across the cluster before using disablement.
Generated
+6 -6
View File
@@ -2,11 +2,11 @@
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1792812153,
"narHash": "sha256-T2+XBfNbf9pecLUWS4+RtuVNZ3W8K5taG5QdV71mWlk=",
"lastModified": 1793466162,
"narHash": "sha256-pt+peAEoOK3lLLdtbnQ1AGIBTZbdB6jrkgmurfcQwig=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "674a2028661e550a97400c1cc992b9cca9a668a1",
"rev": "a0788123ada57ec92a79ab2581cda6d3c6cca75f",
"type": "github"
},
"original": {
@@ -29,11 +29,11 @@
]
},
"locked": {
"lastModified": 1792825530,
"narHash": "sha256-aphXA2IFNd3q48++TKmfuuvDDjkrgGdJDnDIhij9684=",
"lastModified": 1793434469,
"narHash": "sha256-+sgVNI2c67di+XIeMaz5KSei4T65kX68s5Nl0E5Gzbc=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "5b9f1198b59bcb31c5c3250b332e7d77590e6306",
"rev": "6ecf534a7c16e7c969f26838fdd8c93597ae93f3",
"type": "github"
},
"original": {
@@ -50,17 +50,23 @@ pub struct DisableTableBucketHandler {}
#[async_trait::async_trait]
impl Operation for DisableTableBucketHandler {
async fn call(&self, req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
async fn call(&self, mut req: S3Request<Body>, params: Params<'_, '_>) -> S3Result<S3Response<(StatusCode, Body)>> {
let warehouse = warehouse_from_params(&params)?;
let resource = TableCatalogResource::warehouse(&warehouse);
authorize_table_catalog_resource_request(&req, &resource, AdminAction::SetTableBucketAction).await?;
let principal = authorize_table_catalog_resource_request(&req, &resource, AdminAction::SetTableBucketAction).await?;
let cleanup = table_bucket_cleanup_requested_from_query(&req.uri)?;
let app_context = runtime_sources::app_context_from_extensions(&req.extensions);
let backend = table_catalog_backend_from_extensions(&req.extensions)?;
let object_store = runtime_sources::object_store_from_req(&req)
.ok_or_else(|| table_catalog_internal_error("request object store is not initialized"))?;
let store = table_catalog_store_from_backend(backend.clone())?;
let publication = TableCommitObjectBackend::preauthorized(backend);
let response = disable_table_bucket_response(&store, &publication, object_store.as_ref(), &warehouse).await?;
install_table_catalog_s3_request_info(&mut req, &principal)?;
let publication = TableCommitObjectBackend::for_request(backend, req);
let response = if cleanup {
cleanup_empty_table_bucket_response(&store, &publication, object_store.as_ref(), &warehouse).await?
} else {
disable_table_bucket_response(&store, &publication, object_store.as_ref(), &warehouse).await?
};
crate::app::bucket_usecase::notify_table_bucket_metadata_reload(warehouse.clone(), "disable table bucket", app_context)
.await;
build_json_response(StatusCode::OK, &response)
+72 -8
View File
@@ -2092,17 +2092,25 @@ fn warehouse_from_config_query(uri: &http::Uri) -> S3Result<Option<String>> {
}
fn rest_purge_requested_from_query(uri: &http::Uri) -> S3Result<bool> {
let mut purge_requested = None;
table_catalog_boolean_query(uri, "purgeRequested")
}
fn table_bucket_cleanup_requested_from_query(uri: &http::Uri) -> S3Result<bool> {
table_catalog_boolean_query(uri, "cleanup")
}
fn table_catalog_boolean_query(uri: &http::Uri, parameter: &str) -> S3Result<bool> {
let mut requested = None;
if let Some(query) = uri.query() {
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
if key != "purgeRequested" {
if key != parameter {
continue;
}
if purge_requested.is_some() {
if requested.is_some() {
return Err(iceberg_rest_error(
ICEBERG_ERROR_BAD_REQUEST,
StatusCode::BAD_REQUEST,
"purgeRequested query parameter must not be repeated",
format!("{parameter} query parameter must not be repeated"),
));
}
let value = if value.eq_ignore_ascii_case("true") {
@@ -2113,13 +2121,13 @@ fn rest_purge_requested_from_query(uri: &http::Uri) -> S3Result<bool> {
return Err(iceberg_rest_error(
ICEBERG_ERROR_BAD_REQUEST,
StatusCode::BAD_REQUEST,
"purgeRequested query parameter must be true or false",
format!("{parameter} query parameter must be true or false"),
));
};
purge_requested = Some(value);
requested = Some(value);
}
}
Ok(purge_requested.unwrap_or(false))
Ok(requested.unwrap_or(false))
}
fn rest_table_snapshot_selection_from_query(uri: &http::Uri) -> S3Result<RestTableSnapshotSelection> {
@@ -2417,9 +2425,10 @@ fn table_catalog_backend_from_extensions(
) -> S3Result<crate::table_catalog::EcStoreTableCatalogObjectBackend<ECStore>> {
let context = runtime_sources::app_context_from_extensions(extensions)
.ok_or_else(|| table_catalog_internal_error("request application context is not initialized"))?;
Ok(crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
Ok(crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_runtimes(
context.object_store(),
context.table_catalog_strong_runtime(),
context.table_catalog_registration_cache(),
))
}
@@ -2572,6 +2581,61 @@ where
table_bucket_response(store, bucket, true).await
}
async fn cleanup_empty_table_bucket_response<B>(
store: &crate::table_catalog::ConfiguredTableCatalogStore<B>,
publication: &TableCommitObjectBackend<B>,
object_store: &ECStore,
bucket: &str,
) -> S3Result<TableBucketResponse>
where
B: crate::table_catalog::TableCatalogObjectBackend,
{
if !publication.publication_fence_fleet_confirmed {
return Err(catalog_store_error(crate::table_catalog::TableCatalogStoreError::Conflict(
"empty table bucket cleanup requires publication fences on every cluster node".to_string(),
)));
}
crate::table_catalog::TableCommitPublication::begin_table_bucket(publication, bucket)
.await
.map_err(catalog_store_error)?;
let _publication_completion = crate::table_catalog::TableCommitPublicationCompletion::new(publication);
let incarnation = object_store
.bucket_incarnation_id_from_disk(bucket)
.await
.map_err(|err| ApiError::other(format!("failed to read table bucket identity: {err}")))?;
let prepared = store
.prepare_empty_table_bucket_cleanup(table_bucket_entry_from_metadata_marker(bucket), publication)
.await
.map_err(catalog_store_error);
let mut cleanup = publication.finish(prepared).await?;
for object in cleanup.metadata_objects() {
if let Err(err) = publication.authorize(bucket, object, S3Action::DeleteObjectAction).await {
return publication.finish(Err(catalog_store_error(err))).await;
}
}
store
.execute_empty_table_bucket_cleanup(&mut cleanup, incarnation)
.await
.map_err(catalog_store_error)?;
let fence = cleanup.mutation_fence();
object_store
.update_bucket_metadata_config_for_incarnation_validated(
bucket,
crate::table_catalog::TABLE_BUCKET_MARKER_CONFIG,
Vec::new(),
incarnation,
|| {
fence
.ensure_held()
.map_err(|err| crate::admin::storage_api::error::StorageError::other(err.to_string()))
},
)
.await
.map_err(|err| ApiError::other(format!("failed to disable table bucket: {err}")))?;
drop(cleanup);
table_bucket_response(store, bucket, false).await
}
async fn disable_table_bucket_response<S, B>(
store: &S,
publication: &TableCommitObjectBackend<B>,
@@ -87,6 +87,15 @@ async fn call_load_table_handler(request: S3Request<Body>) -> S3Result<S3Respons
RestLoadTableHandler {}.call(request, matched.params).await
}
async fn call_disable_table_bucket_handler(request: S3Request<Body>) -> S3Result<S3Response<(StatusCode, Body)>> {
let mut router = matchit::Router::new();
router.insert("/iceberg/v1/buckets/{warehouse}", ()).unwrap();
router.insert("/_iceberg/v1/buckets/{warehouse}", ()).unwrap();
let path = request.uri.path().to_string();
let matched = router.at(&path).unwrap();
DisableTableBucketHandler {}.call(request, matched.params).await
}
async fn call_maintenance_worker_handler(request: S3Request<Body>) -> S3Result<S3Response<(StatusCode, Body)>> {
let mut router = matchit::Router::new();
router
@@ -1255,6 +1264,28 @@ fn drop_table_purge_query_is_explicit_and_strict() {
}
}
#[test]
fn table_bucket_cleanup_query_is_explicit_and_strict() {
for (uri, expected) in [
("/iceberg/v1/buckets/analytics", false),
("/iceberg/v1/buckets/analytics?cleanup=false", false),
("/iceberg/v1/buckets/analytics?cleanup=true", true),
("/_iceberg/v1/buckets/analytics?cleanup=true", true),
] {
assert_eq!(table_bucket_cleanup_requested_from_query(&uri.parse().unwrap()).unwrap(), expected);
}
for query in [
"cleanup=",
"cleanup=1",
"cleanup=yes",
"cleanup=true&cleanup=false",
"cleanup=true&cleanup=true",
] {
let uri = format!("/iceberg/v1/buckets/analytics?{query}").parse().unwrap();
assert!(table_bucket_cleanup_requested_from_query(&uri).is_err(), "invalid query: {query}");
}
}
#[test]
fn catalog_conflicts_use_operation_specific_iceberg_errors() {
let already_exists = catalog_store_already_exists_error(crate::table_catalog::TableCatalogStoreError::Conflict(
@@ -1689,9 +1720,7 @@ fn table_bucket_toggle_handlers_reload_peer_metadata_after_publication() {
(enable, "enable_table_bucket_response", "enable table bucket"),
(disable, "disable_table_bucket_response", "disable table bucket"),
] {
let response_offset = block
.find(&format!("let response = {response}"))
.expect("table bucket toggle should publish local state");
let response_offset = block.find(response).expect("table bucket toggle should publish local state");
let reload = block
.find(&format!("notify_table_bucket_metadata_reload(warehouse.clone(), \"{operation}\""))
.expect("table bucket toggle should reload peer metadata");
@@ -16274,3 +16303,799 @@ async fn disable_table_bucket_preserves_objects_and_can_be_reenabled() {
.table_bucket_enabled()
);
}
async fn create_dropped_empty_tables_for_cleanup<S, B>(
catalog: &S,
backend: &B,
object_store: &ECStore,
bucket: &str,
table_count: usize,
) -> Vec<String>
where
S: TableCatalogStore + ?Sized,
B: TableCatalogObjectBackend,
{
object_store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
enable_table_bucket_response(catalog, &TableCommitObjectBackend::trusted(backend.clone()), object_store, bucket)
.await
.unwrap();
let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap();
create_namespace_response(
catalog,
bucket,
CreateNamespaceRequest {
namespace: vec!["analytics".to_string()],
properties: BTreeMap::new(),
},
true,
)
.await
.unwrap();
let mut metadata_objects = Vec::new();
for number in 0..table_count {
let name = format!("events_{number:02}");
let request = serde_json::from_value(serde_json::json!({
"name": name,
"schema": {
"type": "struct",
"schema-id": 0,
"fields": [{"id": 1, "name": "id", "required": true, "type": "long"}]
}
}))
.unwrap();
create_table_response(
catalog,
&TableCommitObjectBackend::trusted(backend.clone()),
bucket,
&namespace,
request,
true,
)
.await
.unwrap();
metadata_objects.push(
catalog
.load_table(bucket, &namespace.public_name(), &name)
.await
.unwrap()
.unwrap()
.metadata_location,
);
}
for number in 0..table_count {
catalog
.drop_table(bucket, &namespace.public_name(), &format!("events_{number:02}"))
.await
.unwrap();
}
catalog.drop_namespace(bucket, &namespace.public_name()).await.unwrap();
metadata_objects
}
#[tokio::test]
#[serial_test::serial]
async fn object_catalog_registration_cache_checks_real_records_without_additional_objects() {
use crate::admin::storage_api::RUSTFS_META_BUCKET;
use crate::table_catalog::{
ConfiguredTableCatalogStore, EcStoreTableCatalogObjectBackend, StrongTableCatalogRuntime, TableCatalogBackingMode,
TableCatalogObjectPaths, TableCatalogStoreError,
};
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("registration-cache-{}", Uuid::new_v4().simple());
let backend =
EcStoreTableCatalogObjectBackend::new_with_strong_runtime(object_store.clone(), StrongTableCatalogRuntime::default());
let catalog = ConfiguredTableCatalogStore::new_for_test(backend.clone(), TableCatalogBackingMode::ObjectBacked);
object_store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.unwrap();
enable_table_bucket_response(&catalog, &TableCommitObjectBackend::trusted(backend.clone()), &object_store, &bucket)
.await
.unwrap();
let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap();
create_namespace_response(
&catalog,
&bucket,
CreateNamespaceRequest {
namespace: vec!["analytics".to_string()],
properties: BTreeMap::new(),
},
true,
)
.await
.unwrap();
let paths = TableCatalogObjectPaths::default();
let bucket_entry = paths.table_bucket_entry_path(&bucket);
let catalog_prefix = format!("{}/", bucket_entry.rsplit_once('/').unwrap().0);
let mut create_micros = Vec::new();
for number in 0..100 {
let store = ConfiguredTableCatalogStore::new_for_test(backend.clone(), TableCatalogBackingMode::ObjectBacked);
let request = serde_json::from_value(serde_json::json!({
"name": format!("events_{number:03}"),
"schema": {
"type": "struct",
"schema-id": 0,
"fields": [{"id": 1, "name": "id", "required": true, "type": "long"}]
}
}))
.unwrap();
let started = std::time::Instant::now();
create_table_response(
&store,
&TableCommitObjectBackend::trusted(backend.clone()),
&bucket,
&namespace,
request,
true,
)
.await
.expect("fresh store instances share the runtime cache and create independent tables");
create_micros.push(started.elapsed().as_micros());
if matches!(number + 1, 20 | 100) {
let before = backend.list_objects(RUSTFS_META_BUCKET, &catalog_prefix).await.unwrap();
let cold_backend = EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
object_store.clone(),
StrongTableCatalogRuntime::default(),
);
let probe = ConfiguredTableCatalogStore::new_for_test(cold_backend, TableCatalogBackingMode::ObjectBacked);
let mut duplicate = catalog
.load_table(&bucket, "analytics", &format!("events_{number:03}"))
.await
.unwrap()
.unwrap();
duplicate.table = "duplicate_probe".to_string();
for cache_state in ["cold", "warm"] {
let started = std::time::Instant::now();
assert!(matches!(
probe.create_table(duplicate.clone()).await,
Err(TableCatalogStoreError::Conflict(_))
));
eprintln!(
"registration_check tables={} cache={} elapsed_us={}",
number + 1,
cache_state,
started.elapsed().as_micros()
);
}
assert_eq!(before, backend.list_objects(RUSTFS_META_BUCKET, &catalog_prefix).await.unwrap());
let mut recent = create_micros[create_micros.len() - 5..].to_vec();
recent.sort_unstable();
eprintln!("create_table_response tables={} last_five_median_us={}", number + 1, recent[2]);
}
}
assert_eq!(catalog.list_all_tables(&bucket).await.unwrap().len(), 100);
let namespace_entry = paths.namespace_entry_path(&bucket, &namespace);
let index_prefix = paths.warehouse_index_entries_prefix(&bucket);
let objects = backend.list_objects(RUSTFS_META_BUCKET, &catalog_prefix).await.unwrap();
assert!(objects.iter().all(|key| {
key == &bucket_entry || key == &namespace_entry || key.starts_with(&index_prefix) || key.ends_with("/table-entry.json")
}));
}
#[tokio::test]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_reclaims_twenty_dropped_tables_and_allows_bucket_deletion() {
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("cleanup-{}", Uuid::new_v4().simple());
let backend = crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
object_store.clone(),
crate::table_catalog::StrongTableCatalogRuntime::default(),
);
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
let metadata_objects = create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 20).await;
assert!(
disable_table_bucket_response(
&catalog,
&TableCommitObjectBackend::trusted(backend.clone()),
object_store.as_ref(),
&bucket,
)
.await
.is_err()
);
for object in &metadata_objects {
assert!(backend.object_exists(&bucket, object).await.unwrap());
}
let authorizations = Arc::new(tokio::sync::Mutex::new(Vec::new()));
let publication = TableCommitObjectBackend::test(backend.clone(), authorizations.clone(), None);
let result = cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket).await;
assert!(!publication.finish(result).await.unwrap().enabled);
for object in &metadata_objects {
assert!(!backend.object_exists(&bucket, object).await.unwrap());
let authorized = authorizations.lock().await;
assert!(authorized.contains(&(object.clone(), S3Action::GetObjectAction)));
assert!(authorized.contains(&(object.clone(), S3Action::DeleteObjectAction)));
}
assert!(
!object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
let publication = TableCommitObjectBackend::trusted(backend);
assert!(
!cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.unwrap()
.enabled
);
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
}
#[tokio::test]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_validates_authorization_and_metadata_before_deleting() {
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("cleanup-check-{}", Uuid::new_v4().simple());
let backend = crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
object_store.clone(),
crate::table_catalog::StrongTableCatalogRuntime::default(),
);
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
let metadata_objects = create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 2).await;
let publication = TableCommitObjectBackend::rolling_upgrade(backend.clone());
assert!(
cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.is_err()
);
for object in &metadata_objects {
assert!(backend.object_exists(&bucket, object).await.unwrap());
}
let authorizations = Arc::new(tokio::sync::Mutex::new(Vec::new()));
let denied_object = metadata_objects.last().unwrap().clone();
let publication = TableCommitObjectBackend::test(backend.clone(), authorizations, Some(denied_object.clone()));
let result = cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket).await;
assert_eq!(publication.finish(result).await.unwrap_err().code(), &S3ErrorCode::AccessDenied);
for object in &metadata_objects {
assert!(backend.object_exists(&bucket, object).await.unwrap());
}
let original = backend.read_object(&bucket, &denied_object).await.unwrap().unwrap().data;
backend
.put_object(
&bucket,
&denied_object,
b"{".to_vec(),
crate::table_catalog::TableCatalogPutPrecondition::Any,
)
.await
.unwrap();
let publication = TableCommitObjectBackend::trusted(backend.clone());
assert!(
cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.is_err()
);
for object in &metadata_objects {
assert!(backend.object_exists(&bucket, object).await.unwrap());
}
assert!(
object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
backend
.put_object(&bucket, &denied_object, original, crate::table_catalog::TableCatalogPutPrecondition::Any)
.await
.unwrap();
let publication = TableCommitObjectBackend::trusted(backend);
assert!(
!cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.unwrap()
.enabled
);
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
}
#[tokio::test]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_handler_enforces_request_object_permissions() {
temp_env::async_with_vars(
[
(
crate::table_catalog::ENV_TABLE_CATALOG_BACKING,
Some(crate::table_catalog::TABLE_CATALOG_BACKING_OBJECT),
),
(crate::table_catalog::ENV_TABLE_CATALOG_PUBLICATION_FENCE_FLEET_CONFIRMED, Some("true")),
],
async {
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("cleanup-request-{}", Uuid::new_v4().simple());
rustfs_iam::store::object::ObjectStore::new(object_store.clone())
.save_iam_config(
serde_json::json!({"version": 1}),
format!("{}/format.json", *rustfs_iam::store::object::IAM_CONFIG_PREFIX),
)
.await
.unwrap();
let iam = rustfs_iam::build_iam_sys(object_store.clone()).await.unwrap();
let access_key = "cleanup-request-user";
let secret_key = "cleanup-request-user-secret";
iam.create_user(
access_key,
&AddOrUpdateUserReq {
secret_key: secret_key.to_string(),
policy: None,
status: AccountStatus::Enabled,
},
)
.await
.unwrap();
let context = Arc::new(AppContext::new(
object_store.clone(),
Arc::new(RequestIam { handle: iam.clone() }),
Arc::new(RequestKms),
));
assert!(context.publish_action_credentials(rustfs_credentials::Credentials {
access_key: "cleanup-request-root".to_string(),
secret_key: "cleanup-request-root-secret".to_string(),
status: "on".to_string(),
..Default::default()
}));
let backend = crate::table_catalog::EcStoreTableCatalogObjectBackend::new_with_strong_runtime(
object_store.clone(),
context.table_catalog_strong_runtime(),
);
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
let metadata_objects =
create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 2).await;
let request = |prefix: &str| {
let mut request = table_catalog_handler_request(context.clone(), access_key, secret_key);
request.method = Method::DELETE;
request.uri = format!("{prefix}/v1/buckets/{bucket}?cleanup=true").parse().unwrap();
request
};
let object_resource = format!("arn:aws:s3:::{bucket}/*");
let first_metadata_resource = format!("arn:aws:s3:::{bucket}/{}", metadata_objects[0]);
for (policy_name, object_statements, allowed) in [
("cleanup-request-no-read", Vec::new(), false),
(
"cleanup-request-partial-delete",
vec![
serde_json::json!({"Effect":"Allow","Action":["s3:GetObject"],"Resource":[object_resource]}),
serde_json::json!({"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":[first_metadata_resource]}),
],
false,
),
(
"cleanup-request-full",
vec![serde_json::json!({
"Effect":"Allow",
"Action":["s3:GetObject","s3:DeleteObject"],
"Resource":[object_resource],
})],
true,
),
] {
let mut statements = vec![serde_json::json!({"Effect":"Allow","Action":["admin:SetTableBucket"]})];
statements.extend(object_statements);
let policy = serde_json::to_vec(&serde_json::json!({"Version":"2012-10-17","Statement":statements})).unwrap();
iam.set_policy(policy_name, Policy::parse_config(&policy).unwrap())
.await
.unwrap();
iam.policy_db_set(access_key, UserType::Reg, false, policy_name)
.await
.unwrap();
let result = call_disable_table_bucket_handler(request(if allowed { "/_iceberg" } else { "/iceberg" })).await;
if allowed {
let response = result.expect("request-scoped object permissions should authorize cleanup");
assert_eq!(response.output.0, StatusCode::OK);
let body: serde_json::Value = serde_json::from_slice(&response.output.1.bytes().unwrap()).unwrap();
assert_eq!(body["enabled"], false);
for object in &metadata_objects {
assert!(!backend.object_exists(&bucket, object).await.unwrap());
}
} else {
assert_eq!(result.unwrap_err().code(), &S3ErrorCode::AccessDenied);
for object in &metadata_objects {
assert!(backend.object_exists(&bucket, object).await.unwrap());
}
assert!(
object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
assert_eq!(
catalog.get_table_bucket(&bucket).await.unwrap().unwrap().state,
crate::table_catalog::TableCatalogEntryState::Active,
);
}
}
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
},
)
.await;
}
#[tokio::test]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_retries_after_marker_write_rejection() {
use crate::table_catalog::TableCommitPublication;
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("cleanup-marker-{}", Uuid::new_v4().simple());
let backend = TestTableCatalogObjectBackend::default();
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
let metadata_objects = create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 2).await;
let publication = TableCommitObjectBackend::trusted(backend.clone());
TableCommitPublication::begin_table_bucket(&publication, &bucket)
.await
.unwrap();
let incarnation = object_store.bucket_incarnation_id_from_disk(&bucket).await.unwrap();
let mut cleanup = catalog
.prepare_empty_table_bucket_cleanup(table_bucket_entry_from_metadata_marker(&bucket), &publication)
.await
.unwrap();
catalog
.execute_empty_table_bucket_cleanup(&mut cleanup, incarnation)
.await
.unwrap();
let marker_result = object_store
.update_bucket_metadata_config_for_incarnation_validated(
&bucket,
crate::table_catalog::TABLE_BUCKET_MARKER_CONFIG,
Vec::new(),
incarnation,
|| {
Err(crate::admin::storage_api::error::StorageError::other(
"injected marker publication rejection",
))
},
)
.await;
assert!(marker_result.is_err());
drop(cleanup);
TableCommitPublication::complete(&publication);
for object in &metadata_objects {
assert!(!backend.object_exists(&bucket, object).await.unwrap());
}
assert_eq!(
catalog.get_table_bucket(&bucket).await.unwrap().unwrap().state,
crate::table_catalog::TableCatalogEntryState::Deleted,
);
assert!(
object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
let publication = TableCommitObjectBackend::trusted(backend);
assert!(
!cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.unwrap()
.enabled
);
assert!(
!object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
}
#[tokio::test]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_reads_incarnation_after_publication_wait() {
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("cleanup-recreated-{}", Uuid::new_v4().simple());
let backend = TestTableCatalogObjectBackend::default();
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 0).await;
let original_incarnation = object_store.bucket_incarnation_id_from_disk(&bucket).await.unwrap();
let publication_lock = crate::table_catalog::default_table_bucket_publication_lock_path();
let guard = backend.acquire_write_lock(&bucket, &publication_lock).await.unwrap();
let attempts = backend.write_lock_acquisition_count(&bucket, &publication_lock).await;
let cleanup_bucket = bucket.clone();
let cleanup_store = object_store.clone();
let publication = TableCommitObjectBackend::trusted(backend.clone());
let cleanup = tokio::spawn(async move {
cleanup_empty_table_bucket_response(&catalog, &publication, cleanup_store.as_ref(), &cleanup_bucket).await
});
tokio::time::timeout(StdDuration::from_secs(5), async {
while backend.write_lock_acquisition_count(&bucket, &publication_lock).await == attempts {
tokio::task::yield_now().await;
}
})
.await
.expect("cleanup should wait for its publication lock");
// Replace the real bucket while the in-memory publication backend holds cleanup at its lock boundary.
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
object_store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.unwrap();
enable_table_bucket_marker(object_store.as_ref(), &bucket).await.unwrap();
let replacement_incarnation = object_store.bucket_incarnation_id_from_disk(&bucket).await.unwrap();
assert_ne!(replacement_incarnation, original_incarnation);
drop(guard);
let response = tokio::time::timeout(StdDuration::from_secs(10), cleanup)
.await
.expect("cleanup should resume after publication becomes available")
.unwrap()
.expect("cleanup must use the incarnation observed while holding its publication lock");
assert!(!response.enabled);
assert_eq!(
object_store.bucket_incarnation_id_from_disk(&bucket).await.unwrap(),
replacement_incarnation
);
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
}
#[tokio::test]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_retries_metadata_delete_failures_without_removing_protection() {
use crate::admin::storage_api::RUSTFS_META_BUCKET;
use crate::table_catalog::{TableCatalogEntryState, TableCatalogObjectPaths};
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
for fail_after_delete in [false, true] {
let bucket = format!("cleanup-retry-{}", Uuid::new_v4().simple());
let backend = TestTableCatalogObjectBackend::content_addressed();
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
let mut metadata_objects =
create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 3).await;
metadata_objects.sort();
let paths = TableCatalogObjectPaths::default();
let index_prefix = paths.warehouse_index_entries_prefix(&bucket);
let indexes = backend.list_objects(RUSTFS_META_BUCKET, &index_prefix).await.unwrap();
assert!(indexes.len() >= metadata_objects.len());
if fail_after_delete {
backend.fail_after_next_delete(&bucket, &metadata_objects[1]).await;
} else {
backend.fail_delete_attempt(&bucket, &metadata_objects[1], 1).await;
}
let publication = TableCommitObjectBackend::trusted(backend.clone());
let error = cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.unwrap_err();
assert!(error.to_string().contains("injected"));
assert!(!backend.object_exists(&bucket, &metadata_objects[0]).await.unwrap());
assert_eq!(backend.object_exists(&bucket, &metadata_objects[1]).await.unwrap(), !fail_after_delete);
assert!(backend.object_exists(&bucket, &metadata_objects[2]).await.unwrap());
assert_eq!(backend.list_objects(RUSTFS_META_BUCKET, &index_prefix).await.unwrap(), indexes);
assert_eq!(
catalog.get_table_bucket(&bucket).await.unwrap().unwrap().state,
TableCatalogEntryState::Active
);
assert!(
object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
let restarted = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
let publication = TableCommitObjectBackend::trusted(backend.clone());
assert!(
!cleanup_empty_table_bucket_response(&restarted, &publication, object_store.as_ref(), &bucket)
.await
.unwrap()
.enabled
);
assert!(backend.list_objects(&bucket, "").await.unwrap().is_empty());
assert!(
backend
.list_objects(RUSTFS_META_BUCKET, &index_prefix)
.await
.unwrap()
.is_empty()
);
assert_eq!(
restarted.get_table_bucket(&bucket).await.unwrap().unwrap().state,
TableCatalogEntryState::Deleted
);
assert!(
!object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
}
}
#[tokio::test]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_retries_partial_warehouse_index_deletion() {
use crate::admin::storage_api::RUSTFS_META_BUCKET;
use crate::table_catalog::{TableCatalogEntryState, TableCatalogObjectPaths};
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("cleanup-index-retry-{}", Uuid::new_v4().simple());
let backend = TestTableCatalogObjectBackend::content_addressed();
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 2).await;
let index_prefix = TableCatalogObjectPaths::default().warehouse_index_entries_prefix(&bucket);
let indexes = backend.list_objects(RUSTFS_META_BUCKET, &index_prefix).await.unwrap();
assert!(indexes.len() >= 2);
let last_index = indexes.last().unwrap();
backend.fail_delete_attempt(RUSTFS_META_BUCKET, last_index, 1).await;
let publication = TableCommitObjectBackend::trusted(backend.clone());
let error = cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.unwrap_err();
assert!(error.to_string().contains("injected"));
assert!(backend.list_objects(&bucket, "").await.unwrap().is_empty());
assert_eq!(
backend.list_objects(RUSTFS_META_BUCKET, &index_prefix).await.unwrap(),
vec![last_index.clone()]
);
assert_eq!(
catalog.get_table_bucket(&bucket).await.unwrap().unwrap().state,
TableCatalogEntryState::Active
);
assert!(
object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
let publication = TableCommitObjectBackend::trusted(backend.clone());
assert!(
!cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.unwrap()
.enabled
);
assert!(
backend
.list_objects(RUSTFS_META_BUCKET, &index_prefix)
.await
.unwrap()
.is_empty()
);
assert!(
!object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial_test::serial]
async fn cleanup_empty_table_bucket_stops_before_delete_when_publication_lease_is_lost() {
use crate::admin::storage_api::RUSTFS_META_BUCKET;
use crate::table_catalog::test_support::RecordingLeaseClient;
use crate::table_catalog::{TableCatalogEntryState, TableCatalogLockGuard, TableCatalogObjectPaths, TableCommitPublication};
use rustfs_lock::LockClient;
let (_temp_dir, _disk_paths, object_store) = crate::app::gating_test_env::isolated_multi_pool_ecstore().await;
let bucket = format!("cleanup-lease-{}", Uuid::new_v4().simple());
let backend = TestTableCatalogObjectBackend::content_addressed();
let catalog = crate::table_catalog::ConfiguredTableCatalogStore::new_for_test(
backend.clone(),
crate::table_catalog::TableCatalogBackingMode::ObjectBacked,
);
let metadata_objects = create_dropped_empty_tables_for_cleanup(&catalog, &backend, object_store.as_ref(), &bucket, 1).await;
let index_prefix = TableCatalogObjectPaths::default().warehouse_index_entries_prefix(&bucket);
let indexes = backend.list_objects(RUSTFS_META_BUCKET, &index_prefix).await.unwrap();
let publication = TableCommitObjectBackend::trusted(backend.clone());
TableCommitPublication::begin_table_bucket(&publication, &bucket)
.await
.unwrap();
let client = Arc::new(RecordingLeaseClient {
inner: rustfs_lock::LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::Enabled(Arc::new(
rustfs_lock::FastObjectLockManager::new(),
)))),
acquired: std::sync::Mutex::new(None),
});
let lock = rustfs_lock::NamespaceLockWrapper::new(
rustfs_lock::NamespaceLock::with_clients_and_quorum(
"cleanup-publication-fence".to_string(),
vec![client.clone() as Arc<dyn LockClient>],
1,
),
rustfs_lock::ObjectKey::new(bucket.as_str(), "cleanup-publication-fence"),
"cleanup-publication-owner".to_string(),
);
let guard = lock.get_read_lock(StdDuration::from_secs(5)).await.unwrap();
let signal = guard.lock_lost_signal().unwrap();
let lock_id = client.acquired.lock().unwrap().clone().unwrap();
publication
.publication
.lock()
.guards
.push(TableCatalogLockGuard::test_namespace(guard));
let mut cleanup = catalog
.prepare_empty_table_bucket_cleanup(table_bucket_entry_from_metadata_marker(&bucket), &publication)
.await
.unwrap();
let incarnation = object_store.bucket_incarnation_id_from_disk(&bucket).await.unwrap();
let pause = backend.pause_next_delete(&bucket, &metadata_objects[0]).await;
let operation = catalog.execute_empty_table_bucket_cleanup(&mut cleanup, incarnation);
let interfere = async {
tokio::time::timeout(StdDuration::from_secs(5), pause.wait_started())
.await
.unwrap();
assert!(client.force_release(&lock_id).await.unwrap());
tokio::time::timeout(StdDuration::from_secs(15), signal.notified())
.await
.expect("cleanup publication must observe lease loss");
pause.release();
};
let (result, ()) = tokio::join!(operation, interfere);
assert!(matches!(result, Err(crate::table_catalog::TableCatalogStoreError::Unavailable(_))));
drop(cleanup);
TableCommitPublication::complete(&publication);
assert!(backend.object_exists(&bucket, &metadata_objects[0]).await.unwrap());
assert_eq!(backend.list_objects(RUSTFS_META_BUCKET, &index_prefix).await.unwrap(), indexes);
assert_eq!(
catalog.get_table_bucket(&bucket).await.unwrap().unwrap().state,
TableCatalogEntryState::Active
);
assert!(
object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
let publication = TableCommitObjectBackend::trusted(backend.clone());
assert!(
!cleanup_empty_table_bucket_response(&catalog, &publication, object_store.as_ref(), &bucket)
.await
.unwrap()
.enabled
);
assert!(!backend.object_exists(&bucket, &metadata_objects[0]).await.unwrap());
assert!(
!object_store
.get_bucket_metadata(&bucket)
.await
.unwrap()
.table_bucket_enabled()
);
object_store.delete_bucket(&bucket, &Default::default()).await.unwrap();
}
+7
View File
@@ -76,6 +76,7 @@ pub struct AppContext {
object_data_cache: Arc<ObjectDataCacheAdapter>,
object_traffic_health: Arc<ObjectTrafficHealth>,
table_catalog_strong_runtime: crate::table_catalog::StrongTableCatalogRuntime,
table_catalog_registration_cache: crate::table_catalog::TableCatalogRegistrationCache,
}
impl AppContext {
@@ -127,6 +128,7 @@ impl AppContext {
object_data_cache,
object_traffic_health: Arc::new(ObjectTrafficHealth::from_env()),
table_catalog_strong_runtime: crate::table_catalog::StrongTableCatalogRuntime::default(),
table_catalog_registration_cache: crate::table_catalog::TableCatalogRegistrationCache::default(),
}
}
@@ -150,6 +152,10 @@ impl AppContext {
self.table_catalog_strong_runtime.clone()
}
pub(crate) fn table_catalog_registration_cache(&self) -> crate::table_catalog::TableCatalogRegistrationCache {
self.table_catalog_registration_cache.clone()
}
pub fn iam(&self) -> Arc<dyn IamInterface> {
self.iam.clone()
}
@@ -360,6 +366,7 @@ impl AppContext {
object_data_cache: ObjectDataCacheAdapter::disabled_arc(),
object_traffic_health: Arc::new(ObjectTrafficHealth::from_env()),
table_catalog_strong_runtime: crate::table_catalog::StrongTableCatalogRuntime::default(),
table_catalog_registration_cache: crate::table_catalog::TableCatalogRegistrationCache::default(),
}
}
+6 -1
View File
@@ -490,7 +490,8 @@ pub(crate) mod table {
pub(crate) mod list {
pub(crate) use super::super::super::storage_contracts::{
ListObjectVersionsInfo, ListObjectsV2Info, ListOperations, ObjectInfoOrErr, WalkOptions,
AuthoritativeListOperations, ListObjectVersionsInfo, ListObjectsV2Info, ListOperations, ObjectInfoOrErr,
WalkOptions,
};
}
@@ -498,6 +499,10 @@ pub(crate) mod table {
pub(crate) use super::super::super::storage_contracts::NamespaceLocking;
}
pub(crate) mod multipart {
pub(crate) use super::super::super::storage_contracts::MultipartUploadInspection;
}
pub(crate) mod object {
pub(crate) use super::super::super::storage_contracts::{ObjectIO, ObjectOperations};
}
@@ -0,0 +1,342 @@
// 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.
use super::*;
/// Validates one metadata object; callers must also validate the complete object inventory.
pub(crate) fn validate_empty_table_cleanup_metadata(
table_bucket: &str,
object_key: &str,
metadata: &[u8],
) -> TableCatalogStoreResult<()> {
let (namespace, table) = table_identity_from_metadata_object_key(object_key).ok_or_else(|| {
TableCatalogStoreError::Invalid("cleanup metadata must use the default table metadata directory".to_string())
})?;
let metadata = decode_table_metadata_json(object_key, metadata)?;
validate_supported_table_metadata(&metadata)?;
// Future metadata fields may introduce additional object references.
for field in metadata.as_object().expect("validated metadata is a JSON object").keys() {
if !matches!(
field.as_str(),
"format-version"
| "table-uuid"
| "location"
| "last-sequence-number"
| "last-updated-ms"
| "last-column-id"
| "schema"
| "schemas"
| "current-schema-id"
| "partition-spec"
| "partition-specs"
| "default-spec-id"
| "last-partition-id"
| "properties"
| "current-snapshot-id"
| "snapshots"
| "snapshot-log"
| "metadata-log"
| "sort-orders"
| "default-sort-order-id"
| "refs"
| "statistics"
| "partition-statistics"
) {
return Err(TableCatalogStoreError::Unsupported(format!(
"empty table cleanup does not support metadata field {field}"
)));
}
}
for field in ["snapshots", "snapshot-log", "statistics", "partition-statistics"] {
let Some(value) = metadata.get(field) else {
continue;
};
let entries = value
.as_array()
.ok_or_else(|| TableCatalogStoreError::Invalid(format!("cleanup metadata field {field} must be an array")))?;
if !entries.is_empty() {
return Err(TableCatalogStoreError::Conflict(format!(
"empty table cleanup requires metadata field {field} to be empty"
)));
}
}
if let Some(value) = metadata.get("refs") {
let refs = value
.as_object()
.ok_or_else(|| TableCatalogStoreError::Invalid("cleanup metadata refs must be an object".to_string()))?;
if !refs.is_empty() {
return Err(TableCatalogStoreError::Conflict(
"empty table cleanup requires metadata refs to be empty".to_string(),
));
}
}
let table_uuid = table_metadata_uuid(&metadata)?;
if Uuid::parse_str(table_uuid).ok().filter(|uuid| !uuid.is_nil()).is_none() {
return Err(TableCatalogStoreError::Invalid(
"cleanup metadata table-uuid must be a non-nil UUID".to_string(),
));
}
let warehouse_prefix = table_warehouse_object_prefix_from_location(table_bucket, table_metadata_location(&metadata)?)?;
if warehouse_prefix
.strip_prefix("tables/")
.and_then(|prefix| prefix.strip_suffix('/'))
.and_then(|table_id| Uuid::parse_str(table_id).ok())
.filter(|table_id| !table_id.is_nil())
.is_none()
{
return Err(TableCatalogStoreError::Conflict(
"empty table cleanup requires the default tables/<table-id> warehouse location".to_string(),
));
}
if let Some(entries) = metadata.get("metadata-log").and_then(serde_json::Value::as_array) {
for entry in entries {
let entry = entry.as_object().expect("validated metadata log entries are JSON objects");
if entry
.keys()
.any(|field| !matches!(field.as_str(), "timestamp-ms" | "metadata-file"))
{
return Err(TableCatalogStoreError::Unsupported(
"empty table cleanup does not support unknown metadata-log fields".to_string(),
));
}
let location = entry["metadata-file"]
.as_str()
.expect("validated metadata log entries contain metadata-file");
table_catalog_object_key_from_location(table_bucket, location)
.filter(|location| is_valid_table_metadata_location(&namespace, &table, location))
.filter(|location| location != object_key)
.ok_or_else(|| {
TableCatalogStoreError::Invalid(
"cleanup metadata-log must reference another file in the same table metadata directory".to_string(),
)
})?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::table_catalog::test_support::table_metadata_json;
use serde_json::{Value, json};
use std::io::Write;
const BUCKET: &str = "warehouse";
const TABLE_UUID: &str = "f6dd46c2-4971-4d41-b188-452d5f5c2c01";
const WAREHOUSE_LOCATION: &str = "s3://warehouse/tables/a9d8f3b1-abde-4a0b-b6fb-e36a30abff16";
const OBJECT: &str =
".rustfs-table/warehouses/default/namespaces/analytics/events/tables/orders/metadata/00002.metadata.json";
const PREVIOUS: &str =
".rustfs-table/warehouses/default/namespaces/analytics/events/tables/orders/metadata/00001.metadata.json";
fn empty_metadata() -> Value {
table_metadata_json(TABLE_UUID, WAREHOUSE_LOCATION)
}
fn validate(metadata: &Value) -> TableCatalogStoreResult<()> {
validate_empty_table_cleanup_metadata(BUCKET, OBJECT, &serde_json::to_vec(metadata).unwrap())
}
#[test]
fn empty_table_cleanup_accepts_v2_and_same_directory_history() {
let mut metadata = empty_metadata();
metadata["metadata-log"] = json!([
{"timestamp-ms": 1, "metadata-file": PREVIOUS},
{"timestamp-ms": 1, "metadata-file": format!("s3://{BUCKET}/{PREVIOUS}")}
]);
assert!(validate(&metadata).is_ok());
}
#[test]
fn empty_table_cleanup_accepts_v1_without_snapshots() {
let mut metadata = json!({
"format-version": 1,
"table-uuid": TABLE_UUID,
"location": WAREHOUSE_LOCATION,
"last-updated-ms": 1,
"last-column-id": 0,
"schema": {"type": "struct", "fields": []},
"partition-spec": [],
"current-snapshot-id": -1
});
assert!(validate(&metadata).is_ok());
metadata["snapshots"] = json!([{
"snapshot-id": 1,
"timestamp-ms": 1,
"manifests": ["s3://warehouse/tables/table-id/metadata/manifest.avro"]
}]);
validate_supported_table_metadata(&metadata).unwrap();
assert!(matches!(validate(&metadata), Err(TableCatalogStoreError::Conflict(_))));
}
#[test]
fn empty_table_cleanup_rejects_unsupported_versions_and_unknown_references() {
for version in [0, 3, 4] {
let mut metadata = empty_metadata();
metadata["format-version"] = json!(version);
assert!(validate(&metadata).is_err(), "version {version}");
}
for field in [
"manifest-list",
"manifests",
"data-files",
"delete-files",
"next-row-id",
"future-field",
] {
let mut metadata = empty_metadata();
metadata[field] = json!([]);
assert!(validate(&metadata).is_err(), "field {field}");
}
}
#[test]
fn empty_table_cleanup_rejects_snapshot_and_history_references() {
let mut metadata = empty_metadata();
metadata["snapshots"] = json!([{
"snapshot-id": 1,
"sequence-number": 0,
"timestamp-ms": 1,
"manifest-list": "s3://warehouse/tables/table-id/metadata/list.avro",
"summary": {"operation": "append"}
}]);
validate_supported_table_metadata(&metadata).unwrap();
assert!(matches!(validate(&metadata), Err(TableCatalogStoreError::Conflict(_))));
let mut metadata = empty_metadata();
metadata["snapshot-log"] = json!([{"timestamp-ms": 1, "snapshot-id": 1}]);
assert!(validate(&metadata).is_err());
metadata = empty_metadata();
metadata["refs"] = json!({"main": {"snapshot-id": 1, "type": "branch"}});
assert!(validate(&metadata).is_err());
metadata = empty_metadata();
metadata["current-snapshot-id"] = json!(1);
assert!(validate(&metadata).is_err());
}
#[test]
fn empty_table_cleanup_accepts_only_absent_null_or_minus_one_current_snapshot() {
for version in [1, 2] {
let mut metadata = empty_metadata();
metadata["format-version"] = json!(version);
if version == 1 {
metadata["schema"] = metadata["schemas"][0].clone();
metadata["partition-spec"] = json!([]);
}
assert!(validate(&metadata).is_ok());
for value in [Value::Null, json!(-1)] {
metadata["current-snapshot-id"] = value;
assert!(validate(&metadata).is_ok(), "version {version}");
}
for value in [json!(1), json!(0), json!(-2), json!("1"), json!(false), json!([])] {
metadata["current-snapshot-id"] = value;
assert!(validate(&metadata).is_err(), "version {version}");
}
}
}
#[test]
fn empty_table_cleanup_rejects_statistics_references_and_malformed_empty_fields() {
for field in ["snapshots", "snapshot-log", "statistics", "partition-statistics"] {
for value in [Value::Null, json!({}), json!("empty"), json!([{}])] {
let mut metadata = empty_metadata();
metadata[field] = value;
assert!(validate(&metadata).is_err(), "field {field}");
}
}
for value in [Value::Null, json!([]), json!("empty")] {
let mut metadata = empty_metadata();
metadata["refs"] = value;
assert!(validate(&metadata).is_err());
}
}
#[test]
fn empty_table_cleanup_rejects_unknown_or_cross_table_history() {
for location in [
format!("s3://other/{PREVIOUS}"),
PREVIOUS.replace("/orders/", "/other/"),
PREVIOUS.replace("/analytics/events/", "/another/"),
PREVIOUS.replace("00001.metadata.json", "../00001.metadata.json"),
PREVIOUS.replace("00001.metadata.json", "%2e%2e.json"),
format!("{PREVIOUS}?versionId=previous"),
format!("/{PREVIOUS}"),
OBJECT.to_string(),
] {
let mut metadata = empty_metadata();
metadata["metadata-log"] = json!([{"timestamp-ms": 1, "metadata-file": location}]);
assert!(validate(&metadata).is_err(), "location {location}");
}
let mut metadata = empty_metadata();
metadata["metadata-log"] = json!([{"timestamp-ms": 1, "metadata-file": PREVIOUS, "future-file": "data.parquet"}]);
assert!(validate(&metadata).is_err());
}
#[test]
fn empty_table_cleanup_requires_valid_schema_uuid_and_warehouse() {
for uuid in ["table-uuid", "00000000-0000-0000-0000-000000000000", ""] {
let mut metadata = empty_metadata();
metadata["table-uuid"] = json!(uuid);
assert!(validate(&metadata).is_err());
}
for location in [
"s3://other/tables/table-id",
"s3://warehouse/",
"s3://warehouse/.rustfs-table/metadata",
"file:///table",
"s3://warehouse/custom/table-id",
"s3://warehouse/tables/table-id",
"s3://warehouse/tables/00000000-0000-0000-0000-000000000000",
"s3://warehouse/tables/a9d8f3b1-abde-4a0b-b6fb-e36a30abff16/nested",
] {
let mut metadata = empty_metadata();
metadata["location"] = json!(location);
assert!(validate(&metadata).is_err());
}
let mut metadata = empty_metadata();
metadata["schemas"] = json!([]);
assert!(validate(&metadata).is_err());
}
#[test]
fn empty_table_cleanup_rejects_non_default_metadata_paths() {
let bytes = serde_json::to_vec(&empty_metadata()).unwrap();
for object in [
OBJECT.replace("/default/", "/custom/"),
OBJECT.replace("/tables/", "/views/"),
OBJECT.replace("/metadata/", "/data/"),
OBJECT.replace("00002.metadata.json", "part.parquet"),
OBJECT.replace("00002.metadata.json", "nested/00002.metadata.json"),
format!("s3://{BUCKET}/{OBJECT}"),
] {
assert!(validate_empty_table_cleanup_metadata(BUCKET, &object, &bytes).is_err(), "object {object}");
}
}
#[test]
fn empty_table_cleanup_decodes_gzip_and_rejects_invalid_json() {
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(&serde_json::to_vec(&empty_metadata()).unwrap()).unwrap();
let bytes = encoder.finish().unwrap();
let object = OBJECT.replace(".metadata.json", ".gz.metadata.json");
assert!(validate_empty_table_cleanup_metadata(BUCKET, &object, &bytes).is_ok());
assert!(validate_empty_table_cleanup_metadata(BUCKET, OBJECT, b"{}").is_err());
assert!(validate_empty_table_cleanup_metadata(BUCKET, OBJECT, b"[").is_err());
assert!(validate_empty_table_cleanup_metadata(BUCKET, &object, b"invalid gzip").is_err());
}
}
+11 -4
View File
@@ -28,9 +28,11 @@ use std::{
use crate::storage_api::table::contract::http::HTTPPreconditions;
use crate::storage_api::table::contract::list::{
ListObjectVersionsInfo as StorageListObjectVersionsInfo, ListObjectsV2Info as StorageListObjectsV2Info,
ListOperations as StorageListOperations, ObjectInfoOrErr as StorageObjectInfoOrErr, WalkOptions as StorageWalkOptions,
AuthoritativeListOperations as StorageAuthoritativeListOperations, ListObjectVersionsInfo as StorageListObjectVersionsInfo,
ListObjectsV2Info as StorageListObjectsV2Info, ListOperations as StorageListOperations,
ObjectInfoOrErr as StorageObjectInfoOrErr, WalkOptions as StorageWalkOptions,
};
use crate::storage_api::table::contract::multipart::MultipartUploadInspection as StorageMultipartUploadInspection;
use crate::storage_api::table::contract::namespace::NamespaceLocking as StorageNamespaceLocking;
use crate::storage_api::table::contract::object::{ObjectIO as StorageObjectIO, ObjectOperations as StorageObjectOperations};
use crate::storage_api::table::contract::range::HTTPRangeSpec;
@@ -58,6 +60,7 @@ use crate::storage_api::table::{
StorageObjectOptions as ObjectOptions, StorageObjectToDelete as ObjectToDelete, StoragePutObjReader as PutObjReader,
};
mod cleanup_metadata;
mod error;
mod iceberg;
mod identifier;
@@ -246,7 +249,9 @@ pub(crate) trait TableCatalogStorage:
WalkOptions = CatalogWalkOptions,
WalkCancellation = tokio_util::sync::CancellationToken,
WalkResultSender = tokio::sync::mpsc::Sender<CatalogObjectInfoOrErr>,
> + StorageNamespaceLocking<Error = EcstoreError, NamespaceLock = rustfs_lock::NamespaceLockWrapper>
> + StorageAuthoritativeListOperations
+ StorageNamespaceLocking<Error = EcstoreError, NamespaceLock = rustfs_lock::NamespaceLockWrapper>
+ StorageMultipartUploadInspection<Error = EcstoreError>
{
}
@@ -274,7 +279,9 @@ impl<T> TableCatalogStorage for T where
WalkOptions = CatalogWalkOptions,
WalkCancellation = tokio_util::sync::CancellationToken,
WalkResultSender = tokio::sync::mpsc::Sender<CatalogObjectInfoOrErr>,
> + StorageNamespaceLocking<Error = EcstoreError, NamespaceLock = rustfs_lock::NamespaceLockWrapper>
> + StorageAuthoritativeListOperations
+ StorageNamespaceLocking<Error = EcstoreError, NamespaceLock = rustfs_lock::NamespaceLockWrapper>
+ StorageMultipartUploadInspection<Error = EcstoreError>
{
}
+267
View File
@@ -0,0 +1,267 @@
// 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.
use super::object::{
next_table_catalog_update_time, table_warehouse_index_state_ready, validate_table_warehouse_index_entry_object,
};
use super::*;
pub(super) struct TableBucketDisablement {
pub(super) entry: TableBucketEntry,
guards: Vec<TableCatalogLockGuard>,
}
/// An in-memory, fenced cleanup plan. No mutation occurs until every object has
/// been validated and the caller has authorized all metadata deletions.
pub(crate) struct EmptyTableBucketCleanup {
disablement: TableBucketDisablement,
metadata: Vec<(String, String)>,
indexes: Vec<(String, String)>,
fence: TableCatalogObjectMutationFence,
}
impl EmptyTableBucketCleanup {
pub(crate) fn metadata_objects(&self) -> impl Iterator<Item = &str> {
self.metadata.iter().map(|(key, _)| key.as_str())
}
pub(crate) fn ensure_held(&self) -> TableCatalogStoreResult<()> {
self.fence.ensure_held()
}
pub(crate) fn mutation_fence(&self) -> TableCatalogObjectMutationFence {
self.fence.clone()
}
}
fn cleanup_conflict(message: impl Into<String>) -> TableCatalogStoreError {
TableCatalogStoreError::Conflict(message.into())
}
impl<B: TableCatalogObjectBackend> ObjectTableCatalogStore<B> {
pub(super) async fn begin_table_bucket_disablement(
&self,
mut entry: TableBucketEntry,
publication: Option<&dyn TableCommitPublication>,
) -> TableCatalogStoreResult<TableBucketDisablement> {
validate_table_bucket_entry(&entry)?;
let mut guards = Vec::new();
if publication.is_some_and(|publication| publication.catalog_migration_read_permit_status() == Some(true)) {
if self
.backend
.read_object(self.catalog_bucket(), &self.paths.backing_migration_global_fence_path())
.await?
.is_some()
{
return Err(cleanup_conflict("table bucket registry migration is in progress"));
}
self.ensure_object_backed_catalog_write_permit_after_lock(&entry.table_bucket)
.await?;
} else {
guards.push(self.acquire_table_bucket_registry_write_permit().await?);
guards.push(self.acquire_object_backed_catalog_write_permit(&entry.table_bucket).await?);
}
let object = self.paths.table_bucket_entry_path(&entry.table_bucket);
guards.push(self.backend.acquire_write_lock(self.catalog_bucket(), &object).await?);
if let Some((current, _)) = self.read_table_bucket_with_etag_unlocked(&entry.table_bucket).await? {
if current.active_rename_id.is_some()
|| !matches!(current.state, TableCatalogEntryState::Active | TableCatalogEntryState::Deleted)
{
return Err(cleanup_conflict("table bucket has an operation in progress"));
}
entry = current;
}
Ok(TableBucketDisablement { entry, guards })
}
pub(super) async fn finish_table_bucket_disablement(
&self,
disablement: &mut TableBucketDisablement,
) -> TableCatalogStoreResult<()> {
let mut entry = disablement.entry.clone();
entry.state = TableCatalogEntryState::Deleted;
entry.updated_at = Some(next_table_catalog_update_time(entry.updated_at.as_deref()));
self.write_entry_unlocked(
self.catalog_bucket(),
&self.paths.table_bucket_entry_path(&entry.table_bucket),
&entry,
TableCatalogPutPrecondition::Any,
disablement
.guards
.iter()
.flat_map(TableCatalogLockGuard::write_commit_guards)
.collect(),
)
.await
}
async fn prepare_empty_table_bucket_cleanup(
&self,
entry: TableBucketEntry,
publication: &impl TableCatalogObjectBackend,
) -> TableCatalogStoreResult<EmptyTableBucketCleanup> {
if !publication.holds_table_bucket(&entry.table_bucket) {
return Err(cleanup_conflict("empty table bucket cleanup requires a publication fence"));
}
let disablement = self.begin_table_bucket_disablement(entry, Some(publication)).await?;
let bucket = &disablement.entry.table_bucket;
let mut fence = publication
.object_mutation_fence()
.ok_or_else(|| cleanup_conflict("cleanup requires storage fencing"))?;
fence
.signals
.extend(disablement.guards.iter().filter_map(TableCatalogLockGuard::lock_lost_signal));
fence.ensure_held()?;
let catalog_objects = self
.backend
.list_objects_for_cleanup(self.catalog_bucket(), &self.paths.table_bucket_root_prefix(bucket))
.await?;
let bucket_path = self.paths.table_bucket_entry_path(bucket);
let index_state_path = self.paths.warehouse_index_state_path(bucket);
let index_prefix = self.paths.warehouse_index_entries_prefix(bucket);
let mut indexes = Vec::new();
for object in catalog_objects {
if object.delete_marker
|| object
.version_id
.as_deref()
.is_some_and(|version| !version.is_empty() && version != "null")
{
return Err(cleanup_conflict("catalog contains versioned or deleted records"));
}
if object.key == bucket_path {
continue;
}
let etag = if object.key == index_state_path {
let (state, etag) = self
.read_entry::<TableWarehouseIndexStateEntry>(self.catalog_bucket(), &object.key)
.await?
.ok_or_else(|| cleanup_conflict("warehouse index state changed during cleanup"))?;
table_warehouse_index_state_ready(&state, bucket)?;
if !matches!(state.state, TableCatalogEntryState::Active | TableCatalogEntryState::Deleted) {
return Err(cleanup_conflict("warehouse index has an operation in progress"));
}
etag
} else if object.key.starts_with(&index_prefix) {
let (index, etag) = self
.read_entry::<TableWarehouseIndexEntry>(self.catalog_bucket(), &object.key)
.await?
.ok_or_else(|| cleanup_conflict("warehouse index changed during cleanup"))?;
validate_table_warehouse_index_entry_object(&self.paths, &object.key, &index)?;
if index.table_bucket != *bucket || index.state != TableCatalogEntryState::Deleted {
return Err(cleanup_conflict("table bucket contains an active warehouse index"));
}
Namespace::parse(&index.namespace).map_err(|err| cleanup_conflict(err.to_string()))?;
IdentifierSegment::parse(index.table.clone()).map_err(|err| cleanup_conflict(err.to_string()))?;
if Uuid::parse_str(&index.table_id).ok().filter(|id| !id.is_nil()).is_none() {
return Err(cleanup_conflict("warehouse index table identity is invalid"));
}
let expected = format!("tables/{}/", index.table_id);
if index.warehouse_object_prefix != expected {
return Err(cleanup_conflict("cleanup requires the default table warehouse location"));
}
etag
} else {
return Err(cleanup_conflict("table bucket contains namespaces or retained catalog resources"));
};
let etag = etag.ok_or_else(|| cleanup_conflict("catalog cleanup object has no etag"))?;
indexes.push((object.key, etag));
}
self.backend.ensure_no_multipart_uploads(bucket).await?;
let mut metadata = Vec::new();
for object in self.backend.list_objects_for_cleanup(bucket, "").await? {
if object.delete_marker
|| object
.version_id
.as_deref()
.is_some_and(|version| !version.is_empty() && version != "null")
{
return Err(cleanup_conflict("table bucket contains object versions or delete markers"));
}
let value = publication
.read_object_limited(bucket, &object.key, TABLE_METADATA_JSON_MAX_SIZE)
.await?
.ok_or_else(|| cleanup_conflict("metadata object changed during cleanup"))?;
crate::table_catalog::cleanup_metadata::validate_empty_table_cleanup_metadata(bucket, &object.key, &value.data)?;
let etag = value
.etag
.ok_or_else(|| cleanup_conflict("metadata cleanup object has no etag"))?;
metadata.push((object.key, etag));
}
fence.ensure_held()?;
Ok(EmptyTableBucketCleanup {
disablement,
metadata,
indexes,
fence,
})
}
async fn execute_empty_table_bucket_cleanup(
&self,
cleanup: &mut EmptyTableBucketCleanup,
incarnation: Uuid,
) -> TableCatalogStoreResult<()> {
let bucket = &cleanup.disablement.entry.table_bucket;
for (key, etag) in &cleanup.metadata {
cleanup.ensure_held()?;
self.backend
.delete_object_if_match_fenced_for_incarnation(bucket, key, etag, incarnation, &cleanup.fence)
.await?;
}
// A retry inventories the remaining metadata. Keep warehouse protection
// until all user objects and uploads have been checked again.
if !self.backend.list_objects_for_cleanup(bucket, "").await?.is_empty() {
return Err(cleanup_conflict("table bucket changed during cleanup"));
}
self.backend.ensure_no_multipart_uploads(bucket).await?;
for (key, etag) in &cleanup.indexes {
cleanup.ensure_held()?;
self.backend
.delete_object_if_match_fenced(self.catalog_bucket(), key, etag, &cleanup.fence)
.await?;
}
cleanup.ensure_held()?;
self.finish_table_bucket_disablement(&mut cleanup.disablement).await
}
}
impl<B: TableCatalogObjectBackend> ConfiguredTableCatalogStore<B> {
pub(crate) async fn prepare_empty_table_bucket_cleanup(
&self,
entry: TableBucketEntry,
publication: &impl TableCatalogObjectBackend,
) -> TableCatalogStoreResult<EmptyTableBucketCleanup> {
match self {
Self::ObjectBacked(store) => store.prepare_empty_table_bucket_cleanup(entry, publication).await,
Self::DurableStrong(_) => Err(TableCatalogStoreError::Unsupported(
"empty table bucket cleanup requires object-backed catalog storage".to_string(),
)),
}
}
pub(crate) async fn execute_empty_table_bucket_cleanup(
&self,
cleanup: &mut EmptyTableBucketCleanup,
incarnation: Uuid,
) -> TableCatalogStoreResult<()> {
match self {
Self::ObjectBacked(store) => store.execute_empty_table_bucket_cleanup(cleanup, incarnation).await,
Self::DurableStrong(_) => Err(TableCatalogStoreError::Unsupported(
"empty table bucket cleanup requires object-backed catalog storage".to_string(),
)),
}
}
}
+202 -3
View File
@@ -17,8 +17,13 @@ use super::*;
use crate::storage_api::table::{WriteCommitGuard, WriteCompletion};
mod backup;
mod cleanup;
mod migration;
mod object;
mod registration_cache;
#[cfg(test)]
mod registration_cache_tests;
pub(crate) use registration_cache::TableCatalogRegistrationCache;
mod strong;
pub(crate) use backup::{TableCatalogBackupReport, TableCatalogRestoreReport};
@@ -775,6 +780,14 @@ pub(crate) struct TableCatalogObjectListPage {
pub is_truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TableCatalogCleanupObject {
pub key: String,
pub version_id: Option<String>,
pub etag: Option<String>,
pub delete_marker: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum TableCatalogPutPrecondition {
Any,
@@ -803,6 +816,10 @@ pub(in crate::table_catalog) fn catalog_list_next_continuation(
#[async_trait::async_trait]
pub(crate) trait TableCatalogObjectBackend: Clone + Send + Sync + 'static {
fn registration_cache(&self) -> Option<TableCatalogRegistrationCache> {
None
}
fn strong_catalog_runtime(&self) -> Option<StrongTableCatalogRuntime> {
None
}
@@ -918,6 +935,30 @@ pub(crate) trait TableCatalogObjectBackend: Clone + Send + Sync + 'static {
fence.ensure_held()
}
async fn put_object_unlocked_fenced(
&self,
bucket: &str,
object: &str,
data: Vec<u8>,
precondition: TableCatalogPutPrecondition,
_write_guards: Vec<WriteCommitGuard>,
fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
self.put_object_fenced(bucket, object, data, precondition, fence).await
}
async fn delete_object_unlocked_fenced(
&self,
bucket: &str,
object: &str,
_write_guards: Vec<WriteCommitGuard>,
fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
fence.ensure_held()?;
self.delete_object_unlocked(bucket, object).await?;
fence.ensure_held()
}
async fn delete_object(&self, bucket: &str, object: &str) -> TableCatalogStoreResult<()>;
async fn delete_object_if_match(&self, bucket: &str, object: &str, expected_etag: &str) -> TableCatalogStoreResult<()>;
@@ -934,12 +975,41 @@ pub(crate) trait TableCatalogObjectBackend: Clone + Send + Sync + 'static {
fence.ensure_held()
}
async fn delete_object_if_match_fenced_for_incarnation(
&self,
_bucket: &str,
_object: &str,
_expected_etag: &str,
_expected_incarnation_id: Uuid,
_fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
Err(TableCatalogStoreError::Unsupported(
"incarnation-checked cleanup is not supported by this backend".to_string(),
))
}
async fn delete_object_unlocked(&self, bucket: &str, object: &str) -> TableCatalogStoreResult<()> {
self.delete_object(bucket, object).await
}
async fn list_objects(&self, bucket: &str, prefix: &str) -> TableCatalogStoreResult<Vec<String>>;
async fn list_objects_for_cleanup(
&self,
_bucket: &str,
_prefix: &str,
) -> TableCatalogStoreResult<Vec<TableCatalogCleanupObject>> {
Err(TableCatalogStoreError::Unsupported(
"authoritative cleanup listing is not supported by this backend".to_string(),
))
}
async fn ensure_no_multipart_uploads(&self, _bucket: &str) -> TableCatalogStoreResult<()> {
Err(TableCatalogStoreError::Unsupported(
"multipart cleanup validation is not supported by this backend".to_string(),
))
}
async fn list_objects_page(
&self,
bucket: &str,
@@ -2204,6 +2274,7 @@ where
pub(crate) struct EcStoreTableCatalogObjectBackend<S> {
store: Arc<S>,
strong_runtime: StrongTableCatalogRuntime,
registration_cache: TableCatalogRegistrationCache,
}
impl<S> Clone for EcStoreTableCatalogObjectBackend<S> {
@@ -2211,6 +2282,7 @@ impl<S> Clone for EcStoreTableCatalogObjectBackend<S> {
Self {
store: self.store.clone(),
strong_runtime: self.strong_runtime.clone(),
registration_cache: self.registration_cache.clone(),
}
}
}
@@ -2220,7 +2292,19 @@ where
S: TableCatalogStorage,
{
pub fn new_with_strong_runtime(store: Arc<S>, strong_runtime: StrongTableCatalogRuntime) -> Self {
Self { store, strong_runtime }
Self::new_with_runtimes(store, strong_runtime, TableCatalogRegistrationCache::default())
}
pub fn new_with_runtimes(
store: Arc<S>,
strong_runtime: StrongTableCatalogRuntime,
registration_cache: TableCatalogRegistrationCache,
) -> Self {
Self {
store,
strong_runtime,
registration_cache,
}
}
}
@@ -2231,6 +2315,10 @@ impl<S> TableCatalogObjectBackend for EcStoreTableCatalogObjectBackend<S>
where
S: TableCatalogStorage,
{
fn registration_cache(&self) -> Option<TableCatalogRegistrationCache> {
Some(self.registration_cache.clone())
}
fn strong_catalog_runtime(&self) -> Option<StrongTableCatalogRuntime> {
Some(self.strong_runtime.clone())
}
@@ -2390,6 +2478,46 @@ where
.await
}
async fn put_object_unlocked_fenced(
&self,
bucket: &str,
object: &str,
data: Vec<u8>,
precondition: TableCatalogPutPrecondition,
write_guards: Vec<WriteCommitGuard>,
fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
fence.ensure_held()?;
self.put_object_with_options(bucket, object, data, precondition, Some(write_guards), Some(fence))
.await
}
async fn delete_object_unlocked_fenced(
&self,
bucket: &str,
object: &str,
write_guards: Vec<WriteCommitGuard>,
fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
fence.ensure_held()?;
if write_guards.is_empty() {
return Err(TableCatalogStoreError::Internal("catalog delete has no namespace owner".to_string()));
}
let mut options = ObjectOptions {
no_lock: true,
..Default::default()
};
fence.add_to_object_options(&mut options);
for guard in &write_guards {
options.add_write_commit_guard(guard);
}
match self.store.delete_object(bucket, object, options).await {
Ok(_) => fence.ensure_held(),
Err(err) if is_missing_storage_error(&err) => fence.ensure_held(),
Err(err) => Err(storage_error_to_catalog("delete fenced catalog object", err)),
}
}
async fn put_object_fenced(
&self,
bucket: &str,
@@ -2412,7 +2540,7 @@ where
}
async fn delete_object_if_match(&self, bucket: &str, object: &str, expected_etag: &str) -> TableCatalogStoreResult<()> {
self.delete_object_if_match_with_fence(bucket, object, expected_etag, None)
self.delete_object_if_match_with_fence(bucket, object, expected_etag, None, None)
.await
}
@@ -2424,7 +2552,25 @@ where
fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
fence.ensure_held()?;
self.delete_object_if_match_with_fence(bucket, object, expected_etag, Some(fence))
self.delete_object_if_match_with_fence(bucket, object, expected_etag, Some(fence), None)
.await
}
async fn delete_object_if_match_fenced_for_incarnation(
&self,
bucket: &str,
object: &str,
expected_etag: &str,
expected_incarnation_id: Uuid,
fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
if expected_incarnation_id.is_nil() {
return Err(TableCatalogStoreError::Invalid(
"cleanup requires a non-nil bucket incarnation".to_string(),
));
}
fence.ensure_held()?;
self.delete_object_if_match_with_fence(bucket, object, expected_etag, Some(fence), Some(expected_incarnation_id))
.await
}
@@ -2498,6 +2644,57 @@ where
})
}
async fn list_objects_for_cleanup(
&self,
bucket: &str,
prefix: &str,
) -> TableCatalogStoreResult<Vec<TableCatalogCleanupObject>> {
let cancel = tokio_util::sync::CancellationToken::new();
let _cancel_on_drop = cancel.clone().drop_guard();
let (sender, mut receiver) = tokio::sync::mpsc::channel::<CatalogObjectInfoOrErr>(100);
let walk = self.store.clone().walk_authoritative(
cancel,
bucket,
prefix,
sender,
CatalogWalkOptions {
include_free_versions: true,
..Default::default()
},
);
let collect = async move {
let mut objects = Vec::new();
while let Some(result) = receiver.recv().await {
if let Some(err) = result.err {
return Err(storage_error_to_catalog("inspect cleanup object versions", err));
}
let object = result.item.ok_or_else(|| {
TableCatalogStoreError::Internal("cleanup object walk returned an empty result".to_string())
})?;
objects.push(TableCatalogCleanupObject {
key: object.name,
version_id: object.version_id.filter(|id| !id.is_nil()).map(|id| id.to_string()),
etag: object.etag,
delete_marker: object.delete_marker,
});
}
Ok(objects)
};
let (walk_result, objects) = tokio::join!(walk, collect);
let objects = objects?;
walk_result.map_err(|err| storage_error_to_catalog("list cleanup object versions", err))?;
Ok(objects)
}
async fn ensure_no_multipart_uploads(&self, bucket: &str) -> TableCatalogStoreResult<()> {
self.store.ensure_no_multipart_uploads(bucket).await.map_err(|err| match err {
StorageError::BucketNotEmpty(_) => {
TableCatalogStoreError::Conflict(format!("table bucket {bucket} contains unfinished multipart uploads"))
}
other => storage_error_to_catalog("inspect unfinished multipart uploads", other),
})
}
async fn acquire_write_lock(&self, bucket: &str, object: &str) -> TableCatalogStoreResult<TableCatalogLockGuard> {
let lock = self
.store
@@ -2534,12 +2731,14 @@ where
object: &str,
expected_etag: &str,
fence: Option<&TableCatalogObjectMutationFence>,
expected_incarnation_id: Option<Uuid>,
) -> TableCatalogStoreResult<()> {
let mut options = ObjectOptions {
http_preconditions: Some(HTTPPreconditions {
if_match: Some(expected_etag.to_string()),
..Default::default()
}),
expected_bucket_incarnation_id: expected_incarnation_id,
..Default::default()
};
if let Some(fence) = fence {
+154 -94
View File
@@ -13,7 +13,9 @@
// limitations under the License.
use super::*;
use futures::{StreamExt, TryStreamExt, stream};
pub(super) const TABLE_REGISTRATION_READ_CONCURRENCY: usize = 8;
const TABLE_MAINTENANCE_RENAME_MAX_OBJECTS: usize = 4096;
const TABLE_MAINTENANCE_SCHEDULER_HISTORY_MAX_OBJECTS: usize = 4096;
@@ -261,7 +263,7 @@ fn validate_table_rename_intent_object(
Ok(())
}
fn next_table_catalog_update_time(previous: Option<&str>) -> String {
pub(super) fn next_table_catalog_update_time(previous: Option<&str>) -> String {
let now = OffsetDateTime::now_utc();
let update_time = previous
.and_then(|value| OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339).ok())
@@ -360,7 +362,7 @@ pub(super) fn validate_table_maintenance_report_owner(
Ok(())
}
fn validate_table_warehouse_index_entry_object(
pub(super) fn validate_table_warehouse_index_entry_object(
paths: &TableCatalogObjectPaths,
object: &str,
index: &TableWarehouseIndexEntry,
@@ -374,7 +376,10 @@ fn validate_table_warehouse_index_entry_object(
Ok(())
}
fn table_warehouse_index_state_ready(state: &TableWarehouseIndexStateEntry, table_bucket: &str) -> TableCatalogStoreResult<bool> {
pub(super) fn table_warehouse_index_state_ready(
state: &TableWarehouseIndexStateEntry,
table_bucket: &str,
) -> TableCatalogStoreResult<bool> {
if state.version == 0 || state.version > TABLE_WAREHOUSE_INDEX_STATE_VERSION {
return Err(TableCatalogStoreError::Invalid(format!(
"unsupported warehouse index state version: {}",
@@ -1217,7 +1222,7 @@ where
.await
}
async fn write_entry_unlocked<T>(
pub(super) async fn write_entry_unlocked<T>(
&self,
bucket: &str,
object: &str,
@@ -1225,14 +1230,39 @@ where
precondition: TableCatalogPutPrecondition,
write_guards: Vec<WriteCommitGuard>,
) -> TableCatalogStoreResult<()>
where
T: Serialize,
{
self.write_entry_unlocked_with_fence(bucket, object, entry, precondition, write_guards, None)
.await
}
async fn write_entry_unlocked_with_fence<T>(
&self,
bucket: &str,
object: &str,
entry: &T,
precondition: TableCatalogPutPrecondition,
write_guards: Vec<WriteCommitGuard>,
fence: Option<&TableCatalogObjectMutationFence>,
) -> TableCatalogStoreResult<()>
where
T: Serialize,
{
let data = serde_json::to_vec(entry)
.map_err(|err| TableCatalogStoreError::Internal(format!("failed to serialize catalog entry {object}: {err}")))?;
self.backend
.put_object_unlocked(bucket, object, data, precondition, write_guards)
.await
match fence {
Some(fence) => {
self.backend
.put_object_unlocked_fenced(bucket, object, data, precondition, write_guards, fence)
.await
}
None => {
self.backend
.put_object_unlocked(bucket, object, data, precondition, write_guards)
.await
}
}
}
async fn write_exact_entry_unlocked<T>(
@@ -1243,11 +1273,27 @@ where
precondition: TableCatalogPutPrecondition,
write_guards: Vec<WriteCommitGuard>,
) -> TableCatalogStoreResult<String>
where
T: DeserializeOwned + PartialEq + Serialize,
{
self.write_exact_entry_unlocked_with_fence(bucket, object, entry, precondition, write_guards, None)
.await
}
async fn write_exact_entry_unlocked_with_fence<T>(
&self,
bucket: &str,
object: &str,
entry: &T,
precondition: TableCatalogPutPrecondition,
write_guards: Vec<WriteCommitGuard>,
fence: Option<&TableCatalogObjectMutationFence>,
) -> TableCatalogStoreResult<String>
where
T: DeserializeOwned + PartialEq + Serialize,
{
let write_result = self
.write_entry_unlocked(bucket, object, entry, precondition, write_guards)
.write_entry_unlocked_with_fence(bucket, object, entry, precondition, write_guards, fence)
.await;
let current = self.read_entry_unlocked::<T>(bucket, object).await?;
match current {
@@ -1264,7 +1310,7 @@ where
}
}
async fn read_table_bucket_with_etag_unlocked(
pub(super) async fn read_table_bucket_with_etag_unlocked(
&self,
table_bucket: &str,
) -> TableCatalogStoreResult<Option<(TableBucketEntry, String)>> {
@@ -1387,6 +1433,7 @@ where
"table rename recovery requires a table-bucket publication fence".to_string(),
));
}
let mutation_fence = publication.object_mutation_fence().unwrap_or_default();
let bucket_object = self.paths.table_bucket_entry_path(table_bucket);
let Some((observed_bucket, _)) = self
.read_entry::<TableBucketEntry>(self.catalog_bucket(), &bucket_object)
@@ -1511,7 +1558,7 @@ where
{
Some((current, _)) if current == source_fence || current == source_tombstone => {}
Some((current, current_etag)) if current == intent.source && current_etag == intent.source_etag => {
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&source_object,
&source_fence,
@@ -1520,6 +1567,7 @@ where
.iter()
.flat_map(TableCatalogLockGuard::write_commit_guards)
.collect(),
Some(&mutation_fence),
)
.await?;
}
@@ -1549,7 +1597,7 @@ where
{
Some((current, _)) if current == destination_fence || current == intent.destination => {}
None if intent.destination_etag.is_none() => {
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&destination_object,
&destination_fence,
@@ -1558,6 +1606,7 @@ where
.iter()
.flat_map(TableCatalogLockGuard::write_commit_guards)
.collect(),
Some(&mutation_fence),
)
.await?;
}
@@ -1565,7 +1614,7 @@ where
if current.state == TableCatalogEntryState::Deleted
&& Some(current_etag.as_str()) == intent.destination_etag.as_deref() =>
{
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&destination_object,
&destination_fence,
@@ -1574,6 +1623,7 @@ where
.iter()
.flat_map(TableCatalogLockGuard::write_commit_guards)
.collect(),
Some(&mutation_fence),
)
.await?;
}
@@ -1601,7 +1651,7 @@ where
{
Some((current, _)) if current == source_tombstone => {}
Some((current, current_etag)) if current == source_fence => {
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&source_object,
&source_tombstone,
@@ -1610,6 +1660,7 @@ where
.iter()
.flat_map(TableCatalogLockGuard::write_commit_guards)
.collect(),
Some(&mutation_fence),
)
.await?;
}
@@ -1647,7 +1698,7 @@ where
"table rename warehouse index changed during recovery".to_string(),
));
}
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&index_object,
&destination_index,
@@ -1656,6 +1707,7 @@ where
.iter()
.flat_map(TableCatalogLockGuard::write_commit_guards)
.collect(),
Some(&mutation_fence),
)
.await?;
}
@@ -1674,7 +1726,7 @@ where
{
Some((current, _)) if current == intent.destination => {}
Some((current, current_etag)) if current == destination_fence => {
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&destination_object,
&intent.destination,
@@ -1683,6 +1735,7 @@ where
.iter()
.flat_map(TableCatalogLockGuard::write_commit_guards)
.collect(),
Some(&mutation_fence),
)
.await?;
}
@@ -1720,12 +1773,13 @@ where
}
bucket_entry.active_rename_id = None;
bucket_entry.updated_at = Some(next_table_catalog_update_time(bucket_entry.updated_at.as_deref()));
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&bucket_object,
&bucket_entry,
TableCatalogPutPrecondition::IfMatch(bucket_etag),
_bucket_guard.write_commit_guards(),
Some(&mutation_fence),
)
.await?;
Ok(())
@@ -1873,7 +1927,12 @@ where
let candidate = table_warehouse_index_entry(entry)?;
validate_table_entry_version_and_id(entry)?;
for existing in self
.list_all_table_entries_with_limit(&candidate.table_bucket, None, locked_table_entry)
.list_all_table_entries_with_limit(
&candidate.table_bucket,
None,
locked_table_entry,
TABLE_REGISTRATION_READ_CONCURRENCY,
)
.await?
{
if existing.state != TableCatalogEntryState::Active {
@@ -1896,34 +1955,38 @@ where
}
}
let state_object = self.paths.warehouse_index_state_path(&candidate.table_bucket);
for object in self
let index_objects = self
.backend
.list_objects(self.catalog_bucket(), &self.paths.warehouse_index_entries_prefix(&candidate.table_bucket))
.await?
{
if object == state_object {
continue;
}
let Some((existing, _)) = self
.read_entry::<TableWarehouseIndexEntry>(self.catalog_bucket(), &object)
.await?
else {
continue;
};
validate_table_warehouse_index_entry_object(&self.paths, &object, &existing)?;
if existing.table_id == candidate.table_id || existing.state != TableCatalogEntryState::Active {
continue;
}
if warehouse_object_prefixes_overlap(&existing.warehouse_object_prefix, &candidate.warehouse_object_prefix)
&& self.warehouse_index_entry_has_active_owner(&existing).await?
{
return Err(TableCatalogStoreError::Conflict(format!(
"table warehouse location overlaps an active table: {}",
candidate.warehouse_object_prefix
)));
}
}
Ok(())
.await?;
stream::iter(index_objects.into_iter().filter(|object| object != &state_object))
.map(|object| {
let candidate = &candidate;
async move {
let Some((existing, _)) = self
.read_entry::<TableWarehouseIndexEntry>(self.catalog_bucket(), &object)
.await?
else {
return Ok(());
};
validate_table_warehouse_index_entry_object(&self.paths, &object, &existing)?;
if existing.table_id == candidate.table_id || existing.state != TableCatalogEntryState::Active {
return Ok(());
}
if warehouse_object_prefixes_overlap(&existing.warehouse_object_prefix, &candidate.warehouse_object_prefix)
&& self.warehouse_index_entry_has_active_owner(&existing).await?
{
return Err(TableCatalogStoreError::Conflict(format!(
"table warehouse location overlaps an active table: {}",
candidate.warehouse_object_prefix
)));
}
Ok::<_, TableCatalogStoreError>(())
}
})
.buffered(TABLE_REGISTRATION_READ_CONCURRENCY)
.try_for_each(|()| async { Ok(()) })
.await
}
async fn reserve_table_warehouse_index(
@@ -2364,7 +2427,7 @@ where
) -> TableCatalogStoreResult<Option<TableDataPlaneResource>> {
let mut matched: Option<TableDataPlaneResource> = None;
for table in self
.list_all_table_entries_with_limit(table_bucket, Some(TABLE_DATA_PLANE_INDEX_MISS_SCAN_MAX_CATALOG_OBJECTS), None)
.list_all_table_entries_with_limit(table_bucket, Some(TABLE_DATA_PLANE_INDEX_MISS_SCAN_MAX_CATALOG_OBJECTS), None, 1)
.await?
{
if table.state != TableCatalogEntryState::Active {
@@ -2456,7 +2519,7 @@ where
return Ok(());
}
let tables = self
.list_all_table_entries_with_limit(table_bucket, max_catalog_objects, None)
.list_all_table_entries_with_limit(table_bucket, max_catalog_objects, None, 1)
.await?
.into_iter()
.filter(|table| table.state == TableCatalogEntryState::Active)
@@ -2537,7 +2600,7 @@ where
}
async fn list_all_table_entries(&self, table_bucket: &str) -> TableCatalogStoreResult<Vec<TableEntry>> {
self.list_all_table_entries_with_limit(table_bucket, None, None).await
self.list_all_table_entries_with_limit(table_bucket, None, None, 1).await
}
async fn list_table_entry_objects_for_data_plane_scan(
@@ -2586,8 +2649,8 @@ where
table_bucket: &str,
max_catalog_objects: Option<usize>,
locked_table_entry: Option<&str>,
read_concurrency: usize,
) -> TableCatalogStoreResult<Vec<TableEntry>> {
let mut entries = Vec::new();
let table_objects = match max_catalog_objects {
Some(max_catalog_objects) => {
self.list_table_entry_objects_for_data_plane_scan(table_bucket, max_catalog_objects)
@@ -2601,19 +2664,24 @@ where
.filter(|object| object.ends_with(TABLE_ENTRY_FILE))
.collect(),
};
for object in table_objects {
// Only the exact entry protected by the caller's write lock can bypass a read lock.
let entry = if locked_table_entry == Some(object.as_str()) {
self.read_entry_unlocked::<TableEntry>(self.catalog_bucket(), &object).await?
} else {
self.read_entry::<TableEntry>(self.catalog_bucket(), &object).await?
};
let Some((entry, _)) = entry else {
continue;
};
validate_table_entry_object(&self.paths, &object, &entry)?;
entries.push(entry);
}
let mut entries = stream::iter(table_objects)
.map(|object| async move {
// Only the exact entry protected by the caller's write lock can bypass a read lock.
let entry = if locked_table_entry == Some(object.as_str()) {
self.read_entry_unlocked::<TableEntry>(self.catalog_bucket(), &object).await?
} else {
self.read_entry::<TableEntry>(self.catalog_bucket(), &object).await?
};
let Some((entry, _)) = entry else {
return Ok(None);
};
validate_table_entry_object(&self.paths, &object, &entry)?;
Ok::<_, TableCatalogStoreError>(Some(entry))
})
.buffered(read_concurrency)
.try_filter_map(|entry| async move { Ok(entry) })
.try_collect::<Vec<_>>()
.await?;
entries.sort_by(|left, right| (&left.namespace, &left.table).cmp(&(&right.namespace, &right.table)));
Ok(entries)
}
@@ -2772,8 +2840,7 @@ where
"table registration requires a table publication fence".to_string(),
));
}
self.ensure_table_warehouse_prefix_available(&entry, Some(&table_path))
.await?;
self.check_registration_ownership(&entry, &table_path, publication).await?;
let reservation = self.reserve_table_warehouse_index(&entry, true, &table_path).await?;
if !publication.holds_table_bucket(&entry.table_bucket)
|| !publication.holds_table(&entry.table_bucket, &entry.namespace, &entry.table)
@@ -2784,20 +2851,23 @@ where
"table registration publication fence was lost before catalog update".to_string(),
));
}
let mutation_fence = publication.object_mutation_fence().unwrap_or_default();
let result = self
.write_entry_unlocked(
.write_entry_unlocked_with_fence(
self.catalog_bucket(),
&table_path,
&entry,
precondition,
_table_guard.write_commit_guards(),
Some(&mutation_fence),
)
.await;
if result.is_err() {
self.rollback_table_warehouse_index_reservation(&entry, reservation, "table entry write failed")
.await;
}
result
result?;
Ok(())
}
async fn write_view_entry(&self, entry: ViewEntry, precondition: TableCatalogPutPrecondition) -> TableCatalogStoreResult<()> {
@@ -6258,27 +6328,15 @@ where
.await
}
async fn disable_empty_table_bucket(&self, mut entry: TableBucketEntry) -> TableCatalogStoreResult<()> {
validate_table_bucket_entry(&entry)?;
let _registry_guard = self.acquire_table_bucket_registry_write_permit().await?;
let _migration_guard = self.acquire_object_backed_catalog_write_permit(&entry.table_bucket).await?;
let object = self.paths.table_bucket_entry_path(&entry.table_bucket);
let _guard = self.backend.acquire_write_lock(self.catalog_bucket(), &object).await?;
if let Some((current, _)) = self.read_table_bucket_with_etag_unlocked(&entry.table_bucket).await? {
if current.active_rename_id.is_some()
|| !matches!(current.state, TableCatalogEntryState::Active | TableCatalogEntryState::Deleted)
{
return Err(TableCatalogStoreError::Conflict("table bucket has an operation in progress".to_string()));
}
entry = current;
}
async fn disable_empty_table_bucket(&self, entry: TableBucketEntry) -> TableCatalogStoreResult<()> {
let mut disablement = self.begin_table_bucket_disablement(entry, None).await?;
// Namespace creation holds this same bucket lock. Retained table, view, and
// maintenance records also prevent removing their data-plane protections.
let page = self
.backend
.list_objects_page(
self.catalog_bucket(),
&self.paths.namespace_entries_prefix(&entry.table_bucket),
&self.paths.namespace_entries_prefix(&disablement.entry.table_bucket),
None,
NonZeroUsize::MIN,
)
@@ -6288,16 +6346,7 @@ where
"table bucket contains namespaces or retained catalog resources".to_string(),
));
}
entry.state = TableCatalogEntryState::Deleted;
entry.updated_at = Some(next_table_catalog_update_time(entry.updated_at.as_deref()));
self.write_entry_unlocked(
self.catalog_bucket(),
&object,
&entry,
TableCatalogPutPrecondition::Any,
_guard.write_commit_guards(),
)
.await
self.finish_table_bucket_disablement(&mut disablement).await
}
async fn create_namespace(&self, entry: NamespaceEntry) -> TableCatalogStoreResult<()> {
@@ -6681,6 +6730,7 @@ where
));
}
let _publication_completion = TableCommitPublicationCompletion::new(&publication);
let mutation_fence = publication.object_mutation_fence().unwrap_or_default();
self.recover_active_table_rename(table_bucket, &publication).await?;
{
@@ -6820,12 +6870,13 @@ where
));
}
None => {
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&index_object,
&source_index,
TableCatalogPutPrecondition::IfAbsent,
_index_guard.write_commit_guards(),
Some(&mutation_fence),
)
.await?
}
@@ -6846,22 +6897,24 @@ where
validate_table_rename_intent_object(&self.paths, &intent_object, &intent)?;
// An orphan intent has no catalog effect; a published bucket fence without its intent cannot be recovered safely.
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&intent_object,
&intent,
TableCatalogPutPrecondition::IfAbsent,
_intent_guard.write_commit_guards(),
Some(&mutation_fence),
)
.await?;
bucket_entry.active_rename_id = Some(rename_id);
bucket_entry.updated_at = Some(now);
self.write_exact_entry_unlocked(
self.write_exact_entry_unlocked_with_fence(
self.catalog_bucket(),
&bucket_object,
&bucket_entry,
TableCatalogPutPrecondition::IfMatch(bucket_etag),
_bucket_guard.write_commit_guards(),
Some(&mutation_fence),
)
.await?;
}
@@ -7311,13 +7364,15 @@ where
}
let cas_started = Instant::now();
let mutation_fence = publication.object_mutation_fence().unwrap_or_default();
let cas_result = self
.write_entry_unlocked(
.write_entry_unlocked_with_fence(
self.catalog_bucket(),
&table_path,
&next,
TableCatalogPutPrecondition::IfMatch(current_etag),
_guard.write_commit_guards(),
Some(&mutation_fence),
)
.await;
record_table_commit_cas_result(&request.operation, cas_started, &cas_result);
@@ -7388,6 +7443,7 @@ where
table.as_str()
)));
};
let mutation_fence = publication.object_mutation_fence().unwrap_or_default();
self.tombstone_table_warehouse_index_for_drop(&entry, false).await?;
if !publication.holds_table_bucket(table_bucket)
|| !publication.holds_table(table_bucket, &namespace.public_name(), table.as_str())
@@ -7398,7 +7454,11 @@ where
"table drop publication fence was lost before catalog update".to_string(),
));
}
if let Err(err) = self.backend.delete_object_unlocked(self.catalog_bucket(), &object).await {
if let Err(err) = self
.backend
.delete_object_unlocked_fenced(self.catalog_bucket(), &object, _guard.write_commit_guards(), &mutation_fence)
.await
{
match self.read_table_with_etag_unlocked(table_bucket, &namespace, &table).await {
Ok(None) => return Ok(()),
Ok(Some((current, _))) if current == entry => {
@@ -0,0 +1,298 @@
// 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.
use super::object::{
TABLE_REGISTRATION_READ_CONCURRENCY, table_warehouse_index_state_ready, validate_table_entry_object,
validate_table_warehouse_index_entry_object,
};
use super::*;
use futures::{StreamExt, TryStreamExt, stream};
use std::sync::OnceLock;
const REGISTRATION_CACHE_BYTES: u64 = 16 * 1024 * 1024;
#[derive(Clone)]
struct CachedOwner {
etag: String,
owner: Arc<TableWarehouseIndexEntry>,
}
/// Runtime-local object projections. Every lookup requires a fresh committed inventory.
#[derive(Clone)]
pub(crate) struct TableCatalogRegistrationCache {
entries: Arc<OnceLock<moka::sync::Cache<String, CachedOwner>>>,
capacity_bytes: u64,
}
impl Default for TableCatalogRegistrationCache {
fn default() -> Self {
Self::with_capacity(REGISTRATION_CACHE_BYTES)
}
}
impl TableCatalogRegistrationCache {
fn with_capacity(bytes: u64) -> Self {
Self {
entries: Arc::new(OnceLock::new()),
capacity_bytes: bytes,
}
}
fn entries(&self) -> &moka::sync::Cache<String, CachedOwner> {
self.entries.get_or_init(|| {
moka::sync::Cache::builder()
.max_capacity(self.capacity_bytes)
.weigher(|key: &String, value: &CachedOwner| {
let owner = &value.owner;
let bytes = [
key.len(),
value.etag.len(),
owner.table_bucket.len(),
owner.namespace.len(),
owner.table.len(),
owner.table_id.len(),
owner.warehouse_object_prefix.len(),
]
.into_iter()
.fold(256_usize, usize::saturating_add);
u32::try_from(bytes).unwrap_or(u32::MAX)
})
.build()
})
}
fn get(&self, object: &TableCatalogCleanupObject) -> Option<Arc<TableWarehouseIndexEntry>> {
let etag = object.etag.as_deref().filter(|etag| !etag.is_empty())?;
self.entries
.get()?
.get(&object.key)
.filter(|cached| cached.etag == etag)
.map(|cached| cached.owner)
}
fn insert(&self, object: String, etag: Option<String>, owner: Arc<TableWarehouseIndexEntry>) {
if let Some(etag) = etag.filter(|etag| !etag.is_empty()) {
self.entries().insert(object, CachedOwner { etag, owner });
}
}
#[cfg(test)]
pub(in crate::table_catalog) fn clear(&self) {
if let Some(entries) = self.entries.get() {
entries.invalidate_all();
entries.run_pending_tasks();
}
}
}
fn validate_inventory(objects: &mut [TableCatalogCleanupObject], prefix: &str) -> TableCatalogStoreResult<()> {
objects.sort_unstable_by(|left, right| left.key.cmp(&right.key));
if objects.iter().any(|object| {
!object.key.starts_with(prefix)
|| object.delete_marker
|| object
.version_id
.as_deref()
.is_some_and(|version| !version.is_empty() && version != "null")
}) || objects.windows(2).any(|pair| pair[0].key == pair[1].key)
{
return Err(TableCatalogStoreError::Invalid(
"registration requires an unversioned, complete catalog inventory".to_string(),
));
}
Ok(())
}
impl<B: TableCatalogObjectBackend> ObjectTableCatalogStore<B> {
async fn registration_owner(
&self,
object: TableCatalogCleanupObject,
table_record: bool,
locked_table_entry: &str,
cache: Option<&TableCatalogRegistrationCache>,
) -> TableCatalogStoreResult<Arc<TableWarehouseIndexEntry>> {
if let Some(owner) = cache.and_then(|cache| cache.get(&object)) {
return Ok(owner);
}
let (owner, etag) = if table_record {
let value = if object.key == locked_table_entry {
self.read_entry_unlocked::<TableEntry>(self.catalog_bucket(), &object.key)
.await?
} else {
self.read_entry::<TableEntry>(self.catalog_bucket(), &object.key).await?
};
let (entry, etag) = value.ok_or_else(|| {
TableCatalogStoreError::Unavailable("table record changed during registration inventory".to_string())
})?;
validate_table_entry_object(&self.paths, &object.key, &entry)?;
(table_warehouse_index_entry(&entry)?, etag)
} else {
let (entry, etag) = self
.read_entry::<TableWarehouseIndexEntry>(self.catalog_bucket(), &object.key)
.await?
.ok_or_else(|| {
TableCatalogStoreError::Unavailable("warehouse index changed during registration inventory".to_string())
})?;
validate_table_warehouse_index_entry_object(&self.paths, &object.key, &entry)?;
(entry, etag)
};
let owner = Arc::new(owner);
if let Some(cache) = cache {
// A concurrent index repair may change its ETag after enumeration.
// Associate the projection only with the object that GET validated.
cache.insert(object.key, etag, Arc::clone(&owner));
}
Ok(owner)
}
pub(super) async fn check_registration_ownership(
&self,
entry: &TableEntry,
locked_table_entry: &str,
publication: &(dyn TableCommitPublication + Sync),
) -> TableCatalogStoreResult<()> {
if !publication.holds_table_bucket(&entry.table_bucket) {
return Err(TableCatalogStoreError::Unavailable("registration publication fence was lost".to_string()));
}
validate_table_entry_version_and_id(entry)?;
let candidate = table_warehouse_index_entry(entry)?;
let namespace_prefix = self.paths.namespace_entries_prefix(&entry.table_bucket);
let index_prefix = self.paths.warehouse_index_entries_prefix(&entry.table_bucket);
// The backend must preserve system-bucket committed-read semantics as
// well as completeness; ordinary S3 LIST is insufficient for cache hits.
let mut tables = self
.backend
.list_objects_for_cleanup(self.catalog_bucket(), &namespace_prefix)
.await?;
let mut indexes = self
.backend
.list_objects_for_cleanup(self.catalog_bucket(), &index_prefix)
.await?;
validate_inventory(&mut tables, &namespace_prefix)?;
validate_inventory(&mut indexes, &index_prefix)?;
let cache = self.backend.registration_cache();
let mut owners = BTreeMap::new();
let mut table_ids = BTreeSet::new();
let mut table_reads = stream::iter(tables.into_iter().filter(|object| object.key.ends_with(TABLE_ENTRY_FILE)))
.map(|object| self.registration_owner(object, true, locked_table_entry, cache.as_ref()))
.buffered(TABLE_REGISTRATION_READ_CONCURRENCY);
while let Some(owner) = table_reads.try_next().await? {
if owner.state != TableCatalogEntryState::Active {
continue;
}
if !table_ids.insert(owner.table_id.clone())
|| (owner.table_id == candidate.table_id
&& (owner.namespace != candidate.namespace || owner.table != candidate.table))
{
return Err(TableCatalogStoreError::Conflict(
"table id is already registered in this table bucket".to_string(),
));
}
if owner.table_id != candidate.table_id
&& warehouse_object_prefixes_overlap(&owner.warehouse_object_prefix, &candidate.warehouse_object_prefix)
{
return Err(TableCatalogStoreError::Conflict(
"table warehouse location overlaps an active table".to_string(),
));
}
owners.insert((owner.namespace.clone(), owner.table.clone()), owner);
}
let mut prefixes = owners
.values()
.map(|owner| owner.warehouse_object_prefix.as_str())
.collect::<Vec<_>>();
prefixes.sort_unstable();
if prefixes
.windows(2)
.any(|pair| warehouse_object_prefixes_overlap(pair[0], pair[1]))
{
return Err(TableCatalogStoreError::Conflict("active table warehouse locations overlap".to_string()));
}
let state_path = self.paths.warehouse_index_state_path(&entry.table_bucket);
let has_state = indexes.iter().any(|object| object.key == state_path);
let mut index_reads = stream::iter(indexes.into_iter().filter(|object| object.key != state_path))
.map(|object| self.registration_owner(object, false, locked_table_entry, cache.as_ref()))
.buffered(TABLE_REGISTRATION_READ_CONCURRENCY);
while let Some(index) = index_reads.try_next().await? {
if index.table_id == candidate.table_id || index.state != TableCatalogEntryState::Active {
continue;
}
if warehouse_object_prefixes_overlap(&index.warehouse_object_prefix, &candidate.warehouse_object_prefix) {
parse_namespace_for_store(&index.namespace)?;
parse_table_for_store(&index.table)?;
if owners
.get(&(index.namespace.clone(), index.table.clone()))
.is_some_and(|owner| {
owner.table_id == index.table_id && owner.warehouse_object_prefix == index.warehouse_object_prefix
})
{
return Err(TableCatalogStoreError::Conflict(
"table warehouse location overlaps an active table".to_string(),
));
}
}
}
if has_state {
let (state, _) = self
.read_entry::<TableWarehouseIndexStateEntry>(self.catalog_bucket(), &state_path)
.await?
.ok_or_else(|| {
TableCatalogStoreError::Unavailable("warehouse index state changed during registration inventory".to_string())
})?;
table_warehouse_index_state_ready(&state, &entry.table_bucket)?;
}
if !publication.holds_table_bucket(&entry.table_bucket) {
return Err(TableCatalogStoreError::Unavailable("registration publication fence was lost".to_string()));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::super::registration_cache_tests::{cache_fixture, registration_entry};
use super::*;
#[tokio::test]
async fn registration_cache_capacity_and_oversized_owners_preserve_checks() {
let (backend, _, namespace) = cache_fixture().await;
let cache = TableCatalogRegistrationCache::with_capacity(1024);
let backend = crate::table_catalog::test_support::TestCatalogObjectBackend {
registration_cache: cache.clone(),
..backend
};
let store = ObjectTableCatalogStore::new(backend.clone());
let mut oversized = registration_entry(&namespace, "oversized");
oversized.warehouse_location = format!("s3://analytics/{}", "directory".repeat(512));
store.create_table(oversized.clone()).await.unwrap();
for number in 0..12 {
store
.create_table(registration_entry(&namespace, &format!("table_{number}")))
.await
.unwrap();
}
cache.entries().run_pending_tasks();
assert!(cache.entries().weighted_size() <= 1024);
backend.reset_call_counts().await;
let mut candidate = registration_entry(&namespace, "conflicting");
candidate.warehouse_location = format!("{}/child", oversized.warehouse_location);
assert!(matches!(store.create_table(candidate).await, Err(TableCatalogStoreError::Conflict(_))));
assert!(
backend.read_call_count().await > 0,
"eviction must cause reads instead of accepting an absent owner"
);
cache.entries().run_pending_tasks();
assert!(cache.entries().weighted_size() <= 1024);
}
}
@@ -0,0 +1,376 @@
// 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.
use super::*;
use crate::table_catalog::test_support::{RecordingLeaseClient, TestCatalogObjectBackend};
use crate::table_catalog::tests::{test_bucket_entry, test_namespace_entry, test_table_entry};
use rustfs_lock::LockClient;
use std::sync::{Arc, Mutex};
use std::time::Duration;
pub(super) fn registration_entry(namespace: &Namespace, name: &str) -> TableEntry {
let table = IdentifierSegment::parse(name).expect("valid test table name");
let mut entry = test_table_entry(
"analytics",
namespace,
&table,
default_table_metadata_file_path(namespace, &table, "00001.metadata.json"),
);
entry.table_id = format!("id-{name}");
entry.warehouse_location = format!("s3://analytics/tables/id-{name}");
entry
}
pub(super) async fn cache_fixture() -> (TestCatalogObjectBackend, ObjectTableCatalogStore<TestCatalogObjectBackend>, Namespace) {
let backend = TestCatalogObjectBackend::default();
let store = ObjectTableCatalogStore::new(backend.clone());
let namespace = Namespace::parse("sales").unwrap();
store.put_table_bucket(test_bucket_entry("analytics")).await.unwrap();
store
.create_namespace(test_namespace_entry("analytics", &namespace))
.await
.unwrap();
store.create_table(registration_entry(&namespace, "orders")).await.unwrap();
store.create_table(registration_entry(&namespace, "warmup")).await.unwrap();
(backend, store, namespace)
}
#[tokio::test]
async fn registration_cache_binds_projection_to_the_get_etag() {
let (backend, store, namespace) = cache_fixture().await;
backend.registration_cache.clear();
let path = store
.paths
.table_entry_path("analytics", &namespace, &IdentifierSegment::parse("orders").unwrap());
let key = (RUSTFS_META_BUCKET.to_string(), path.clone());
let original = backend.state.lock().await.objects.get(&key).unwrap().clone();
let pause = backend.pause_before_next_read(RUSTFS_META_BUCKET, &path).await;
let task_store = store.clone();
let entry = registration_entry(&namespace, "unrelated");
let task = tokio::spawn(async move { task_store.create_table(entry).await });
tokio::time::timeout(Duration::from_secs(5), pause.wait_started())
.await
.unwrap();
let mut changed = registration_entry(&namespace, "orders");
changed.warehouse_location = "s3://analytics/changed".to_string();
backend
.seed_object(RUSTFS_META_BUCKET, &path, serde_json::to_vec(&changed).unwrap())
.await;
pause.release();
tokio::time::timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap()
.unwrap();
backend.state.lock().await.objects.insert(key, original);
let mut candidate = registration_entry(&namespace, "candidate");
candidate.warehouse_location = "s3://analytics/changed/child".to_string();
store
.create_table(candidate)
.await
.expect("a GET projection cannot inherit an earlier inventory ETag");
}
#[tokio::test]
async fn registration_cache_observes_changed_and_removed_objects() {
let (backend, store, namespace) = cache_fixture().await;
let path = store
.paths
.table_entry_path("analytics", &namespace, &IdentifierSegment::parse("orders").unwrap());
let mut changed = registration_entry(&namespace, "orders");
changed.warehouse_location = "s3://analytics/relocated".to_string();
backend
.seed_object(RUSTFS_META_BUCKET, &path, serde_json::to_vec(&changed).unwrap())
.await;
let mut candidate = registration_entry(&namespace, "candidate");
candidate.warehouse_location = "s3://analytics/relocated/child".to_string();
assert!(matches!(
store.create_table(candidate.clone()).await,
Err(TableCatalogStoreError::Conflict(_))
));
backend.delete_object(RUSTFS_META_BUCKET, &path).await.unwrap();
candidate.table_id = changed.table_id;
store
.create_table(candidate)
.await
.expect("removed records cannot remain active through the cache");
}
#[tokio::test]
async fn registration_cache_revalidates_missing_etags_and_corrupt_changed_indexes() {
let (backend, store, namespace) = cache_fixture().await;
let path = store
.paths
.table_entry_path("analytics", &namespace, &IdentifierSegment::parse("orders").unwrap());
backend
.state
.lock()
.await
.etagless_objects
.insert((RUSTFS_META_BUCKET.to_string(), path.clone()));
backend.fail_next_read(RUSTFS_META_BUCKET, &path).await;
assert!(store.create_table(registration_entry(&namespace, "candidate")).await.is_err());
backend.state.lock().await.etagless_objects.clear();
let index = store.paths.warehouse_index_entry_path("analytics", "tables/id-orders/");
backend
.seed_object(RUSTFS_META_BUCKET, &index, b"invalid json".to_vec())
.await;
assert!(store.create_table(registration_entry(&namespace, "candidate")).await.is_err());
assert!(store.load_table("analytics", "sales", "candidate").await.unwrap().is_none());
}
#[tokio::test]
async fn registration_cache_rejects_incomplete_and_versioned_inventories() {
let (backend, store, namespace) = cache_fixture().await;
let namespace_prefix = store.paths.namespace_entries_prefix("analytics");
let index_prefix = store.paths.warehouse_index_entries_prefix("analytics");
for prefix in [&namespace_prefix, &index_prefix] {
backend.state.lock().await.failed_inventory_prefixes.insert(prefix.clone());
assert!(store.create_table(registration_entry(&namespace, "candidate")).await.is_err());
backend.state.lock().await.failed_inventory_prefixes.clear();
}
for (version_id, delete_marker) in [(Some(Uuid::new_v4().to_string()), false), (None, true)] {
backend.state.lock().await.inventory_overrides.insert(
namespace_prefix.clone(),
vec![TableCatalogCleanupObject {
key: format!("{namespace_prefix}unexpected"),
version_id,
etag: Some("etag".to_string()),
delete_marker,
}],
);
assert!(store.create_table(registration_entry(&namespace, "candidate")).await.is_err());
}
backend.state.lock().await.inventory_overrides.clear();
assert!(store.load_table("analytics", "sales", "candidate").await.unwrap().is_none());
let mut duplicate = registration_entry(&namespace, "candidate");
duplicate.table_id = "id-orders".to_string();
assert!(matches!(store.create_table(duplicate).await, Err(TableCatalogStoreError::Conflict(_))));
}
#[tokio::test]
async fn registration_cache_cancellation_does_not_publish_a_partial_catalog() {
let (backend, store, namespace) = cache_fixture().await;
backend.registration_cache.clear();
let path = store
.paths
.table_entry_path("analytics", &namespace, &IdentifierSegment::parse("warmup").unwrap());
let pause = backend.pause_before_next_read(RUSTFS_META_BUCKET, &path).await;
let task_store = store.clone();
let candidate = registration_entry(&namespace, "cancelled");
let task = tokio::spawn(async move { task_store.create_table(candidate).await });
tokio::time::timeout(Duration::from_secs(5), pause.wait_started())
.await
.unwrap();
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
pause.release();
assert!(store.load_table("analytics", "sales", "cancelled").await.unwrap().is_none());
let mut changed = registration_entry(&namespace, "warmup");
changed.warehouse_location = "s3://analytics/changed".to_string();
backend
.seed_object(RUSTFS_META_BUCKET, &path, serde_json::to_vec(&changed).unwrap())
.await;
let mut candidate = registration_entry(&namespace, "after_cancel");
candidate.warehouse_location = "s3://analytics/changed/child".to_string();
assert!(matches!(store.create_table(candidate).await, Err(TableCatalogStoreError::Conflict(_))));
}
#[tokio::test]
async fn registration_cache_isolated_runtimes_do_not_share_matching_etags() {
let (first, first_store, namespace) = cache_fixture().await;
let (second, second_store, _) = cache_fixture().await;
let path = first_store
.paths
.table_entry_path("analytics", &namespace, &IdentifierSegment::parse("orders").unwrap());
let mut changed = registration_entry(&namespace, "orders");
changed.warehouse_location = "s3://analytics/second-only".to_string();
let first_etag = first
.state
.lock()
.await
.objects
.get(&(RUSTFS_META_BUCKET.to_string(), path.clone()))
.unwrap()
.etag
.clone();
second.registration_cache.clear();
{
let mut state = second.state.lock().await;
let object = state.objects.get_mut(&(RUSTFS_META_BUCKET.to_string(), path)).unwrap();
object.data = serde_json::to_vec(&changed).unwrap();
object.etag = first_etag;
}
let mut candidate = registration_entry(&namespace, "candidate");
candidate.warehouse_location = "s3://analytics/second-only/child".to_string();
assert!(matches!(
second_store.create_table(candidate.clone()).await,
Err(TableCatalogStoreError::Conflict(_))
));
first_store
.create_table(candidate)
.await
.expect("the first runtime has no such owner");
}
#[tokio::test]
async fn registration_cache_preserves_identity_after_lost_response_and_failed_rollback() {
for lost_response in [false, true] {
let (backend, store, namespace) = cache_fixture().await;
let entry = registration_entry(&namespace, "ambiguous");
let path = store
.paths
.table_entry_path("analytics", &namespace, &IdentifierSegment::parse(&entry.table).unwrap());
let index = store.paths.warehouse_index_entry_path("analytics", "tables/id-ambiguous/");
if lost_response {
backend.fail_after_next_put(RUSTFS_META_BUCKET, &path).await;
} else {
backend.fail_next_put(RUSTFS_META_BUCKET, &path).await;
}
backend.fail_delete_attempt(RUSTFS_META_BUCKET, &index, 1).await;
assert!(store.create_table(entry.clone()).await.is_err());
let mut candidate = registration_entry(&namespace, "candidate");
candidate.table_id = entry.table_id;
let result = store.create_table(candidate).await;
if lost_response {
assert!(matches!(result, Err(TableCatalogStoreError::Conflict(_))));
} else {
result.expect("failed primary writes cannot reserve identity through cached results");
}
}
}
async fn leased_registration_publication<'a>(
backend: &'a TestCatalogObjectBackend,
lock: &rustfs_lock::NamespaceLock,
owner: &str,
) -> (
TableCommitLockPublication<'a, TestCatalogObjectBackend>,
Arc<rustfs_lock::distributed_lock::LockLostSignal>,
) {
let guard = lock
.lock_guard(
rustfs_lock::ObjectKey::new("analytics", default_table_bucket_publication_lock_path()),
owner,
Duration::from_secs(5),
Duration::from_secs(3),
)
.await
.expect("publication lease acquisition succeeds")
.expect("publication lease is acquired");
let signal = guard.lock_lost_signal().expect("distributed publication has a loss signal");
let publication = TableCommitLockPublication::new(backend);
{
let mut state = publication.state.lock();
state.table_bucket = Some("analytics".to_string());
state.guards.push(TableCatalogLockGuard::namespace(guard));
}
(publication, signal)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn registration_cache_rejects_delayed_table_write_after_publication_lease_loss() {
let backend = TestCatalogObjectBackend {
reject_reads_while_write_locked: true,
..Default::default()
};
let store = ObjectTableCatalogStore::new(backend.clone());
let stalled_namespace = Namespace::parse("stalled").unwrap();
let active_namespace = Namespace::parse("active").unwrap();
store.put_table_bucket(test_bucket_entry("analytics")).await.unwrap();
for namespace in [&stalled_namespace, &active_namespace] {
store
.create_namespace(test_namespace_entry("analytics", namespace))
.await
.unwrap();
}
let initial = registration_entry(&active_namespace, "initial");
store.create_table(initial.clone()).await.unwrap();
let client = Arc::new(RecordingLeaseClient {
inner: rustfs_lock::LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::Enabled(Arc::new(
rustfs_lock::FastObjectLockManager::new(),
)))),
acquired: Mutex::new(None),
});
let lock = rustfs_lock::NamespaceLock::with_clients_and_quorum(
"registration-publication-loss".to_string(),
vec![client.clone() as Arc<dyn LockClient>],
1,
);
let (old_publication, old_signal) = leased_registration_publication(&backend, &lock, "old-writer").await;
let old_lease = client.acquired.lock().unwrap().clone().unwrap();
let delayed = registration_entry(&stalled_namespace, "delayed");
let delayed_path =
store
.paths
.table_entry_path("analytics", &stalled_namespace, &IdentifierSegment::parse(&delayed.table).unwrap());
let pause = backend.pause_put_attempt(RUSTFS_META_BUCKET, &delayed_path, 1).await;
let replacement = registration_entry(&active_namespace, "replacement");
let delayed_write = store.register_table_with_publication(delayed.clone(), &old_publication);
let takeover = async {
tokio::time::timeout(Duration::from_secs(5), pause.wait_started())
.await
.expect("old writer reaches the table-entry commit");
assert!(client.force_release(&old_lease).await.unwrap());
tokio::time::timeout(Duration::from_secs(10), old_signal.notified())
.await
.expect("heartbeat observes publication lease loss");
assert!(!old_publication.holds_table_bucket("analytics"));
let (new_publication, _) = leased_registration_publication(&backend, &lock, "new-writer").await;
backend.reset_call_counts().await;
tokio::time::timeout(
Duration::from_secs(5),
store.register_table_with_publication(replacement.clone(), &new_publication),
)
.await
.expect("replacement writer completes while the old put is paused")
.expect("replacement writer publishes its table after a fresh inventory");
assert!(backend.list_call_count().await > 0, "takeover inventories the catalog");
pause.release();
};
let (delayed_result, ()) = tokio::time::timeout(Duration::from_secs(25), async { tokio::join!(delayed_write, takeover) })
.await
.expect("both writers finish after the paused put is resumed");
assert!(
matches!(delayed_result, Err(TableCatalogStoreError::Unavailable(_))),
"the delayed storage commit must reject the lost publication fence: {delayed_result:?}"
);
assert_eq!(backend.put_attempt_count(RUSTFS_META_BUCKET, &delayed_path).await, 1);
assert!(
backend
.read_object(RUSTFS_META_BUCKET, &delayed_path)
.await
.unwrap()
.is_none()
);
for entry in [&initial, &replacement] {
assert_eq!(
store.load_table("analytics", &entry.namespace, &entry.table).await.unwrap(),
Some(entry.clone())
);
}
let subsequent = registration_entry(&active_namespace, "subsequent");
store.create_table(subsequent.clone()).await.unwrap();
for entry in [&initial, &replacement, &subsequent] {
let mut duplicate = registration_entry(&active_namespace, "duplicate");
duplicate.table_id = entry.table_id.clone();
assert!(matches!(store.create_table(duplicate).await, Err(TableCatalogStoreError::Conflict(_))));
}
store
.create_table(delayed)
.await
.expect("the rejected writer left no active table");
}
+53
View File
@@ -411,6 +411,7 @@ pub(crate) struct TestCatalogObjectBackend {
pub(crate) state: Arc<tokio::sync::Mutex<TestCatalogObjectState>>,
pub(crate) locks: TestCatalogObjectLocks,
pub(crate) strong_runtime: Option<StrongTableCatalogRuntime>,
pub(crate) registration_cache: TableCatalogRegistrationCache,
// One-shot, path-keyed injection knobs from the admin handler tests'
// former TestTableCatalogObjectBackend (backlog#1837 PR2): each fires
// once for the named object and clears itself, mirroring the original
@@ -543,8 +544,11 @@ pub(crate) struct TestCatalogObjectState {
pub(crate) write_lock_acquisitions: BTreeMap<(String, String), usize>,
pub(crate) read_lock_acquisitions: BTreeMap<(String, String), usize>,
pub(crate) read_calls: usize,
pub(crate) read_bytes: usize,
pub(crate) metadata_calls: usize,
pub(crate) list_calls: usize,
pub(crate) failed_inventory_prefixes: BTreeSet<String>,
pub(crate) inventory_overrides: BTreeMap<String, Vec<TableCatalogCleanupObject>>,
pub(crate) next_etag: u64,
}
@@ -608,6 +612,7 @@ impl TestCatalogObjectBackend {
pub(crate) async fn reset_call_counts(&self) {
let mut state = self.state.lock().await;
state.read_calls = 0;
state.read_bytes = 0;
state.metadata_calls = 0;
state.list_calls = 0;
}
@@ -955,6 +960,10 @@ impl TestCatalogObjectState {
#[async_trait::async_trait]
impl TableCatalogObjectBackend for TestCatalogObjectBackend {
fn registration_cache(&self) -> Option<TableCatalogRegistrationCache> {
Some(self.registration_cache.clone())
}
fn strong_catalog_runtime(&self) -> Option<StrongTableCatalogRuntime> {
self.strong_runtime.clone()
}
@@ -1018,6 +1027,7 @@ impl TableCatalogObjectBackend for TestCatalogObjectBackend {
etag: (!etagless).then(|| record.etag.clone()),
mod_time: record.mod_time,
});
state.read_bytes += result.as_ref().map_or(0, |object| object.data.len());
let pause = state
.pause_read_attempts
.get_mut(&key)
@@ -1142,6 +1152,17 @@ impl TableCatalogObjectBackend for TestCatalogObjectBackend {
.await
}
async fn delete_object_if_match_fenced_for_incarnation(
&self,
bucket: &str,
object: &str,
expected_etag: &str,
_expected_incarnation_id: Uuid,
fence: &TableCatalogObjectMutationFence,
) -> TableCatalogStoreResult<()> {
self.delete_object_if_match_fenced(bucket, object, expected_etag, fence).await
}
async fn list_objects(&self, bucket: &str, prefix: &str) -> TableCatalogStoreResult<Vec<String>> {
let mut state = self.state.lock().await;
state.list_calls += 1;
@@ -1153,6 +1174,38 @@ impl TableCatalogObjectBackend for TestCatalogObjectBackend {
.collect())
}
async fn list_objects_for_cleanup(
&self,
bucket: &str,
prefix: &str,
) -> TableCatalogStoreResult<Vec<TableCatalogCleanupObject>> {
let mut state = self.state.lock().await;
state.list_calls += 1;
if state.failed_inventory_prefixes.contains(prefix) {
return Err(TableCatalogStoreError::Unavailable(
"injected authoritative inventory failure".to_string(),
));
}
if let Some(objects) = state.inventory_overrides.get(prefix) {
return Ok(objects.clone());
}
Ok(state
.objects
.iter()
.filter(|((entry_bucket, object), _)| entry_bucket == bucket && object.starts_with(prefix))
.map(|(key, record)| TableCatalogCleanupObject {
key: key.1.clone(),
version_id: None,
etag: (!state.etagless_objects.contains(key)).then(|| record.etag.clone()),
delete_marker: false,
})
.collect())
}
async fn ensure_no_multipart_uploads(&self, _bucket: &str) -> TableCatalogStoreResult<()> {
Ok(())
}
async fn acquire_write_lock(&self, bucket: &str, object: &str) -> TableCatalogStoreResult<TableCatalogLockGuard> {
self.lock_attempts.lock().await.push((bucket.to_string(), object.to_string()));
{
+432 -3
View File
@@ -7145,6 +7145,228 @@ async fn table_data_plane_resource_does_not_match_sibling_prefix() {
assert_eq!(backend.list_call_count().await, 1);
}
async fn cached_registration_fixture() -> (TestCatalogObjectBackend, ObjectTableCatalogStore<TestCatalogObjectBackend>, Namespace)
{
let backend = TestCatalogObjectBackend {
reject_reads_while_write_locked: true,
..Default::default()
};
let store = ObjectTableCatalogStore::new(backend.clone());
let namespace = Namespace::parse("sales").expect("test namespace is valid");
store
.put_table_bucket(test_bucket_entry("analytics"))
.await
.expect("bucket is created");
store
.create_namespace(test_namespace_entry("analytics", &namespace))
.await
.expect("namespace is created");
(backend, store, namespace)
}
fn cached_registration_entry(namespace: &Namespace, name: &str) -> TableEntry {
let table = IdentifierSegment::parse(name).expect("test table name is valid");
let mut entry = test_table_entry(
"analytics",
namespace,
&table,
default_table_metadata_file_path(namespace, &table, "00001.metadata.json"),
);
entry.table_id = format!("id-{name}");
entry.warehouse_location = format!("s3://analytics/tables/id-{name}");
entry
}
#[tokio::test]
async fn object_catalog_registration_cache_bounds_reads_across_store_instances() {
let (backend, _, namespace) = cached_registration_fixture().await;
for number in 0..256 {
let store = ObjectTableCatalogStore::new(backend.clone());
backend.reset_call_counts().await;
store
.create_table(cached_registration_entry(&namespace, &format!("table_{number:04}")))
.await
.expect("each new store instance shares validated registration projections");
if number >= 32 {
let state = backend.state.lock().await;
assert_eq!(state.list_calls, 2, "each registration inventories both catalog ranges");
assert!(
state.read_calls < 24,
"registration used {} object reads at table {number}",
state.read_calls
);
assert!(
state.read_bytes < 256 * 1024,
"registration read {} bytes at table {number}",
state.read_bytes
);
}
}
}
#[tokio::test]
async fn object_catalog_registration_cache_preserves_identity_and_overlap_checks() {
let (backend, store, namespace) = cached_registration_fixture().await;
let mut existing = cached_registration_entry(&namespace, "orders");
existing.warehouse_location = "s3://analytics/shared/orders".to_string();
store.create_table(existing.clone()).await.expect("initial table is created");
backend
.delete_object(RUSTFS_META_BUCKET, &store.paths.warehouse_index_entry_path("analytics", "shared/orders/"))
.await
.expect("simulate a missing materialized warehouse index");
let mut duplicate = cached_registration_entry(&namespace, "duplicate");
duplicate.table_id = existing.table_id.clone();
assert_matches!(store.create_table(duplicate).await, Err(TableCatalogStoreError::Conflict(_)));
for location in [
"s3://analytics/shared",
"s3://analytics/shared/orders",
"s3://analytics/shared/orders/child",
] {
let mut conflicting = cached_registration_entry(&namespace, "conflicting");
conflicting.warehouse_location = location.to_string();
assert_matches!(store.create_table(conflicting).await, Err(TableCatalogStoreError::Conflict(_)));
}
let mut adjacent = cached_registration_entry(&namespace, "adjacent");
adjacent.warehouse_location = "s3://analytics/shared/orders2".to_string();
store
.create_table(adjacent)
.await
.expect("a different directory remains available");
}
#[tokio::test]
async fn object_catalog_registration_cache_rechecks_after_failed_write_and_drop() {
let (backend, store, namespace) = cached_registration_fixture().await;
store
.create_table(cached_registration_entry(&namespace, "orders"))
.await
.expect("initial table is created");
let returns = IdentifierSegment::parse("returns").expect("test name is valid");
let table_path = store.paths.table_entry_path("analytics", &namespace, &returns);
backend.fail_next_put(RUSTFS_META_BUCKET, &table_path).await;
assert!(
store
.create_table(cached_registration_entry(&namespace, "returns"))
.await
.is_err()
);
assert!(
store
.load_table("analytics", "sales", "returns")
.await
.expect("table lookup succeeds")
.is_none()
);
store
.create_table(cached_registration_entry(&namespace, "returns"))
.await
.expect("retry reads the authoritative records");
store
.drop_table("analytics", "sales", "orders")
.await
.expect("drop removes the active owner");
let mut replacement = cached_registration_entry(&namespace, "replacement");
replacement.table_id = "id-orders".to_string();
replacement.warehouse_location = "s3://analytics/tables/id-orders".to_string();
store
.create_table(replacement)
.await
.expect("a dropped owner no longer reserves its identity");
}
#[tokio::test]
async fn object_catalog_registration_cache_observes_pointer_commits_and_rename() {
let (backend, store, namespace) = cached_registration_fixture().await;
let entry = cached_registration_entry(&namespace, "orders");
store.create_table(entry.clone()).await.expect("initial table is created");
let metadata_directory = entry
.metadata_location
.rsplit_once('/')
.expect("metadata has a parent directory")
.0;
let next_metadata = format!("{metadata_directory}/00002.metadata.json");
backend
.seed_object(
"analytics",
&next_metadata,
serde_json::to_vec(&serde_json::json!({"location": entry.warehouse_location})).unwrap(),
)
.await;
store
.commit_table(TableCommitRequest {
table_bucket: "analytics".to_string(),
namespace: "sales".to_string(),
table: "orders".to_string(),
commit_id: "pointer-only".to_string(),
idempotency_key: None,
operation: "append".to_string(),
expected_version_token: entry.version_token,
expected_metadata_location: entry.metadata_location,
new_metadata_location: next_metadata,
requirements: Vec::new(),
writer: None,
})
.await
.expect("metadata pointer commit succeeds");
backend.reset_call_counts().await;
store
.create_table(cached_registration_entry(&namespace, "returns"))
.await
.unwrap();
assert_eq!(
backend.list_call_count().await,
2,
"pointer changes are checked through fresh inventories"
);
store
.rename_table("analytics", "sales", "orders", "sales", "renamed")
.await
.unwrap();
backend.reset_call_counts().await;
store
.create_table(cached_registration_entry(&namespace, "shipments"))
.await
.unwrap();
assert!(
backend.list_call_count().await > 0,
"rename is visible in the next authoritative inventory"
);
let mut duplicate = cached_registration_entry(&namespace, "duplicate");
duplicate.table_id = "id-orders".to_string();
assert_matches!(store.create_table(duplicate).await, Err(TableCatalogStoreError::Conflict(_)));
}
#[tokio::test]
async fn object_catalog_registration_cache_observes_an_independent_writer() {
let (backend, store, namespace) = cached_registration_fixture().await;
store
.create_table(cached_registration_entry(&namespace, "orders"))
.await
.unwrap();
let scan_store = ObjectTableCatalogStore::new(TestCatalogObjectBackend {
registration_cache: TableCatalogRegistrationCache::default(),
..backend.clone()
});
scan_store
.create_table(cached_registration_entry(&namespace, "returns"))
.await
.unwrap();
backend.reset_call_counts().await;
store
.create_table(cached_registration_entry(&namespace, "shipments"))
.await
.unwrap();
assert!(
backend.list_call_count().await > 0,
"an independent writer is visible in the next authoritative inventory"
);
let mut duplicate = cached_registration_entry(&namespace, "duplicate");
duplicate.table_id = "id-returns".to_string();
assert_matches!(store.create_table(duplicate).await, Err(TableCatalogStoreError::Conflict(_)));
}
#[tokio::test]
async fn object_catalog_registration_scans_warehouse_prefixes_once() {
let backend = TestCatalogObjectBackend::default();
@@ -7173,10 +7395,217 @@ async fn object_catalog_registration_scans_warehouse_prefixes_once() {
reads.push(backend.read_call_count().await);
assert_eq!(backend.list_call_count().await, 2, "one table scan and one warehouse index scan");
}
assert_eq!(reads[2] - reads[1], 2, "each existing table and its index should be read once");
assert_eq!(reads[2], reads[1], "unchanged validated objects should not require another GET");
assert_eq!(store.list_tables(bucket, &namespace.public_name()).await.unwrap().len(), 3);
}
#[tokio::test]
async fn object_catalog_registration_bounds_concurrent_catalog_reads() {
const MAX_CONCURRENT_READS: usize = 8;
let backend = TestCatalogObjectBackend {
reject_reads_while_write_locked: true,
..Default::default()
};
let store = ObjectTableCatalogStore::new(backend.clone());
let bucket = "analytics";
let namespace = Namespace::parse("sales").unwrap();
store.put_table_bucket(test_bucket_entry(bucket)).await.unwrap();
store
.create_namespace(test_namespace_entry(bucket, &namespace))
.await
.unwrap();
let mut table_objects = Vec::new();
let mut index_objects = Vec::new();
for number in 0..MAX_CONCURRENT_READS + 2 {
let name = format!("orders_{number:02}");
let table = IdentifierSegment::parse(&name).unwrap();
let mut entry = test_table_entry(
bucket,
&namespace,
&table,
default_table_metadata_file_path(&namespace, &table, "00001.metadata.json"),
);
entry.table_id = format!("table-{name}");
entry.warehouse_location = format!("s3://{bucket}/tables/{name}");
store.create_table(entry).await.unwrap();
table_objects.push(store.paths.table_entry_path(bucket, &namespace, &table));
index_objects.push(store.paths.warehouse_index_entry_path(bucket, &format!("tables/{name}/")));
}
backend.registration_cache.clear();
let mut scans = Vec::new();
for mut objects in [table_objects, index_objects] {
objects.sort();
let mut scan = Vec::new();
for object in objects {
let previous_reads = backend
.state
.lock()
.await
.read_attempts
.get(&(RUSTFS_META_BUCKET.to_string(), object.clone()))
.copied()
.unwrap_or_default();
let pause = backend.pause_before_next_read(RUSTFS_META_BUCKET, &object).await;
scan.push((object, pause, previous_reads));
}
scans.push(scan);
}
let table = IdentifierSegment::parse("new_orders").unwrap();
let mut entry = test_table_entry(
bucket,
&namespace,
&table,
default_table_metadata_file_path(&namespace, &table, "00001.metadata.json"),
);
entry.table_id = "new-table-id".to_string();
entry.warehouse_location = format!("s3://{bucket}/tables/new_orders");
let registering_store = store.clone();
let registration = tokio::spawn(async move { registering_store.create_table(entry).await });
for scan in scans {
for (_, pause, _) in scan.iter().take(MAX_CONCURRENT_READS) {
tokio::time::timeout(TABLE_CATALOG_TEST_TIMEOUT, pause.wait_started())
.await
.expect("independent catalog reads should start concurrently");
}
let state = backend.state.lock().await;
let started = scan
.iter()
.filter(|(object, _, previous_reads)| {
state
.read_attempts
.get(&(RUSTFS_META_BUCKET.to_string(), object.clone()))
.copied()
.unwrap_or_default()
> *previous_reads
})
.count();
assert_eq!(started, MAX_CONCURRENT_READS, "catalog reads must respect the concurrency limit");
drop(state);
for (_, pause, _) in scan {
pause.release();
}
}
tokio::time::timeout(TABLE_CATALOG_TEST_TIMEOUT, registration)
.await
.expect("registration should finish after its reads are released")
.unwrap()
.unwrap();
assert!(
store
.load_table(bucket, &namespace.public_name(), table.as_str())
.await
.unwrap()
.is_some()
);
}
#[tokio::test]
async fn object_catalog_registration_propagates_catalog_scan_read_errors() {
for fail_index_read in [false, true] {
let backend = TestCatalogObjectBackend::default();
let store = ObjectTableCatalogStore::new(backend.clone());
let bucket = "analytics";
let namespace = Namespace::parse("sales").unwrap();
let existing = IdentifierSegment::parse("orders").unwrap();
seed_table_for_metadata_maintenance(
&store,
bucket,
&namespace,
&existing,
default_table_metadata_file_path(&namespace, &existing, "00001.metadata.json"),
)
.await;
let failed_object = if fail_index_read {
store.paths.warehouse_index_entry_path(bucket, "tables/table-id/")
} else {
store.paths.table_entry_path(bucket, &namespace, &existing)
};
backend.fail_next_read(RUSTFS_META_BUCKET, &failed_object).await;
let table = IdentifierSegment::parse("returns").unwrap();
let mut entry = test_table_entry(
bucket,
&namespace,
&table,
default_table_metadata_file_path(&namespace, &table, "00001.metadata.json"),
);
entry.table_id = "new-table-id".to_string();
entry.warehouse_location = format!("s3://{bucket}/tables/new-table-id");
assert_matches!(
store.create_table(entry.clone()).await,
Err(TableCatalogStoreError::Internal(message)) if message.contains(&failed_object)
);
assert!(
store
.load_table(bucket, &namespace.public_name(), table.as_str())
.await
.unwrap()
.is_none()
);
assert!(
backend
.read_object(
RUSTFS_META_BUCKET,
&store.paths.warehouse_index_entry_path(bucket, "tables/new-table-id/")
)
.await
.unwrap()
.is_none()
);
store
.create_table(entry)
.await
.expect("a failed scan must release its read locks for retry");
}
}
#[tokio::test]
async fn object_catalog_registration_reuses_locked_deleted_entry() {
let backend = TestCatalogObjectBackend {
reject_reads_while_write_locked: true,
..Default::default()
};
let store = ObjectTableCatalogStore::new(backend.clone());
let bucket = "analytics";
let namespace = Namespace::parse("sales").unwrap();
let table = IdentifierSegment::parse("orders").unwrap();
store.put_table_bucket(test_bucket_entry(bucket)).await.unwrap();
store
.create_namespace(test_namespace_entry(bucket, &namespace))
.await
.unwrap();
let mut entry = test_table_entry(
bucket,
&namespace,
&table,
default_table_metadata_file_path(&namespace, &table, "00001.metadata.json"),
);
entry.state = TableCatalogEntryState::Deleted;
backend
.seed_object(
RUSTFS_META_BUCKET,
&store.paths.table_entry_path(bucket, &namespace, &table),
serde_json::to_vec(&entry).unwrap(),
)
.await;
entry.state = TableCatalogEntryState::Active;
entry.table_id = "replacement-table-id".to_string();
store.create_table(entry.clone()).await.unwrap();
assert_eq!(
store
.load_table(bucket, &namespace.public_name(), table.as_str())
.await
.unwrap(),
Some(entry)
);
}
#[tokio::test]
async fn catalog_backings_reject_overlapping_registered_warehouse_prefixes() {
let backend = TestCatalogObjectBackend::default();
@@ -20526,9 +20955,9 @@ async fn object_table_catalog_store_reuses_old_prefix_after_failed_relocation_in
let mut next_entry = test_table_entry(bucket, &namespace, &next_table, current_metadata);
next_entry.table_id = "next-table-id".to_string();
next_entry.warehouse_location = format!("s3://{bucket}/tables/table-id");
store
.create_table(next_entry)
tokio::time::timeout(std::time::Duration::from_secs(5), store.create_table(next_entry))
.await
.expect("stale warehouse prefix reuse completes")
.expect("stale old warehouse index should not block prefix reuse");
let (index, _) = store
+1 -1
View File
@@ -22,7 +22,7 @@ class RegistryTests(unittest.TestCase):
def test_all_workflow_responsibilities_and_suite_exits_are_wired(self):
self.assertTrue(registry.check_wiring(self.registry))
self.assertEqual(len(self.registry["suites"]), 12)
self.assertEqual(sum(item["origin"] == "baseline" for item in self.registry["workflows"]), 60)
self.assertEqual(sum(item["origin"] == "baseline" for item in self.registry["workflows"]), 61)
self.assertEqual(len(self.registry["workflows"]), len(list((registry.ROOT / ".github/workflows").glob("*.yml"))))
def test_manual_and_periodic_plan_choose_identical_responsibilities(self):