diff --git a/clients/python/src/objectstore_client/_resumable.py b/clients/python/src/objectstore_client/_resumable.py new file mode 100644 index 00000000..8c467ade --- /dev/null +++ b/clients/python/src/objectstore_client/_resumable.py @@ -0,0 +1,209 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import IO, TYPE_CHECKING +from urllib.parse import urlencode + +import urllib3 + +from objectstore_client.errors import RequestError, raise_for_status +from objectstore_client.metrics import measure_storage_operation +from objectstore_client.tracing import storage_span + +if TYPE_CHECKING: + from objectstore_client.client import Session + + +class ResumableUploadUnavailable(RequestError): + """The upload session expired, was canceled, or could not be found.""" + + +class UploadOffsetMismatch(RequestError): + """The server rejected a chunk and reported its offset.""" + + def __init__(self, offset: int, response: urllib3.BaseHTTPResponse): + super().__init__( + f"Upload offset mismatch (server holds {offset} bytes)", + response.status, + response.data.decode("utf-8", "replace"), + ) + self.offset = offset + + +class ChunkTooSmall(ValueError): + """A non-final chunk is shorter than the upload granularity.""" + + +@dataclass(frozen=True) +class UploadIncomplete: + """The upload expects more bytes, starting at the given offset.""" + + offset: int + + +@dataclass(frozen=True) +class UploadComplete: + """The upload is complete.""" + + +UploadProgress = UploadIncomplete | UploadComplete + + +def parse_progress_response(response: urllib3.BaseHTTPResponse) -> UploadProgress: + if response.status == 409: + raise UploadOffsetMismatch(int(response.headers["Upload-Offset"]), response) + if response.status in (404, 410): + raise_for_status(response, error_type=ResumableUploadUnavailable) + raise_for_status(response) + if response.status == 201: + return UploadComplete() + return UploadIncomplete(int(response.headers["Upload-Offset"])) + + +class ResumableUpload: + """A handle bound to one resumable upload session.""" + + def __init__( + self, + session: Session, + key: str, + token: str, + total_length: int | None = None, + granularity: int | None = None, + ): + self._session = session + self._key = key + self._token = token + self._total_length = total_length + self._granularity = granularity + + @property + def key(self) -> str: + return self._key + + @property + def token(self) -> str: + return self._token + + @property + def granularity(self) -> int | None: + """The persistence unit for non-final chunks, if known.""" + return self._granularity + + def progress(self) -> UploadProgress: + """Query the server's authoritative offset. + + Raises `ResumableUploadUnavailable` for an unavailable session. + """ + session = self._session + query = urlencode({"session": self.token}) + headers = session._make_headers() + headers["Upload-Offset"] = "*" + with ( + storage_span( + "resumable.progress", session._usecase, session._scope, key=self.key + ), + measure_storage_operation( + session._metrics_backend, "resumable.progress", session._usecase.name + ), + ): + response = session._pool.request( + "PUT", + f"{session._make_url(self.key)}?{query}", + headers=headers, + preload_content=True, + decode_content=True, + ) + return parse_progress_response(response) + + def put( + self, offset: int, contents: bytes | tuple[IO[bytes], int] + ) -> UploadProgress: + """Uploads `contents` starting at `offset`. + + For streaming payloads, supply a tuple of the stream and its exact length + in bytes. + + This method doesn't perform any automatic compression of the payload, so + the caller is responsible for applying compression to the entire payload + beforehand and passing chunks of the already compressed payload. + + Raises `UploadOffsetMismatch` when the server rejects the offset, + `ResumableUploadUnavailable` for an unavailable session, or `ChunkTooSmall` + for a non-final chunk shorter than the granularity. + """ + if isinstance(contents, bytes): + body: bytes | IO[bytes] = contents + length = len(contents) + else: + body, length = contents + + if offset < 0 or length < 0: + raise ValueError("Chunk offset and length must not be negative") + if ( + self._granularity is not None + and self._total_length is not None + and 0 < length < self._granularity + and offset + length < self._total_length + ): + raise ChunkTooSmall( + f"Non-final chunk {length} is smaller than upload granularity " + f"{self._granularity}" + ) + + session = self._session + query = urlencode({"session": self.token}) + headers = session._make_headers() + headers["Upload-Offset"] = str(offset) + headers["Content-Length"] = str(length) + with ( + storage_span( + "resumable.put", + session._usecase, + session._scope, + key=self.key, + offset=offset, + size=length, + ), + measure_storage_operation( + session._metrics_backend, "resumable.put", session._usecase.name + ) as metrics, + ): + response = session._pool.request( + "PUT", + f"{session._make_url(self.key)}?{query}", + headers=headers, + body=body, + preload_content=True, + decode_content=True, + ) + progress = parse_progress_response(response) + metrics.record_size(length) + return progress + + def cancel(self) -> None: + """Cancels the upload session, discarding uploaded bytes.""" + session = self._session + query = urlencode({"session": self.token}) + headers = session._make_headers() + with ( + storage_span( + "resumable.cancel", session._usecase, session._scope, key=self.key + ), + measure_storage_operation( + session._metrics_backend, "resumable.cancel", session._usecase.name + ), + ): + response = session._pool.request( + "DELETE", + f"{session._make_url(self.key)}?{query}", + headers=headers, + preload_content=True, + decode_content=True, + ) + error_type = ( + ResumableUploadUnavailable + if response.status in (404, 410) + else RequestError + ) + raise_for_status(response, error_type=error_type) diff --git a/clients/python/src/objectstore_client/client.py b/clients/python/src/objectstore_client/client.py index 3e87c38d..579e9e3b 100644 --- a/clients/python/src/objectstore_client/client.py +++ b/clients/python/src/objectstore_client/client.py @@ -15,7 +15,7 @@ import zstandard from urllib3.connectionpool import HTTPConnectionPool -from objectstore_client import presign, utils +from objectstore_client import _resumable, presign, utils from objectstore_client.auth import Permission, SecretKey, TokenProvider from objectstore_client.errors import ( ExpiryExtensionRejected, @@ -320,6 +320,33 @@ def _make_headers(self) -> dict[str, str]: headers["x-os-auth"] = f"Bearer {token}" return headers + def _metadata_headers( + self, + compression: Compression | None, + content_type: str | None = None, + metadata: dict[str, str] | None = None, + expiration_policy: ExpirationPolicy | None = None, + origin: str | None = None, + filename: str | None = None, + ) -> dict[str, str]: + """Build upload headers with the given compression and usecase expiration.""" + headers = self._make_headers() + if compression and compression != "none": + headers["Content-Encoding"] = compression + if content_type: + headers["Content-Type"] = content_type + expiration_policy = expiration_policy or self._usecase._expiration_policy + if expiration_policy: + headers[HEADER_EXPIRATION] = format_expiration(expiration_policy) + if origin: + headers[HEADER_ORIGIN] = utils.encode_header_value(origin) + if filename is not None: + headers[HEADER_FILENAME] = utils.encode_header_value(filename) + if metadata: + for k, v in metadata.items(): + headers[f"{HEADER_META_PREFIX}{k}"] = utils.encode_header_value(v) + return headers + def _base_url(self) -> str: # urllib3 stores IPv6 hosts unbracketed (e.g. "::1"); bracket them so # the result is a valid absolute URL. @@ -404,13 +431,10 @@ def put( if precompressed and precompressed != "zstd": raise ValueError(f"Invalid compression: {precompressed}") - headers = self._make_headers() body = BytesIO(contents) if isinstance(contents, bytes) else contents original_body: IO[bytes] = body encoding = precompressed or compress or self._usecase._compression - if encoding != "none": - headers["Content-Encoding"] = encoding compress_with = encoding if precompressed is None else "none" if compress_with == "zstd": @@ -418,22 +442,14 @@ def put( body = cctx.stream_reader(original_body) body = cast(IO[bytes], utils._ZstdCompressionReaderWrapper(body)) - if content_type: - headers["Content-Type"] = content_type - - expiration_policy = expiration_policy or self._usecase._expiration_policy - if expiration_policy: - headers[HEADER_EXPIRATION] = format_expiration(expiration_policy) - - if origin: - headers[HEADER_ORIGIN] = utils.encode_header_value(origin) - - if filename is not None: - headers[HEADER_FILENAME] = utils.encode_header_value(filename) - - if metadata: - for k, v in metadata.items(): - headers[f"{HEADER_META_PREFIX}{k}"] = utils.encode_header_value(v) + headers = self._metadata_headers( + compression=encoding, + content_type=content_type, + metadata=metadata, + expiration_policy=expiration_policy, + origin=origin, + filename=filename, + ) if key == "": key = None @@ -779,6 +795,74 @@ def delete(self, key: str) -> None: ) raise_for_status(response) + def _create_upload( + self, + object_length: int, + key: str | None = None, + compression: Compression | None = None, + content_type: str | None = None, + metadata: dict[str, str] | None = None, + expiration_policy: ExpirationPolicy | None = None, + origin: str | None = None, + filename: str | None = None, + ) -> _resumable.ResumableUpload | None: + """Create a resumable upload, or return None if the server declines. + + `object_length` is the total length of the object to be uploaded. + Unlike regular uploads, the client does not automatically compress chunk + contents. + The caller must pre-compress the object according to `compression`, then + create the upload with the post-compression `object_length`. Offsets + similarly refer to the bytes after compression. + """ + if object_length < 0: + raise ValueError("Object length must not be negative") + if compression is not None and compression not in ("none", "zstd"): + raise ValueError(f"Invalid compression: {compression}") + + headers = self._metadata_headers( + compression=compression, + content_type=content_type, + metadata=metadata, + expiration_policy=expiration_policy, + origin=origin, + filename=filename, + ) + headers["Upload-Length"] = str(object_length) + + key = key or None + with ( + storage_span( + "resumable.create", self._usecase, self._scope, key=key + ) as span, + measure_storage_operation( + self._metrics_backend, "resumable.create", self._usecase.name + ), + ): + response = self._pool.request( + "PUT" if key else "POST", + f"{self._make_url(key)}?upload_type=resumable", + headers=headers, + preload_content=True, + decode_content=True, + ) + if response.status == 501: + return None + raise_for_status(response) + res = response.json() + span.set_attribute("objectstore.key", res["key"]) + return _resumable.ResumableUpload( + self, + res["key"], + res["session"], + object_length, + res.get("granularity", 0), + ) + + def _resume_upload(self, key: str, token: str) -> _resumable.ResumableUpload: + """Reconstruct a resumable upload handle, without contacting the server.""" + return _resumable.ResumableUpload(self, key, token) + def initiate_multipart_upload( self, *, @@ -805,28 +889,14 @@ def initiate_multipart_upload( if compression and compression not in ("none", "zstd"): raise ValueError(f"Invalid compression: {compression}") - headers = self._make_headers() - - compression = compression or self._usecase._compression - if compression and compression != "none": - headers["Content-Encoding"] = compression - - if content_type: - headers["Content-Type"] = content_type - - expiration_policy = expiration_policy or self._usecase._expiration_policy - if expiration_policy: - headers[HEADER_EXPIRATION] = format_expiration(expiration_policy) - - if origin: - headers[HEADER_ORIGIN] = utils.encode_header_value(origin) - - if filename is not None: - headers[HEADER_FILENAME] = utils.encode_header_value(filename) - - if metadata: - for k, v in metadata.items(): - headers[f"{HEADER_META_PREFIX}{k}"] = utils.encode_header_value(v) + headers = self._metadata_headers( + compression=compression or self._usecase._compression, + content_type=content_type, + metadata=metadata, + expiration_policy=expiration_policy, + origin=origin, + filename=filename, + ) if key == "": key = None diff --git a/clients/python/tests/test_e2e.py b/clients/python/tests/test_e2e.py index 2d2839a9..8529d57c 100644 --- a/clients/python/tests/test_e2e.py +++ b/clients/python/tests/test_e2e.py @@ -23,6 +23,12 @@ Session, Usecase, ) +from objectstore_client._resumable import ( + ResumableUploadUnavailable, + UploadComplete, + UploadIncomplete, + UploadOffsetMismatch, +) from objectstore_client.auth import Permission, SecretKey from objectstore_client.errors import RequestError from objectstore_client.metadata import TimeToLive @@ -179,6 +185,88 @@ def test_full_cycle(server_url: str) -> None: assert session.get(object_key) is None +def test_resumable_upload(server_url: str) -> None: + session = Client(server_url, token=TestSecretKey.get()).session( + Usecase("test-usecase", expiration_policy=TimeToLive(timedelta(days=1))), + org=42, + project=1337, + ) + upload = session._create_upload( + 6, + key="resumable-python", + content_type="text/plain", + metadata={"source": "test"}, + origin="203.0.113.42", + filename="example.txt", + ) + assert upload is not None + assert upload.key == "resumable-python" + assert upload.granularity is not None + assert upload.progress() == UploadIncomplete(0) + assert upload.put(0, b"abc") == UploadIncomplete(3) + + resumed = session._resume_upload(upload.key, upload.token) + assert resumed.granularity is None + assert resumed.progress() == UploadIncomplete(3) + with pytest.raises(UploadOffsetMismatch) as mismatch: + resumed.put(0, b"abc") + assert mismatch.value.status == 409 + assert mismatch.value.offset == 3 + with pytest.raises(RequestError) as oversized: + resumed.put(3, b"defg") + assert oversized.value.status == 400 + stream = BytesIO(b"prefix-def") + stream.seek(7) + assert resumed.put(3, (stream, 3)) == UploadComplete() + + response = session.get(upload.key) + assert response is not None + # The usecase defaults to zstd, but resumable creation must not inherit it. + assert response.metadata.compression is None + assert response.payload.read() == b"abcdef" + assert response.metadata.content_type == "text/plain" + assert response.metadata.expiration_policy == TimeToLive(timedelta(days=1)) + assert response.metadata.custom == {"source": "test"} + assert response.metadata.origin == "203.0.113.42" + assert response.metadata.filename == "example.txt" + + +def test_resumable_upload_precompressed(server_url: str) -> None: + session = Client(server_url, token=TestSecretKey.get()).session( + Usecase("test-usecase", compression="none"), org=42, project=1337 + ) + payload = b"abcdef" + compressed = zstandard.ZstdCompressor().compress(payload) + upload = session._create_upload(len(compressed), compression="zstd") + assert upload is not None + split = len(compressed) // 2 + assert upload.put(0, compressed[:split]) == UploadIncomplete(split) + stream = UnrewindableStream(compressed[split:]) + assert upload.put(split, (stream, len(compressed) - split)) == UploadComplete() + + response = session.get(upload.key, decompress=False) + assert response is not None + assert response.metadata.compression == "zstd" + assert response.payload.read() == compressed + response = session.get(upload.key) + assert response is not None + assert response.payload.read() == payload + + +def test_resumable_upload_cancel(server_url: str) -> None: + session = Client(server_url, token=TestSecretKey.get()).session( + Usecase("test-usecase"), org=42, project=1337 + ) + upload = session._create_upload(6) + assert upload is not None + assert upload.put(0, b"abc") == UploadIncomplete(3) + upload.cancel() + + with pytest.raises(ResumableUploadUnavailable): + upload.progress() + assert session.get(upload.key) is None + + def test_head(server_url: str) -> None: client = Client( server_url,