"""HTTP client for OpenProject REST API v3. Auth is HTTP Basic with username 'apikey' and password = the API token. Errors are normalized to OpenProjectError with a transient flag so the sync layer can decide retry policy. """ from __future__ import annotations import base64 import json from typing import Any, Dict, List, Optional import httpx from src.integrations.openproject.config import OpenProjectConfig from src.utils.logging import get_logger logger = get_logger(__name__) class OpenProjectError(Exception): """Wrapper around OpenProject HTTP errors with a transient flag.""" def __init__( self, message: str, *, status_code: Optional[int] = None, body_excerpt: Optional[str] = None, transient: bool = False, ): super().__init__(message) self.status_code = status_code self.body_excerpt = body_excerpt self.transient = transient class OpenProjectClient: """Thin synchronous client over httpx.Client. Methods raise OpenProjectError on failure; on success return parsed JSON. No internal retry loop — the caller (sync.py / retry_loop.py) decides. """ def __init__(self, config: OpenProjectConfig): self._config = config token_blob = f"apikey:{config.api_token}".encode("utf-8") self._auth_header = "Basic " + base64.b64encode(token_blob).decode("ascii") # ---- public API ---- def create_work_package( self, payload: Dict[str, Any], *, project_identifier: Optional[str] = None ) -> Dict[str, Any]: """POST /api/v3/projects/{identifier}/work_packages. Returns parsed JSON. ``project_identifier`` overrides the default from config — used by the bug-ticket sync to honor the user's per-bug project choice. """ pid = (project_identifier or self._config.project_identifier).strip() path = f"/api/v3/projects/{pid}/work_packages" return self._request_json("POST", path, json_body=payload) def list_projects(self) -> List[Dict[str, Any]]: """GET /api/v3/projects. Returns a flat list of {id, identifier, name}. Only projects the API token can access are returned. Archived projects are filtered out (HAL exposes ``active=False`` for those). """ out = self._request_json("GET", "/api/v3/projects?pageSize=200") elements = ((out or {}).get("_embedded") or {}).get("elements") or [] items: List[Dict[str, Any]] = [] for p in elements: if not isinstance(p, dict): continue if p.get("active") is False: continue identifier = p.get("identifier") if not identifier: continue items.append( { "id": p.get("id"), "identifier": identifier, "name": p.get("name") or identifier, } ) # Stable alphabetical sort for the dropdown. items.sort(key=lambda x: (x.get("name") or "").lower()) return items # ---- project-scoped enums (categories, versions) ---- def list_categories(self, project_identifier: str) -> List[Dict[str, Any]]: """GET /api/v3/projects/{id}/categories → [{id, name}].""" path = f"/api/v3/projects/{project_identifier}/categories" out = self._request_json("GET", path) elements = ((out or {}).get("_embedded") or {}).get("elements") or [] return [ {"id": el.get("id"), "name": el.get("name")} for el in elements if isinstance(el, dict) and el.get("id") and el.get("name") ] def list_versions(self, project_identifier: str) -> List[Dict[str, Any]]: """GET /api/v3/projects/{id}/versions → [{id, name, status}].""" path = f"/api/v3/projects/{project_identifier}/versions" out = self._request_json("GET", path) elements = ((out or {}).get("_embedded") or {}).get("elements") or [] return [ { "id": el.get("id"), "name": el.get("name"), "status": el.get("status"), } for el in elements if isinstance(el, dict) and el.get("id") and el.get("name") ] def list_types(self, project_identifier: str) -> List[Dict[str, Any]]: """GET /api/v3/projects/{id}/types → [{id, name}].""" path = f"/api/v3/projects/{project_identifier}/types" out = self._request_json("GET", path) elements = ((out or {}).get("_embedded") or {}).get("elements") or [] return [ {"id": el.get("id"), "name": el.get("name")} for el in elements if isinstance(el, dict) and el.get("id") and el.get("name") ] def list_summary_tasks( self, project_identifier: str, *, page_size: int = 100 ) -> List[Dict[str, Any]]: """List "Summary task" work packages of a project — the candidates for the parent dropdown. Sorted alphabetically by subject.""" # Resolve the "Summary task" type id for this project. type_id = None for t in self.list_types(project_identifier): if (t.get("name") or "").strip().lower() == "summary task": type_id = t.get("id") break if type_id is None: return [] # Filter work packages by that type. import json as _json filters = _json.dumps([{"type": {"operator": "=", "values": [str(type_id)]}}]) from urllib.parse import quote path = ( f"/api/v3/projects/{project_identifier}/work_packages" f"?filters={quote(filters)}&pageSize={page_size}" ) out = self._request_json("GET", path) elements = ((out or {}).get("_embedded") or {}).get("elements") or [] items: List[Dict[str, Any]] = [] for el in elements: if not isinstance(el, dict): continue wp_id = el.get("id") subject = el.get("subject") if not wp_id or not subject: continue items.append( { "id": wp_id, "subject": subject, "status": (el.get("_links", {}) or {}) .get("status", {}) .get("title"), } ) items.sort(key=lambda x: (x.get("subject") or "").lower()) return items def attach_file( self, work_package_id: int, *, filename: str, content: bytes, content_type: str, description: Optional[str] = None, ) -> Dict[str, Any]: """POST /api/v3/work_packages/{id}/attachments (multipart).""" path = f"/api/v3/work_packages/{work_package_id}/attachments" metadata = {"fileName": filename} if description: metadata["description"] = {"raw": description} files = { # OpenProject expects `metadata` as JSON-content part and `file` as the binary. "metadata": (None, json.dumps(metadata), "application/json"), "file": (filename, content, content_type), } return self._request_json("POST", path, files=files) def make_ui_url(self, work_package_id: int) -> str: """Build the human-facing URL for a work package.""" return f"{self._config.base_url}/work_packages/{work_package_id}" # ---- internals ---- def _request_json( self, method: str, path: str, *, json_body: Optional[Dict[str, Any]] = None, files: Optional[Dict[str, Any]] = None, client: Optional[httpx.Client] = None, ) -> Dict[str, Any]: url = f"{self._config.base_url}{path}" headers = { "Authorization": self._auth_header, "Accept": "application/json", } # httpx sets Content-Type automatically for json= and files=. own_client = client is None cli = client or httpx.Client(timeout=self._config.timeout_seconds) try: try: response = cli.request( method, url, headers=headers, json=json_body if files is None else None, files=files, ) except httpx.TimeoutException as exc: raise OpenProjectError( f"Timeout calling OpenProject {method} {path}: {exc}", transient=True, ) from exc except httpx.RequestError as exc: raise OpenProjectError( f"Connection error calling OpenProject {method} {path}: {exc}", transient=True, ) from exc return self._parse_response(response, method, path) finally: if own_client: cli.close() @staticmethod def _parse_response( response: httpx.Response, method: str, path: str ) -> Dict[str, Any]: status = response.status_code log_extra = { "component": "openproject", "method": method, "path": path, "status_code": status, } if 200 <= status < 300: try: data = response.json() except ValueError as exc: raise OpenProjectError( f"OpenProject {method} {path} returned non-JSON body", status_code=status, body_excerpt=response.text[:200], transient=False, ) from exc logger.info("openproject_request_ok", extra=log_extra) return data body_excerpt = response.text[:500] # 5xx and 429 are transient; 4xx (auth, validation) are permanent. transient = status >= 500 or status == 429 logger.warning( "openproject_request_failed", extra={**log_extra, "transient": transient, "body_excerpt": body_excerpt[:200]}, ) raise OpenProjectError( f"OpenProject {method} {path} returned HTTP {status}", status_code=status, body_excerpt=body_excerpt, transient=transient, )