Fix type hints and resource management in coe_mirror
- Add precise type hints: Optional[Tuple[str, str]] for _fetch_creds(), List[Tuple[str, str, str]] for notify() - Wrap requests.Session in context manager for proper cleanup - Remove unreachable return False after retry loop in _send_matrix()
This commit is contained in:
+35
-36
@@ -17,7 +17,7 @@ import zipfile
|
|||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from fcntl import flock, LOCK_EX, LOCK_NB
|
from fcntl import flock, LOCK_EX, LOCK_NB
|
||||||
from typing import Optional
|
from typing import List, Optional, Tuple
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
@@ -340,7 +340,7 @@ def _write_token_cache(access_token: str, expires_at_iso: str) -> None:
|
|||||||
logger.warning("token cache write failed: %s", exc)
|
logger.warning("token cache write failed: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
def _fetch_creds() -> Optional[tuple]:
|
def _fetch_creds() -> Optional[Tuple[str, str]]:
|
||||||
"""Fetch (user, password) from Infisical via creds. Return None on failure."""
|
"""Fetch (user, password) from Infisical via creds. Return None on failure."""
|
||||||
try:
|
try:
|
||||||
user = subprocess.run(
|
user = subprocess.run(
|
||||||
@@ -415,44 +415,43 @@ def _send_matrix(message: str) -> bool:
|
|||||||
Non-fatal: any failure logs WARN and returns False. Never raises.
|
Non-fatal: any failure logs WARN and returns False. Never raises.
|
||||||
Implements one 401 retry with token refresh.
|
Implements one 401 retry with token refresh.
|
||||||
"""
|
"""
|
||||||
session = requests.Session()
|
with requests.Session() as session:
|
||||||
session.headers.update({"User-Agent": USER_AGENT})
|
session.headers.update({"User-Agent": USER_AGENT})
|
||||||
|
|
||||||
encoded_room = quote(MATRIX_ROOM, safe="")
|
encoded_room = quote(MATRIX_ROOM, safe="")
|
||||||
url = f"{MATRIX_HOMESERVER}/_matrix/client/r0/rooms/{encoded_room}/send/m.room.message"
|
url = f"{MATRIX_HOMESERVER}/_matrix/client/r0/rooms/{encoded_room}/send/m.room.message"
|
||||||
body = {"msgtype": "m.text", "body": message}
|
body = {"msgtype": "m.text", "body": message}
|
||||||
|
|
||||||
for attempt in (1, 2):
|
for attempt in (1, 2):
|
||||||
token = _get_matrix_token(session, force_refresh=(attempt == 2))
|
token = _get_matrix_token(session, force_refresh=(attempt == 2))
|
||||||
if not token:
|
if not token:
|
||||||
logger.warning("matrix send aborted: no token (attempt %d)", attempt)
|
logger.warning("matrix send aborted: no token (attempt %d)", attempt)
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
resp = session.post(
|
resp = session.post(
|
||||||
url,
|
url,
|
||||||
json=body,
|
json=body,
|
||||||
headers={"Authorization": f"Bearer {token}"},
|
headers={"Authorization": f"Bearer {token}"},
|
||||||
timeout=MATRIX_TIMEOUT,
|
timeout=MATRIX_TIMEOUT,
|
||||||
)
|
)
|
||||||
if resp.status_code == 200:
|
if resp.status_code == 200:
|
||||||
logger.info("matrix sent: %s", message[:80])
|
logger.info("matrix sent: %s", message[:80])
|
||||||
return True
|
return True
|
||||||
if resp.status_code == 401 and attempt == 1:
|
if resp.status_code == 401 and attempt == 1:
|
||||||
logger.info("matrix 401 on send; refreshing token and retrying")
|
logger.info("matrix 401 on send; refreshing token and retrying")
|
||||||
continue
|
continue
|
||||||
logger.warning("matrix send failed: HTTP %d body=%s",
|
logger.warning("matrix send failed: HTTP %d body=%s",
|
||||||
resp.status_code, resp.text[:200])
|
resp.status_code, resp.text[:200])
|
||||||
return False
|
return False
|
||||||
except requests.RequestException as exc:
|
except requests.RequestException as exc:
|
||||||
logger.warning("matrix send network error: %s", exc)
|
logger.warning("matrix send network error: %s", exc)
|
||||||
return False
|
return False
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.warning("matrix send unexpected error: %s", exc)
|
logger.warning("matrix send unexpected error: %s", exc)
|
||||||
return False
|
return False
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def notify(summary: list) -> None:
|
def notify(summary: List[Tuple[str, str, str]]) -> None:
|
||||||
"""Build a Matrix message and POST it. Non-fatal."""
|
"""Build a Matrix message and POST it. Non-fatal."""
|
||||||
if not summary:
|
if not summary:
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user