Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/uipath-platform/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "uipath-platform"
version = "0.3.23"
version = "0.3.24"
description = "HTTP client library for programmatic access to UiPath Platform"
readme = { file = "README.md", content-type = "text/markdown" }
requires-python = ">=3.11"
Expand Down Expand Up @@ -50,6 +50,7 @@ dev = [
"pytest-mock>=3.11.1",
"pre-commit>=4.1.0",
"types-PyYAML>=6.0",
"opentelemetry-instrumentation-httpx>=0.60b0",
]

[tool.hatch.build.targets.wheel]
Expand Down
7 changes: 6 additions & 1 deletion packages/uipath-platform/src/uipath/platform/common/retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
)
from tenacity import RetryCallState

from ..errors import EnrichedException
from ..errors import BucketFileReadError, EnrichedException

RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({408, 429, 502, 503, 504, 524})
NON_RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({400, 401, 403, 404, 413, 422})
Expand Down Expand Up @@ -76,6 +76,11 @@ def is_retryable_platform_exception(exception: BaseException) -> bool:
# A failed connect never sent the request, so any method is safe to retry.
if isinstance(exception, (ConnectError, TimeoutException)):
return True
# Reading the bucket file the request was sending failed, so the request
# was not sent in full: sending it again is safe, and sends the whole file
# from a new download.
if isinstance(exception, BucketFileReadError):
return True
if isinstance(exception, EnrichedException):
return exception.status_code in RETRYABLE_STATUS_CODES
return False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

Available exceptions:
- BaseUrlMissingError: Raised when base URL is not configured
- BucketFileChangedError: Raised when a bucket file changes while it is being read
- BucketFileReadError: Raised when downloading a bucket file fails while it is read
- SecretMissingError: Raised when access token is not configured
- FolderNotFoundException: Raised when a folder cannot be found
- UnsupportedDataSourceException: Raised when an operation is attempted on an unsupported data source type
Expand All @@ -20,6 +22,8 @@
from ._base_url_missing_error import BaseUrlMissingError
from ._batch_transform_failed_exception import BatchTransformFailedException
from ._batch_transform_not_complete_exception import BatchTransformNotCompleteException
from ._bucket_file_changed_error import BucketFileChangedError
from ._bucket_file_read_error import BucketFileReadError
from ._context_grounding_index_not_found_exception import (
ContextGroundingIndexNotFoundError,
)
Expand All @@ -40,6 +44,8 @@
"DataFabricErrorCategory",
"BatchTransformFailedException",
"BatchTransformNotCompleteException",
"BucketFileChangedError",
"BucketFileReadError",
"ContextGroundingIndexNotFoundError",
"EnrichedException",
"ExtractedErrorInfo",
Expand Down
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

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 22 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=UiPath_uipath-python&issues=AaI7ieJZ0xt5VkUz4d0k&open=AaI7ieJZ0xt5VkUz4d0k&pullRequest=2036
"""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)
Comment thread
alexandrujircan marked this conversation as resolved.
Resolved
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
Comment thread
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 (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

native Orchestrator can stream without ETag or Content-Length. after a rewind, the cached size can truncate a larger replacement or accept a shorter one, and matching sizes can still mix versions. let's require a reliable storage version or fail a reopen we can't validate. earlier version-check thread

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
Comment thread
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
Loading
Loading