"""Async Microsoft Graph client.
Behaviour every module gets for free:
* **Throttling:** 429 and 503/504 responses are retried after the
``Retry-After`` delay (or exponential backoff with jitter). While one
request is throttled, all requests through the same client pause, which is
what Graph expects of a well-behaved client.
* **Concurrency limit:** at most ``max_concurrency`` requests in flight.
* **Auth:** a 401 triggers one token refresh and retry.
* **Paging:** :meth:`GraphClient.paginate` follows ``@odata.nextLink``.
* **Delta queries:** :meth:`GraphClient.delta` returns items plus the new
``@odata.deltaLink``; an expired link raises :class:`DeltaExpiredError` so
the module can do a full resync.
* **Batching:** :meth:`GraphClient.batch` sends up to 20 requests per call.
* **Streaming:** :meth:`GraphClient.stream` downloads content without holding
it in memory.
"""
from __future__ import annotations
import asyncio
import random
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from email.utils import parsedate_to_datetime
from typing import Any
import httpx
from s365b import __version__
from s365b.core.logging import get_logger
from s365b.graph.auth import TokenProvider
[docs]
GRAPH_V1 = "https://graph.microsoft.com/v1.0"
[docs]
RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
# For a request that must not run twice (creating something): retried only
# when it certainly was not carried out. Throttling responses mean the
# request was not processed; a 500 or a lost response could mean it was.
[docs]
RETRY_STATUSES_UNSAFE = frozenset({429, 503})
[docs]
NOT_SENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
[docs]
log = get_logger(__name__)
[docs]
class GraphError(Exception):
"""An error response from Microsoft Graph.
Attributes:
status: HTTP status code.
code: Graph error code, e.g. ``"ErrorItemNotFound"``.
message: Graph error message.
request_id: ``request-id`` header, useful for Microsoft support.
"""
def __init__(self, status: int, code: str, message: str, request_id: str | None = None):
suffix = f" (request-id {request_id})" if request_id else ""
super().__init__(f"Graph {status} {code}: {message}{suffix}")
[docs]
self.request_id = request_id
@classmethod
[docs]
def from_response(cls, resp: httpx.Response) -> GraphError:
"""Build an error from an HTTP response.
Args:
resp: The failed response.
Returns:
The error (a :class:`DeltaExpiredError` for expired delta links).
"""
code, message = "unknown", resp.reason_phrase
try:
err = resp.json().get("error", {})
code, message = err.get("code", code), err.get("message", message)
except ValueError:
pass
error_cls = DeltaExpiredError if resp.status_code == 410 else cls
return error_cls(resp.status_code, code, message, resp.headers.get("request-id"))
[docs]
class DeltaExpiredError(GraphError):
"""The delta link is no longer valid; a full resync is needed."""
@dataclass(slots=True)
[docs]
class DeltaResult:
"""Result of a delta query.
Attributes:
items: Changed items. Deleted items carry an ``@removed`` key.
delta_link: Link to pass next time to get only later changes (last
page only).
next_link: Link to the next page; saving it lets an interrupted
first sync resume where it stopped.
"""
[docs]
items: list[dict[str, Any]] = field(default_factory=list)
[docs]
delta_link: str | None = None
[docs]
next_link: str | None = None
@dataclass(frozen=True, slots=True)
[docs]
class BatchRequest:
"""One request inside a JSON batch.
Attributes:
id: Caller-chosen ID to match responses.
method: HTTP method.
url: URL relative to the API version, e.g. ``/users/{id}``.
body: Optional JSON body.
"""
[docs]
body: dict[str, Any] | None = None
@dataclass(frozen=True, slots=True)
[docs]
class BatchResponse:
"""One response from a JSON batch.
Attributes:
id: Matching :attr:`BatchRequest.id`.
status: HTTP status of this sub-request.
body: Parsed body (may be empty).
"""
[docs]
body: dict[str, Any]
def _loggable(url: str, authenticate: bool) -> str:
"""What of a request URL may be logged: its path, never its query string.
Args:
url: The absolute request URL.
authenticate: Whether the request carries our token (otherwise the
URL is its own credential, and only the host is shown).
Returns:
The text to log.
"""
parsed = httpx.URL(url)
if not authenticate:
return f"{parsed.host} (pre-authenticated URL)"
return parsed.path
[docs]
class GraphClient:
"""Async client for Microsoft Graph.
Args:
token_provider: Supplies access tokens.
base_url: API root, ``https://graph.microsoft.com/v1.0`` by default.
max_concurrency: Maximum parallel requests.
max_retries: Retries per request for throttling and server errors.
max_backoff: Upper bound in seconds for any single wait.
http: Optional pre-built ``httpx.AsyncClient`` (tests).
"""
def __init__(
self,
token_provider: TokenProvider,
*,
base_url: str = GRAPH_V1,
max_concurrency: int = 4,
max_retries: int = 8,
max_backoff: float = 120.0,
http: httpx.AsyncClient | None = None,
) -> None:
self._tokens = token_provider
[docs]
self.base_url = base_url.rstrip("/")
self._sem = asyncio.Semaphore(max_concurrency)
self._max_retries = max_retries
self._max_backoff = max_backoff
self._paused_until = 0.0
self._http = http or httpx.AsyncClient(
timeout=httpx.Timeout(60.0, connect=15.0),
follow_redirects=True, # httpx drops Authorization on cross-origin redirects
headers={"User-Agent": f"Mail Safehouse/{__version__}"},
)
[docs]
async def aclose(self) -> None:
"""Close the underlying HTTP connections."""
await self._http.aclose()
async def __aenter__(self) -> GraphClient:
return self
async def __aexit__(self, *exc: object) -> None:
await self.aclose()
def _url(self, url: str) -> str:
return url if url.startswith("https://") else f"{self.base_url}/{url.lstrip('/')}"
# -- core request loop ---------------------------------------------------
@asynccontextmanager
async def _send(
self,
method: str,
url: str,
*,
json: Any = None,
content: bytes | None = None,
params: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
stream: bool = False,
authenticate: bool = True,
idempotent: bool = True,
) -> AsyncIterator[httpx.Response]:
"""Send a request with retries; yields the successful response.
``authenticate=False`` sends no token, for pre-authenticated URLs
such as a mailbox import session's. ``idempotent=False`` is for
requests that create something: they are retried only when they
certainly did not reach Microsoft or were throttled, never after a
lost response, which could leave a duplicate.
"""
retry_statuses = RETRY_STATUSES if idempotent else RETRY_STATUSES_UNSAFE
refreshed = not authenticate # nothing to refresh without a token
attempt = 0
# A pre-authenticated URL carries its own credential (in the path or
# the query): only its host is ever logged.
shown = _loggable(self._url(url), authenticate)
while True:
await self._wait_if_paused()
hdrs = dict(headers or {})
if authenticate:
token = await self._tokens.get_token(force_refresh=refreshed and attempt == 0)
hdrs["Authorization"] = f"Bearer {token}"
req = self._http.build_request(
method, self._url(url), json=json, content=content, params=params, headers=hdrs
)
started = time.monotonic()
try:
async with self._sem:
resp = await self._http.send(req, stream=stream)
except httpx.TransportError as exc:
if attempt >= self._max_retries or not (idempotent or isinstance(exc, NOT_SENT)):
raise
delay = self._backoff(attempt)
log.warning("graph.transport_error", url=shown, error=str(exc), retry_in=delay)
attempt += 1
await asyncio.sleep(delay)
continue
if resp.status_code == 401 and not refreshed:
await resp.aclose()
refreshed, attempt = True, 0
continue
if resp.status_code in retry_statuses and attempt < self._max_retries:
delay = self._retry_after(resp) or self._backoff(attempt)
if resp.status_code == 429:
self._paused_until = max(self._paused_until, time.monotonic() + delay)
log.warning(
"graph.retry", url=shown, status=resp.status_code, retry_in=round(delay, 1)
)
await resp.aclose()
attempt += 1
await asyncio.sleep(delay)
continue
ms = round((time.monotonic() - started) * 1000)
if resp.is_error:
if stream:
await resp.aread()
await resp.aclose()
err = GraphError.from_response(resp)
# Logged even when the caller handles it (e.g. a 404 for an
# item deleted meanwhile): the request ID lets Microsoft
# support trace it. No bodies or tokens are logged.
log.info(
"graph.error",
method=method,
path=shown,
status=err.status,
code=err.code,
message=err.message[:300],
request_id=err.request_id,
ms=ms,
)
raise err
log.debug(
"graph.request",
method=method,
path=shown,
status=resp.status_code,
request_id=resp.headers.get("request-id"),
ms=ms,
)
try:
yield resp
finally:
await resp.aclose()
return
async def _wait_if_paused(self) -> None:
delay = self._paused_until - time.monotonic()
if delay > 0:
await asyncio.sleep(delay)
def _backoff(self, attempt: int) -> float:
return float(min(self._max_backoff, (2**attempt) + random.uniform(0, 1))) # noqa: S311
def _retry_after(self, resp: httpx.Response) -> float | None:
value = resp.headers.get("Retry-After")
if not value:
return None
try:
seconds = float(value)
except ValueError:
try:
seconds = parsedate_to_datetime(value).timestamp() - time.time()
except (TypeError, ValueError):
return None
return float(min(self._max_backoff, max(0.0, seconds)))
# -- public API ----------------------------------------------------------
[docs]
async def request(
self,
method: str,
url: str,
*,
json: Any = None,
content: bytes | None = None,
params: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
authenticate: bool = True,
idempotent: bool = True,
) -> httpx.Response:
"""Send a request and return the (fully read) response.
Args:
method: HTTP method.
url: Absolute URL or path relative to :attr:`base_url`.
json: JSON body.
content: Raw body (e.g. a piece of a file upload), instead of
``json``.
params: Query parameters.
headers: Extra headers (e.g. ``ConsistencyLevel: eventual``).
authenticate: False to send no access token (pre-authenticated
URLs).
idempotent: False for a request that creates something; it is
not retried when it may already have been carried out.
Returns:
The successful response.
Raises:
GraphError: For error responses after retries.
"""
async with self._send(
method,
url,
json=json,
content=content,
params=params,
headers=headers,
authenticate=authenticate,
idempotent=idempotent,
) as resp:
await resp.aread()
return resp
[docs]
async def get_json(
self,
url: str,
*,
params: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> dict[str, Any]:
"""GET a URL and return the JSON body.
Args:
url: Absolute URL or path.
params: Query parameters.
headers: Extra headers, e.g. ``Prefer: IdType="ImmutableId"``.
Returns:
The parsed body.
"""
resp = await self.request("GET", url, params=params, headers=headers)
data: dict[str, Any] = resp.json()
return data
[docs]
async def paginate(
self,
url: str,
*,
params: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> AsyncIterator[dict[str, Any]]:
"""Yield every item of a collection, following ``@odata.nextLink``.
Args:
url: Collection URL or path.
params: Query parameters for the first page.
headers: Extra headers for every page.
Yields:
Items from the ``value`` arrays.
"""
next_url: str | None = url
next_params = params
while next_url:
page = await self.get_json(next_url, params=next_params, headers=headers)
for item in page.get("value", []):
yield item
next_url, next_params = page.get("@odata.nextLink"), None
[docs]
async def delta(
self,
url: str,
*,
delta_link: str | None = None,
params: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> AsyncIterator[DeltaResult]:
"""Run a delta query page by page.
Each yielded :class:`DeltaResult` holds one page of items; the last
one also carries ``delta_link``. Modules can checkpoint after each
page.
Args:
url: Delta URL for the first full sync, e.g.
``/users/{id}/mailFolders/{fid}/messages/delta``.
delta_link: Saved delta link from the previous run; when given,
``url`` and ``params`` are ignored.
params: Query parameters for the initial request.
headers: Extra headers for every page (e.g. ``Prefer`` for
immutable IDs or page size).
Yields:
Pages of changes.
Raises:
DeltaExpiredError: If ``delta_link`` has expired (HTTP 410).
"""
next_url: str | None = delta_link or url
next_params = None if delta_link else params
while next_url:
page = await self.get_json(next_url, params=next_params, headers=headers)
next_params = None
next_url = page.get("@odata.nextLink")
result = DeltaResult(items=list(page.get("value", [])), next_link=next_url)
if not next_url:
result.delta_link = page.get("@odata.deltaLink")
yield result
[docs]
async def batch(self, requests: list[BatchRequest]) -> list[BatchResponse]:
"""Send requests as JSON batches of up to 20, retrying throttled ones.
Args:
requests: Requests with unique IDs.
Returns:
Responses in the same order as ``requests``.
"""
results: dict[str, BatchResponse] = {}
pending = list(requests)
attempt = 0
while pending:
retry: list[BatchRequest] = []
wait = 0.0
for start in range(0, len(pending), BATCH_LIMIT):
chunk = pending[start : start + BATCH_LIMIT]
body = {
"requests": [
{"id": r.id, "method": r.method, "url": r.url}
| (
{"body": r.body, "headers": {"Content-Type": "application/json"}}
if r.body is not None
else {}
)
for r in chunk
]
}
resp = await self.request("POST", "$batch", json=body)
by_id = {r.id: r for r in chunk}
for sub in resp.json().get("responses", []):
status = int(sub.get("status", 0))
if status in RETRY_STATUSES and attempt < self._max_retries:
retry.append(by_id[sub["id"]])
ra = (sub.get("headers") or {}).get("Retry-After")
wait = max(wait, float(ra) if ra else self._backoff(attempt))
else:
results[sub["id"]] = BatchResponse(sub["id"], status, sub.get("body") or {})
pending = retry
if pending:
attempt += 1
await asyncio.sleep(min(wait, self._max_backoff))
return [results[r.id] for r in requests]
[docs]
async def stream(
self,
url: str,
*,
chunk_size: int = 1024 * 1024,
headers: dict[str, str] | None = None,
) -> AsyncIterator[bytes]:
"""Download content as a stream of byte chunks.
Args:
url: Content URL, e.g. ``/users/{id}/messages/{mid}/$value``.
chunk_size: Preferred piece size.
headers: Extra headers.
Yields:
Pieces of the body.
"""
async with self._send("GET", url, stream=True, headers=headers) as resp:
async for piece in resp.aiter_bytes(chunk_size):
yield piece