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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@
import time
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, TYPE_CHECKING

from opentelemetry import context as otel_context

from rapidata.rapidata_client.api.rapidata_api_client import (
suppress_rapidata_error_logging,
)
from rapidata.rapidata_client.config import logger, rapidata_config
from rapidata.rapidata_client.exceptions.failed_upload import FailedUpload
from rapidata.rapidata_client.datapoints._asset_uploader import AssetUploader
Expand Down Expand Up @@ -325,8 +329,16 @@ def _process_single_batch(
batch_upload_id=batch_id
)

# The API returns each URL as it normalised it, so one it rewrote has no item
# under the caller's spelling: those are uploaded on their own below.
submitted = set(batch_to_urls.get(batch_id, []))
returned = {item.url for item in result.items}

# Process each URL in the batch result
for item in result.items:
if submitted and item.url not in submitted:
continue

# Per-item warnings (e.g. "video longer than 25 seconds") ride
# alongside an otherwise-successful upload. Read defensively:
# the field is only present once the asset service exposing it
Expand Down Expand Up @@ -373,6 +385,12 @@ def _process_single_batch(
f"URL failed in batch: {item.url} - {item.error_message}"
)

uploaded, failed = self._upload_individually(
[url for url in batch_to_urls.get(batch_id, []) if url not in returned]
)
successful_urls.extend(uploaded)
failed_uploads.extend(failed)

except Exception as e:
logger.error(f"Failed to fetch results for batch {batch_id}: {e}")
# Create individual FailedUpload for each URL in the failed batch
Expand All @@ -393,6 +411,39 @@ def _process_single_batch(

return successful_urls, failed_uploads

def _upload_individually(
self, urls: list[str]
) -> tuple[list[str], list[FailedUpload[str]]]:
"""Upload each URL through the single-URL endpoint, which answers with the file name itself."""
if not urls:
return [], []

current_context = otel_context.get_current()

def upload(url: str) -> FailedUpload[str] | None:
token = otel_context.attach(current_context)
try:
with suppress_rapidata_error_logging():
self.asset_uploader.upload_asset(url)
return None
except Exception as e:
failure = FailedUpload.from_exception(url, e)
logger.warning(
f"URL failed to upload: {url.strip()} - {failure.error_message}"
)
return failure
finally:
otel_context.detach(token)

with ThreadPoolExecutor(
max_workers=rapidata_config.upload.maxWorkers
) as executor:
outcomes = list(executor.map(upload, urls))

failed = [outcome for outcome in outcomes if outcome is not None]
failed_urls = {failure.item for failure in failed}
return [url for url in urls if url not in failed_urls], failed

def _create_submission_failures(self, urls: list[str]) -> list[FailedUpload[str]]:
"""Create FailedUpload instances for all URLs when submission fails."""
return [
Expand Down
120 changes: 120 additions & 0 deletions tests/rapidata_client/datapoints/test_batch_rewritten_urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""The batch-upload API returns each URL as it normalised it (trimmed, lower-cased
host, default port dropped, escapes decoded), not as the caller wrote it."""

from __future__ import annotations

from unittest.mock import MagicMock, patch

from rapidata.api_client.models.batch_upload_url_status import BatchUploadUrlStatus
from rapidata.rapidata_client.datapoints._asset_uploader import AssetUploader
from rapidata.rapidata_client.datapoints._batch_asset_uploader import BatchAssetUploader
from rapidata.rapidata_client.datapoints._single_flight_cache import SingleFlightCache
from rapidata.rapidata_client.exceptions.rapidata_error import RapidataError

FROM_A_TEXT_FILE = "https://host/a.jpg\n"
AS_THE_API_RETURNS_IT = "https://host/a.jpg"
UNCHANGED = "https://host/b.jpg"


def _item(url: str, status: BatchUploadUrlStatus, file_name: str | None) -> MagicMock:
item = MagicMock()
item.url = url
item.status = status
item.file_name = file_name
item.warnings = None
item.error_message = (
None if file_name else "The remote asset could not be retrieved."
)
item.stage = None if file_name else "download"
item.upstream_http_status = None if file_name else 404
return item


def _uploader(items: list[MagicMock]) -> tuple[BatchAssetUploader, MagicMock]:
openapi_service = MagicMock()
openapi_service.environment = "rapidata.ai"
result = MagicMock()
result.items = items
openapi_service.asset.batch_upload_api.asset_batch_upload_batch_upload_id_get.return_value = (
result
)
return BatchAssetUploader(openapi_service), openapi_service


def test_url_the_api_rewrote_is_uploaded_under_the_callers_spelling():
cache = SingleFlightCache("test url cache", storage={})
with patch.object(AssetUploader, "_url_cache", cache):
uploader, openapi_service = _uploader(
[
_item(
AS_THE_API_RETURNS_IT, BatchUploadUrlStatus.COMPLETED, "batch-a.jpg"
),
_item(UNCHANGED, BatchUploadUrlStatus.COMPLETED, "batch-b.jpg"),
]
)
single = MagicMock()
single.file_name = "single-a.jpg"
single.warnings = None
openapi_service.asset.asset_api.asset_url_post.return_value = single

successful, failed = uploader._process_single_batch(
"batch-1", {"batch-1": [FROM_A_TEXT_FILE, UNCHANGED]}
)

assert failed == []
assert sorted(successful) == sorted([FROM_A_TEXT_FILE, UNCHANGED])
openapi_service.asset.asset_api.asset_url_post.assert_called_once_with(
url=FROM_A_TEXT_FILE
)
asset_uploader = uploader.asset_uploader
assert cache.get_storage() == {
asset_uploader.get_url_cache_key(FROM_A_TEXT_FILE): "single-a.jpg",
asset_uploader.get_url_cache_key(UNCHANGED): "batch-b.jpg",
}


def test_rewritten_url_that_fails_is_reported_under_the_callers_spelling():
cache = SingleFlightCache("test url cache", storage={})
with patch.object(AssetUploader, "_url_cache", cache):
uploader, openapi_service = _uploader(
[_item(AS_THE_API_RETURNS_IT, BatchUploadUrlStatus.FAILED, None)]
)
openapi_service.asset.asset_api.asset_url_post.side_effect = RapidataError(
status_code=400,
message="The remote asset could not be retrieved.",
details={
"title": "The remote asset could not be retrieved.",
"stage": "download",
"upstreamHttpStatus": 404,
},
)

successful, failed = uploader._process_single_batch(
"batch-1", {"batch-1": [FROM_A_TEXT_FILE]}
)

assert successful == []
assert [(f.item, f.error_message, f.stage, f.http_status) for f in failed] == [
(
FROM_A_TEXT_FILE,
"The remote asset could not be retrieved.",
"download",
404,
)
]
assert cache.get_storage() == {}


def test_batch_without_rewritten_urls_makes_no_single_uploads():
cache = SingleFlightCache("test url cache", storage={})
with patch.object(AssetUploader, "_url_cache", cache):
uploader, openapi_service = _uploader(
[_item(UNCHANGED, BatchUploadUrlStatus.COMPLETED, "batch-b.jpg")]
)

successful, failed = uploader._process_single_batch(
"batch-1", {"batch-1": [UNCHANGED]}
)

assert (successful, failed) == ([UNCHANGED], [])
openapi_service.asset.asset_api.asset_url_post.assert_not_called()
Loading