Repository navigation
feat(buckets): open a bucket file as a streamed, seekable file #2036
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
8de166c
58d907c
ac464e1
fa4f69f
30ca8f3
ebdb5c1
711c23e
70485df
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| class BucketFileChangedError(Exception): | ||
| """Raised when a bucket file changes while it is being read. | ||
|
|
||
| A file opened with `sdk.buckets.open` is downloaded again when it is read from | ||
| another position, as a retried upload does. If the file in the bucket was | ||
| replaced in the meantime, the new download would return another version, so | ||
| the read fails instead of mixing bytes of the two versions. Open the file | ||
| again to read its current version. | ||
|
|
||
| Only an ETag tells two versions of the same size apart. When the storage | ||
| reports no ETag, a new download from the start of the file is checked by | ||
| its length, and a new download from the middle of the file is refused: that | ||
| read fails with this error too, with `verified` False. | ||
| """ | ||
|
|
||
| def __init__(self, name: str, *, verified: bool = True) -> None: | ||
| self.name = name | ||
| self.verified = verified | ||
| if verified: | ||
| reason = "changed while it was being read" | ||
| else: | ||
| reason = ( | ||
| "can't be downloaded again from the middle while it is being read: " | ||
| "the storage reports no version (ETag) for it, so a change could " | ||
| "not be detected" | ||
| ) | ||
| self.message = ( | ||
| f"The bucket file '{name}' {reason}. " | ||
| "Open it again to read its current version." | ||
| ) | ||
| super().__init__(self.message) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| class BucketFileReadError(Exception): | ||
| """Raised when downloading a bucket file from storage fails while it is read. | ||
|
|
||
| A file opened with `sdk.buckets.open` is downloaded as it is read. If the | ||
| connection to the storage fails, or the storage ends a download before the | ||
| end of the file, the read raises this error, with the network error, if | ||
| any, as its cause. | ||
|
|
||
| Reading the file again starts a new download. The platform retry treats | ||
| this error as transient: a request that was sending the file, such as a | ||
| `sdk.documents` upload, failed before it was sent in full, so it is sent | ||
| again, with the whole file. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, name: str, reason: str = "the connection to the storage failed" | ||
| ) -> None: | ||
| self.name = name | ||
| self.message = f"Downloading the bucket file '{name}' failed: {reason}." | ||
| super().__init__(self.message) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| """A read-only, seekable file over a bucket file, streamed from storage as it's read.""" | ||
|
|
||
| import io | ||
| from typing import TYPE_CHECKING, Callable, Iterator, Optional | ||
|
|
||
| import httpx | ||
|
|
||
| from ..errors import BucketFileChangedError, BucketFileReadError | ||
|
|
||
| if TYPE_CHECKING: | ||
| from _typeshed import WriteableBuffer | ||
|
|
||
| CHUNK_SIZE = 64 * 1024 | ||
|
|
||
|
|
||
| class BucketFileReader(io.RawIOBase): | ||
| """Raw binary file over a bucket file, downloaded as it is read. | ||
|
|
||
| Only the chunk being read is in memory. Seeking only moves the position: the | ||
| next read continues the open download when it is already there, and starts a | ||
| new download from that position otherwise. The size comes from the | ||
| download's headers, so asking for it starts the download that the first | ||
| read then continues. When the storage reports no size, it is known once a | ||
| download reaches the end of the file. Every download must return the same | ||
| version of the file, by ETag and size; if the file was replaced in the | ||
| bucket, the read raises `BucketFileChangedError`. Without an ETag, a new | ||
| download from the start of the file is checked by its length, and one from | ||
| the middle is refused. A failed download raises `BucketFileReadError`; the | ||
| reader doesn't retry it, whoever reads the file does. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, name: str, open_download: Callable[[int], httpx.Response] | ||
| ) -> None: | ||
| """Create a reader. | ||
|
|
||
| Args: | ||
| name: The file name, without the bucket path. | ||
| open_download: Starts a streamed GET of the file from a byte offset. | ||
| """ | ||
| super().__init__() | ||
| self._response: Optional[httpx.Response] = None | ||
| self._chunks: Iterator[bytes] = iter(()) | ||
| self._pending = b"" | ||
| self._download_position = 0 # offset of the next byte in _pending/_chunks | ||
| self._position = 0 | ||
| self._size: Optional[int] = None | ||
| self._size_checked = False # a download has reported its headers | ||
| self._etag: Optional[str] = None | ||
| self._downloaded = False # a download with content has started | ||
| self._download_sized = False # the open download reported the file size | ||
| self._open_download = open_download | ||
| self.name = name | ||
|
|
||
| def readable(self) -> bool: | ||
| """Return True: the file can be read.""" | ||
| return True | ||
|
|
||
| def seekable(self) -> bool: | ||
| """Return True: the file supports seek and tell.""" | ||
| return True | ||
|
|
||
| def tell(self) -> int: | ||
| """Return the current position.""" | ||
| self._checkClosed() | ||
| return self._position | ||
|
|
||
| def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: | ||
| """Move to a new position; nothing is downloaded until the next read.""" | ||
| self._checkClosed() | ||
| if whence == io.SEEK_SET: | ||
| position = offset | ||
| elif whence == io.SEEK_CUR: | ||
| position = self._position + offset | ||
| elif whence == io.SEEK_END: | ||
| position = self._file_size() + offset | ||
| else: | ||
| raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)") | ||
| if position < 0: | ||
| raise ValueError(f"negative seek position {position}") | ||
| self._position = position | ||
| return position | ||
|
|
||
| def readinto(self, buffer: "WriteableBuffer", /) -> int: | ||
|
Check failure on line 84 in packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py
|
||
| """Read the next bytes of the file into `buffer`.""" | ||
| self._checkClosed() | ||
| if self._size is not None and self._position >= self._size: | ||
| if ( | ||
| self._response is not None | ||
| and not self._download_sized | ||
| and self._download_position == self._size | ||
| and (self._pending or self._next_chunk()) | ||
| ): | ||
| # A download that reported no size has more bytes than the file | ||
| # had: it is another version. | ||
| self._release() | ||
| raise BucketFileChangedError(self.name) | ||
| self._release() | ||
| return 0 | ||
| if self._response is None or self._download_position != self._position: | ||
| self._start(self._position) | ||
| if self._response is None: # the position is past the end of the file | ||
| return 0 | ||
| if not self._pending: | ||
| self._pending = self._next_chunk() | ||
| if not self._pending: | ||
| self._release() | ||
| if self._size is None: # the download ran to the end of the file | ||
| self._size = self._download_position | ||
| elif self._download_position < self._size: | ||
| if not self._download_sized: | ||
| # The storage sent all of the file, and it is shorter | ||
| # than it was: it is another version. | ||
| raise BucketFileChangedError(self.name) | ||
| # A storage can send less than the range asked for. | ||
| raise BucketFileReadError( | ||
| self.name, | ||
| "the storage ended the download before the end of the file", | ||
| ) | ||
| return 0 | ||
|
alexandrujircan marked this conversation as resolved.
Resolved
|
||
| view = memoryview(buffer).cast("B") | ||
| count = min(len(view), len(self._pending)) | ||
| if self._size is not None: # never past the end of the file | ||
| count = min(count, self._size - self._position) | ||
| view[:count] = self._pending[:count] | ||
| self._pending = self._pending[count:] | ||
| self._position += count | ||
| self._download_position += count | ||
| return count | ||
|
|
||
| def close(self) -> None: | ||
| """Close the file and any download still open.""" | ||
| self._release() | ||
| super().close() | ||
|
|
||
| def _file_size(self) -> int: | ||
| if not self._size_checked: | ||
| self._start(self._position) | ||
| if self._size is None: | ||
| raise io.UnsupportedOperation("the storage did not report the file size") | ||
| return self._size | ||
|
|
||
| def _start(self, start: int) -> None: | ||
| self._release() | ||
| try: | ||
| response = self._open_download(start) | ||
| except httpx.TransportError as error: | ||
| raise BucketFileReadError(self.name) from error | ||
| if response.status_code == 416: # Range Not Satisfiable: start is past the end | ||
| response.close() | ||
| # Content-Range: bytes */<total> | ||
| self._check_version(response, _total_size(response, partial=True)) | ||
| return | ||
| partial = response.status_code == 206 | ||
| size = _total_size(response, partial) | ||
| try: | ||
| self._check_version(response, size, start=start) | ||
| except BucketFileChangedError: | ||
| response.close() | ||
| raise | ||
| self._response = response | ||
| self._download_sized = size is not None | ||
| # Raw bytes: the size the storage reports is the size of the stored bytes. | ||
| self._chunks = response.iter_raw(CHUNK_SIZE) | ||
| self._download_position = start if partial else 0 | ||
| # The storage ignored the Range header and sent the whole file: skip ahead. | ||
| while self._download_position < start: | ||
| chunk = self._next_chunk() | ||
| if not chunk: | ||
| break | ||
| skipped = min(len(chunk), start - self._download_position) | ||
| self._download_position += skipped | ||
| self._pending = chunk[skipped:] | ||
|
|
||
| def _check_version( | ||
| self, | ||
| response: httpx.Response, | ||
| size: Optional[int], | ||
| *, | ||
| start: Optional[int] = None, | ||
| ) -> None: | ||
| """Keep the first download's version; fail if a later download differs. | ||
|
|
||
| Every download of the file must return the same version: a rewind or a | ||
| retried upload after the file was replaced would otherwise cut a larger | ||
| file off at the old size, or mix bytes of the two versions. Only an | ||
| ETag tells two versions of the same size apart. Without one, a new | ||
| download from the start can't mix versions, as it has the whole file, | ||
| so it is only checked by its size; its length is checked as it is read | ||
| when it reports none. A new download from the middle is refused. | ||
|
|
||
| Args: | ||
| response: The download's response. | ||
| size: The file size the response reports, if any. | ||
| start: Where the download's bytes are read from; None for a | ||
| response without the file's bytes, a 416. | ||
| """ | ||
| etag = response.headers.get("ETag") | ||
| if (etag and self._etag and etag != self._etag) or ( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. native Orchestrator can stream without |
||
| size is not None and self._size is not None and size != self._size | ||
| ): | ||
| raise BucketFileChangedError(self.name) | ||
| if start is not None: | ||
| if self._downloaded and start and not (etag and self._etag): | ||
| raise BucketFileChangedError(self.name, verified=False) | ||
| if not self._downloaded: | ||
| self._etag = etag | ||
| self._downloaded = True | ||
| if self._size is None: | ||
| self._size = size | ||
| self._size_checked = True | ||
|
|
||
| def _next_chunk(self) -> bytes: | ||
| """Return the download's next chunk, or b"" at its end.""" | ||
| try: | ||
| return next(self._chunks, b"") | ||
| except httpx.TransportError as error: | ||
| # Drop the failed download, so that the next read starts a new one. | ||
| self._release() | ||
| raise BucketFileReadError(self.name) from error | ||
| except BaseException: | ||
| self._release() | ||
| raise | ||
|
alexandrujircan marked this conversation as resolved.
Resolved
|
||
|
|
||
| def _release(self) -> None: | ||
| if self._response is not None: | ||
| self._response.close() | ||
| self._response = None | ||
| self._chunks = iter(()) | ||
| self._pending = b"" | ||
|
|
||
|
|
||
| def _total_size(response: httpx.Response, partial: bool) -> Optional[int]: | ||
| if partial: # Content-Range: bytes <first>-<last>/<total> | ||
| total = response.headers.get("Content-Range", "").rpartition("/")[2] | ||
| else: | ||
| total = response.headers.get("Content-Length", "") | ||
| return int(total) if total.isdigit() else None | ||
Uh oh!
There was an error while loading. Please reload this page.