|
| 1 | +################################################################################ |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +################################################################################ |
| 18 | + |
| 19 | +import io |
| 20 | +from abc import ABC, abstractmethod |
| 21 | +from pathlib import Path |
| 22 | +from typing import Any, Optional |
| 23 | +from urllib.parse import urlparse, ParseResult |
| 24 | + |
| 25 | +import requests |
| 26 | +from cachetools import LRUCache |
| 27 | +from readerwriterlock import rwlock |
| 28 | + |
| 29 | +from pypaimon.common.config import CatalogOptions |
| 30 | + |
| 31 | + |
| 32 | +class UriReader(ABC): |
| 33 | + @classmethod |
| 34 | + def from_http(cls) -> 'HttpUriReader': |
| 35 | + return HttpUriReader() |
| 36 | + |
| 37 | + @classmethod |
| 38 | + def from_file(cls, file_io: Any) -> 'FileUriReader': |
| 39 | + return FileUriReader(file_io) |
| 40 | + |
| 41 | + @classmethod |
| 42 | + def get_file_path(cls, uri: str): |
| 43 | + parsed_uri = urlparse(uri) |
| 44 | + if parsed_uri.scheme == 'file': |
| 45 | + path = Path(parsed_uri.path) |
| 46 | + elif parsed_uri.scheme and parsed_uri.scheme != '': |
| 47 | + path = Path(parsed_uri.netloc + parsed_uri.path) |
| 48 | + else: |
| 49 | + path = Path(uri) |
| 50 | + return path |
| 51 | + |
| 52 | + @abstractmethod |
| 53 | + def new_input_stream(self, uri: str): |
| 54 | + pass |
| 55 | + |
| 56 | + |
| 57 | +class FileUriReader(UriReader): |
| 58 | + |
| 59 | + def __init__(self, file_io: Any): |
| 60 | + self._file_io = file_io |
| 61 | + |
| 62 | + def new_input_stream(self, uri: str): |
| 63 | + try: |
| 64 | + path = self.get_file_path(uri) |
| 65 | + return self._file_io.new_input_stream(path) |
| 66 | + except Exception as e: |
| 67 | + raise IOError(f"Failed to read file {uri}: {e}") |
| 68 | + |
| 69 | + |
| 70 | +class HttpUriReader(UriReader): |
| 71 | + |
| 72 | + def new_input_stream(self, uri: str): |
| 73 | + try: |
| 74 | + response = requests.get(uri) |
| 75 | + if response.status_code != 200: |
| 76 | + raise RuntimeError(f"Failed to read HTTP URI {uri} status code {response.status_code}") |
| 77 | + return io.BytesIO(response.content) |
| 78 | + except Exception as e: |
| 79 | + raise RuntimeError(f"Failed to read HTTP URI {uri}: {e}") |
| 80 | + |
| 81 | + |
| 82 | +class UriKey: |
| 83 | + |
| 84 | + def __init__(self, scheme: Optional[str], authority: Optional[str]) -> None: |
| 85 | + self._scheme = scheme |
| 86 | + self._authority = authority |
| 87 | + self._hash = hash((self._scheme, self._authority)) |
| 88 | + |
| 89 | + @property |
| 90 | + def scheme(self) -> Optional[str]: |
| 91 | + return self._scheme |
| 92 | + |
| 93 | + @property |
| 94 | + def authority(self) -> Optional[str]: |
| 95 | + return self._authority |
| 96 | + |
| 97 | + def __eq__(self, other: object) -> bool: |
| 98 | + if not isinstance(other, UriKey): |
| 99 | + return False |
| 100 | + |
| 101 | + return (self._scheme == other._scheme and |
| 102 | + self._authority == other._authority) |
| 103 | + |
| 104 | + def __hash__(self) -> int: |
| 105 | + return self._hash |
| 106 | + |
| 107 | + def __repr__(self) -> str: |
| 108 | + return f"UriKey(scheme='{self._scheme}', authority='{self._authority}')" |
| 109 | + |
| 110 | + |
| 111 | +class UriReaderFactory: |
| 112 | + |
| 113 | + def __init__(self, catalog_options: dict) -> None: |
| 114 | + self.catalog_options = catalog_options |
| 115 | + self._readers = LRUCache(CatalogOptions.BLOB_FILE_IO_DEFAULT_CACHE_SIZE) |
| 116 | + self._readers_lock = rwlock.RWLockFair() |
| 117 | + |
| 118 | + def create(self, input_uri: str) -> UriReader: |
| 119 | + try: |
| 120 | + parsed_uri = urlparse(input_uri) |
| 121 | + except Exception as e: |
| 122 | + raise ValueError(f"Invalid URI: {input_uri}") from e |
| 123 | + |
| 124 | + key = UriKey(parsed_uri.scheme, parsed_uri.netloc or None) |
| 125 | + rlock = self._readers_lock.gen_rlock() |
| 126 | + rlock.acquire() |
| 127 | + try: |
| 128 | + reader = self._readers.get(key) |
| 129 | + if reader is not None: |
| 130 | + return reader |
| 131 | + finally: |
| 132 | + rlock.release() |
| 133 | + wlock = self._readers_lock.gen_wlock() |
| 134 | + wlock.acquire() |
| 135 | + try: |
| 136 | + reader = self._readers.get(key) |
| 137 | + if reader is not None: |
| 138 | + return reader |
| 139 | + reader = self._new_reader(key, parsed_uri) |
| 140 | + self._readers[key] = reader |
| 141 | + return reader |
| 142 | + finally: |
| 143 | + wlock.release() |
| 144 | + |
| 145 | + def _new_reader(self, key: UriKey, parsed_uri: ParseResult) -> UriReader: |
| 146 | + scheme = key.scheme |
| 147 | + if scheme in ('http', 'https'): |
| 148 | + return UriReader.from_http() |
| 149 | + try: |
| 150 | + # Import FileIO here to avoid circular imports |
| 151 | + from pypaimon.common.file_io import FileIO |
| 152 | + uri_string = parsed_uri.geturl() |
| 153 | + file_io = FileIO(uri_string, self.catalog_options) |
| 154 | + return UriReader.from_file(file_io) |
| 155 | + except Exception as e: |
| 156 | + raise RuntimeError(f"Failed to create reader for URI {parsed_uri.geturl()}") from e |
| 157 | + |
| 158 | + def clear_cache(self) -> None: |
| 159 | + self._readers.clear() |
| 160 | + |
| 161 | + def get_cache_size(self) -> int: |
| 162 | + return len(self._readers) |
| 163 | + |
| 164 | + def __getstate__(self): |
| 165 | + state = self.__dict__.copy() |
| 166 | + del state['_readers_lock'] |
| 167 | + return state |
| 168 | + |
| 169 | + def __setstate__(self, state): |
| 170 | + self.__dict__.update(state) |
| 171 | + self._readers_lock = rwlock.RWLockFair() |
0 commit comments