|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import time |
| 4 | +import hashlib |
| 5 | +import inspect |
| 6 | +from typing import BinaryIO, Callable, Optional, Protocol, Awaitable, ContextManager, AsyncContextManager |
| 7 | +from dataclasses import dataclass |
| 8 | + |
| 9 | +import anyio |
| 10 | +import httpx |
| 11 | +from anyio import to_thread |
| 12 | + |
| 13 | +from .._exceptions import KernelError |
| 14 | + |
| 15 | +_DEFAULT_MAX_TRANSFER_RETRIES = 6 |
| 16 | +_MAX_CHUNK_ROWS = 50_000 |
| 17 | +_MAX_RETRY_DELAY = 8.0 |
| 18 | + |
| 19 | + |
| 20 | +class AuditLogDownloadError(KernelError): |
| 21 | + pass |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(frozen=True) |
| 25 | +class AuditLogDownloadResult: |
| 26 | + bytes_written: int |
| 27 | + chunks: int |
| 28 | + rows: int |
| 29 | + |
| 30 | + |
| 31 | +@dataclass(frozen=True) |
| 32 | +class AuditLogDownloadProgress(AuditLogDownloadResult): |
| 33 | + chunk_rows: int |
| 34 | + |
| 35 | + |
| 36 | +class _SyncChunkResponse(Protocol): |
| 37 | + @property |
| 38 | + def headers(self) -> httpx.Headers: ... |
| 39 | + |
| 40 | + def read(self) -> bytes: ... |
| 41 | + |
| 42 | + def close(self) -> None: ... |
| 43 | + |
| 44 | + |
| 45 | +class _AsyncChunkResponse(Protocol): |
| 46 | + @property |
| 47 | + def headers(self) -> httpx.Headers: ... |
| 48 | + |
| 49 | + async def read(self) -> bytes: ... |
| 50 | + |
| 51 | + async def close(self) -> None: ... |
| 52 | + |
| 53 | + |
| 54 | +SyncFetchChunk = Callable[[Optional[str]], ContextManager[_SyncChunkResponse]] |
| 55 | +AsyncFetchChunk = Callable[[Optional[str]], AsyncContextManager[_AsyncChunkResponse]] |
| 56 | +ProgressCallback = Callable[[AuditLogDownloadProgress], None] |
| 57 | +AsyncProgressCallback = Callable[[AuditLogDownloadProgress], Optional[Awaitable[None]]] |
| 58 | + |
| 59 | + |
| 60 | +def download_audit_logs( |
| 61 | + fetch_chunk: SyncFetchChunk, |
| 62 | + destination: BinaryIO, |
| 63 | + *, |
| 64 | + on_progress: ProgressCallback | None = None, |
| 65 | + max_transfer_retries: int = _DEFAULT_MAX_TRANSFER_RETRIES, |
| 66 | +) -> AuditLogDownloadResult: |
| 67 | + if not callable(getattr(destination, "write", None)): |
| 68 | + raise TypeError("audit log download destination must provide write()") |
| 69 | + _validate_max_transfer_retries(max_transfer_retries) |
| 70 | + |
| 71 | + cursor: str | None = None |
| 72 | + result = AuditLogDownloadResult(bytes_written=0, chunks=0, rows=0) |
| 73 | + seen_cursors: set[str] = set() |
| 74 | + while True: |
| 75 | + body, headers = _fetch_verified_chunk(fetch_chunk, cursor, max_transfer_retries) |
| 76 | + chunk_rows, next_cursor, has_more = _parse_chunk_headers(headers, cursor) |
| 77 | + if has_more and next_cursor is not None: |
| 78 | + if next_cursor in seen_cursors: |
| 79 | + raise AuditLogDownloadError("response repeated X-Next-Cursor header") |
| 80 | + seen_cursors.add(next_cursor) |
| 81 | + _write_chunk(destination, body) |
| 82 | + |
| 83 | + cursor = next_cursor |
| 84 | + result = AuditLogDownloadResult( |
| 85 | + bytes_written=result.bytes_written + len(body), |
| 86 | + chunks=result.chunks + 1, |
| 87 | + rows=result.rows + chunk_rows, |
| 88 | + ) |
| 89 | + if on_progress is not None: |
| 90 | + on_progress( |
| 91 | + AuditLogDownloadProgress( |
| 92 | + bytes_written=result.bytes_written, |
| 93 | + chunks=result.chunks, |
| 94 | + rows=result.rows, |
| 95 | + chunk_rows=chunk_rows, |
| 96 | + ) |
| 97 | + ) |
| 98 | + if not has_more: |
| 99 | + return result |
| 100 | + |
| 101 | + |
| 102 | +async def async_download_audit_logs( |
| 103 | + fetch_chunk: AsyncFetchChunk, |
| 104 | + destination: BinaryIO, |
| 105 | + *, |
| 106 | + on_progress: AsyncProgressCallback | None = None, |
| 107 | + max_transfer_retries: int = _DEFAULT_MAX_TRANSFER_RETRIES, |
| 108 | +) -> AuditLogDownloadResult: |
| 109 | + if not callable(getattr(destination, "write", None)): |
| 110 | + raise TypeError("audit log download destination must provide write()") |
| 111 | + _validate_max_transfer_retries(max_transfer_retries) |
| 112 | + |
| 113 | + cursor: str | None = None |
| 114 | + result = AuditLogDownloadResult(bytes_written=0, chunks=0, rows=0) |
| 115 | + seen_cursors: set[str] = set() |
| 116 | + while True: |
| 117 | + body, headers = await _async_fetch_verified_chunk(fetch_chunk, cursor, max_transfer_retries) |
| 118 | + chunk_rows, next_cursor, has_more = _parse_chunk_headers(headers, cursor) |
| 119 | + if has_more and next_cursor is not None: |
| 120 | + if next_cursor in seen_cursors: |
| 121 | + raise AuditLogDownloadError("response repeated X-Next-Cursor header") |
| 122 | + seen_cursors.add(next_cursor) |
| 123 | + await to_thread.run_sync(_write_chunk, destination, body) |
| 124 | + |
| 125 | + cursor = next_cursor |
| 126 | + result = AuditLogDownloadResult( |
| 127 | + bytes_written=result.bytes_written + len(body), |
| 128 | + chunks=result.chunks + 1, |
| 129 | + rows=result.rows + chunk_rows, |
| 130 | + ) |
| 131 | + if on_progress is not None: |
| 132 | + callback_result = on_progress( |
| 133 | + AuditLogDownloadProgress( |
| 134 | + bytes_written=result.bytes_written, |
| 135 | + chunks=result.chunks, |
| 136 | + rows=result.rows, |
| 137 | + chunk_rows=chunk_rows, |
| 138 | + ) |
| 139 | + ) |
| 140 | + if inspect.isawaitable(callback_result): |
| 141 | + await callback_result |
| 142 | + if not has_more: |
| 143 | + return result |
| 144 | + |
| 145 | + |
| 146 | +def _fetch_verified_chunk( |
| 147 | + fetch_chunk: SyncFetchChunk, cursor: str | None, max_transfer_retries: int |
| 148 | +) -> tuple[bytes, httpx.Headers]: |
| 149 | + for retries in range(max_transfer_retries + 1): |
| 150 | + transfer_error: Exception | None = None |
| 151 | + with fetch_chunk(cursor) as response: |
| 152 | + try: |
| 153 | + body = response.read() |
| 154 | + headers = httpx.Headers(response.headers) |
| 155 | + _verify_checksum(body, headers) |
| 156 | + except Exception as error: |
| 157 | + transfer_error = error |
| 158 | + else: |
| 159 | + return body, headers |
| 160 | + assert transfer_error is not None |
| 161 | + if retries == max_transfer_retries: |
| 162 | + raise transfer_error |
| 163 | + time.sleep(min(2**retries, _MAX_RETRY_DELAY)) |
| 164 | + raise AssertionError("unreachable") |
| 165 | + |
| 166 | + |
| 167 | +async def _async_fetch_verified_chunk( |
| 168 | + fetch_chunk: AsyncFetchChunk, cursor: str | None, max_transfer_retries: int |
| 169 | +) -> tuple[bytes, httpx.Headers]: |
| 170 | + for retries in range(max_transfer_retries + 1): |
| 171 | + transfer_error: Exception | None = None |
| 172 | + async with fetch_chunk(cursor) as response: |
| 173 | + try: |
| 174 | + body = await response.read() |
| 175 | + headers = httpx.Headers(response.headers) |
| 176 | + await to_thread.run_sync(_verify_checksum, body, headers) |
| 177 | + except Exception as error: |
| 178 | + transfer_error = error |
| 179 | + else: |
| 180 | + return body, headers |
| 181 | + assert transfer_error is not None |
| 182 | + if retries == max_transfer_retries: |
| 183 | + raise transfer_error |
| 184 | + await anyio.sleep(min(2**retries, _MAX_RETRY_DELAY)) |
| 185 | + raise AssertionError("unreachable") |
| 186 | + |
| 187 | + |
| 188 | +def _verify_checksum(body: bytes, headers: httpx.Headers) -> None: |
| 189 | + expected = headers.get("x-content-sha256") |
| 190 | + if not expected: |
| 191 | + raise AuditLogDownloadError("response missing X-Content-Sha256 header") |
| 192 | + actual = hashlib.sha256(body).hexdigest() |
| 193 | + if actual != expected: |
| 194 | + raise AuditLogDownloadError(f"audit log chunk checksum mismatch (got {actual}, want {expected})") |
| 195 | + |
| 196 | + |
| 197 | +def _parse_chunk_headers(headers: httpx.Headers, current_cursor: str | None) -> tuple[int, str | None, bool]: |
| 198 | + has_more_value = headers.get("x-has-more") |
| 199 | + if has_more_value not in {"true", "false"}: |
| 200 | + raise AuditLogDownloadError("response missing or invalid X-Has-More header") |
| 201 | + has_more = has_more_value == "true" |
| 202 | + |
| 203 | + row_count = headers.get("x-row-count") |
| 204 | + if row_count is None or not row_count.isascii() or not row_count.isdecimal(): |
| 205 | + raise AuditLogDownloadError("response missing or invalid X-Row-Count header") |
| 206 | + normalized_row_count = row_count.lstrip("0") or "0" |
| 207 | + if len(normalized_row_count) > len(str(_MAX_CHUNK_ROWS)): |
| 208 | + raise AuditLogDownloadError("response missing or invalid X-Row-Count header") |
| 209 | + rows = int(normalized_row_count) |
| 210 | + if rows > _MAX_CHUNK_ROWS: |
| 211 | + raise AuditLogDownloadError("response missing or invalid X-Row-Count header") |
| 212 | + |
| 213 | + next_cursor = headers.get("x-next-cursor") or None |
| 214 | + if has_more and (not next_cursor or next_cursor == current_cursor): |
| 215 | + raise AuditLogDownloadError("response has invalid X-Next-Cursor header") |
| 216 | + if not has_more and next_cursor: |
| 217 | + raise AuditLogDownloadError("response returned a cursor after the final chunk") |
| 218 | + return rows, next_cursor, has_more |
| 219 | + |
| 220 | + |
| 221 | +def _write_chunk(destination: BinaryIO, body: bytes) -> None: |
| 222 | + remaining = memoryview(body) |
| 223 | + while remaining: |
| 224 | + written = destination.write(remaining) |
| 225 | + if type(written) is not int or written <= 0 or written > len(remaining): |
| 226 | + raise AuditLogDownloadError("audit log download destination performed a short write") |
| 227 | + remaining = remaining[written:] |
| 228 | + |
| 229 | + |
| 230 | +def _validate_max_transfer_retries(max_transfer_retries: int) -> None: |
| 231 | + if type(max_transfer_retries) is not int or max_transfer_retries < 0: |
| 232 | + raise ValueError("max_transfer_retries must be a non-negative integer") |
0 commit comments