From e90fd7b933c43bc24a49dee3850c72c7e2298cf5 Mon Sep 17 00:00:00 2001 From: paul-ciobanu Date: Fri, 27 Nov 2026 13:27:58 +0200 Subject: [PATCH] feat(documents): stream a document to digitization with no local copy Add a `file_stream: StreamingFile` input to start_ixp_extraction, classify and extract (sync and async). The SDK uploads the document to digitization/start while it reads the source, so the caller needs no local copy and memory use stays flat. - StreamingFile has a name, a size, a content type and an `open` callable that returns sync or async byte chunks. Each attempt calls `open` again and reads from byte 0. - The multipart body is built by hand with a known Content-Length, so the upload is not sent with chunked transfer encoding. - Retryable errors (connect, timeout, 408, 429, 502, 503, 504, 524) retry the upload with a new body. Other errors are not retried. - A source that yields more or fewer bytes than its size fails with a ValueError, and the upload is not retried. - BaseService gets _request_once and _request_once_async: one attempt, no retry. request and request_async call them and do not change. - uipath-platform 0.3.21 -> 0.3.22. Co-Authored-By: Claude Opus 5.5 --- packages/uipath-platform/pyproject.toml | 2 +- .../uipath/platform/common/_base_service.py | 48 +- .../src/uipath/platform/documents/__init__.py | 4 + .../platform/documents/_documents_service.py | 130 +++- .../platform/documents/_streaming_upload.py | 138 +++++ .../uipath/platform/documents/documents.py | 61 +- .../tests/services/test_base_service.py | 32 + .../tests/services/test_documents_service.py | 12 +- .../test_documents_streaming_upload.py | 561 ++++++++++++++++++ packages/uipath-platform/uv.lock | 2 +- packages/uipath/uv.lock | 2 +- 11 files changed, 971 insertions(+), 21 deletions(-) create mode 100644 packages/uipath-platform/src/uipath/platform/documents/_streaming_upload.py create mode 100644 packages/uipath-platform/tests/services/test_documents_streaming_upload.py diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index 7be2bf4af..611fea927 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.21" +version = "0.3.22" description = "HTTP client library for programmatic access to UiPath Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath-platform/src/uipath/platform/common/_base_service.py b/packages/uipath-platform/src/uipath/platform/common/_base_service.py index cc875bfa6..740eaf053 100644 --- a/packages/uipath-platform/src/uipath/platform/common/_base_service.py +++ b/packages/uipath-platform/src/uipath/platform/common/_base_service.py @@ -212,10 +212,36 @@ def request( scoped: Literal["org", "tenant"] = "tenant", **kwargs: Any, ) -> Response: + # Resolved here, not in `_request_once`: the caller lookup walks only a + # few frames, and the extra method would use one of them. + return self._request_once( + method, + url, + scoped=scoped, + caller_component=_get_caller_component(), + **kwargs, + ) + + def _request_once( + self, + method: str, + url: URL | str, + *, + scoped: Literal["org", "tenant"] = "tenant", + caller_component: str | None = None, + **kwargs: Any, + ) -> Response: + """Send one request, with no retry. + + For a body that cannot be sent twice, such as a generator: the caller + retries and builds a new body for each attempt. + """ self._logger.debug(f"Request: {method} {url}") self._logger.debug(f"HEADERS: {kwargs.get('headers', self._client.headers)}") - specific_component = _get_caller_component() + specific_component = ( + _get_caller_component() if caller_component is None else caller_component + ) # Copy: never write into the caller's dict. kwargs["headers"] = dict(kwargs.get("headers") or {}) @@ -257,6 +283,24 @@ async def request_async( scoped: Literal["org", "tenant"] = "tenant", **kwargs: Any, ) -> Response: + return await self._request_once_async( + method, + url, + scoped=scoped, + caller_component=self._specific_component, + **kwargs, + ) + + async def _request_once_async( + self, + method: str, + url: URL | str, + *, + scoped: Literal["org", "tenant"] = "tenant", + caller_component: str | None = None, + **kwargs: Any, + ) -> Response: + """Asynchronous version of `_request_once`: one request, with no retry.""" self._logger.debug(f"Request: {method} {url}") self._logger.debug( f"HEADERS: {kwargs.get('headers', self._client_async.headers)}" @@ -265,7 +309,7 @@ async def request_async( # Copy: never write into the caller's dict. kwargs["headers"] = dict(kwargs.get("headers") or {}) kwargs["headers"][HEADER_USER_AGENT] = user_agent_value( - self._specific_component + self._specific_component if caller_component is None else caller_component ) _inject_trace_context(kwargs["headers"]) self._add_authorization(kwargs["headers"]) diff --git a/packages/uipath-platform/src/uipath/platform/documents/__init__.py b/packages/uipath-platform/src/uipath/platform/documents/__init__.py index 0b522e182..2a1695653 100644 --- a/packages/uipath-platform/src/uipath/platform/documents/__init__.py +++ b/packages/uipath-platform/src/uipath/platform/documents/__init__.py @@ -16,12 +16,14 @@ FieldGroupValueProjection, FieldType, FieldValueProjection, + FileChunks, FileContent, ProjectType, Reference, StartExtractionResponse, StartExtractionValidationResponse, StartOperationResponse, + StreamingFile, ValidateClassificationAction, ValidateExtractionAction, ValidationAction, @@ -46,6 +48,8 @@ "ClassificationResult", "ClassificationResponse", "FileContent", + "FileChunks", + "StreamingFile", "StartExtractionResponse", "StartOperationResponse", "StartExtractionValidationResponse", diff --git a/packages/uipath-platform/src/uipath/platform/documents/_documents_service.py b/packages/uipath-platform/src/uipath/platform/documents/_documents_service.py index 0357ea20a..aabe024f5 100644 --- a/packages/uipath-platform/src/uipath/platform/documents/_documents_service.py +++ b/packages/uipath-platform/src/uipath/platform/documents/_documents_service.py @@ -7,6 +7,12 @@ from urllib.parse import quote from uuid import UUID +from tenacity import ( + AsyncRetrying, + Retrying, + retry_if_exception, + stop_after_attempt, +) from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -15,7 +21,13 @@ from ..common._execution_context import UiPathExecutionContext from ..common._folder_context import FolderContext from ..common._models import Endpoint +from ..common.retry import ( + MAX_RETRY_ATTEMPTS, + is_retryable_platform_exception, + platform_wait_strategy, +) from ..errors import OperationFailedException, OperationNotCompleteException +from ._streaming_upload import MultipartLayout, aiter_body, iter_body, multipart_layout from .documents import ( ActionPriority, ClassificationResponse, @@ -26,10 +38,20 @@ ProjectType, StartExtractionResponse, StartExtractionValidationResponse, + StreamingFile, ValidateClassificationAction, ValidateExtractionAction, ) +# Same rules as BaseService.request, applied to the whole upload so that every +# attempt reads the StreamingFile again from its first byte. +_STREAMING_UPLOAD_RETRY: Dict[str, Any] = { + "retry": retry_if_exception(is_retryable_platform_exception), + "wait": platform_wait_strategy, + "stop": stop_after_attempt(MAX_RETRY_ATTEMPTS), + "reraise": True, +} + POLLING_INTERVAL = 2 # seconds POLLING_TIMEOUT = 300 # seconds @@ -124,8 +146,11 @@ def _validate_classify_params( project_name: Optional[str], file: Optional[FileContent], file_path: Optional[str], + file_stream: Optional[StreamingFile] = None, ) -> None: - _exactly_one_must_be_provided(file=file, file_path=file_path) + _exactly_one_must_be_provided( + file=file, file_path=file_path, file_stream=file_stream + ) if project_type == ProjectType.PRETRAINED: _must_not_be_provided( project_name=project_name, @@ -148,9 +173,12 @@ def _validate_extract_params_and_get_project_type( classification_result: Optional[ClassificationResult], project_type: Optional[ProjectType], document_type_name: Optional[str], + file_stream: Optional[StreamingFile] = None, ) -> ProjectType: - if file or file_path: - _exactly_one_must_be_provided(file=file, file_path=file_path) + if file or file_path or file_stream is not None: + _exactly_one_must_be_provided( + file=file, file_path=file_path, file_stream=file_stream + ) _must_be_provided(project_type=project_type) _must_not_be_provided( classification_result=classification_result, @@ -178,6 +206,7 @@ def _validate_extract_params_and_get_project_type( project_type=project_type, file=file, file_path=file_path, + file_stream=file_stream, document_type_name=document_type_name, ) project_type = classification_result.project_type @@ -463,6 +492,7 @@ def _get_document_id( file: Optional[FileContent], file_path: Optional[str], classification_result: Optional[ClassificationResult], + file_stream: Optional[StreamingFile] = None, ) -> str: if classification_result is not None: return classification_result.document_id @@ -471,6 +501,7 @@ def _get_document_id( project_id=project_id, file=file, file_path=file_path, + file_stream=file_stream, ) self._wait_for_digitization( project_id=project_id, @@ -485,6 +516,7 @@ async def _get_document_id_async( file: Optional[FileContent], file_path: Optional[str], classification_result: Optional[ClassificationResult], + file_stream: Optional[StreamingFile] = None, ) -> str: if classification_result is not None: return classification_result.document_id @@ -493,6 +525,7 @@ async def _get_document_id_async( project_id=project_id, file=file, file_path=file_path, + file_stream=file_stream, ) await self._wait_for_digitization_async( project_id=project_id, @@ -607,12 +640,61 @@ async def _get_tag_async( return tag + def _digitization_stream_headers(self, layout: MultipartLayout) -> Dict[str, str]: + # An explicit Content-Length keeps httpx from switching to chunked encoding. + return { + **self._get_common_headers(), + "Content-Type": layout.content_type, + "Content-Length": str(layout.content_length), + } + + def _start_digitization_stream( + self, project_id: str, file_stream: StreamingFile + ) -> str: + layout = multipart_layout(file_stream, field_name="File") + for attempt in Retrying(**_STREAMING_UPLOAD_RETRY): + with attempt: + body = iter_body(layout, file_stream) + try: + response = self._request_once( + "POST", + url=_framework_url(project_id, "digitization", "start"), + params={"api-version": self._api_version}, + headers=self._digitization_stream_headers(layout), + content=body, + ) + finally: + body.close() + return _camel_case_keys(response.json())["documentId"] + + async def _start_digitization_stream_async( + self, project_id: str, file_stream: StreamingFile + ) -> str: + layout = multipart_layout(file_stream, field_name="File") + async for attempt in AsyncRetrying(**_STREAMING_UPLOAD_RETRY): + with attempt: + body = aiter_body(layout, file_stream) + try: + response = await self._request_once_async( + "POST", + url=_framework_url(project_id, "digitization", "start"), + params={"api-version": self._api_version}, + headers=self._digitization_stream_headers(layout), + content=body, + ) + finally: + await body.aclose() + return _camel_case_keys(response.json())["documentId"] + def _start_digitization( self, project_id: str, file: Optional[FileContent] = None, file_path: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> str: + if file_stream is not None: + return self._start_digitization_stream(project_id, file_stream) with open(Path(file_path), "rb") if file_path else nullcontext(file) as handle: return self._request_json( "POST", @@ -627,7 +709,10 @@ async def _start_digitization_async( project_id: str, file: Optional[FileContent] = None, file_path: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> str: + if file_stream is not None: + return await self._start_digitization_stream_async(project_id, file_stream) with open(Path(file_path), "rb") if file_path else nullcontext(file) as handle: return ( await self._request_json_async( @@ -1084,6 +1169,7 @@ def classify( project_name: Optional[str] = None, file: Optional[FileContent] = None, file_path: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> List[ClassificationResult]: """Classify a document using a DU Modern project. @@ -1094,9 +1180,11 @@ def classify( version (int, optional): Version of the published project. It can be used instead of `tag`. file (FileContent, optional): The document file to be classified. file_path (str, optional): Path to the document file to be classified. + file_stream (StreamingFile, optional): A document uploaded while it is + read from its source, with no local copy. See `StreamingFile`. Note: - Either `file` or `file_path` must be provided, but not both. + Exactly one of `file`, `file_path` or `file_stream` must be provided. Returns: List[ClassificationResult]: A list of classification results. @@ -1126,6 +1214,7 @@ def classify( project_name=project_name, file=file, file_path=file_path, + file_stream=file_stream, ) project_id = self._get_project_id( @@ -1139,6 +1228,7 @@ def classify( file=file, file_path=file_path, classification_result=None, + file_stream=file_stream, ) classifier_id = self._get_classifier_id( @@ -1177,6 +1267,7 @@ async def classify_async( project_name: Optional[str] = None, file: Optional[FileContent] = None, file_path: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> List[ClassificationResult]: """Asynchronously version of the [`classify`][uipath.platform.documents._documents_service.DocumentsService.classify] method.""" _validate_classify_params( @@ -1186,6 +1277,7 @@ async def classify_async( project_name=project_name, file=file, file_path=file_path, + file_stream=file_stream, ) project_id = await self._get_project_id_async( @@ -1199,6 +1291,7 @@ async def classify_async( file=file, file_path=file_path, classification_result=None, + file_stream=file_stream, ) classifier_id = await self._get_classifier_id_async( @@ -1235,6 +1328,7 @@ def start_ixp_extraction( tag: str, file: Optional[FileContent] = None, file_path: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> StartExtractionResponse: """Start an IXP extraction process without waiting for results (non-blocking). @@ -1247,9 +1341,13 @@ def start_ixp_extraction( tag (str): Tag of the published project version (e.g., "staging"). file (FileContent, optional): The document file to be processed. file_path (str, optional): Path to the document file to be processed. + file_stream (StreamingFile, optional): A document uploaded while it is + read from its source, with no local copy. Its `open` must return an + `Iterable[bytes]` here; the async method also accepts an + `AsyncIterable[bytes]`. Each upload attempt calls `open` again. Note: - Either `file` or `file_path` must be provided, but not both. + Exactly one of `file`, `file_path` or `file_stream` must be provided. Returns: ExtractionStartResponse: Contains the operation_id, document_id, project_id, and tag @@ -1264,7 +1362,9 @@ def start_ixp_extraction( # start_response.operation_id can be used to poll for results later ``` """ - _exactly_one_must_be_provided(file=file, file_path=file_path) + _exactly_one_must_be_provided( + file=file, file_path=file_path, file_stream=file_stream + ) project_id = self._get_project_id( project_type=ProjectType.IXP, @@ -1276,6 +1376,7 @@ def start_ixp_extraction( project_id=project_id, file=file, file_path=file_path, + file_stream=file_stream, ) return self._start_extraction( @@ -1293,9 +1394,12 @@ async def start_ixp_extraction_async( tag: str, file: Optional[FileContent] = None, file_path: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> StartExtractionResponse: """Asynchronous version of the [`start_ixp_extraction`][uipath.platform.documents._documents_service.DocumentsService.start_ixp_extraction] method.""" - _exactly_one_must_be_provided(file=file, file_path=file_path) + _exactly_one_must_be_provided( + file=file, file_path=file_path, file_stream=file_stream + ) project_id = await self._get_project_id_async( project_type=ProjectType.IXP, @@ -1307,6 +1411,7 @@ async def start_ixp_extraction_async( project_id=project_id, file=file, file_path=file_path, + file_stream=file_stream, ) return await self._start_extraction_async( @@ -1453,6 +1558,7 @@ def extract( classification_result: Optional[ClassificationResult] = None, project_type: Optional[ProjectType] = None, document_type_name: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> Union[ExtractionResponse, ExtractionResponseIXP]: """Extract predicted data from a document using an DU Modern/IXP project. @@ -1462,12 +1568,13 @@ def extract( version (int, optional): Version of the published project. It can be used instead of `tag`. file (FileContent, optional): The document file to be processed. Must be provided if `classification_result` is not provided. file_path (str, optional): Path to the document file to be processed. Must be provided if `classification_result` is not provided. + file_stream (StreamingFile, optional): A document uploaded while it is read from its source, with no local copy. It can be used instead of `file` or `file_path`. See `StreamingFile`. project_type (ProjectType, optional): Type of the project. Must be provided if `project_name` is provided. document_type_name (str, optional): Document type name associated with the extractor to be used for extraction. Required if `project_type` is `ProjectType.MODERN` and `project_name` is provided. - classification_result (ClassificationResult, optional): The classification result obtained from a previous classification step. If provided, `project_name`, `project_type`, `file`, `file_path`, and `document_type_name` must not be provided. + classification_result (ClassificationResult, optional): The classification result obtained from a previous classification step. If provided, `project_name`, `project_type`, `file`, `file_path`, `file_stream`, and `document_type_name` must not be provided. Note: - Either `file` or `file_path` must be provided, but not both. + Exactly one of `file`, `file_path` or `file_stream` must be provided, unless `classification_result` is provided. Returns: Union[ExtractionResponse, ExtractionResponseIXP]: The extraction response containing the extracted data. @@ -1518,6 +1625,7 @@ def extract( classification_result=classification_result, project_type=project_type, document_type_name=document_type_name, + file_stream=file_stream, ) project_id = self._get_project_id( @@ -1546,6 +1654,7 @@ def extract( file=file, file_path=file_path, classification_result=classification_result, + file_stream=file_stream, ) document_type_id = self._get_document_type_id( @@ -1590,6 +1699,7 @@ async def extract_async( classification_result: Optional[ClassificationResult] = None, project_type: Optional[ProjectType] = None, document_type_name: Optional[str] = None, + file_stream: Optional[StreamingFile] = None, ) -> Union[ExtractionResponse, ExtractionResponseIXP]: """Asynchronously version of the [`extract`][uipath.platform.documents._documents_service.DocumentsService.extract] method.""" project_type = _validate_extract_params_and_get_project_type( @@ -1601,6 +1711,7 @@ async def extract_async( classification_result=classification_result, project_type=project_type, document_type_name=document_type_name, + file_stream=file_stream, ) project_id = await self._get_project_id_async( @@ -1629,6 +1740,7 @@ async def extract_async( file=file, file_path=file_path, classification_result=classification_result, + file_stream=file_stream, ) document_type_id = await self._get_document_type_id_async( diff --git a/packages/uipath-platform/src/uipath/platform/documents/_streaming_upload.py b/packages/uipath-platform/src/uipath/platform/documents/_streaming_upload.py new file mode 100644 index 000000000..a815bd4cc --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/documents/_streaming_upload.py @@ -0,0 +1,138 @@ +"""Multipart bodies for documents that are uploaded while they are read. + +httpx builds a multipart body from a file object, but it needs `fileno()` or +`seek()` to find the length. A network stream has neither, so httpx falls back to +chunked transfer encoding, and on a retry it cannot rewind the stream. Here the +body is built by hand: the length is known before the first byte is sent, and +each attempt reads the source again from the start. + +The part has the same bytes httpx would write for +`files={"File": (name, content, content_type)}`, so the service sees no change. +""" + +import os +from collections.abc import AsyncGenerator, AsyncIterator, Iterable, Iterator +from dataclasses import dataclass + +from .documents import FileChunks, StreamingFile + +# Same escaping httpx applies to form parameters (HTML5 multipart rules). +_PARAM_REPLACEMENTS = {'"': "%22", "\\": "\\\\", "\r": "%0D", "\n": "%0A"} + + +def _quote_param(value: str) -> str: + return "".join(_PARAM_REPLACEMENTS.get(char, char) for char in value) + + +@dataclass(frozen=True) +class MultipartLayout: + """The fixed parts of a one-file multipart body.""" + + content_type: str + head: bytes + tail: bytes + content_length: int + + +def multipart_layout(source: StreamingFile, field_name: str) -> MultipartLayout: + """Build the boundary, part headers and total length for `source`.""" + boundary = os.urandom(16).hex() + head = ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="{_quote_param(field_name)}"; ' + f'filename="{_quote_param(source.name)}"\r\n' + f"Content-Type: {source.content_type}\r\n" + "\r\n" + ).encode() + tail = f"\r\n--{boundary}--\r\n".encode() + return MultipartLayout( + content_type=f"multipart/form-data; boundary={boundary}", + head=head, + tail=tail, + content_length=len(head) + source.size + len(tail), + ) + + +def _size_error(source: StreamingFile, sent: int) -> ValueError: + return ValueError( + f"StreamingFile '{source.name}' declared {source.size} bytes, " + f"but its source yielded {'more than ' if sent > source.size else ''}{sent}." + ) + + +def iter_body(layout: MultipartLayout, source: StreamingFile) -> Iterator[bytes]: + """Yield one attempt's body. Opens the source, and closes it when done.""" + chunks = source.open() + if not isinstance(chunks, Iterable): + raise TypeError( + "The synchronous methods need a StreamingFile whose `open` returns " + "an Iterable[bytes]. Use the asynchronous method for an async source." + ) + iterator = iter(chunks) + try: + yield layout.head + sent = 0 + for chunk in iterator: + sent += len(chunk) + if sent > source.size: + raise _size_error(source, sent) + if chunk: + yield bytes(chunk) + if sent != source.size: + raise _size_error(source, sent) + yield layout.tail + finally: + close = getattr(iterator, "close", None) + if close is not None: + close() + + +async def aiter_body( + layout: MultipartLayout, source: StreamingFile +) -> AsyncIterator[bytes]: + """Asynchronous version of `iter_body`. Accepts a sync or an async source.""" + chunks: FileChunks = source.open() + reader = _aiter_chunks(chunks) + try: + yield layout.head + sent = 0 + async for chunk in reader: + sent += len(chunk) + if sent > source.size: + raise _size_error(source, sent) + if chunk: + yield bytes(chunk) + if sent != source.size: + raise _size_error(source, sent) + yield layout.tail + finally: + await reader.aclose() + aclose = getattr(chunks, "aclose", None) + close = getattr(chunks, "close", None) + if aclose is not None: + await aclose() + elif close is not None: + close() + + +async def _aiter_chunks(chunks: FileChunks) -> AsyncGenerator[bytes, None]: + if isinstance(chunks, Iterable): + iterator = iter(chunks) + try: + for chunk in iterator: + yield chunk + finally: + if iterator is not chunks: + close = getattr(iterator, "close", None) + if close is not None: + close() + else: + async_iterator = aiter(chunks) + try: + async for chunk in async_iterator: + yield chunk + finally: + if async_iterator is not chunks: + aclose = getattr(async_iterator, "aclose", None) + if aclose is not None: + await aclose() diff --git a/packages/uipath-platform/src/uipath/platform/documents/documents.py b/packages/uipath-platform/src/uipath/platform/documents/documents.py index f21f998d5..92d0032b0 100644 --- a/packages/uipath-platform/src/uipath/platform/documents/documents.py +++ b/packages/uipath-platform/src/uipath/platform/documents/documents.py @@ -3,12 +3,71 @@ from __future__ import annotations from enum import Enum -from typing import IO, Any, List, Literal, Optional, Union +from typing import ( + IO, + Any, + AsyncIterable, + Callable, + Iterable, + List, + Literal, + Optional, + Union, +) from pydantic import BaseModel, ConfigDict, Field FileContent = Union[IO[bytes], bytes, str] +FileChunks = Union[Iterable[bytes], AsyncIterable[bytes]] + + +class StreamingFile(BaseModel): + """A document that is uploaded while it is read, with no local copy. + + Use it to send a document from another service, such as an Orchestrator + bucket, straight to Document Understanding. Nothing holds the whole file in + memory or on disk. + + `open` is called once for each upload attempt, and each call must start the + document from its first byte. A retry therefore reads the source again + instead of sending a stream that is already partly read. + + `size` is sent as the Content-Length of the file part, so it must be the + exact byte count. A source that yields more or fewer bytes fails the upload. + + The synchronous methods accept only an `Iterable[bytes]`. The asynchronous + methods accept an `Iterable[bytes]` or an `AsyncIterable[bytes]`. A + synchronous source blocks the event loop while it waits for each chunk. + + Examples: + ```python + async def read_blob(): + async with client.stream("GET", read_uri) as response: + response.raise_for_status() + async for chunk in response.aiter_bytes(1024 * 1024): + yield chunk + + source = StreamingFile(name="appraisal.pdf", size=57_671_680, open=read_blob) + await uipath.documents.start_ixp_extraction_async( + project_name="MyIXPProjectName", tag="live", file_stream=source + ) + ``` + """ + + model_config = ConfigDict(frozen=True) + + name: str = Field(min_length=1, description="File name sent to the service.") + size: int = Field(ge=0, description="Exact number of bytes `open` yields.") + open: Callable[[], FileChunks] = Field( + description="Returns the document's bytes from the start, once per attempt." + ) + content_type: str = Field( + default="application/octet-stream", + description="Media type of the file part, for example application/pdf.", + ) + + # DU Framework API version: `DocumentsService` calls 1.1, `DocumentsServiceV2` calls 2.0. DocumentsApiVersion = Literal["1.1", "2.0"] diff --git a/packages/uipath-platform/tests/services/test_base_service.py b/packages/uipath-platform/tests/services/test_base_service.py index 946cb8dad..9a1ee5602 100644 --- a/packages/uipath-platform/tests/services/test_base_service.py +++ b/packages/uipath-platform/tests/services/test_base_service.py @@ -151,6 +151,38 @@ def test_503_retried( assert response.status_code == 200 assert len(httpx_mock.get_requests()) == 2 + def test_request_once_does_not_retry( + self, + httpx_mock: HTTPXMock, + service: BaseService, + base_url: str, + org: str, + tenant: str, + ): + url = self._url(base_url, org, tenant) + httpx_mock.add_response(url=url, status_code=503) + + with pytest.raises(EnrichedException) as exc_info: + service._request_once("GET", "/endpoint") + assert exc_info.value.status_code == 503 + assert len(httpx_mock.get_requests()) == 1 + + async def test_request_once_async_does_not_retry( + self, + httpx_mock: HTTPXMock, + service: BaseService, + base_url: str, + org: str, + tenant: str, + ): + url = self._url(base_url, org, tenant) + httpx_mock.add_response(url=url, status_code=503) + + with pytest.raises(EnrichedException) as exc_info: + await service._request_once_async("GET", "/endpoint") + assert exc_info.value.status_code == 503 + assert len(httpx_mock.get_requests()) == 1 + def test_400_not_retried( self, httpx_mock: HTTPXMock, diff --git a/packages/uipath-platform/tests/services/test_documents_service.py b/packages/uipath-platform/tests/services/test_documents_service.py index a63760456..be79501b1 100644 --- a/packages/uipath-platform/tests/services/test_documents_service.py +++ b/packages/uipath-platform/tests/services/test_documents_service.py @@ -93,7 +93,7 @@ class TestDocumentsService: ProjectType.MODERN, None, None, - "Exactly one of `file, file_path` must be provided", + "Exactly one of `file, file_path, file_stream` must be provided", ), ( "Production", @@ -111,7 +111,7 @@ class TestDocumentsService: ProjectType.MODERN, b"something", "something", - "Exactly one of `file, file_path` must be provided", + "Exactly one of `file, file_path, file_stream` must be provided", ), ( "Production", @@ -138,7 +138,7 @@ class TestDocumentsService: ProjectType.PRETRAINED, b"something", "pathto/file.pdf", - "Exactly one of `file, file_path` must be provided", + "Exactly one of `file, file_path, file_stream` must be provided", ), ], ) @@ -899,7 +899,7 @@ async def test_classify_modern_with_tag( None, ProjectType.MODERN, "dummy doctype", - "Exactly one of `file, file_path` must be provided", + "Exactly one of `file, file_path, file_stream` must be provided", ), ( "live", @@ -1776,7 +1776,7 @@ async def test_extract_with_both_file_and_file_path_provided( # ACT & ASSERT with pytest.raises( ValueError, - match="Exactly one of `file, file_path` must be provided", + match="Exactly one of `file, file_path, file_stream` must be provided", ): if mode == "async": await service.extract_async( @@ -3183,7 +3183,7 @@ async def test_start_ixp_extraction_invalid_parameters( # ACT & ASSERT with pytest.raises( ValueError, - match="Exactly one of `file, file_path` must be provided", + match="Exactly one of `file, file_path, file_stream` must be provided", ): if mode == "async": await service.start_ixp_extraction_async( diff --git a/packages/uipath-platform/tests/services/test_documents_streaming_upload.py b/packages/uipath-platform/tests/services/test_documents_streaming_upload.py new file mode 100644 index 000000000..89fa93c2a --- /dev/null +++ b/packages/uipath-platform/tests/services/test_documents_streaming_upload.py @@ -0,0 +1,561 @@ +import json +from collections.abc import AsyncIterator, Iterator +from pathlib import Path +from typing import Any +from uuid import UUID, uuid4 + +import pytest +from httpx._multipart import MultipartStream +from pytest_httpx import HTTPXMock + +from uipath.platform import UiPathApiConfig, UiPathExecutionContext +from uipath.platform.documents import ( + ClassificationResult, + DocumentsService, + DocumentsServiceV2, + ProjectType, + StreamingFile, +) +from uipath.platform.documents._streaming_upload import ( + aiter_body, + iter_body, + multipart_layout, +) +from uipath.platform.errors import EnrichedException + +DATA = b"%PDF-1.7 " + bytes(range(256)) * 40 # 10 KiB, every byte value +CHUNK = 4096 + + +@pytest.fixture(params=[DocumentsService, DocumentsServiceV2], ids=["v1.1", "v2"]) +def service( + request: pytest.FixtureRequest, + config: UiPathApiConfig, + execution_context: UiPathExecutionContext, +) -> DocumentsService | DocumentsServiceV2: + return request.param(config=config, execution_context=execution_context) + + +def api_version(service: DocumentsService | DocumentsServiceV2) -> str: + return "2.0" if isinstance(service, DocumentsServiceV2) else "1.1" + + +def tag_route(service: DocumentsService | DocumentsServiceV2, tag: str) -> str: + return f"tags/{tag}" if isinstance(service, DocumentsServiceV2) else tag + + +class Source: + """Counts how often `open` is called, and whether each opened stream closed.""" + + def __init__(self, data: bytes = DATA) -> None: + self.data = data + self.opened = 0 + self.closed = 0 + + def sync(self) -> Iterator[bytes]: + self.opened += 1 + try: + for start in range(0, len(self.data), CHUNK): + yield self.data[start : start + CHUNK] + finally: + self.closed += 1 + + async def asynchronous(self) -> AsyncIterator[bytes]: + self.opened += 1 + try: + for start in range(0, len(self.data), CHUNK): + yield self.data[start : start + CHUNK] + finally: + self.closed += 1 + + +def streaming_file(open_: Any, size: int = len(DATA)) -> StreamingFile: + return StreamingFile( + name="appraisal.pdf", size=size, open=open_, content_type="application/pdf" + ) + + +async def call( + service: DocumentsService | DocumentsServiceV2, + method: str, + mode: str, + **kwargs: Any, +) -> Any: + """Call `method`, or await `_async`, so one test covers both.""" + if mode == "sync": + return getattr(service, method)(**kwargs) + return await getattr(service, f"{method}_async")(**kwargs) + + +def source_for(source: "Source", mode: str) -> Any: + """The sync generator for the sync method, the async one for the async method.""" + return source.sync if mode == "sync" else source.asynchronous + + +def expected_files() -> dict[str, Any]: + return {"File": ("appraisal.pdf", DATA, "application/pdf")} + + +def add_project_and_extraction( + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + root: str, + project_id: str, + document_id: str, + operation_id: str, +) -> None: + httpx_mock.add_response( + url=f"{root}/du_/api/framework/projects?api-version={api_version(service)}&type=IXP", + json={"projects": [{"id": project_id, "name": "LoanProject"}]}, + ) + httpx_mock.add_response( + method="POST", + url=f"{root}/du_/api/framework/projects/{project_id}/{tag_route(service, 'live')}/document-types/{UUID(int=0)}/extraction/start?api-version={api_version(service)}", + match_json={"documentId": document_id}, + json={"operationId": operation_id}, + ) + + +def digitization_url( + service: DocumentsService | DocumentsServiceV2, root: str, project_id: str +) -> str: + return f"{root}/du_/api/framework/projects/{project_id}/digitization/start?api-version={api_version(service)}" + + +class TestMultipartLayout: + @pytest.mark.parametrize( + "name", + ["appraisal.pdf", 'loan "final".pdf', "back\\slash.pdf", "line\r\nbreak.pdf"], + ) + def test_body_matches_what_httpx_writes(self, name: str): + source = Source() + file = StreamingFile( + name=name, size=len(DATA), open=source.sync, content_type="application/pdf" + ) + layout = multipart_layout(file, field_name="File") + boundary = layout.content_type.split("boundary=")[1].encode() + + body = b"".join(iter_body(layout, file)) + + httpx_body = b"".join( + MultipartStream({}, {"File": (name, DATA, "application/pdf")}, boundary) + ) + assert body == httpx_body + assert layout.content_length == len(body) + + def test_each_layout_has_its_own_boundary(self): + file = streaming_file(Source().sync) + first = multipart_layout(file, "File") + second = multipart_layout(file, "File") + assert first.content_type != second.content_type + + async def test_async_body_accepts_a_sync_source(self): + source = Source() + file = streaming_file(source.sync) + layout = multipart_layout(file, field_name="File") + + body = b"".join([chunk async for chunk in aiter_body(layout, file)]) + + assert body == layout.head + DATA + layout.tail + assert (source.opened, source.closed) == (1, 1) + + +class TestStartIxpExtractionWithFileStream: + @pytest.mark.parametrize("mode", ["sync", "async", "async-with-sync-source"]) + async def test_uploads_the_stream_with_a_content_length( + self, + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + base_url: str, + org: str, + tenant: str, + mode: str, + ): + root = f"{base_url}{org}{tenant}" + project_id, document_id, operation_id = str(uuid4()), str(uuid4()), str(uuid4()) + add_project_and_extraction( + httpx_mock, service, root, project_id, document_id, operation_id + ) + httpx_mock.add_response( + method="POST", + url=digitization_url(service, root, project_id), + match_headers={"X-UiPath-Internal-ConsumptionSourceType": "CodedAgents"}, + match_files=expected_files(), + json={"documentId": document_id}, + ) + source = Source() + + if mode == "sync": + response = service.start_ixp_extraction( + project_name="LoanProject", + tag="live", + file_stream=streaming_file(source.sync), + ) + else: + open_ = source.asynchronous if mode == "async" else source.sync + response = await service.start_ixp_extraction_async( + project_name="LoanProject", + tag="live", + file_stream=streaming_file(open_), + ) + + assert response.document_id == document_id + assert response.operation_id == operation_id + assert (source.opened, source.closed) == (1, 1) + upload = next( + r for r in httpx_mock.get_requests() if r.url.path.endswith("/start") + ) + assert "transfer-encoding" not in upload.headers + assert int(upload.headers["content-length"]) == len(upload.content) + + @pytest.mark.parametrize("mode", ["sync", "async"]) + async def test_retry_reads_the_source_again_from_the_start( + self, + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + base_url: str, + org: str, + tenant: str, + mode: str, + ): + root = f"{base_url}{org}{tenant}" + project_id, document_id, operation_id = str(uuid4()), str(uuid4()), str(uuid4()) + add_project_and_extraction( + httpx_mock, service, root, project_id, document_id, operation_id + ) + url = digitization_url(service, root, project_id) + httpx_mock.add_response( + method="POST", + url=url, + match_files=expected_files(), + status_code=503, + headers={"retry-after": "0"}, + ) + httpx_mock.add_response( + method="POST", + url=url, + match_files=expected_files(), + json={"documentId": document_id}, + ) + source = Source() + + if mode == "sync": + response = service.start_ixp_extraction( + project_name="LoanProject", + tag="live", + file_stream=streaming_file(source.sync), + ) + else: + response = await service.start_ixp_extraction_async( + project_name="LoanProject", + tag="live", + file_stream=streaming_file(source.asynchronous), + ) + + assert response.document_id == document_id + assert (source.opened, source.closed) == (2, 2) + + @pytest.mark.parametrize("mode", ["sync", "async"]) + async def test_client_error_is_not_retried( + self, + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + base_url: str, + org: str, + tenant: str, + mode: str, + ): + root = f"{base_url}{org}{tenant}" + project_id = str(uuid4()) + httpx_mock.add_response( + url=f"{root}/du_/api/framework/projects?api-version={api_version(service)}&type=IXP", + json={"projects": [{"id": project_id, "name": "LoanProject"}]}, + ) + httpx_mock.add_response( + method="POST", + url=digitization_url(service, root, project_id), + status_code=413, + ) + source = Source() + file_stream = streaming_file(source_for(source, mode)) + + with pytest.raises(EnrichedException) as exc_info: + await call( + service, + "start_ixp_extraction", + mode, + project_name="LoanProject", + tag="live", + file_stream=file_stream, + ) + + assert exc_info.value.status_code == 413 + assert (source.opened, source.closed) == (1, 1) + + @pytest.mark.httpx_mock(assert_all_responses_were_requested=False) + @pytest.mark.parametrize("mode", ["sync", "async"]) + @pytest.mark.parametrize( + "declared, match", + [(len(DATA) + 1, "but its source yielded"), (len(DATA) - 1, "more than")], + ids=["too-few-bytes", "too-many-bytes"], + ) + async def test_wrong_size_fails_without_retry( + self, + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + base_url: str, + org: str, + tenant: str, + mode: str, + declared: int, + match: str, + ): + root = f"{base_url}{org}{tenant}" + project_id = str(uuid4()) + httpx_mock.add_response( + url=f"{root}/du_/api/framework/projects?api-version={api_version(service)}&type=IXP", + json={"projects": [{"id": project_id, "name": "LoanProject"}]}, + ) + httpx_mock.add_response( + method="POST", + url=digitization_url(service, root, project_id), + json={"documentId": str(uuid4())}, + ) + source = Source() + file_stream = streaming_file(source_for(source, mode), size=declared) + + with pytest.raises(ValueError, match=match): + await call( + service, + "start_ixp_extraction", + mode, + project_name="LoanProject", + tag="live", + file_stream=file_stream, + ) + + assert (source.opened, source.closed) == (1, 1) + + @pytest.mark.httpx_mock(assert_all_responses_were_requested=False) + async def test_sync_method_rejects_an_async_source( + self, + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + base_url: str, + org: str, + tenant: str, + ): + root = f"{base_url}{org}{tenant}" + httpx_mock.add_response( + url=f"{root}/du_/api/framework/projects?api-version={api_version(service)}&type=IXP", + json={"projects": [{"id": str(uuid4()), "name": "LoanProject"}]}, + ) + file_stream = streaming_file(Source().asynchronous) + + with pytest.raises(TypeError, match="AsyncIterable|async source"): + service.start_ixp_extraction( + project_name="LoanProject", + tag="live", + file_stream=file_stream, + ) + + @pytest.mark.parametrize("mode", ["sync", "async"]) + async def test_file_stream_cannot_be_combined_with_file( + self, + service: DocumentsService | DocumentsServiceV2, + mode: str, + ): + file_stream = streaming_file(Source().sync) + with pytest.raises(ValueError, match="Exactly one of"): + await call( + service, + "start_ixp_extraction", + mode, + project_name="LoanProject", + tag="live", + file=b"x", + file_stream=file_stream, + ) + + +PRETRAINED_PROJECT_ID = str(UUID(int=0)) + + +def add_digitization( + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + root: str, + document_id: str, +) -> None: + project = f"{root}/du_/api/framework/projects/{PRETRAINED_PROJECT_ID}" + httpx_mock.add_response( + method="POST", + url=f"{project}/digitization/start?api-version={api_version(service)}", + match_files=expected_files(), + json={"documentId": document_id}, + ) + httpx_mock.add_response( + url=f"{project}/digitization/result/{document_id}?api-version={api_version(service)}", + json={"status": "Succeeded", "result": {}}, + ) + + +class TestClassifyAndExtractWithFileStream: + @pytest.mark.parametrize("mode", ["sync", "async"]) + async def test_classify_uploads_the_stream( + self, + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + base_url: str, + org: str, + tenant: str, + mode: str, + classification_response: dict[str, Any], + ): + root = f"{base_url}{org}{tenant}" + project = f"{root}/du_/api/framework/projects/{PRETRAINED_PROJECT_ID}" + document_id, operation_id = str(uuid4()), str(uuid4()) + add_digitization(httpx_mock, service, root, document_id) + httpx_mock.add_response( + method="POST", + url=f"{project}/classifiers/ml-classification/classification/start?api-version={api_version(service)}", + match_json={"documentId": document_id}, + json={"operationId": operation_id}, + ) + httpx_mock.add_response( + url=f"{project}/classifiers/ml-classification/classification/result/{operation_id}?api-version={api_version(service)}", + json={"status": "Succeeded", "result": classification_response}, + ) + source = Source() + + if mode == "sync": + results = service.classify( + project_type=ProjectType.PRETRAINED, + file_stream=streaming_file(source.sync), + ) + else: + results = await service.classify_async( + project_type=ProjectType.PRETRAINED, + file_stream=streaming_file(source.asynchronous), + ) + + assert ( + results[0].document_id + == classification_response["classificationResults"][0]["DocumentId"] + ) + assert (source.opened, source.closed) == (1, 1) + + @pytest.mark.parametrize("mode", ["sync", "async"]) + async def test_extract_uploads_the_stream( + self, + httpx_mock: HTTPXMock, + service: DocumentsService | DocumentsServiceV2, + base_url: str, + org: str, + tenant: str, + mode: str, + documents_tests_data_path: Path, + ): + modern_extraction_response = json.loads( + (documents_tests_data_path / "modern_extraction_response.json").read_text() + ) + root = f"{base_url}{org}{tenant}" + project = f"{root}/du_/api/framework/projects/{PRETRAINED_PROJECT_ID}" + document_id, operation_id = str(uuid4()), str(uuid4()) + add_digitization(httpx_mock, service, root, document_id) + httpx_mock.add_response( + url=f"{project}/document-types?api-version={api_version(service)}", + json={"documentTypes": [{"id": "invoices", "name": "Invoice"}]}, + ) + httpx_mock.add_response( + method="POST", + url=f"{project}/extractors/invoices/extraction/start?api-version={api_version(service)}", + match_json={"documentId": document_id}, + json={"operationId": operation_id}, + ) + httpx_mock.add_response( + url=f"{project}/extractors/invoices/extraction/result/{operation_id}?api-version={api_version(service)}", + json={"status": "Succeeded", "result": modern_extraction_response}, + ) + source = Source() + + if mode == "sync": + response = service.extract( + project_type=ProjectType.PRETRAINED, + document_type_name="Invoice", + file_stream=streaming_file(source.sync), + ) + else: + response = await service.extract_async( + project_type=ProjectType.PRETRAINED, + document_type_name="Invoice", + file_stream=streaming_file(source.asynchronous), + ) + + assert response.extractor_id == "invoices" + assert response.document_type_id == "invoices" + assert (source.opened, source.closed) == (1, 1) + + @pytest.mark.parametrize("mode", ["sync", "async"]) + async def test_classify_rejects_file_stream_with_file_path( + self, + service: DocumentsService | DocumentsServiceV2, + mode: str, + ): + file_stream = streaming_file(Source().sync) + with pytest.raises( + ValueError, + match="Exactly one of `file, file_path, file_stream` must be provided", + ): + await call( + service, + "classify", + mode, + project_type=ProjectType.PRETRAINED, + file_path="document.pdf", + file_stream=file_stream, + ) + + @pytest.mark.parametrize("mode", ["sync", "async"]) + async def test_extract_rejects_file_stream_with_a_classification_result( + self, + service: DocumentsService | DocumentsServiceV2, + mode: str, + classification_response: dict[str, Any], + ): + result = ClassificationResult.model_validate( + { + **classification_response["classificationResults"][0], + "ProjectId": PRETRAINED_PROJECT_ID, + "ProjectType": ProjectType.PRETRAINED.value, + "ClassifierId": "ml-classification", + "Tag": None, + } + ) + file_stream = streaming_file(Source().sync) + # Same rule as for `file`: a document and a classification result exclude + # each other. + args: dict[str, Any] = { + "classification_result": result, + "project_type": ProjectType.PRETRAINED, + "document_type_name": "Invoice", + "file_stream": file_stream, + } + with pytest.raises( + ValueError, match="`classification_result` must not be provided" + ): + await call(service, "extract", mode, **args) + + +class TestStreamingFileModel: + def test_rejects_a_negative_size(self): + with pytest.raises(ValueError): + StreamingFile(name="a.pdf", size=-1, open=lambda: iter([b""])) + + def test_rejects_an_empty_name(self): + with pytest.raises(ValueError): + StreamingFile(name="", size=0, open=lambda: iter([b""])) + + def test_defaults_to_octet_stream(self): + file = StreamingFile(name="a.pdf", size=0, open=lambda: iter([])) + assert file.content_type == "application/octet-stream" diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index 181411d29..249f0a23b 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1091,7 +1091,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.21" +version = "0.3.22" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index 105930f09..ae9a7d45a 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.21" +version = "0.3.22" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" },