Samad14 commited on
Commit
e47db42
·
1 Parent(s): fee674e

Phase 0c: offload large artifacts to Supabase Storage (docking, pipeline, sequencing)

Browse files
bioai-platform/backend/app/routers/docking.py CHANGED
@@ -61,11 +61,18 @@ def _prune_old(supabase, max_rows: int = 200):
61
  def _row_to_response(row: dict) -> dict:
62
  """Convert a Supabase row to the frontend DockingResult shape."""
63
  result = None
64
- if row.get("result_sdf"):
 
 
 
 
 
 
65
  try:
66
  result = json.loads(row["result_sdf"])
67
  except Exception:
68
  pass
 
69
  return {
70
  "job_id": row["id"],
71
  "status": row["status"],
@@ -74,6 +81,16 @@ def _row_to_response(row: dict) -> dict:
74
  }
75
 
76
 
 
 
 
 
 
 
 
 
 
 
77
  # ---------------------------------------------------------------------------
78
  # Background worker
79
  # ---------------------------------------------------------------------------
@@ -178,11 +195,14 @@ def _run_docking_sync(job_id: str, payload: dict):
178
  "ligand_pdb": vina_result.get("ligand_pdb", ""),
179
  }
180
 
 
 
 
 
181
  supabase.table(_TABLE).update({
182
- # Keep the persisted value aligned with the frontend's terminal
183
- # status contract (and the other job runners in this service).
184
  "status": "complete",
185
- "result_sdf": json.dumps(result_obj),
 
186
  }).eq("id", job_id).execute()
187
 
188
  except Exception as exc:
@@ -696,13 +716,22 @@ async def get_docking_job(job_id: str, user_id: str = Depends(require_user_id)):
696
  @router.get("/result/{job_id}/pdb")
697
  async def get_docking_pdb(job_id: str, user_id: str = Depends(require_user_id)):
698
  supabase = get_client()
699
- result = supabase.table(_TABLE).select("result_sdf").eq("id", job_id).eq("user_id", user_id).single().execute()
700
- if not result.data or not result.data.get("result_sdf"):
 
 
 
 
 
 
 
 
 
 
 
 
 
701
  raise HTTPException(status_code=404, detail="Docking result not found")
702
- try:
703
- data = json.loads(result.data["result_sdf"])
704
- except Exception:
705
- raise HTTPException(status_code=500, detail="Invalid result data")
706
  ligand_pdb = data.get("ligand_pdb", "")
707
  if not ligand_pdb:
708
  raise HTTPException(status_code=404, detail="No ligand PDB available")
@@ -722,4 +751,4 @@ async def list_docking_jobs(limit: int = 50, user_id: str = Depends(require_user
722
  .execute()
723
  .data
724
  )
725
- return {"jobs": [_row_to_response(r) for r in rows]}
 
61
  def _row_to_response(row: dict) -> dict:
62
  """Convert a Supabase row to the frontend DockingResult shape."""
63
  result = None
64
+
65
+ # Prefer Storage URL (Phase 0c)
66
+ storage_url = row.get("storage_url")
67
+ if storage_url:
68
+ from app.services.artifact_storage import download_json
69
+ result = download_json(storage_url)
70
+ elif row.get("result_sdf"):
71
  try:
72
  result = json.loads(row["result_sdf"])
73
  except Exception:
74
  pass
75
+
76
  return {
77
  "job_id": row["id"],
78
  "status": row["status"],
 
81
  }
82
 
83
 
84
+ def _row_to_list_response(row: dict) -> dict:
85
+ """Lightweight row conversion for list views — skips Storage downloads."""
86
+ return {
87
+ "job_id": row["id"],
88
+ "status": row["status"],
89
+ "result": None,
90
+ "error": row.get("error"),
91
+ }
92
+
93
+
94
  # ---------------------------------------------------------------------------
95
  # Background worker
96
  # ---------------------------------------------------------------------------
 
195
  "ligand_pdb": vina_result.get("ligand_pdb", ""),
196
  }
197
 
198
+ # Offload to Supabase Storage; DB keeps only the URL
199
+ from app.services.artifact_storage import upload_json
200
+ storage_url = upload_json(job_id, "result", result_obj)
201
+
202
  supabase.table(_TABLE).update({
 
 
203
  "status": "complete",
204
+ "storage_url": storage_url,
205
+ "result_sdf": None, # cleared — data lives in Storage now
206
  }).eq("id", job_id).execute()
207
 
208
  except Exception as exc:
 
716
  @router.get("/result/{job_id}/pdb")
717
  async def get_docking_pdb(job_id: str, user_id: str = Depends(require_user_id)):
718
  supabase = get_client()
719
+ row = supabase.table(_TABLE).select("result_sdf,storage_url").eq("id", job_id).eq("user_id", user_id).single().execute()
720
+ if not row.data:
721
+ raise HTTPException(status_code=404, detail="Docking result not found")
722
+
723
+ data = None
724
+ if row.data.get("storage_url"):
725
+ from app.services.artifact_storage import download_json
726
+ data = download_json(row.data["storage_url"])
727
+ elif row.data.get("result_sdf"):
728
+ try:
729
+ data = json.loads(row.data["result_sdf"])
730
+ except Exception:
731
+ pass
732
+
733
+ if not data:
734
  raise HTTPException(status_code=404, detail="Docking result not found")
 
 
 
 
735
  ligand_pdb = data.get("ligand_pdb", "")
736
  if not ligand_pdb:
737
  raise HTTPException(status_code=404, detail="No ligand PDB available")
 
751
  .execute()
752
  .data
753
  )
754
+ return {"jobs": [_row_to_list_response(r) for r in rows]}
bioai-platform/backend/app/routers/jobs.py CHANGED
@@ -42,6 +42,14 @@ async def get_job(job_id: str, user_id: str | None = Depends(get_user_id)):
42
  job = result.data[0]
43
  if user_id and job.get("user_id") and job["user_id"] != user_id:
44
  raise HTTPException(status_code=403, detail="Access denied")
 
 
 
 
 
 
 
 
45
  return job
46
 
47
 
 
42
  job = result.data[0]
43
  if user_id and job.get("user_id") and job["user_id"] != user_id:
44
  raise HTTPException(status_code=403, detail="Access denied")
45
+
46
+ # Hydrate from Storage if result was offloaded
47
+ if job.get("storage_url") and not job.get("results"):
48
+ from app.services.artifact_storage import download_json
49
+ results = download_json(job["storage_url"])
50
+ if results:
51
+ job["results"] = results
52
+
53
  return job
54
 
55
 
bioai-platform/backend/app/routers/sequencing.py CHANGED
@@ -84,7 +84,18 @@ def _read(job_id: str, user_id: str | None = None) -> dict | None:
84
  if user_id:
85
  query = query.eq("user_id", user_id)
86
  rows = query.execute().data
87
- return dict(rows[0]) if rows else None
 
 
 
 
 
 
 
 
 
 
 
88
 
89
 
90
  async def _worker(job_id: str) -> None:
@@ -111,7 +122,10 @@ async def _worker(job_id: str) -> None:
111
  if "error" in result and not result.get("steps_completed"):
112
  _patch(job_id, status="failed", error=result["error"], done_at=datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S'))
113
  else:
114
- _patch(job_id, status="complete", result=result, done_at=datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S'))
 
 
 
115
 
116
 
117
  VALID_DEMO = {"synthetic", "demo", "test"}
 
84
  if user_id:
85
  query = query.eq("user_id", user_id)
86
  rows = query.execute().data
87
+ if not rows:
88
+ return None
89
+ job = dict(rows[0])
90
+
91
+ # Hydrate from Storage if result was offloaded
92
+ if job.get("storage_url") and not job.get("result"):
93
+ from app.services.artifact_storage import download_json
94
+ result = download_json(job["storage_url"])
95
+ if result:
96
+ job["result"] = result
97
+
98
+ return job
99
 
100
 
101
  async def _worker(job_id: str) -> None:
 
122
  if "error" in result and not result.get("steps_completed"):
123
  _patch(job_id, status="failed", error=result["error"], done_at=datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S'))
124
  else:
125
+ # Offload large result to Storage
126
+ from app.services.artifact_storage import upload_json
127
+ storage_url = upload_json(job_id, "result", result)
128
+ _patch(job_id, status="complete", storage_url=storage_url, result=None, done_at=datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S'))
129
 
130
 
131
  VALID_DEMO = {"synthetic", "demo", "test"}
bioai-platform/backend/app/services/artifact_storage.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Supabase Storage wrapper for large job artifacts.
3
+
4
+ Uploads large payloads (docking PDBQT, pipeline context, sequencing consensus)
5
+ to a Supabase Storage bucket and returns a public URL reference. The DB row
6
+ stores only the URL, not the payload itself.
7
+
8
+ Buckets must be created manually in the Supabase dashboard or via migration:
9
+ - 'job-artifacts' (private, with public read for authenticated users)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import logging
16
+ from typing import Optional
17
+
18
+ from app.services.supabase import get_client
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ BUCKET = "job-artifacts"
23
+
24
+
25
+ def _ensure_bucket() -> None:
26
+ """Create the bucket if it doesn't exist (idempotent)."""
27
+ try:
28
+ sb = get_client()
29
+ buckets = sb.storage.list_buckets()
30
+ names = [b.name for b in buckets] if buckets else []
31
+ if BUCKET not in names:
32
+ sb.storage.create_bucket(BUCKET, options={"public": True})
33
+ logger.info("Created Supabase Storage bucket: %s", BUCKET)
34
+ except Exception:
35
+ logger.warning("Could not ensure bucket %s — uploads may fail", BUCKET)
36
+
37
+
38
+ def upload_artifact(job_id: str, kind: str, data: str, content_type: str = "application/json") -> str:
39
+ """Upload a string payload to Storage and return its public URL.
40
+
41
+ Args:
42
+ job_id: The job UUID.
43
+ kind: Artifact type (e.g. 'result', 'context', 'consensus').
44
+ data: The string content to upload.
45
+ content_type: MIME type.
46
+
47
+ Returns:
48
+ Public URL of the uploaded artifact.
49
+ """
50
+ _ensure_bucket()
51
+ path = f"{job_id}/{kind}.json"
52
+ sb = get_client()
53
+ # Upsert (overwrite if exists)
54
+ sb.storage.from_(BUCKET).upload(
55
+ path,
56
+ data.encode("utf-8"),
57
+ {"content-type": content_type, "upsert": "true"},
58
+ )
59
+ url = sb.storage.from_(BUCKET).get_public_url(path)
60
+ return url
61
+
62
+
63
+ def upload_json(job_id: str, kind: str, payload: dict) -> str:
64
+ """Upload a dict as JSON to Storage and return its public URL."""
65
+ return upload_artifact(job_id, kind, json.dumps(payload), "application/json")
66
+
67
+
68
+ def download_artifact(url_or_path: str) -> Optional[str]:
69
+ """Download artifact content from a Storage URL or path.
70
+
71
+ If the input is a full URL, extracts the path and downloads from Storage.
72
+ If it's a relative path, downloads directly.
73
+ Returns the content as a string, or None on failure.
74
+ """
75
+ if not url_or_path:
76
+ return None
77
+
78
+ # Extract path from full URL: https://xxx.supabase.co/storage/v1/object/public/bucket/path
79
+ path = url_or_path
80
+ if "storage/v1" in url_or_path:
81
+ # Extract everything after '/object/public/bucket-name/'
82
+ parts = url_or_path.split(f"{BUCKET}/", 1)
83
+ if len(parts) > 1:
84
+ path = parts[1]
85
+
86
+ try:
87
+ sb = get_client()
88
+ res = sb.storage.from_(BUCKET).download(path)
89
+ if isinstance(res, bytes):
90
+ return res.decode("utf-8")
91
+ return str(res)
92
+ except Exception:
93
+ logger.warning("Failed to download artifact: %s", url_or_path)
94
+ return None
95
+
96
+
97
+ def download_json(url_or_path: str) -> Optional[dict]:
98
+ """Download and parse a JSON artifact."""
99
+ raw = download_artifact(url_or_path)
100
+ if raw is None:
101
+ return None
102
+ try:
103
+ return json.loads(raw)
104
+ except Exception:
105
+ return None
bioai-platform/backend/app/workers/pipeline_worker.py CHANGED
@@ -77,12 +77,18 @@ async def process_job(job_id: str) -> None:
77
  result = await run_pipeline(query, organism=organism, analysis_type=analysis_type)
78
 
79
  done_at = datetime.datetime.utcnow().isoformat()
 
 
 
 
 
80
  await _patch(
81
  "jobs",
82
  job_id,
83
  {
84
  "status": "completed",
85
- "results": result,
 
86
  "updated_at": done_at,
87
  "completed_at": done_at,
88
  },
 
77
  result = await run_pipeline(query, organism=organism, analysis_type=analysis_type)
78
 
79
  done_at = datetime.datetime.utcnow().isoformat()
80
+
81
+ # Offload large result to Supabase Storage
82
+ from app.services.artifact_storage import upload_json
83
+ storage_url = upload_json(job_id, "context", result)
84
+
85
  await _patch(
86
  "jobs",
87
  job_id,
88
  {
89
  "status": "completed",
90
+ "storage_url": storage_url,
91
+ "results": None,
92
  "updated_at": done_at,
93
  "completed_at": done_at,
94
  },
bioai-platform/backend/migrations/006_artifact_storage.sql ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Phase 0c: Add storage_url columns for large artifact offloading to Supabase Storage.
2
+
3
+ -- docking_jobs: result_sdf moves to Storage; DB keeps only the URL.
4
+ ALTER TABLE docking_jobs
5
+ ADD COLUMN IF NOT EXISTS storage_url text;
6
+
7
+ -- jobs: context_json / result moves to Storage for large payloads.
8
+ ALTER TABLE jobs
9
+ ADD COLUMN IF NOT EXISTS storage_url text;
10
+
11
+ -- sequencing_jobs: consensus_sequence and large result sub-objects move to Storage.
12
+ ALTER TABLE sequencing_jobs
13
+ ADD COLUMN IF NOT EXISTS storage_url text;