#!/usr/bin/env python3 """Split rustfs/src/app/multipart_usecase.rs into one file per operation. Preparatory refactor P3 of the s3s to rustfs-gateway migration. A pure code move: every top-level item, every method of `impl DefaultMultipartUsecase` and every test is assigned to a target file by the explicit tables below, and is moved verbatim with its attributes and doc comments. Nothing is renamed and no body changes, with these exceptions, each mechanical and listed here so a reviewer knows where the output differs from the input: * the three test fixtures (`s3_op_total`, `build_request`, `make_usecase`) gain `pub(super)` because they move to `test_support.rs`; * the test module's `use` items become `pub(super) use` re-exports in `test_support.rs` (names the parent already imports are not repeated), so every per-operation test module reaches them with one glob; * code-position `s3s::` paths in the new files become `crate::app::storage_api::s3::`, the sanctioned s3s funnel, so the number of files naming s3s (scripts/check_s3s_footprint.sh) does not grow. The funnel gains two re-exports, `dto` and `xml`, in rustfs/src/app/storage_api.rs; * the nextest filter that names the one test it pins follows the test to its new module path. Layout produced (parent keeps the struct, its constructors and accessors, the shared helpers and the test fixtures): multipart_usecase.rs shared state and helpers multipart_usecase/test_support.rs fixtures and test-only imports multipart_usecase/{abort,create,list,upload_part,complete,upload_part_copy}.rs one operation: its helpers, its `impl DefaultMultipartUsecase` block, its tests multipart_usecase/upload_part/tests/body_read_tests.rs multipart_usecase/upload_part_copy/tests/copy_admission_tests.rs the two former test files, unchanged Usage: scripts/codemods/split_multipart_usecase.py [--no-fmt] [--report] scripts/codemods/split_multipart_usecase.py --self-test The input is the unsplit tree. A tree that is already split is refused, as is any top-level item, method or test without an assignment, any table entry that matches nothing, and any private item that a file other than its own refers to. Re-running therefore means restoring the pre-split files first: git checkout -- rustfs/src/app/multipart_usecase.rs \\ rustfs/src/app/multipart_usecase rustfs/src/app/storage_api.rs .config/nextest.toml git clean -fd rustfs/src/app/multipart_usecase and then running this script. rustfmt formats the written files unless --no-fmt is given. --report prints the item to file assignment and the cross-file reference check and writes nothing. Exit status: 0 on success, 1 when the input cannot be split as asked (the message says why), 2 for a usage error. """ import argparse import re import subprocess import sys import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[2] APP = "rustfs/src/app" SOURCE = f"{APP}/multipart_usecase.rs" OUT_DIR = f"{APP}/multipart_usecase" STORAGE_API = f"{APP}/storage_api.rs" NEXTEST = ".config/nextest.toml" STRUCT = "DefaultMultipartUsecase" FUNNEL = "crate::app::storage_api::s3::" PARENT = "parent" SUPPORT = "test_support" OPS = ("abort", "create", "list", "upload_part", "complete", "upload_part_copy") OP_DOC = { "abort": "AbortMultipartUpload.", "create": "CreateMultipartUpload.", "list": "ListMultipartUploads and ListParts.", "upload_part": "UploadPart.", "complete": "CompleteMultipartUpload.", "upload_part_copy": "UploadPartCopy.", } # Test files that already existed, moved unchanged: (old path, operation). OLD_TEST_FILES = { "body_read_tests": (f"{OUT_DIR}/tests/body_read_tests.rs", "upload_part"), "copy_admission_tests": (f"{OUT_DIR}/tests/copy_admission_tests.rs", "upload_part_copy"), } # --------------------------------------------------------------------------- # Assignment tables: item name -> target file. Every name must be listed; the # script fails on a missing or an unused entry. # --------------------------------------------------------------------------- def assigned(target, names): return {name: target for name in names.split()} # Top-level functions (everything that is not an import, the struct, its impl # or the test module). A helper stays in the parent when more than one # operation, or a cross-operation test, uses it. FUNCTIONS = { **assigned( PARENT, """ merge_part_encryption_metadata multipart_plaintext_size multipart_part_numbers multipart_max_total_object_size validate_table_catalog_object_mutation internal_object_info_lookup_opts multipart_upload_api_error """, ), **assigned( "upload_part_copy", "normalize_copy_source_version_id format_copy_source_version_id validate_copy_source_range_not_exceeds", ), **assigned( "complete", """ validate_complete_multipart_parts normalize_complete_multipart_parts complete_part_from_s3 has_complete_multipart_object_lock_headers validate_complete_multipart_checksum_type quota_accounting_object_size encode_s3_path extract_request_scheme extract_request_host build_complete_multipart_location """, ), **assigned("create", "create_multipart_upload_metadata should_advertise_session_compression"), **assigned( "upload_part", """ resolve_upload_part_size require_upload_part_size upload_part_body_read_timeout passthrough_part_actual_size normalize_presigned_part_checksums """, ), } # Methods of `impl DefaultMultipartUsecase`. METHODS = { **assigned( PARENT, "without_context from_global with_context with_context_and_concurrency_manager" " bucket_metadata_sys object_store object_data_cache concurrency_manager", ), **assigned("abort", "execute_abort_multipart_upload"), **assigned("complete", "execute_complete_multipart_upload execute_complete_multipart_upload_owned"), **assigned("create", "execute_create_multipart_upload"), **assigned("upload_part", "execute_upload_part"), **assigned("list", "execute_list_multipart_uploads execute_list_parts"), **assigned("upload_part_copy", "execute_upload_part_copy"), } # Items of `mod tests`. A test that drives more than one operation, and the # tests of the shared helpers, stay in the parent's own `mod tests`. TESTS = { **assigned(SUPPORT, "s3_op_total build_request make_usecase"), **assigned( PARENT, """ internal_object_info_lookup_opts_drops_http_preconditions merge_part_encryption_metadata_keeps_source_metadata_unchanged managed_multipart_roundtrip_preserves_session_nonce_between_parts multipart_upload_rejects_reserved_directory_markers multipart_max_total_object_size_reads_compatible_internal_metadata multipart_upload_api_error_reports_malformed_upload_id_as_no_such_upload multipart_handlers_reject_another_callers_denied_kms_upload """, ), **assigned("abort", "execute_abort_multipart_upload_returns_internal_error_when_store_uninitialized"), **assigned( "create", """ session_compression_is_advertised_only_for_non_passthrough_compressible_uploads execute_create_multipart_upload_rejects_invalid_storage_class create_multipart_upload_metadata_persists_dto_storage_class_without_raw_header create_multipart_upload_metadata_keeps_user_and_system_namespaces_separate create_multipart_rejects_ciphertext_replication_before_parts_are_staged """, ), **assigned( "list", """ execute_list_multipart_uploads_returns_internal_error_when_store_uninitialized execute_list_multipart_uploads_rejects_invalid_key_marker_before_store_lookup execute_list_multipart_uploads_rejects_invalid_max_uploads_before_store_lookup execute_list_parts_returns_internal_error_when_store_uninitialized execute_list_parts_rejects_negative_part_number_marker_before_store_lookup execute_list_parts_rejects_invalid_max_parts_before_store_lookup """, ), **assigned( "upload_part", """ presigned_checksum_request normalize_presigned_part_checksums_validates_body normalize_presigned_part_checksums_accepts_sdk_crc32_default normalize_presigned_part_checksums_rejects_ambiguous_values normalize_presigned_part_checksums_preserves_headers_and_rejects_invalid_values normalize_presigned_part_checksums_requires_verified_presign resolve_upload_part_size_uses_normalized_logical_length upload_part_length_contract_rejects_unknown_and_all_negative_lengths upload_part_timeout_policy_preserves_disabled_and_capped_floor execute_upload_part_rejects_missing_body execute_upload_part_rejects_oversize_declared_part_before_reading_the_body execute_upload_part_rejects_invalid_part_number_before_body_lookup execute_upload_part_rejects_unknown_length_before_admission_or_body_polling execute_upload_part_progress_timeout_releases_admission_and_leaves_no_part execute_upload_part_rejects_when_foreground_write_admission_is_full """, ), **assigned( "upload_part_copy", """ execute_upload_part_copy_returns_internal_error_when_store_uninitialized execute_upload_part_copy_rejects_invalid_part_number_before_store_lookup test_validate_copy_source_range_not_exceeds_returns_invalid_range_when_range_exceeds test_validate_copy_source_range_not_exceeds_ok_when_range_valid test_validate_copy_source_range_not_exceeds_ok_for_suffix_range upload_part_copy_normalizes_and_formats_source_version_id """, ), **assigned( "complete", """ upload_metadata_with_checksum_type headers_with_checksum_type complete_multipart_checksum_type_matching_the_upload_is_accepted complete_multipart_checksum_type_contradicting_the_upload_is_rejected complete_multipart_checksum_type_without_both_sides_is_accepted quota_accounting_uses_logical_size_when_available quota_accounting_fails_closed_only_when_quota_is_configured test_build_complete_multipart_location_uses_forwarded_proto_and_encodes_key test_build_complete_multipart_location_falls_back_to_uri_authority_and_scheme test_build_complete_multipart_location_returns_path_without_host execute_complete_multipart_upload_rejects_missing_parts_payload execute_complete_multipart_upload_rejects_missing_parts_list compressed_complete_records_logical_quota_usage_and_overwrite_delta authorized_replica_only_multipart_complete_preserves_persisted_anti_cascade_state authorized_replica_only_multipart_complete_preserves_persisted_anti_cascade_state_inner ssec_completion_and_replay_require_key_before_disclosing_plaintext_checksums assert_multipart_etag_listings kms_multipart_completion_and_replay_preserve_etag_in_versioned_listings conditional_multipart_upload_if_none_match_returns_precondition_failed_when_object_exists conditional_multipart_upload_if_none_match_returns_precondition_failed_when_object_exists_inner concurrent_completions_share_durable_bucket_quota_reservations multipart_completion_commits_after_quota_fleet_proof_loss_before_rename data_movement_multipart_completion_has_zero_quota_growth cancelled_multipart_completion_emits_once_and_replay_does_not_emit rejected_empty_parts_preserve_existing_object_and_staging execute_complete_multipart_upload_allows_duplicate_part_numbers_by_using_last_occurrence execute_complete_multipart_upload_rejects_out_of_order_parts validate_complete_multipart_parts_enforces_part_number_range normalize_complete_multipart_parts_keeps_last_duplicate_part execute_complete_multipart_upload_rejects_object_lock_headers """, ), } # Test module items that are not code to assign. TEST_MODS = ("body_read_tests", "copy_admission_tests") CODE, COMMENT, LITERAL = 0, 1, 2 IDENT_CHARS = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") CHAR_LITERAL = re.compile(r"'(?:\\(?:[nrt\\0'\"]|x[0-9a-fA-F]{2}|u\{[0-9a-fA-F_]{1,6}\})|[^\\'\n])'") RAW_STRING_START = re.compile(r'r(#*)"') # A relative path in code moved one module down: `super::object::..` named a sibling of # multipart_usecase, and from an operation file that is `super::super::object::..`. SUPER_PATH = re.compile(r"(?= n: raise SplitError(f"{what}: an item starting at line {start + 1} never closes") items.append(Item(lines[start : j + 1], code_lines[start : j + 1])) i = j + 1 return items def canonical(items, separator): return separator.join(item.text for item in items) # --------------------------------------------------------------------------- # Use trees. # --------------------------------------------------------------------------- def split_top(inner): parts, depth, current = [], 0, [] for ch in inner: if ch == "{": depth += 1 elif ch == "}": depth -= 1 if ch == "," and depth == 0: parts.append("".join(current)) current = [] else: current.append(ch) parts.append("".join(current)) return [p.strip() for p in parts if p.strip()] def flatten_use(tree, prefix=""): """[(full path, bound name)] for a use tree; a glob binds `*`, `as _` binds `_`.""" tree = tree.strip() brace = tree.find("{") if brace >= 0: head = tree[:brace].strip() inner = tree[brace + 1 : tree.rindex("}")] base = prefix + head found = [] for part in split_top(inner): found.extend(flatten_use(part, base)) return found alias = None if " as " in tree: tree, alias = (side.strip() for side in tree.split(" as ", 1)) path = prefix + tree last = path.split("::")[-1] if last == "self": path = path[: -len("::self")] last = path.split("::")[-1] return [(path, alias if alias else last)] def use_paths(item): body = re.sub(r"^\s*(?:#\[[^\n]*\]\s*)*", "", item.code, flags=re.S) body = re.sub(r"^" + VIS + r"use\s+", "", body.strip()) body = body.rstrip().rstrip(";") return flatten_use(body) # --------------------------------------------------------------------------- # The parsed input. # --------------------------------------------------------------------------- class Parsed: pass def parse(text): lines = text.split("\n") if lines and lines[-1] == "": lines.pop() code_lines = code_only("\n".join(lines)).split("\n") # Leading licence and `//!` lines are the file preamble. first = 0 while first < len(lines) and (lines[first].startswith("//") or not lines[first].strip()): first += 1 preamble = lines[:first] items = split_items(lines[first:], code_lines[first:], "multipart_usecase.rs") parsed = Parsed() parsed.preamble = preamble parsed.imports, parsed.functions, parsed.body = [], [], [] parsed.struct = parsed.impl = parsed.tests = None for item in items: if not item.is_use(): parsed.body.append(item) name = item.name() if item.is_use(): if parsed.functions or parsed.struct or parsed.impl: raise SplitError("a `use` item follows code: imports are expected first") parsed.imports.append(item) elif STRUCT_HEAD.match(item.head) and name == STRUCT: parsed.struct = item elif IMPL_HEAD.match(item.head) and name == STRUCT: if parsed.impl is not None: raise SplitError(f"more than one `impl {STRUCT}` block") parsed.impl = item elif MOD_BLOCK_HEAD.match(item.head) and name == "tests": parsed.tests = item elif FN_HEAD.match(item.head): item.after_impl = parsed.impl is not None parsed.functions.append(item) elif MOD_DECL_HEAD.match(item.head): raise SplitError(f"{SOURCE} already declares {item.head!r}: it is split already; restore the pre-split files first") else: raise SplitError(f"unrecognised top-level item: {item.head!r}") for what, value in (("struct", parsed.struct), ("impl", parsed.impl), ("tests module", parsed.tests)): if value is None: raise SplitError(f"the {what} was not found; is the input already split?") # Spacing must be the canonical one, or the output would not be a move. rebuilt = "\n".join(preamble) + "\n" + "\n".join(i.text for i in parsed.imports) + "\n\n" rebuilt += canonical(parsed.body, "\n\n") if "\n".join(lines) != "\n".join(rebuilt.split("\n")): raise SplitError("the item layout is not the one this script reassembles (spacing differs from rustfmt's)") parsed.impl_methods = body_items(parsed.impl, "impl") parsed.test_items = body_items(parsed.tests, "mod tests") return parsed def body_items(block, what): """Items between the opening line and the closing brace of `block`.""" opening = next(i for i, line in enumerate(block.code_lines) if line.strip() and not line.strip().startswith("#[")) inner, inner_code = block.lines[opening + 1 : -1], block.code_lines[opening + 1 : -1] items = split_items(inner, inner_code, what) return items # --------------------------------------------------------------------------- # Assignment and checks. # --------------------------------------------------------------------------- def assign(items, table, what): placed = {} seen = set() for item in items: name = item.name() if name is None: raise SplitError(f"{what}: cannot name the item {item.head!r}") if name in seen: raise SplitError(f"{what}: two items are named {name}") seen.add(name) target = table.get(name) if target is None: raise SplitError(f"{what}: no assignment for {name} ({item.head[:60]!r})") placed[name] = (target, item) unused = sorted(set(table) - seen) if unused: raise SplitError(f"{what}: assignments that match nothing: {', '.join(unused)}") return placed def check_targets(table, what, allowed): for name, target in table.items(): if target not in allowed: raise SplitError(f"{what}: {name} is assigned to unknown file {target!r}") def word(name): return re.compile(r"(? u8 {", ' let s = "}";', " x", "}", "", "#[cfg(test)]", "mod tests {", " use super::*;", "", " #[test]", " fn t() {}", "}", ] ) def test_items_split_on_balance_not_on_braces_in_strings(self): lines = self.SAMPLE.split("\n")[6:] items = split_items(lines, code_only("\n".join(lines)).split("\n"), "sample") self.assertEqual([i.name() for i in items], ["one", "tests"]) self.assertTrue(items[1].cfg_test) def test_use_tree_flattening(self): paths = flatten_use("a::{b, c::{d as e, f}, g::*}") self.assertEqual(paths, [("a::b", "b"), ("a::c::d", "e"), ("a::c::f", "f"), ("a::g::*", "*")]) def test_s3s_rewrite_skips_strings_and_identifiers(self): text = 'let a = s3s::dto::X; let b = "s3s::dto"; let c = rs3s::y;' self.assertEqual(rewrite_s3s(text), f'let a = {FUNNEL}dto::X; let b = "s3s::dto"; let c = rs3s::y;') def test_unassigned_item_fails(self): lines = self.SAMPLE.split("\n")[6:13] items = split_items(lines, code_only("\n".join(lines)).split("\n"), "sample") with self.assertRaises(SplitError): assign(items, {}, "functions") with self.assertRaises(SplitError): assign(items, {"one": PARENT, "ghost": PARENT}, "functions") def test_unclosed_item_fails(self): with self.assertRaises(SplitError): split_items(["fn a() {"], ["fn a() {"], "sample") if __name__ == "__main__": sys.exit(main(sys.argv[1:]))