jayceslesar commented on code in PR #3361: URL: https://github.com/apache/iceberg-python/pull/3361#discussion_r3928832014
########## pyiceberg/table/maintenance/orphan_files.py: ########## @@ -0,0 +1,414 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +"""Action that removes files from storage that are not reachable from table metadata. + +Lists the table's storage location, computes the set of files referenced by any valid +snapshot or metadata file, and deletes the difference. + +Only acts on files older than 3 days by default. +""" + +from __future__ import annotations + +import logging +import re +from collections.abc import Callable, Iterable +from concurrent.futures import as_completed +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from enum import Enum +from typing import TYPE_CHECKING +from urllib.parse import urlparse + +from pyiceberg.utils.concurrent import ExecutorFactory +from pyiceberg.utils.properties import property_as_bool + +if TYPE_CHECKING: + from pyiceberg.io import FileEntry + from pyiceberg.table import Table + +logger = logging.getLogger(__name__) + + +class PrefixMismatchMode(str, Enum): + """How to treat listed files whose URI scheme or authority differs from the referenced file. + + Files may match a referenced path component-for-component but be served through a different + scheme (s3 vs s3a) or endpoint authority. Use ``equal_schemes`` / ``equal_authorities`` to + declare equivalences; this mode chooses what to do with anything that remains ambiguous. + """ + + ERROR = "ERROR" + IGNORE = "IGNORE" + DELETE = "DELETE" + + +@dataclass(frozen=True) +class RemoveOrphanFilesResult: + """Outcome of a RemoveOrphanFiles execution.""" + + orphan_file_locations: list[str] = field(default_factory=list) + deleted_files: list[str] = field(default_factory=list) + failed_to_delete: list[str] = field(default_factory=list) + total_bytes: int = 0 + + +_DEFAULT_OLDER_THAN = timedelta(days=3) +_DEFAULT_EQUAL_SCHEMES = {"s3a": "s3", "s3n": "s3"} + + +class RemoveOrphanFiles: + r"""Builder for the remove-orphan-files action. + + Usage:: + + result = table.maintenance.remove_orphan_files() \ + .older_than(datetime.now(tz=timezone.utc) - timedelta(days=7)) \ + .execute() + """ + + _table: Table + _location: str | None + _older_than_ms: int + _dry_run: bool + _delete_with: Callable[[str], None] | None + _max_concurrency: int | None + _prefix_mismatch_mode: PrefixMismatchMode + _equal_schemes: dict[str, str] + _equal_authorities: dict[str, str] + _compare_to_file_list: Iterable[tuple[str, datetime]] | None + + def __init__(self, table: Table) -> None: + self._table = table + self._location = None + self._older_than_ms = _now_ms() - int(_DEFAULT_OLDER_THAN.total_seconds() * 1000) + self._dry_run = False + self._delete_with = None + self._max_concurrency = None + self._prefix_mismatch_mode = PrefixMismatchMode.ERROR + self._equal_schemes = dict(_DEFAULT_EQUAL_SCHEMES) + self._equal_authorities = {} + self._compare_to_file_list = None + + def location(self, location: str) -> RemoveOrphanFiles: + """Restrict the scan to a specific location. Defaults to the table's root location.""" + self._location = location + return self + + def older_than(self, value: datetime | timedelta) -> RemoveOrphanFiles: + """Only consider files modified strictly before this point. + + Accepts either an absolute datetime or a timedelta interpreted as "files older + than this much" relative to now. Defaults to 3 days ago. + """ + if isinstance(value, timedelta): + self._older_than_ms = _now_ms() - int(value.total_seconds() * 1000) + else: + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + self._older_than_ms = int(value.timestamp() * 1000) + return self + + def dry_run(self, enabled: bool = True) -> RemoveOrphanFiles: + """When enabled, identify orphans but do not delete them.""" + self._dry_run = enabled + return self + + def delete_with(self, delete_func: Callable[[str], None]) -> RemoveOrphanFiles: + """Use a custom deleter instead of FileIO.delete. + + Useful for dry runs that collect orphans, or for routing deletes through a + different sink. + """ + self._delete_with = delete_func + return self + + def max_concurrency(self, max_workers: int) -> RemoveOrphanFiles: Review Comment: why not just use https://github.com/apache/iceberg-python/blob/main/pyiceberg/utils/concurrent.py#L30 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
