Skip to content
Merged
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
59 changes: 44 additions & 15 deletions pyporscheconnectapi/connection.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# SPDX-License-Identifier: Apache-2.0

Check failure on line 1 in pyporscheconnectapi/connection.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (CPY001)

pyporscheconnectapi/connection.py:1:1: CPY001 Missing copyright notice at top of file
"""Python Package for controlling Porsche Connect API."""

from __future__ import annotations

import asyncio
import logging
import secrets

Check failure on line 8 in pyporscheconnectapi/connection.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (F401)

pyporscheconnectapi/connection.py:8:8: F401 `secrets` imported but unused help: Remove unused import: `secrets`

import httpx

Expand All @@ -14,6 +15,24 @@

_LOGGER = logging.getLogger(__name__)

# HTTP status codes that justify a retry (transient server-side issues):
# 429 (rate limit), 502/503/504 (gateway / upstream timeouts)
_RETRY_STATUS_CODES = frozenset({429, 502, 503, 504})
_MAX_RETRIES = 3
_MAX_RETRY_DELAY = 30.0


def _compute_retry_delay(response: httpx.Response, attempt: int) -> float:
"""Return how many seconds to wait before retrying after a transient error.

Prefer the server-provided Retry-After header (RFC 9110 §10.2.3) if
provided as digit, otherwise fall back to exponential backoff (2s, 4s, 8s).
"""
retry_after = response.headers.get("retry-after", "")
if retry_after.isdigit():
return min(float(retry_after), _MAX_RETRY_DELAY)
return min((2 ** (attempt + 1)), _MAX_RETRY_DELAY)


async def log_request(request):
"""Provide formatting for http logging."""
Expand All @@ -32,7 +51,7 @@
:param leeway: time in seconds to consider token as expired before it actually expires
"""

def __init__(

Check failure on line 54 in pyporscheconnectapi/connection.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (PLR0917)

pyporscheconnectapi/connection.py:54:9: PLR0917 Too many positional arguments (7 > 5)
self,
email: str | None = None,
password: str | None = None,
Expand Down Expand Up @@ -81,22 +100,32 @@
"""Make a DELETE request to the Porsche Connect API."""
return await self.request("DELETE", url, data=data, json=json)

async def request(self, method, url, **kwargs):
async def request(self, method, url, **kwargs): # noqa: RET503 - loop body always returns or raises
"""Create a request to the Porsche Connect API."""
try:
async with self.token_lock:
await self.oauth2_client.ensure_valid_token(self.token)
resp = await self.asyncClient.request(
method,
f"{API_BASE_URL}{url}",
headers=self.headers | {"Authorization": f"Bearer {self.token.access_token}"},
timeout=TIMEOUT,
**kwargs,
)
resp.raise_for_status() # A common error seem to be: httpx.HTTPStatusError: Server error '504 Gateway Time-out'
return resp.json()
except httpx.HTTPStatusError as exc:
raise PorscheExceptionError(exc.response.status_code) from exc
async with self.token_lock:
await self.oauth2_client.ensure_valid_token(self.token)

for attempt in range(_MAX_RETRIES + 1):
try:
resp = await self.asyncClient.request(
method,
f"{API_BASE_URL}{url}",
headers=self.headers | {"Authorization": f"Bearer {self.token.access_token}"},
timeout=TIMEOUT,
**kwargs,
)
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError as exc: # noqa: PERF203
status = exc.response.status_code
if status not in _RETRY_STATUS_CODES or attempt == _MAX_RETRIES:
raise PorscheExceptionError(status) from exc
delay = _compute_retry_delay(exc.response, attempt)
_LOGGER.warning(
"Transient HTTP %s on %s - retrying in %.1fs (attempt %d/%d)",
status, url, delay, attempt + 1, _MAX_RETRIES,
)
await asyncio.sleep(delay)

async def close(self):
"""Close the asyncClient connection."""
Expand Down
Loading