Repository navigation
feat(py-client): Add private resumable upload API #665
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
62f8fb8
feat(python): Add private resumable upload API
lcian b9541d9
ref(python): Simplify resumable internals and test bounded reads
lcian b8f0e39
ref(python): Remove resumable upload stream wrapper
lcian d313cde
ref(python): Clarify resumable upload internals
lcian 391c7fd
improve
lcian 7a77b0f
docs(python): Clarify resumable upload compression requirements
lcian 2934f1a
chore: Merge main into Python resumable uploads
lcian File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.