"""Background sync from local BugTicket → OpenProject work package. Idempotency note (MVP): we do NOT auto-retry an in-flight 'syncing' ticket because OP create is not idempotent — a duplicate WP could be produced. Manual retry via the UI is allowed but documented as best-effort. """ from __future__ import annotations import asyncio from typing import Optional from src.db import BugTicketRepository from src.db.database import get_db from src.integrations.openproject.client import OpenProjectClient, OpenProjectError from src.integrations.openproject.config import OpenProjectConfig from src.integrations.openproject.context_loader import ( ScreenshotProvider, load_turn_context_for_bug, ) from src.integrations.openproject.payload_builder import ( ResolvedRefs, ScreenshotMeta, build_work_package_payload, ) from src.utils.logging import get_logger logger = get_logger(__name__) def sync_bug_to_openproject(bug_id: str, *, config: Optional[OpenProjectConfig] = None) -> None: """Synchronously push a BugTicket to OpenProject. Updates sync_status. Safe to call from BackgroundTasks (FastAPI runs sync callables in a threadpool) or from an asyncio loop via asyncio.to_thread. The OpenProject token used for the call is the **bug creator's** token (resolved via :func:`resolve_openproject_token`), with an env fallback in dev mode. If neither is available we mark the bug as ``failed``. """ cfg = config or OpenProjectConfig.from_env() if cfg is None: logger.info("openproject_sync_skipped_no_config", extra={"bug_id": bug_id}) return db = get_db() screenshot_provider = ScreenshotProvider(max_bytes=cfg.max_attachment_bytes) with db.get_session() as session: repo = BugTicketRepository(session) ticket = repo.claim_for_sync(bug_id) if ticket is None: # Either not found or already in 'syncing' state — skip. logger.info("openproject_sync_skipped_already_inflight", extra={"bug_id": bug_id}) return # Resolve the per-user token. created_by is the Supabase user id # (or email in dev) populated by the route handler at create time. from src.integrations.openproject.token_store import resolve_openproject_token resolved = resolve_openproject_token(session, user_id=ticket.created_by) if resolved is None: repo.update_sync_state( ticket.id, status="failed", sync_error=( "no_user_token: bug creator has no OpenProject token configured " "(Profilo → Integrazioni)." ), ) logger.warning( "openproject_sync_no_user_token", extra={"bug_id": bug_id, "user_id": str(ticket.created_by or "")}, ) return # Build a per-call config that injects the user token while inheriting # the rest of the env settings (URL, timeouts, max attachment, ...). runtime_cfg = OpenProjectConfig( url=cfg.url, api_token=resolved.token, project_identifier=cfg.project_identifier, default_type_id=cfg.default_type_id, timeout_seconds=cfg.timeout_seconds, max_attachment_bytes=cfg.max_attachment_bytes, retry_loop_enabled=cfg.retry_loop_enabled, retry_interval_seconds=cfg.retry_interval_seconds, max_sync_attempts=cfg.max_sync_attempts, public_base_url=cfg.public_base_url, ) client = OpenProjectClient(runtime_cfg) cfg = runtime_cfg # rest of the function uses cfg.public_base_url etc. # Build context + screenshot OUTSIDE the create call so failures # in those phases don't get conflated with OP HTTP errors. try: turn_context = load_turn_context_for_bug(session, ticket) except Exception as exc: logger.warning( "openproject_sync_turn_context_load_failed", extra={"bug_id": bug_id, "error": str(exc)[:200]}, ) turn_context = None screenshot_payload = None screenshot_bytes = None try: shot = screenshot_provider.get_bytes_for_bug(session, ticket) if shot is not None: content, filename, content_type = shot screenshot_bytes = (content, filename, content_type) screenshot_payload = ScreenshotMeta(filename=filename, content_type=content_type) except Exception as exc: logger.warning( "openproject_sync_screenshot_resolve_failed", extra={"bug_id": bug_id, "error": str(exc)[:200]}, ) # ---- Determine target project + resolve enum refs by name ---- target_project = ( (ticket.external_project_identifier or "").strip() or cfg.project_identifier ) if not target_project: repo.update_sync_state( ticket.id, status="failed", sync_error=( "no_target_project: pick an OpenProject project from the " "dropdown when creating the bug, or set " "OPENPROJECT_PROJECT_IDENTIFIER as default" ), ) return refs = _resolve_refs_for_project(client, target_project, cfg) # User pick wins over the env default. explicit_category = (ticket.external_category_id or "").strip() if explicit_category: try: refs = ResolvedRefs( type_id=refs.type_id, category_id=int(explicit_category), version_id=refs.version_id, ) except (TypeError, ValueError): logger.warning( "openproject_invalid_category_id", extra={"bug_id": bug_id, "value": explicit_category}, ) # Compose the work package body. try: payload = build_work_package_payload( bug=ticket, turn=turn_context or load_turn_context_for_bug(session, ticket), screenshot=screenshot_payload, config=cfg, refs=refs, ) except Exception as exc: logger.exception( "openproject_sync_payload_build_failed", extra={"bug_id": bug_id} ) repo.update_sync_state( ticket.id, status="failed", sync_error=f"payload_build_failed: {exc}"[:500], ) return try: wp_response = client.create_work_package( payload, project_identifier=target_project ) except OpenProjectError as exc: logger.warning( "openproject_create_failed", extra={ "bug_id": bug_id, "status_code": exc.status_code, "transient": exc.transient, }, ) repo.update_sync_state( ticket.id, status="failed", sync_error=f"create_failed: {exc}"[:500], ) return except Exception as exc: logger.exception("openproject_create_unexpected", extra={"bug_id": bug_id}) repo.update_sync_state( ticket.id, status="failed", sync_error=f"create_unexpected: {exc}"[:500], ) return wp_id = wp_response.get("id") if not isinstance(wp_id, int): try: wp_id = int(wp_id) except (TypeError, ValueError): wp_id = None if wp_id is None: repo.update_sync_state( ticket.id, status="failed", sync_error="create_returned_no_id", ) return external_id = str(wp_id) external_url = client.make_ui_url(wp_id) # ---- Attach screenshot (best-effort) ---- attach_error: Optional[str] = None if screenshot_bytes is not None: content, filename, content_type = screenshot_bytes try: client.attach_file( wp_id, filename=filename, content=content, content_type=content_type, description="Turn screenshot", ) except OpenProjectError as exc: attach_error = f"attachment_failed: {exc}" logger.warning( "openproject_attach_failed", extra={ "bug_id": bug_id, "wp_id": wp_id, "status_code": exc.status_code, }, ) except Exception as exc: attach_error = f"attachment_failed: {exc}" logger.exception( "openproject_attach_unexpected", extra={"bug_id": bug_id, "wp_id": wp_id}, ) # WP exists → mark synced even if attachment failed (informative warning). repo.update_sync_state( ticket.id, status="synced", external_id=external_id, external_url=external_url, sync_error=attach_error[:500] if attach_error else None, mark_synced_at=True, ) logger.info( "openproject_sync_ok", extra={ "bug_id": bug_id, "wp_id": wp_id, "with_attachment": screenshot_bytes is not None and not attach_error, }, ) async def sync_bug_to_openproject_async(bug_id: str) -> None: """Async wrapper used by FastAPI BackgroundTasks. Runs the blocking sync function in a worker thread to avoid blocking the event loop.""" try: await asyncio.to_thread(sync_bug_to_openproject, bug_id) except Exception: # BackgroundTasks won't surface exceptions to the request — log them. logger.exception("openproject_sync_background_failed", extra={"bug_id": bug_id}) # ---- ref resolver with small in-memory cache ---------------------- import time as _time _REFS_TTL = 600 # 10 minutes _refs_cache: dict = {} def _resolve_refs_for_project( client: OpenProjectClient, project_identifier: str, cfg: OpenProjectConfig ) -> ResolvedRefs: """Resolve type/category/version IDs by name for the given project. Cached per-project for ``_REFS_TTL`` seconds. A failed lookup logs a warning and leaves the corresponding field as None — the WP create proceeds without that link, OP will fall back to defaults. """ cache_key = (project_identifier, cfg.default_type_name, cfg.default_category_name, cfg.default_version_name) now = _time.monotonic() cached = _refs_cache.get(cache_key) if cached is not None: ts, refs = cached if now - ts < _REFS_TTL: return refs refs = ResolvedRefs() try: for t in client.list_types(project_identifier): if (t.get("name") or "").strip().lower() == cfg.default_type_name.strip().lower(): refs = ResolvedRefs(type_id=t.get("id")) break except Exception as exc: logger.warning( "openproject_resolve_type_failed", extra={"project": project_identifier, "error": str(exc)[:200]}, ) try: for c in client.list_categories(project_identifier): if (c.get("name") or "").strip().lower() == cfg.default_category_name.strip().lower(): refs = ResolvedRefs( type_id=refs.type_id, category_id=c.get("id"), version_id=refs.version_id, ) break except Exception as exc: logger.warning( "openproject_resolve_category_failed", extra={"project": project_identifier, "error": str(exc)[:200]}, ) try: for v in client.list_versions(project_identifier): if (v.get("name") or "").strip().lower() == cfg.default_version_name.strip().lower(): refs = ResolvedRefs( type_id=refs.type_id, category_id=refs.category_id, version_id=v.get("id"), ) break except Exception as exc: logger.warning( "openproject_resolve_version_failed", extra={"project": project_identifier, "error": str(exc)[:200]}, ) _refs_cache[cache_key] = (now, refs) return refs