From f253ebf8526fd54d6004d4e7ff39757c53f72c94 Mon Sep 17 00:00:00 2001
From: "Ian Grant (aider)" <ian.conway.grant@gmail.com>
Date: Fri, 16 May 2025 16:44:52 -0400
Subject: [PATCH] refactor: wrap MAAP API calls in Job in _safe_request

---
 maap_utils/Job.py | 38 +++++++++++++++++++++++++++-----------
 1 file changed, 27 insertions(+), 11 deletions(-)

diff --git a/maap_utils/Job.py b/maap_utils/Job.py
index e0929c8..bbf5dca 100644
--- a/maap_utils/Job.py
+++ b/maap_utils/Job.py
@@ -1,5 +1,6 @@
+import logging
 from maap.maap import MAAP
-from typing import Optional, Dict
+from typing import Optional, Dict, Any, Callable
 
 maap = MAAP(maap_host="api.maap-project.org")
 
@@ -10,6 +11,8 @@ class Job:
     def __init__(self, kwargs: Dict):
         self._kwargs = kwargs
         self._job_id: Optional[str] = None
+        self._status: Optional[str] = None
+        self._result_url: Optional[str] = None
 
     @property
     def kwargs(self) -> Dict:
@@ -22,28 +25,41 @@ class Job:
         return self._job_id
 
     def __repr__(self) -> str:
-        return f"Job(job_id={self._job_id})"
-        self._status: Optional[str] = None
-        self._result_url: Optional[str] = None
+        return f"Job(job_id={self._job_id}, status={self._status})"
+
+    def _safe_request(self, fn: Callable[..., Any], *args, **kwargs) -> Any:
+        """Call a MAAP function, catch and log exceptions."""
+        try:
+            return fn(*args, **kwargs)
+        except Exception as e:
+            logging.error(f"MAAP API error in {fn.__name__}: {e}")
+            return None
 
     def submit(self) -> None:
         """Submit this job to MAAP"""
-        job = maap.submitJob(**self.kwargs)
-        self._job_id = job.id
+        job_obj = self._safe_request(maap.submitJob, **self.kwargs)
+        if job_obj and hasattr(job_obj, "id"):
+            self._job_id = job_obj.id
+        else:
+            raise RuntimeError("Failed to submit job—no job ID returned")
 
-    def get_status(self) -> str:
+    def get_status(self) -> Optional[str]:
         """Get current job status from MAAP API"""
-        self._status = maap.getJobStatus(self.job_id)
+        status = self._safe_request(maap.getJobStatus, self.job_id)
+        if status is not None:
+            self._status = status
         return self._status
 
-    def get_result(self) -> str:
+    def get_result(self) -> Optional[str]:
         """Get job result URL from MAAP API"""
-        self._result_url = maap.getJobResult(self.job_id)[0]
+        result = self._safe_request(maap.getJobResult, self.job_id)
+        if result:
+            self._result_url = result[0]
         return self._result_url
 
     def cancel(self) -> None:
         """Cancel this job"""
-        maap.cancelJob(self.job_id)
+        self._safe_request(maap.cancelJob, self.job_id)
 
     def __hash__(self) -> int:
         """Hash function for the job object"""
-- 
GitLab