zilapi 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
zilapi/_downloads.py ADDED
@@ -0,0 +1,260 @@
1
+ """Atomic, streamed downloads from signed storage links."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import os
7
+ import secrets
8
+ from collections.abc import Awaitable, Callable
9
+ from datetime import datetime, timedelta, timezone
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING
12
+
13
+ import httpx
14
+
15
+ from ._base import connection_error, log_request, retry_delay, status_error
16
+ from .errors import IncompleteDownloadError
17
+ from .types import OutputLink
18
+
19
+ # Refresh a signed link this close to its expiry before retrying with it.
20
+ REFRESH_MARGIN = timedelta(seconds=60)
21
+
22
+ if TYPE_CHECKING:
23
+ from ._client import AsyncZilAPI, ZilAPI
24
+
25
+
26
+ def _target(path: str | os.PathLike[str], link: OutputLink, overwrite: bool) -> Path:
27
+ target = Path(path)
28
+ if target.is_dir():
29
+ name = link.filename.replace("\\", "/").rsplit("/", 1)[-1]
30
+ if name in ("", ".", ".."):
31
+ raise ValueError("Output filename must have a valid basename")
32
+ target = target / name
33
+ if target.exists() and not overwrite:
34
+ raise FileExistsError(target)
35
+ return target
36
+
37
+
38
+ def _temporary(directory: Path) -> tuple[Path, io.BufferedWriter]:
39
+ """Create a private-named temp file with normal umask-based permissions (not mkstemp's 0600)."""
40
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
41
+ for _ in range(100):
42
+ path = directory / f".zilapi-{secrets.token_hex(8)}"
43
+ try:
44
+ descriptor = os.open(path, flags, 0o666)
45
+ except FileExistsError:
46
+ continue
47
+ return path, os.fdopen(descriptor, "wb")
48
+ raise FileExistsError(directory / ".zilapi-*")
49
+
50
+
51
+ def _place(temporary: Path, target: Path, overwrite: bool) -> None:
52
+ if overwrite:
53
+ os.replace(temporary, target)
54
+ return
55
+ try:
56
+ os.link(temporary, target) # Atomic and fails if another writer created the target meanwhile.
57
+ except FileExistsError:
58
+ raise FileExistsError(target) from None
59
+ except OSError: # Filesystems without hard links.
60
+ if target.exists():
61
+ raise FileExistsError(target) from None
62
+ os.replace(temporary, target)
63
+
64
+
65
+ SIGNATURE_STATUSES = (400, 401, 403)
66
+
67
+
68
+ class _Short(Exception):
69
+ """Internal: the body was incomplete. ``wire`` is True when it disagreed with its own Content-Length."""
70
+
71
+ def __init__(self, received: int, expected: int, *, wire: bool) -> None:
72
+ super().__init__(received, expected)
73
+ self.received = received
74
+ self.expected = expected
75
+ self.wire = wire
76
+
77
+
78
+ def _verify(response: httpx.Response, written: int, expected: int | None) -> None:
79
+ """Raise _Short when the body is shorter or longer than announced or than the stored output."""
80
+ length = response.headers.get("Content-Length", "")
81
+ received = response.num_bytes_downloaded # Raw bytes on the wire, as Content-Length counts them.
82
+ if length.isdigit() and int(length) != received:
83
+ raise _Short(received, int(length), wire=True)
84
+ if expected is not None and written != expected:
85
+ raise _Short(written, expected, wire=False)
86
+
87
+
88
+ def _partial(response: httpx.Response | None, written: int, expected: int | None) -> _Short | None:
89
+ """For a connection drop after some bytes arrived: what was received against what was expected."""
90
+ if response is None or response.num_bytes_downloaded == 0:
91
+ return None
92
+ if expected is not None:
93
+ return _Short(written, expected, wire=False)
94
+ length = response.headers.get("Content-Length", "")
95
+ return _Short(response.num_bytes_downloaded, int(length), wire=True) if length.isdigit() else None
96
+
97
+
98
+ def _expiring(link: OutputLink) -> bool:
99
+ return link.expires_at - datetime.now(timezone.utc) <= REFRESH_MARGIN
100
+
101
+
102
+ class _Policy:
103
+ """Retry decisions for one download. Each returns (delay, refresh_link) or (None, False) to give up.
104
+
105
+ - Transport drops and bodies that disagree with their Content-Length: the client's retry limit; the
106
+ link is refreshed only when it is about to expire.
107
+ - A storage 400/401/403 (usually an expired signature): one retry with a fresh link, and only when
108
+ the link is near expiry or this is the first failure.
109
+ - A body that matches its Content-Length but not the stored size: one retry with a fresh link.
110
+ - 429/5xx: the client's retry limit and Retry-After, as before.
111
+ """
112
+
113
+ def __init__(self, retries: int, can_refresh: bool) -> None:
114
+ self.retries = retries
115
+ self.can_refresh = can_refresh
116
+ self.signature_retried = False
117
+ self.size_retried = False
118
+
119
+ def status(self, attempt: int, link: OutputLink, response: httpx.Response) -> tuple[float | None, bool]:
120
+ if attempt >= self.retries:
121
+ return None, False
122
+ if response.status_code in SIGNATURE_STATUSES:
123
+ if not self.can_refresh or self.signature_retried or not (attempt == 0 or _expiring(link)):
124
+ return None, False
125
+ self.signature_retried = True
126
+ return retry_delay(attempt), True
127
+ return retry_delay(attempt, response), self.can_refresh and _expiring(link)
128
+
129
+ def short(self, attempt: int, link: OutputLink, short: _Short) -> tuple[float | None, bool]:
130
+ if attempt >= self.retries:
131
+ return None, False
132
+ if not short.wire:
133
+ if self.size_retried:
134
+ return None, False
135
+ self.size_retried = True
136
+ return retry_delay(attempt), self.can_refresh
137
+ return retry_delay(attempt), self.can_refresh and _expiring(link)
138
+
139
+ def transport(self, attempt: int, link: OutputLink) -> tuple[float | None, bool]:
140
+ if attempt >= self.retries:
141
+ return None, False
142
+ return retry_delay(attempt), self.can_refresh and _expiring(link)
143
+
144
+
145
+ def _incomplete(link: OutputLink, short: _Short) -> IncompleteDownloadError:
146
+ return IncompleteDownloadError(
147
+ request=link.url, received_bytes=short.received, expected_bytes=short.expected
148
+ )
149
+
150
+
151
+ def download(
152
+ client: ZilAPI,
153
+ link: OutputLink,
154
+ path: str | os.PathLike[str],
155
+ overwrite: bool,
156
+ *,
157
+ expected_size: int | None = None,
158
+ refresh: Callable[[], OutputLink] | None = None,
159
+ ) -> Path:
160
+ """Stream to a temp file, verify its size, and rename it into place; retry short or failed bodies."""
161
+ target = _target(path, link, overwrite)
162
+ policy = _Policy(client.max_retries, refresh is not None)
163
+ for attempt in range(client.max_retries + 1):
164
+ temporary: Path | None = None
165
+ response: httpx.Response | None = None
166
+ written = 0
167
+ try:
168
+ with client._storage_client().stream("GET", link.url) as response:
169
+ if response.is_success:
170
+ temporary, out = _temporary(target.parent)
171
+ with out:
172
+ for chunk in response.iter_bytes():
173
+ out.write(chunk)
174
+ written += len(chunk)
175
+ _verify(response, written, expected_size)
176
+ _place(temporary, target, overwrite)
177
+ log_request("GET", link.url, attempt, response, storage=True)
178
+ return target
179
+ response.read()
180
+ delay, renew = policy.status(attempt, link, response)
181
+ if delay is None:
182
+ log_request("GET", link.url, attempt, response, storage=True)
183
+ raise status_error(response, storage=True)
184
+ except _Short as short:
185
+ delay, renew = policy.short(attempt, link, short)
186
+ if delay is None:
187
+ log_request("GET", link.url, attempt, response, storage=True)
188
+ raise _incomplete(link, short) from None
189
+ except httpx.TransportError as exc:
190
+ delay, renew = policy.transport(attempt, link)
191
+ if delay is None:
192
+ log_request("GET", link.url, attempt, storage=True)
193
+ partial = _partial(response, written, expected_size)
194
+ if partial is not None:
195
+ raise _incomplete(link, partial) from None
196
+ raise connection_error(exc, link.url) from None # the cause holds the signed URL
197
+ finally:
198
+ if temporary is not None:
199
+ temporary.unlink(missing_ok=True)
200
+ log_request("GET", link.url, attempt, response, delay, storage=True)
201
+ client._sleep(delay)
202
+ if renew and refresh is not None:
203
+ link = refresh()
204
+ raise RuntimeError("Unreachable retry state")
205
+
206
+
207
+ async def adownload(
208
+ client: AsyncZilAPI,
209
+ link: OutputLink,
210
+ path: str | os.PathLike[str],
211
+ overwrite: bool,
212
+ *,
213
+ expected_size: int | None = None,
214
+ refresh: Callable[[], Awaitable[OutputLink]] | None = None,
215
+ ) -> Path:
216
+ """Async twin of ``download``."""
217
+ target = _target(path, link, overwrite)
218
+ policy = _Policy(client.max_retries, refresh is not None)
219
+ for attempt in range(client.max_retries + 1):
220
+ temporary: Path | None = None
221
+ response: httpx.Response | None = None
222
+ written = 0
223
+ try:
224
+ async with client._storage_client().stream("GET", link.url) as response:
225
+ if response.is_success:
226
+ temporary, out = _temporary(target.parent)
227
+ with out:
228
+ async for chunk in response.aiter_bytes():
229
+ out.write(chunk)
230
+ written += len(chunk)
231
+ _verify(response, written, expected_size)
232
+ _place(temporary, target, overwrite)
233
+ log_request("GET", link.url, attempt, response, storage=True)
234
+ return target
235
+ await response.aread()
236
+ delay, renew = policy.status(attempt, link, response)
237
+ if delay is None:
238
+ log_request("GET", link.url, attempt, response, storage=True)
239
+ raise status_error(response, storage=True)
240
+ except _Short as short:
241
+ delay, renew = policy.short(attempt, link, short)
242
+ if delay is None:
243
+ log_request("GET", link.url, attempt, response, storage=True)
244
+ raise _incomplete(link, short) from None
245
+ except httpx.TransportError as exc:
246
+ delay, renew = policy.transport(attempt, link)
247
+ if delay is None:
248
+ log_request("GET", link.url, attempt, storage=True)
249
+ partial = _partial(response, written, expected_size)
250
+ if partial is not None:
251
+ raise _incomplete(link, partial) from None
252
+ raise connection_error(exc, link.url) from None # the cause holds the signed URL
253
+ finally:
254
+ if temporary is not None:
255
+ temporary.unlink(missing_ok=True)
256
+ log_request("GET", link.url, attempt, response, delay, storage=True)
257
+ await client._sleep(delay)
258
+ if renew and refresh is not None:
259
+ link = await refresh()
260
+ raise RuntimeError("Unreachable retry state")
zilapi/_uploads.py ADDED
@@ -0,0 +1,193 @@
1
+ """Bounded upload readers and retryable storage PUTs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import threading
7
+ from collections.abc import AsyncGenerator, Generator, Mapping
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, BinaryIO
10
+
11
+ import httpx
12
+
13
+ from ._base import content_type_for, log_request, retry_delay
14
+ from .errors import UploadError
15
+
16
+ if TYPE_CHECKING:
17
+ from ._client import AsyncZilAPI, ZilAPI
18
+
19
+
20
+ class Source:
21
+ def __init__(
22
+ self, file: str | os.PathLike[str] | bytes | BinaryIO, filename: str | None, content_type: str | None
23
+ ) -> None:
24
+ self.path: Path | None = None
25
+ self.data: bytes | None = None
26
+ self.stream: BinaryIO | None = None
27
+ self.start = 0
28
+ self.lock = threading.Lock()
29
+ if isinstance(file, (str, os.PathLike)):
30
+ self.path = Path(file)
31
+ filename = filename or self.path.name
32
+ self.size = self.path.stat().st_size
33
+ elif isinstance(file, bytes):
34
+ self.data = file
35
+ self.size = len(file)
36
+ else:
37
+ self.stream = file
38
+ if not file.seekable():
39
+ raise ValueError("Binary streams must be seekable")
40
+ # Like httpx and requests, upload from the stream's current position to its end.
41
+ self.start = file.tell()
42
+ try:
43
+ self.size = file.seek(0, os.SEEK_END) - self.start
44
+ finally:
45
+ file.seek(self.start)
46
+ name = getattr(file, "name", None)
47
+ if filename is None and isinstance(name, (str, os.PathLike)):
48
+ filename = Path(name).name
49
+ if not filename:
50
+ raise ValueError("filename is required")
51
+ if self.size <= 0:
52
+ raise ValueError("File size must be greater than zero (empty file)")
53
+ self.filename = filename
54
+ self.content_type = content_type_for(filename, content_type)
55
+
56
+ def chunks(self, offset: int = 0, length: int | None = None) -> Generator[bytes, None, None]:
57
+ remaining = self.size - offset if length is None else length
58
+ if self.data is not None:
59
+ yield memoryview(self.data)[offset : offset + remaining].tobytes()
60
+ elif self.path is not None:
61
+ with self.path.open("rb") as stream:
62
+ stream.seek(offset)
63
+ while remaining:
64
+ chunk = stream.read(min(65536, remaining))
65
+ if not chunk:
66
+ raise UploadError("Upload source ended before its declared size")
67
+ remaining -= len(chunk)
68
+ yield chunk
69
+ elif self.stream is not None:
70
+ while remaining:
71
+ with self.lock:
72
+ position = self.stream.tell()
73
+ try:
74
+ self.stream.seek(self.start + offset)
75
+ chunk = self.stream.read(min(65536, remaining))
76
+ finally:
77
+ self.stream.seek(position)
78
+ if not chunk:
79
+ raise UploadError("Upload source ended before its declared size")
80
+ remaining -= len(chunk)
81
+ offset += len(chunk)
82
+ yield chunk
83
+
84
+ async def achunks(self, offset: int, length: int) -> AsyncGenerator[bytes, None]:
85
+ chunks = self.chunks(offset, length)
86
+ try:
87
+ while True:
88
+ chunk = next(chunks, b"")
89
+ if not chunk:
90
+ break
91
+ yield chunk
92
+ finally:
93
+ chunks.close()
94
+
95
+
96
+ def put(
97
+ client: ZilAPI,
98
+ source: Source,
99
+ url: str,
100
+ headers: Mapping[str, str],
101
+ *,
102
+ offset: int = 0,
103
+ length: int | None = None,
104
+ part_number: int | None = None,
105
+ ) -> str:
106
+ size = source.size if length is None else length
107
+ merged = httpx.Headers(headers)
108
+ merged["Content-Length"] = str(size)
109
+ for attempt in range(4):
110
+ response = None
111
+ chunks = source.chunks(offset, size)
112
+ try:
113
+ content = (
114
+ source.data if source.data is not None and offset == 0 and size == source.size else chunks
115
+ )
116
+ response = client._storage_client().put(url, headers=merged, content=content)
117
+ except httpx.TransportError:
118
+ delay = retry_delay(attempt) if attempt < 3 else None
119
+ except OSError:
120
+ raise UploadError("Could not read upload source", part_number=part_number) from None
121
+ else:
122
+ if response.is_success:
123
+ log_request("PUT", url, attempt, response, storage=True)
124
+ etag = response.headers.get("ETag")
125
+ if part_number is not None and etag is None:
126
+ raise UploadError(
127
+ "Storage response is missing ETag",
128
+ part_number=part_number,
129
+ status_code=response.status_code,
130
+ )
131
+ return etag or ""
132
+ delay = retry_delay(attempt, response) if attempt < 3 else None
133
+ finally:
134
+ chunks.close()
135
+ log_request("PUT", url, attempt, response, delay, storage=True)
136
+ if delay is None:
137
+ raise UploadError(
138
+ "Storage upload failed",
139
+ part_number=part_number,
140
+ status_code=response.status_code if response is not None else None,
141
+ ) from None
142
+ client._sleep(delay)
143
+ raise RuntimeError("Unreachable retry state")
144
+
145
+
146
+ async def aput(
147
+ client: AsyncZilAPI,
148
+ source: Source,
149
+ url: str,
150
+ headers: Mapping[str, str],
151
+ *,
152
+ offset: int = 0,
153
+ length: int | None = None,
154
+ part_number: int | None = None,
155
+ ) -> str:
156
+ size = source.size if length is None else length
157
+ merged = httpx.Headers(headers)
158
+ merged["Content-Length"] = str(size)
159
+ for attempt in range(4):
160
+ response = None
161
+ chunks = source.achunks(offset, size)
162
+ try:
163
+ content = (
164
+ source.data if source.data is not None and offset == 0 and size == source.size else chunks
165
+ )
166
+ response = await client._storage_client().put(url, headers=merged, content=content)
167
+ except httpx.TransportError:
168
+ delay = retry_delay(attempt) if attempt < 3 else None
169
+ except OSError:
170
+ raise UploadError("Could not read upload source", part_number=part_number) from None
171
+ else:
172
+ if response.is_success:
173
+ log_request("PUT", url, attempt, response, storage=True)
174
+ etag = response.headers.get("ETag")
175
+ if part_number is not None and etag is None:
176
+ raise UploadError(
177
+ "Storage response is missing ETag",
178
+ part_number=part_number,
179
+ status_code=response.status_code,
180
+ )
181
+ return etag or ""
182
+ delay = retry_delay(attempt, response) if attempt < 3 else None
183
+ finally:
184
+ await chunks.aclose()
185
+ log_request("PUT", url, attempt, response, delay, storage=True)
186
+ if delay is None:
187
+ raise UploadError(
188
+ "Storage upload failed",
189
+ part_number=part_number,
190
+ status_code=response.status_code if response is not None else None,
191
+ ) from None
192
+ await client._sleep(delay)
193
+ raise RuntimeError("Unreachable retry state")
zilapi/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ from __future__ import annotations
2
+
3
+ __version__ = "0.5.0"
zilapi/errors.py ADDED
@@ -0,0 +1,153 @@
1
+ """Exceptions raised by the SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ import httpx
8
+
9
+ if TYPE_CHECKING:
10
+ from .types import File, Job
11
+
12
+
13
+ class ZilAPIError(Exception):
14
+ """Base exception for SDK failures."""
15
+
16
+
17
+ class APIConnectionError(ZilAPIError):
18
+ """An API connection failed; request contains a URL without query parameters."""
19
+
20
+ def __init__(self, message: str, *, request: str) -> None:
21
+ self.request = str(httpx.URL(request).copy_with(query=None, fragment=None))
22
+ super().__init__(message)
23
+
24
+
25
+ class APITimeoutError(APIConnectionError):
26
+ """An API request timed out."""
27
+
28
+
29
+ class IncompleteDownloadError(APIConnectionError):
30
+ """A download kept ending short of the expected size; nothing was written at the destination."""
31
+
32
+ def __init__(self, *, request: str, received_bytes: int, expected_bytes: int) -> None:
33
+ self.received_bytes = received_bytes
34
+ self.expected_bytes = expected_bytes
35
+ super().__init__(
36
+ f"Download incomplete: received {received_bytes} of {expected_bytes} bytes", request=request
37
+ )
38
+
39
+
40
+ class APIStatusError(ZilAPIError):
41
+ """A non-success HTTP response, with problem details when available."""
42
+
43
+ def __init__(self, *, status: int, body: Any, headers: httpx.Headers) -> None:
44
+ self.status = status
45
+ self.body = body
46
+ self.headers = headers
47
+ problem = body if isinstance(body, dict) else {}
48
+ self.code: str | None = problem.get("code")
49
+ self.title: str | None = problem.get("title")
50
+ self.detail: str = problem.get("detail") or (str(body)[:200] if not problem else "")
51
+ self.type: str | None = problem.get("type")
52
+ self.request_id: str | None = problem.get("request_id") or headers.get("X-Request-Id")
53
+ super().__init__(f"{status} {self.code}: {self.detail} (request_id={self.request_id})")
54
+
55
+
56
+ class APIResponseValidationError(APIStatusError):
57
+ """A success status whose body is not the expected JSON object (for example a proxy HTML page
58
+ or an empty or incomplete body)."""
59
+
60
+ def __init__(self, *, status: int, body: Any, headers: httpx.Headers, detail: str | None = None) -> None:
61
+ super().__init__(status=status, body=body, headers=headers)
62
+ self.code = "invalid_response"
63
+ self.detail = detail or "The API response was not a JSON object"
64
+ self.args = (f"{status} {self.code}: {self.detail} (request_id={self.request_id})",)
65
+
66
+
67
+ class BadRequestError(APIStatusError):
68
+ """The request is invalid (400)."""
69
+
70
+
71
+ class AuthenticationError(APIStatusError):
72
+ """The API key is missing or invalid (401)."""
73
+
74
+
75
+ class PermissionDeniedError(APIStatusError):
76
+ """The key cannot perform this operation (403)."""
77
+
78
+
79
+ class NotFoundError(APIStatusError):
80
+ """The resource does not exist (404)."""
81
+
82
+
83
+ class ConflictError(APIStatusError):
84
+ """The resource state conflicts with this request (409)."""
85
+
86
+
87
+ class GoneError(APIStatusError):
88
+ """The resource has expired (410)."""
89
+
90
+
91
+ class InsufficientCreditError(APIStatusError):
92
+ """The account needs more credit (402)."""
93
+
94
+
95
+ class FileTooLargeError(APIStatusError):
96
+ """The upload exceeds a size limit (413)."""
97
+
98
+
99
+ class UnsupportedMediaTypeError(APIStatusError):
100
+ """The media type is unsupported (415)."""
101
+
102
+
103
+ class UnprocessableEntityError(APIStatusError):
104
+ """The request cannot be processed (422)."""
105
+
106
+
107
+ class RateLimitError(APIStatusError):
108
+ """A rate or quota limit was reached (429)."""
109
+
110
+ retry_after: float | None = None
111
+
112
+
113
+ class InternalServerError(APIStatusError):
114
+ """The API or storage server failed (5xx)."""
115
+
116
+
117
+ class UploadError(ZilAPIError):
118
+ """A storage PUT failed; signed URLs are never included."""
119
+
120
+ def __init__(
121
+ self, message: str, *, part_number: int | None = None, status_code: int | None = None
122
+ ) -> None:
123
+ self.part_number = part_number
124
+ self.status_code = status_code
125
+ super().__init__(message)
126
+
127
+
128
+ class FileRejectedError(ZilAPIError):
129
+ """File validation failed or the file was deleted."""
130
+
131
+ def __init__(self, file: File) -> None:
132
+ self.file = file
133
+ self.code = "deleted" if file.status == "deleted" else file.error.code if file.error else "rejected"
134
+ self.message = file.error.message if file.error else f"File {file.status}"
135
+ super().__init__(f"{self.code}: {self.message}")
136
+
137
+
138
+ class WaitTimeoutError(ZilAPIError, TimeoutError):
139
+ """Polling timed out; last is the last observed resource."""
140
+
141
+ def __init__(self, last: File | Job) -> None:
142
+ self.last = last
143
+ super().__init__(f"Timed out waiting for {last.id} (status={last.status})")
144
+
145
+
146
+ class JobFailedError(ZilAPIError):
147
+ """A job's output was requested, but the job did not succeed (failed, canceled, or still running)."""
148
+
149
+ def __init__(self, job: Job) -> None:
150
+ self.job = job
151
+ self.code = job.error.code if job.error else job.status
152
+ self.message = job.error.message if job.error else f"Job {job.id} is {job.status}"
153
+ super().__init__(f"{self.code}: {self.message}")
zilapi/py.typed ADDED
File without changes
@@ -0,0 +1,3 @@
1
+ """Resource groups exposed by ZilAPI and AsyncZilAPI."""
2
+
3
+ from __future__ import annotations