diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index cb22f5c61..da92a1a85 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -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" @@ -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] diff --git a/packages/uipath-platform/src/uipath/platform/common/retry.py b/packages/uipath-platform/src/uipath/platform/common/retry.py index 4bbe561a6..f521df872 100644 --- a/packages/uipath-platform/src/uipath/platform/common/retry.py +++ b/packages/uipath-platform/src/uipath/platform/common/retry.py @@ -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}) @@ -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 diff --git a/packages/uipath-platform/src/uipath/platform/errors/__init__.py b/packages/uipath-platform/src/uipath/platform/errors/__init__.py index 012209a0f..bb0a39575 100644 --- a/packages/uipath-platform/src/uipath/platform/errors/__init__.py +++ b/packages/uipath-platform/src/uipath/platform/errors/__init__.py @@ -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 @@ -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, ) @@ -40,6 +44,8 @@ "DataFabricErrorCategory", "BatchTransformFailedException", "BatchTransformNotCompleteException", + "BucketFileChangedError", + "BucketFileReadError", "ContextGroundingIndexNotFoundError", "EnrichedException", "ExtractedErrorInfo", diff --git a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py new file mode 100644 index 000000000..e89db668f --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py @@ -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) diff --git a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_read_error.py b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_read_error.py new file mode 100644 index 000000000..3908a13b7 --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_read_error.py @@ -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) diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py new file mode 100644 index 000000000..768ebcff0 --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py @@ -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: + """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 + 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 */ + 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 ( + 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 + + 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 -/ + total = response.headers.get("Content-Range", "").rpartition("/")[2] + else: + total = response.headers.get("Content-Length", "") + return int(total) if total.isdigit() else None diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py index eb352f8d4..0bc343eab 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py @@ -1,11 +1,15 @@ import asyncio +import io import mimetypes import uuid -from pathlib import Path -from typing import Any, Dict, Optional, Union +from functools import partial +from pathlib import Path, PurePosixPath +from typing import Any, BinaryIO, Dict, NamedTuple, Optional, Union import httpx from anyio import to_thread +from opentelemetry.instrumentation.utils import suppress_http_instrumentation +from tenacity import stop_after_attempt from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -17,6 +21,8 @@ from ..common._models import Endpoint, RequestSpec from ..common.paging import PagedResult from ..common.validation import validate_pagination_params +from ..errors import EnrichedException +from ._bucket_file_reader import CHUNK_SIZE, BucketFileReader from .buckets import Bucket, BucketFile # Pagination limits @@ -24,6 +30,19 @@ MAX_SKIP_OFFSET = 10000 # Maximum skip offset for offset-based pagination +# `request` with a single attempt, for the read-URL lookup of an opened file: +# whoever reads the file retries, so the lookup is retried at that one layer. +_request_once = BaseService.request.retry_with(stop=stop_after_attempt(1)) # type: ignore[attr-defined] + + +class _ReadAccess(NamedTuple): + """Where and how to download a bucket file, from Orchestrator's GetReadUri.""" + + uri: str + headers: Dict[str, str] + requires_auth: bool + + class BucketsService(FolderContext, BaseService): """Service for managing UiPath storage buckets. @@ -429,30 +448,19 @@ def download( bucket = self.retrieve( name=name, key=key, folder_key=folder_key, folder_path=folder_path ) - spec = self._retrieve_readUri_spec( - bucket.id, blob_file_path, folder_key=folder_key, folder_path=folder_path + access = self._get_read_access( + bucket.id, blob_file_path, folder_key, folder_path ) - result = self.request( - spec.method, - url=spec.endpoint, - params=spec.params, - headers=spec.headers, - ).json() - - read_uri = result["Uri"] - - headers = { - key: value - for key, value in zip( - result["Headers"]["Keys"], result["Headers"]["Values"], strict=False - ) - } with open(destination_path, "wb") as file: - if result["RequiresAuth"]: - file_content = self.request("GET", read_uri, headers=headers).content + if access.requires_auth: + file_content = self.request( + "GET", access.uri, headers=access.headers + ).content else: - file_content = self.custom_client.get(read_uri, headers=headers).content + file_content = self.custom_client.get( + access.uri, headers=access.headers + ).content file.write(file_content) @resource_override(resource_type="bucket") @@ -484,38 +492,100 @@ async def download_async( bucket = await self.retrieve_async( name=name, key=key, folder_key=folder_key, folder_path=folder_path ) - spec = self._retrieve_readUri_spec( - bucket.id, blob_file_path, folder_key=folder_key, folder_path=folder_path + access = await self._get_read_access_async( + bucket.id, blob_file_path, folder_key, folder_path ) - result = ( - await self.request_async( - spec.method, - url=spec.endpoint, - params=spec.params, - headers=spec.headers, - ) - ).json() - - read_uri = result["Uri"] - - headers = { - key: value - for key, value in zip( - result["Headers"]["Keys"], result["Headers"]["Values"], strict=False - ) - } - if result["RequiresAuth"]: + if access.requires_auth: file_content = ( - await self.request_async("GET", read_uri, headers=headers) + await self.request_async("GET", access.uri, headers=access.headers) ).content else: file_content = ( - await self.custom_client_async.get(read_uri, headers=headers) + await self.custom_client_async.get(access.uri, headers=access.headers) ).content await asyncio.to_thread(Path(destination_path).write_bytes, file_content) + @resource_override(resource_type="bucket") + @traced(name="buckets_open", run_type="uipath") + def open( + self, + *, + name: Optional[str] = None, + key: Optional[str] = None, + blob_file_path: str, + folder_key: Optional[str] = None, + folder_path: Optional[str] = None, + ) -> BinaryIO: + """Open a file in a bucket for reading, without downloading it first. + + The file is downloaded as it is read, so it is never held whole in memory + or written to disk. The result is a regular read-only binary file, like one + opened with `open(path, "rb")`: it can be read, seeked and passed wherever + such a file is accepted, such as `file=` of + `sdk.documents.start_ixp_extraction`. Moving back, as a retried upload + does, downloads the file again from that position. If the file is + replaced in the bucket while it is being read, a read raises + `BucketFileChangedError` rather than mixing the two versions. A storage + that reports no ETag can't show a replacement of the same size: there, a + new download from the start of the file is checked by its length, and + a new download from the middle raises `BucketFileChangedError` too. + + A read is not retried: whoever reads the file retries. If a download + fails, the read raises `BucketFileReadError`, or `EnrichedException` for + an error status. The platform retry treats `BucketFileReadError` and + statuses such as 503 as transient, so a `sdk.documents` upload sends the + file again. + + Reading waits on the storage, as reading any file waits on the disk. From + async code, do the reading in a worker thread, for example by running + `open` and the call that reads the file in `asyncio.to_thread`. + + Args: + key (Optional[str]): The key of the bucket. + name (Optional[str]): The name of the bucket. + blob_file_path (str): The path to the file in the bucket. + folder_key (Optional[str]): The key of the folder where the bucket resides. + folder_path (Optional[str]): The path of the folder where the bucket resides. + + Returns: + BinaryIO: The opened file. Close it, or use it in a `with` block, when done. + + Raises: + ValueError: If neither key nor name is provided. + Exception: If the bucket with the specified key or name is not found. + BucketFileReadError: When reading, if a download from the storage fails. + BucketFileChangedError: When reading, if the file was replaced in the + bucket, or a replacement can't be ruled out for a download from + the middle of the file. + + Examples: + ```python + with sdk.buckets.open( + name="Loans", blob_file_path="loan-123/application.pdf" + ) as file: + extraction = sdk.documents.start_ixp_extraction( + project_name="LoanQAQC", tag="live", file=file + ) + ``` + + From async code: + ```python + def extract(path): + with sdk.buckets.open(name="Loans", blob_file_path=path) as file: + return sdk.documents.start_ixp_extraction( + project_name="LoanQAQC", tag="live", file=file + ) + + extraction = await asyncio.to_thread(extract, "loan-123/application.pdf") + ``` + """ + bucket = self.retrieve( + name=name, key=key, folder_key=folder_key, folder_path=folder_path + ) + return self._open_reader(bucket.id, blob_file_path, folder_key, folder_path) + @resource_override(resource_type="bucket") @traced(name="buckets_upload", run_type="uipath") def upload( @@ -1654,6 +1724,93 @@ def _retrieve_spec( }, ) + def _get_read_access( + self, + bucket_id: int, + blob_file_path: str, + folder_key: Optional[str], + folder_path: Optional[str], + *, + retry: bool = True, + ) -> _ReadAccess: + spec = self._retrieve_readUri_spec( + bucket_id, blob_file_path, folder_key=folder_key, folder_path=folder_path + ) + send = self.request if retry else partial(_request_once, self) + result = send( + spec.method, url=spec.endpoint, params=spec.params, headers=spec.headers + ).json() + return _read_access(result) + + async def _get_read_access_async( + self, + bucket_id: int, + blob_file_path: str, + folder_key: Optional[str], + folder_path: Optional[str], + ) -> _ReadAccess: + spec = self._retrieve_readUri_spec( + bucket_id, blob_file_path, folder_key=folder_key, folder_path=folder_path + ) + response = await self.request_async( + spec.method, url=spec.endpoint, params=spec.params, headers=spec.headers + ) + return _read_access(response.json()) + + def _open_reader( + self, + bucket_id: int, + blob_file_path: str, + folder_key: Optional[str], + folder_path: Optional[str], + ) -> BinaryIO: + def open_download(start: int) -> httpx.Response: + # A new read URL for every download: the URL expires (after an hour + # on Orchestrator storage), and a new one also misses any cached + # response for an older URL. + access = self._get_read_access( + bucket_id, blob_file_path, folder_key, folder_path, retry=False + ) + return self._start_download(access, start) + + name = PurePosixPath(blob_file_path.replace("\\", "/")).name + reader = BucketFileReader(name, open_download) + return io.BufferedReader(reader, buffer_size=CHUNK_SIZE) + + def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: + """Start a streamed GET of a bucket file from a byte offset. + + Not retried, like the read-URL lookup: whoever reads the file retries, + such as the retry of the `sdk.documents` upload that reads it, so + failures are retried at one layer. + """ + # No compression: the bytes read must be the stored bytes, so that they + # match the size the storage reports. + headers = {**access.headers, "Accept-Encoding": "identity"} + if start: + headers["Range"] = f"bytes={start}-" + if access.requires_auth: + # The current token, as request() sends: it may have been renewed + # since the client was created. + self._add_authorization(headers) + client = self._client if access.requires_auth else self.custom_client + # The read URL's query string is its signature: keep the download out + # of the spans of HTTP client instrumentation, which record its URL. + with suppress_http_instrumentation(): + response = client.send( + client.build_request("GET", access.uri, headers=headers), stream=True + ) + # 416: the start is past the end of the file, which the reader turns + # into end of file. + if response.is_error and response.status_code != 416: + try: + response.read() + finally: + response.close() + error = _status_error_without_query(response) + raise EnrichedException(error) from error + return response + def _retrieve_readUri_spec( self, bucket_id: int, @@ -1814,3 +1971,27 @@ def _get_files_spec( **header_folder(folder_key, folder_path), }, ) + + +def _status_error_without_query(response: httpx.Response) -> httpx.HTTPStatusError: + """The error for a failed download, with no query string in its URL. + + The query string of a read URL is its signature, which gives access to the + file, so it must not reach error messages, logs or traces. The status and + the headers stay, for the retry of whoever reads the file. + """ + url = response.request.url.copy_with(query=None, fragment=None) + response.request = httpx.Request(response.request.method, url) + return httpx.HTTPStatusError( + f"Bucket storage returned {response.status_code} {response.reason_phrase} " + f"for {url}", + request=response.request, + response=response, + ) + + +def _read_access(result: Dict[str, Any]) -> _ReadAccess: + headers = dict( + zip(result["Headers"]["Keys"], result["Headers"]["Values"], strict=False) + ) + return _ReadAccess(result["Uri"], headers, result["RequiresAuth"]) diff --git a/packages/uipath-platform/tests/services/test_buckets_service.py b/packages/uipath-platform/tests/services/test_buckets_service.py index 2ec273972..ef1ba721d 100644 --- a/packages/uipath-platform/tests/services/test_buckets_service.py +++ b/packages/uipath-platform/tests/services/test_buckets_service.py @@ -1,10 +1,31 @@ +import io import os +import traceback from pathlib import Path +from typing import Any, Optional +import httpx import pytest -from pytest_httpx import HTTPXMock +from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, +) +from pytest_httpx import HTTPXMock, IteratorStream +from tenacity import wait_none from uipath.platform import UiPathApiConfig, UiPathExecutionContext +from uipath.platform.common._base_service import BaseService +from uipath.platform.common.retry import ( + extract_retry_after_from_chain, + is_retryable_platform_exception, +) +from uipath.platform.errors import ( + BucketFileChangedError, + BucketFileReadError, + EnrichedException, +) from uipath.platform.orchestrator._buckets_service import BucketsService @@ -2037,3 +2058,674 @@ def test_combined_max_skip_and_top( ) result = service.list(skip=10000, top=1000) assert result is not None + + +class TestOpen: + BUCKET_KEY = "bucket-key" + BLOB_FILE_PATH = "loans/loan-123.pdf" + BLOB_URL = "https://test-storage.com/loans/loan-123.pdf" + UPLOAD_URL = "https://test-du.com/digitization/start" + CONTENT = b"%PDF-1.7\n" + bytes(range(256)) * 1024 # spans several 64 KiB chunks + ETAG = {"ETag": '"v1"'} + + @pytest.fixture + def read_uri_url(self, base_url: str, org: str, tenant: str) -> str: + return ( + f"{base_url}{org}{tenant}/orchestrator_/odata/Buckets(123)" + f"/UiPath.Server.Configuration.OData.GetReadUri?path={self.BLOB_FILE_PATH}" + ) + + @pytest.fixture + def orchestrator( + self, + httpx_mock: HTTPXMock, + base_url: str, + org: str, + tenant: str, + read_uri_url: str, + ): + """Mock the bucket lookup and the read-URL lookups for the file.""" + + def mock( + *, + requires_auth: bool = False, + read_uri_lookups: int = 1, + uri: Optional[str] = None, + ) -> None: + httpx_mock.add_response( + url=f"{base_url}{org}{tenant}/orchestrator_/odata/Buckets/UiPath.Server.Configuration.OData.GetByKey(identifier='{self.BUCKET_KEY}')", + json={ + "value": [{"Id": 123, "Name": "Loans", "Identifier": "bucket-key"}] + }, + ) + for _ in range(read_uri_lookups): + httpx_mock.add_response( + url=read_uri_url, + json={ + "Uri": uri or self.BLOB_URL, + "Headers": { + "Keys": ["x-ms-blob-type"], + "Values": ["BlockBlob"], + }, + "RequiresAuth": requires_auth, + }, + ) + + return mock + + @pytest.fixture + def http_spans(self, httpx_mock: HTTPXMock): + """The spans of httpx instrumentation, as the agents runtime sets it up. + + Instrumented after `httpx_mock`, so that it wraps the mocked transport. + """ + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + instrumentor = HTTPXClientInstrumentor() + instrumentor.instrument(tracer_provider=provider) + try: + yield exporter + finally: + instrumentor.uninstrument() + + def open(self, service: BucketsService): + return service.open(key=self.BUCKET_KEY, blob_file_path=self.BLOB_FILE_PATH) + + def test_reads_the_file_from_one_download( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + assert file.name == "loan-123.pdf" + assert file.read() == self.CONTENT + + [download] = httpx_mock.get_requests(url=self.BLOB_URL) + assert "range" not in download.headers + assert "authorization" not in download.headers + assert download.headers["accept-encoding"] == "identity" + assert download.headers["x-ms-blob-type"] == "BlockBlob" + + def test_the_read_url_is_looked_up_when_the_download_starts( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, + ): + """A URL looked up by open() could expire before the first read.""" + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + assert httpx_mock.get_requests(url=read_uri_url) == [] + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=read_uri_url)) == 1 + + def test_the_size_comes_from_the_download_the_read_continues( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + assert file.seek(0, os.SEEK_END) == len(self.CONTENT) + file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 1 + + def test_rewinding_downloads_again_from_a_new_url( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, + ): + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT, is_reusable=True + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + assert len(httpx_mock.get_requests(url=read_uri_url)) == 2 + + def test_seeking_ahead_downloads_a_range( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={"Content-Range": f"bytes {start}-{size - 1}/{size}"}, + content=self.CONTENT[start:], + ) + + with self.open(service) as file: + file.seek(start) + assert file.read() == self.CONTENT[start:] + assert file.seek(0, os.SEEK_END) == size + + def test_seeking_ahead_when_the_storage_ignores_the_range( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + start = 70_000 + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + content=self.CONTENT, + ) + + with self.open(service) as file: + file.seek(start) + assert file.read() == self.CONTENT[start:] + + def test_storage_that_requires_auth_gets_the_platform_credentials( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + secret: str, + ): + orchestrator(requires_auth=True) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + assert file.read() == self.CONTENT + + [download] = httpx_mock.get_requests(url=self.BLOB_URL) + assert download.headers["authorization"] == f"Bearer {secret}" + + def test_a_failed_download_raises( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, status_code=404, text="BlobNotFound") + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + + assert error.value.status_code == 404 + + def test_a_download_is_not_retried_by_the_reader( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """Whoever reads the file retries, so a storage 503 is retried at one layer.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response(url=self.BLOB_URL, status_code=503) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + assert error.value.status_code == 503 + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 1 + assert file.read() == self.CONTENT # the caller's retry + + def test_uploads_with_its_size_and_resends_whole_on_retry( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """The way `sdk.documents` uploads it: httpx `files=`, sent again on a retry.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT, is_reusable=True + ) + httpx_mock.add_response(url=self.UPLOAD_URL, method="POST", status_code=503) + httpx_mock.add_response(url=self.UPLOAD_URL, method="POST") + + with self.open(service) as file, httpx.Client() as client: + for status_code in (503, 200): + response = client.post(self.UPLOAD_URL, files={"File": file}) + assert response.status_code == status_code + + uploads = httpx_mock.get_requests(url=self.UPLOAD_URL) + assert len(uploads) == 2 + for upload in uploads: + body = upload.read() + assert "transfer-encoding" not in upload.headers + assert int(upload.headers["content-length"]) == len(body) + assert self.CONTENT in body + assert b'filename="loan-123.pdf"' in body + assert b"Content-Type: application/pdf" in body + + def test_a_failed_download_is_started_again_by_the_next_read( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """A rewind after a failure before the first chunk must not read as the end.""" + + class ResetBeforeFirstChunk(httpx.SyncByteStream): + def __iter__(self): + raise httpx.ReadError("connection reset") + yield b"" # makes this a generator + + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, + headers={**self.ETAG, "Content-Length": str(len(self.CONTENT))}, + stream=ResetBeforeFirstChunk(), + ) + httpx_mock.add_response( + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT + ) + + with self.open(service) as file: + with pytest.raises(BucketFileReadError, match="loan-123.pdf") as error: + file.read() + assert isinstance(error.value.__cause__, httpx.ReadError) + file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + + def test_without_a_reported_size_the_end_is_found_by_reading( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response( + url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + ) + + with self.open(service) as file: + with pytest.raises(io.UnsupportedOperation): # no size reported yet + file.seek(0, os.SEEK_END) + assert file.read() == self.CONTENT + assert file.read() == b"" + assert file.seek(0, os.SEEK_END) == len(self.CONTENT) + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 1 + + def test_reading_past_the_end_before_any_read_returns_nothing( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + size = len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={size + 10}-"}, + status_code=416, + headers={"Content-Range": f"bytes */{size}"}, + ) + + with self.open(service) as file: + file.seek(size + 10) + assert file.read() == b"" + assert file.seek(0, os.SEEK_END) == size + + def test_storage_that_requires_auth_gets_the_current_token( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + monkeypatch: pytest.MonkeyPatch, + ): + """A token renewed during the job replaces the one the client was built with.""" + orchestrator(requires_auth=True) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + service._config.secret_from_environment = True + monkeypatch.setattr(service, "_current_secret", lambda: "renewed-token") + + with self.open(service) as file: + assert file.read() == self.CONTENT + + [download] = httpx_mock.get_requests(url=self.BLOB_URL) + assert download.headers["authorization"] == "Bearer renewed-token" + + @pytest.mark.parametrize( + "replacement", + [ + pytest.param({"ETag": '"v2"'}, id="new-etag"), + pytest.param({"ETag": '"v1"', "size": 999}, id="new-size"), + ], + ) + def test_a_file_replaced_in_the_bucket_fails_the_next_download( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + replacement: dict[str, Any], + ): + """A rewind or retried upload must not cut off or mix two versions.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, headers={"ETag": '"v1"'}, content=self.CONTENT + ) + httpx_mock.add_response( + url=self.BLOB_URL, + headers={"ETag": replacement["ETag"]}, + content=b"%" * replacement.get("size", len(self.CONTENT) + 10), + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + with pytest.raises(BucketFileChangedError, match="loan-123.pdf"): + file.read() + + def test_a_later_download_gives_the_size_when_the_first_did_not( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator(read_uri_lookups=2) + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, headers=self.ETAG, stream=IteratorStream([self.CONTENT]) + ) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={**self.ETAG, "Content-Range": f"bytes {start}-{size - 1}/{size}"}, + content=self.CONTENT[start:], + ) + + with self.open(service) as file: + assert file.read(10) == self.CONTENT[:10] + with pytest.raises(io.UnsupportedOperation): # no size reported yet + file.seek(0, os.SEEK_END) + file.seek(start) + assert file.read(10) == self.CONTENT[start : start + 10] + # Known from the 206's Content-Range, before reaching the end. + assert file.seek(0, os.SEEK_END) == size + + def test_an_error_response_is_closed_when_reading_its_body_fails( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + class TimesOutWhileReading(httpx.SyncByteStream): + closed = False + + def __iter__(self): + raise httpx.ReadTimeout("timed out reading the error body") + yield b"" # makes this a generator + + def close(self): + self.closed = True + + orchestrator() + body = TimesOutWhileReading() + httpx_mock.add_response(url=self.BLOB_URL, status_code=503, stream=body) + + with self.open(service) as file: + with pytest.raises(BucketFileReadError) as error: + file.read() + + assert isinstance(error.value.__cause__, httpx.ReadTimeout) + assert body.closed + + def test_a_failed_download_keeps_the_signature_out_of_the_error( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """The query string of a read URL is its signature, which gives access.""" + signed_url = f"{self.BLOB_URL}?sv=2024&se=2099&sig=SECRET" + orchestrator(uri=signed_url) + httpx_mock.add_response( + url=signed_url, status_code=503, headers={"Retry-After": "7"} + ) + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + + assert "SECRET" not in "".join(traceback.format_exception(error.value)) + assert error.value.url == self.BLOB_URL + cause = error.value.__cause__ + assert isinstance(cause, httpx.HTTPStatusError) + assert cause.request.url == self.BLOB_URL + # What the retry of whoever reads the file needs. + assert error.value.status_code == 503 + assert is_retryable_platform_exception(error.value) + assert extract_retry_after_from_chain(error.value) == 7 + + @pytest.mark.parametrize("status_code", [200, 403]) + def test_the_signature_stays_out_of_http_spans( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + http_spans: InMemorySpanExporter, + status_code: int, + ): + """HTTP client spans record the URL; OTel redacts `sig`, not every signature.""" + signed_url = f"{self.BLOB_URL}?X-Amz-Credential=KEY&X-Amz-Signature=SECRET" + orchestrator(uri=signed_url) + httpx_mock.add_response( + url=signed_url, status_code=status_code, content=self.CONTENT + ) + + with self.open(service) as file: + if status_code == 200: + assert file.read() == self.CONTENT + else: + with pytest.raises(EnrichedException): + file.read() + + spans = [span.to_json() for span in http_spans.get_finished_spans()] + # The other requests are traced: the instrumentation is on. + assert any("GetReadUri" in span for span in spans) + assert not any("SECRET" in span for span in spans) + + def test_the_read_url_lookup_is_not_retried_by_the_reader( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, + ): + """Whoever reads the file retries, so a lookup 503 is retried at one layer.""" + orchestrator(read_uri_lookups=0) + httpx_mock.add_response( + url=read_uri_url, status_code=503, headers={"Retry-After": "0"} + ) + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + + assert error.value.status_code == 503 + assert len(httpx_mock.get_requests(url=read_uri_url)) == 1 + + def test_a_lookup_failure_is_retried_at_one_layer_by_an_upload( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, + ): + """The upload's five attempts make five lookups, not five each.""" + orchestrator(read_uri_lookups=0) + httpx_mock.add_response( + url=read_uri_url, + status_code=503, + headers={"Retry-After": "0"}, + is_reusable=True, + ) + + with self.open(service) as file: + with pytest.raises(EnrichedException): + service.request( + "POST", "/du_/api/digitization/start", files={"File": file} + ) + + assert len(httpx_mock.get_requests(url=read_uri_url)) == 5 + + def test_an_upload_retries_a_dropped_download_with_the_whole_file( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + base_url: str, + org: str, + tenant: str, + monkeypatch: pytest.MonkeyPatch, + ): + """A platform upload, as `sdk.documents` makes, sends the file again.""" + + class ResetAfterFirstChunk(httpx.SyncByteStream): + def __init__(self, content: bytes): + self.content = content + + def __iter__(self): + yield self.content[:1000] + raise httpx.ReadError("connection reset") + + monkeypatch.setattr(BaseService.request.retry, "wait", wait_none()) # type: ignore[attr-defined] + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, + headers={**self.ETAG, "Content-Length": str(len(self.CONTENT))}, + stream=ResetAfterFirstChunk(self.CONTENT), + ) + httpx_mock.add_response( + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT + ) + upload_url = f"{base_url}{org}{tenant}/du_/api/digitization/start" + httpx_mock.add_response(url=upload_url, method="POST", is_reusable=True) + + with self.open(service) as file: + service.request("POST", "/du_/api/digitization/start", files={"File": file}) + + upload = httpx_mock.get_requests(url=upload_url)[-1] + body = upload.read() + assert int(upload.headers["content-length"]) == len(body) + assert self.CONTENT in body + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + + def test_a_download_that_ends_before_the_end_of_the_file_raises( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """A storage can send less of the file than the range asked for.""" + orchestrator() + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={ + **self.ETAG, + "Content-Range": f"bytes {start}-{start + 999}/{size}", + }, + content=self.CONTENT[start : start + 1000], + ) + + with self.open(service) as file: + file.seek(start) + with pytest.raises(BucketFileReadError, match="before the end of the file"): + file.read() + + def test_without_an_etag_a_rewind_downloads_the_whole_file_again( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """A download from the start has the whole file, so it can't mix versions.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, content=self.CONTENT, is_reusable=True + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + + def test_without_an_etag_the_file_is_not_downloaded_again_from_the_middle( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """Bytes of two versions of the same size can't be told apart.""" + orchestrator(read_uri_lookups=2) + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={"Content-Range": f"bytes {start}-{size - 1}/{size}"}, + content=self.CONTENT[start:], + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(start) + with pytest.raises(BucketFileChangedError) as error: + file.read() + + assert not error.value.verified + assert "ETag" in str(error.value) + + @pytest.mark.parametrize( + "replacement", + [ + pytest.param(CONTENT + b"%" * 10, id="larger"), + pytest.param(CONTENT[:-10], id="shorter"), + ], + ) + def test_without_an_etag_or_size_a_replacement_of_another_length_fails( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + replacement: bytes, + ): + """The length is checked as the download is read: neither cut nor short.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + ) + httpx_mock.add_response(url=self.BLOB_URL, stream=IteratorStream([replacement])) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + with pytest.raises(BucketFileChangedError) as error: + file.read() + + assert error.value.verified + + def test_an_upload_retries_a_dropped_download_without_a_version_or_size( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + base_url: str, + org: str, + tenant: str, + monkeypatch: pytest.MonkeyPatch, + ): + """A storage that streams with no ETag or size still gets the retry.""" + + class ResetAfterFirstChunk(httpx.SyncByteStream): + def __init__(self, content: bytes): + self.content = content + + def __iter__(self): + yield self.content[:1000] + raise httpx.ReadError("connection reset") + + monkeypatch.setattr(BaseService.request.retry, "wait", wait_none()) # type: ignore[attr-defined] + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, stream=ResetAfterFirstChunk(self.CONTENT) + ) + httpx_mock.add_response( + url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + ) + upload_url = f"{base_url}{org}{tenant}/du_/api/digitization/start" + httpx_mock.add_response(url=upload_url, method="POST", is_reusable=True) + + with self.open(service) as file: + service.request("POST", "/du_/api/digitization/start", files={"File": file}) + + upload = httpx_mock.get_requests(url=upload_url)[-1] + assert upload.headers["transfer-encoding"] == "chunked" # no size to send + assert self.CONTENT in upload.read() + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 diff --git a/packages/uipath-platform/tests/services/test_retry.py b/packages/uipath-platform/tests/services/test_retry.py index f9a4e7741..f1e433ca2 100644 --- a/packages/uipath-platform/tests/services/test_retry.py +++ b/packages/uipath-platform/tests/services/test_retry.py @@ -12,7 +12,7 @@ parse_retry_after, platform_wait_strategy, ) -from uipath.platform.errors import EnrichedException +from uipath.platform.errors import BucketFileReadError, EnrichedException class TestParseRetryAfter: @@ -154,6 +154,17 @@ def test_connect_error(self): err = httpx.ConnectError("[Errno 104] Connection reset by peer") assert is_retryable_platform_exception(err) is True + def test_bucket_file_read_error(self): + """The request sending the file was cut short, so it can be sent again.""" + err = BucketFileReadError("loan-123.pdf") + err.__cause__ = httpx.ReadError("connection reset") + assert is_retryable_platform_exception(err) is True + + def test_read_error_not_retryable(self): + """The service may have the request: only a source read failure retries.""" + err = httpx.ReadError("connection reset") + assert is_retryable_platform_exception(err) is False + def test_enriched_408(self): http_err = _make_http_status_error(408) err = EnrichedException(http_err) diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index 6e32115d0..2bc5a556e 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -472,6 +472,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] +[[package]] +name = "opentelemetry-instrumentation-httpx" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "opentelemetry-util-http" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/43/3204ca7e7d91bd9e1b569a98a5f9252c98ae70ba3bb562d2770c34e21d49/opentelemetry_instrumentation_httpx-0.66b2.tar.gz", hash = "sha256:b4c81e4a6dc7b8d7cb2d3088eb8848f6db6bd4abdc443ac9586ec176f1460187", size = 26638, upload-time = "2026-10-29T17:38:31.46Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/40/37d6161dcd95285c9c3eb75e2dbeb1dbc6e868551532735374918a22e298/opentelemetry_instrumentation_httpx-0.66b2-py3-none-any.whl", hash = "sha256:93e2b6ab1a505d76ec3d98abcf7e8527d4712167d6c3b5ebbb9c68d9309d9ba5", size = 17723, upload-time = "2026-10-29T17:37:33.735Z" }, +] + [[package]] name = "opentelemetry-sdk" version = "1.45.2" @@ -499,6 +515,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] +[[package]] +name = "opentelemetry-util-http" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/57/33566966a7bced4d02fbc672f92029184e4a743f5b531e44b4c0dc4c999b/opentelemetry_util_http-0.66b2.tar.gz", hash = "sha256:7ba066ea609202e474679ddf1d0f753a1e6619bd206b36afaecba4bbb86e25d0", size = 11587, upload-time = "2026-10-29T17:38:56.043Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/8d/39885564eefa43f6181acfa3d698af2f6b5fe3e64c86dce3f1b955f6397f/opentelemetry_util_http-0.66b2-py3-none-any.whl", hash = "sha256:c4bb5d6744e60353bcaa3e325bc529a1515346b51cb4d9c8e5b730579337e06d", size = 8383, upload-time = "2026-10-29T17:38:07.462Z" }, +] + [[package]] name = "outcome" version = "1.3.0.post0" @@ -1091,7 +1116,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "." } dependencies = [ { name = "anyio" }, @@ -1108,6 +1133,7 @@ dependencies = [ dev = [ { name = "bandit" }, { name = "mypy" }, + { name = "opentelemetry-instrumentation-httpx" }, { name = "pre-commit" }, { name = "pytest" }, { name = "pytest-asyncio" }, @@ -1136,6 +1162,7 @@ requires-dist = [ dev = [ { name = "bandit", specifier = ">=1.8.2" }, { name = "mypy", specifier = ">=1.19.0" }, + { name = "opentelemetry-instrumentation-httpx", specifier = ">=0.60b0" }, { name = "pre-commit", specifier = ">=4.1.0" }, { name = "pytest", specifier = ">=7.4.0" }, { name = "pytest-asyncio", specifier = ">=1.0.0" }, diff --git a/packages/uipath/docs/core/functions.md b/packages/uipath/docs/core/functions.md index 598f0df3b..400c70cbb 100644 --- a/packages/uipath/docs/core/functions.md +++ b/packages/uipath/docs/core/functions.md @@ -244,6 +244,19 @@ sdk.buckets.upload( ) ``` +To pass a bucket file on without saving it first, open it. It is downloaded as it is read, so a large file uses neither disk nor memory: + +```python +with sdk.buckets.open( + name="Invoices", + blob_file_path="incoming/acme-001.pdf", + folder_path="Shared", +) as file: + extraction = sdk.documents.start_ixp_extraction( + project_name="Invoices", tag="live", file=file + ) +``` + See [Buckets](./buckets.md) for the full API reference. ### Connections diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index ee06f3d06..9f4febbbf 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" }, @@ -2912,6 +2912,7 @@ requires-dist = [ dev = [ { name = "bandit", specifier = ">=1.8.2" }, { name = "mypy", specifier = ">=1.19.0" }, + { name = "opentelemetry-instrumentation-httpx", specifier = ">=0.60b0" }, { name = "pre-commit", specifier = ">=4.1.0" }, { name = "pytest", specifier = ">=7.4.0" }, { name = "pytest-asyncio", specifier = ">=1.0.0" },