Spaces:
Runtime error

File size: 12,932 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"""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