Skip to content
Merged
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
31 changes: 14 additions & 17 deletions mapilio_kit/components/upload/upload_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,23 +76,20 @@ def upload(
"project-organization-key": organization_key if organization_key else None,
"project-key": project_key if project_key else None
}
try:
resp = requests.post(
f"{MAPILIO_UPLOAD_ENDPOINT_ZIP}",
headers=headers,
files=files
)
resp.raise_for_status()
offset += len(chunk)
for callback in self.callbacks:
callback(chunk, resp)
if not chunk:
if (resp.status_code != 204 and
resp.headers["content-type"].strip().startswith("application/json")):
response_dict = json.loads(resp.text)
return response_dict["hash"]
except requests.exceptions.HTTPError as e:
print(e.response.text)
resp = requests.post(
f"{MAPILIO_UPLOAD_ENDPOINT_ZIP}",
headers=headers,
files=files
)
resp.raise_for_status()
offset += len(chunk)
for callback in self.callbacks:
callback(chunk, resp)
if not chunk:
if (resp.status_code != 204 and
resp.headers["content-type"].strip().startswith("application/json")):
response_dict = json.loads(resp.text)
return response_dict["hash"]


def finish(
Expand Down
11 changes: 9 additions & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,22 @@ def _install_stub(name: str, attrs: dict | None = None) -> None:
sys.modules[name] = module


# ``calculation`` is an in-house package not always installable in CI. The
# only symbol we touch from it is ``calculate_vfov``.
# ``calculation`` is an in-house package not always installable in CI.
# Upload retry tests import the EXIF writer too, but never convert coordinates.
_install_stub("calculation")
_install_stub(
"calculation.util",
{"calculate_vfov": lambda fov, w, h: round(float(fov) * float(h) / max(float(w), 1.0), 2)},
)


def _unexpected_coordinate_conversion(*args, **kwargs):
raise AssertionError("Upload retry tests must not perform EXIF coordinate conversion")


_install_stub("calculation.geospatial_utils", {"decimal_to_dms": _unexpected_coordinate_conversion})


def pytest_collection_modifyitems(config, items):
"""Skip integration tests unless explicitly opted in."""
run_integration = config.getoption("--run-integration", default=False)
Expand Down
27 changes: 27 additions & 0 deletions tests/test_upload_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,30 @@ def test_transfer_follows_server_range_format(monkeypatch, size, offset, expecte
assert server.ranges == expected_ranges
assert server.stored == payload
assert file_hash == "opaque-hash"


@pytest.mark.parametrize("status", [400, 500])
@pytest.mark.parametrize("successful_chunks", [0, 1])
def test_http_error_stops_before_reading_another_chunk(monkeypatch, status, successful_chunks):
sent = []
confirmed = []

def post(url, headers, files):
sent.append((headers["content-range"], files["chunk"][1]))
assert len(sent) <= successful_chunks + 1, "continued after the failed chunk"
if len(sent) <= successful_chunks:
return _response(200, b"{}")
return _response(status, b'{"message": "upload failed"}')

monkeypatch.setattr(upload_manager.requests, "post", post)
manager = UploadManager("synthetic-token", "session-key", 4)
manager.callbacks.append(lambda chunk, response: confirmed.append(chunk))
data = io.BytesIO(b"aabb")

with pytest.raises(requests.HTTPError) as error:
manager.upload(USER, data, offset=0, chunk_size=2)

assert error.value.response.status_code == status
assert sent == [("bytes=0-4/4", b"aa"), ("bytes=2-4/4", b"bb")][:successful_chunks + 1]
assert confirmed == [b"aa"][:successful_chunks]
assert data.tell() == (successful_chunks + 1) * 2
114 changes: 114 additions & 0 deletions tests/test_upload_retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""HTTP failures must reach the existing resumable-upload retry owner."""

import io
import json
import re

import pytest
import requests

from mapilio_kit.components.upload import upload_manager, uploader

USER = {"SettingsEmail": "fixture@example.invalid", "user_upload_token": "synthetic-token"}


def _response(status, body):
response = requests.Response()
response.status_code = status
response._content = json.dumps(body).encode()
response.headers["content-type"] = "application/json"
response.url = "https://upload.example.invalid/upload"
response.request = requests.Request("POST", response.url).prepare()
return response


class UploadServer:
def __init__(self, status=500, persist_failed=False, always_fail=False):
self.status = status
self.persist_failed = persist_failed
self.always_fail = always_fail
self.failed = False
self.stored = b""
self.posts = []
self.offsets = []

def get(self, url, headers):
self.offsets.append(len(self.stored))
return _response(200, {"totalChunkUploaded": len(self.stored)})

def post(self, url, headers, files):
chunk = files["chunk"][1]
self.posts.append((headers["content-range"], chunk))
# Bound the unfixed client's tight loop so the regression fails promptly.
assert len(self.posts) <= (205 if self.always_fail else 20), "unbounded upload loop"
start, end, total = map(int, re.fullmatch(r"bytes=(\d+)-(\d+)/(\d+)", headers["content-range"]).groups())
if self.always_fail or (not self.failed and len(self.stored) == 2):
self.failed = True
if self.persist_failed:
self.stored += chunk
return _response(self.status, {"message": "upload failed"})
if not chunk and start == end == total == len(self.stored):
return _response(200, {"hash": "fixture-hash"})
if start != len(self.stored) or start >= end:
return _response(400, {"message": "Bad chunk provided"})
self.stored += chunk
return _response(200, {})


def _connect(monkeypatch, server):
delays = []
monkeypatch.setattr(upload_manager.requests, "get", server.get)
monkeypatch.setattr(upload_manager.requests, "post", server.post)
monkeypatch.setattr(uploader.time, "sleep", delays.append)
return delays


@pytest.mark.parametrize("persist_failed", [False, True], ids=["chunk-not-stored", "chunk-already-stored"])
def test_http_500_refetches_offset_and_resumes_exact_bytes(monkeypatch, persist_failed):
server = UploadServer(persist_failed=persist_failed)
delays = _connect(monkeypatch, server)

result = uploader._upload_zipfile_fp(USER, io.BytesIO(b"aabbccdd"), 8, 2, session_key="fixture.zip")

assert result == "fixture-hash"
assert server.stored == b"aabbccdd"
assert server.offsets == [0, 4 if persist_failed else 2]
assert delays == [2]
assert server.posts == [
("bytes=0-8/8", b"aa"),
("bytes=2-8/8", b"bb"),
*([] if persist_failed else [("bytes=2-8/8", b"bb")]),
("bytes=4-8/8", b"cc"),
("bytes=6-8/8", b"dd"),
("bytes=8-8/8", b""),
]


@pytest.mark.parametrize("status", [400, 401, 403])
def test_ordinary_http_4xx_stops_without_retry(monkeypatch, status):
server = UploadServer(status=status, always_fail=True)
delays = _connect(monkeypatch, server)

with pytest.raises(requests.HTTPError) as error:
uploader._upload_zipfile_fp(USER, io.BytesIO(b"aabb"), 4, 2, session_key="fixture.zip")

assert error.value.__cause__.response.status_code == status
assert server.posts == [("bytes=0-4/4", b"aa")]
assert server.offsets == [0]
assert server.stored == b""
assert delays == []


def test_permanent_http_500_exhausts_bounded_retry_with_backoff(monkeypatch):
server = UploadServer(always_fail=True)
delays = _connect(monkeypatch, server)

with pytest.raises(requests.HTTPError) as error:
uploader._upload_zipfile_fp(USER, io.BytesIO(b"aabb"), 4, 2, session_key="fixture.zip")

assert error.value.__cause__.response.status_code == 500
assert len(server.posts) == 201
assert server.posts == [("bytes=0-4/4", b"aa")] * 201
assert server.offsets == [0] * 201
assert server.stored == b""
assert delays == [2, 4, 8] + [16] * 197
Loading