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
209 changes: 209 additions & 0 deletions clients/python/src/objectstore_client/_resumable.py
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()
Comment thread
sentry[bot] marked this conversation as resolved.
Resolved
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)
Loading
Loading