5151from contextlib import suppress
5252from datetime import timedelta
5353from pathlib import Path
54- from typing import Any , TypeGuard
54+ from typing import TypeGuard
5555from uuid import uuid4
5656
5757from fastapi import HTTPException
6565from ..schemas import ClinicalCnvKbJobOut , ClinicalCnvKbStatusOut
6666from .access_control import CurrentUser , is_admin_user
6767from .metadata_service import get_current_user_by_id
68+ from .reference_load_jobs import FAILED , JobClosed , JobTable
6869from .reference_metadata_service import apply_reference_dataset_text
6970
7071logger = logging .getLogger (__name__ )
8384 "it was probably restarted or redeployed. Request a new rebuild."
8485)
8586_SCRIPT_MISSING = "The clinical CNV knowledgebase build script is not available on the server."
86- _FAILED = "status = 'failed', worker_id = NULL, completed_at = now(), error = :error"
8787# The build writes the pinned source files it checked to this file in its temporary folder
8888# (--sources-out), and the load records them.
8989_SOURCES_FILE = "clinical_cnv_knowledgebase.sources.json"
@@ -238,35 +238,26 @@ def _job_out(row: RowMapping) -> ClinicalCnvKbJobOut:
238238)
239239
240240
241- async def _close_jobs_whose_worker_is_gone (session : AsyncSession ) -> None :
242- """Close as failed an active job with no sign of its build for the stale window.
243-
244- A running job's last sign is its heartbeat; a queued one's is its request, as its run
245- starts at once. The database clock judges both, as it stamped them. The caller commits.
246- """
247- closed = (
248- await session .execute (
249- text (
250- """
251- UPDATE clinical_cnv_kb_jobs
252- SET status = 'failed', worker_id = NULL, completed_at = now(), error = :error
253- WHERE status IN ('queued', 'running')
254- AND COALESCE(heartbeat_at, requested_at)
255- < now() - CAST(:stale_window AS interval)
256- RETURNING id::text AS id
257- """
258- ),
259- {"stale_window" : CLINICAL_CNV_KB_STALE_HEARTBEAT , "error" : _STALE_ERROR },
260- )
261- ).mappings ().all ()
262- for row in closed :
263- logger .warning ("Closed clinical CNV knowledgebase rebuild %s: its worker is gone" , row ["id" ])
241+ # The rebuild's job table (``reference_load_jobs``): claimed, written and closed as the
242+ # reference loads' jobs are.
243+ _JOBS = JobTable (
244+ table = "clinical_cnv_kb_jobs" ,
245+ what = "clinical CNV knowledgebase rebuild" ,
246+ claimed = (
247+ "assembly_id::text AS assembly_id, assembly_name, skip_clinvar, requested_by, "
248+ "requested_by_id::text AS requested_by_id"
249+ ),
250+ stale_window = CLINICAL_CNV_KB_STALE_HEARTBEAT ,
251+ stale_error = _STALE_ERROR ,
252+ heartbeat_seconds = CLINICAL_CNV_KB_HEARTBEAT_SECONDS ,
253+ log = logger ,
254+ )
264255
265256
266257async def get_clinical_cnv_kb_status (session : AsyncSession ) -> ClinicalCnvKbStatusOut :
267258 # What the admin page polls: a job whose worker is gone is closed here, so it no longer
268259 # shows as active and a new rebuild can be requested.
269- await _close_jobs_whose_worker_is_gone (session )
260+ await _JOBS . close_stale (session )
270261 await session .commit ()
271262 rows = (
272263 await session .execute (
@@ -323,7 +314,7 @@ async def queue_clinical_cnv_kb_rebuild(
323314 # partial unique index idx_clinical_cnv_kb_jobs_one_active (02_reference.sql). A job
324315 # whose worker is gone is closed first, in the same transaction.
325316 try :
326- await _close_jobs_whose_worker_is_gone (session )
317+ await _JOBS . close_stale (session )
327318 row = (
328319 await session .execute (
329320 text (
@@ -406,71 +397,6 @@ async def queue_clinical_cnv_kb_rebuild_if_missing(
406397 )
407398
408399
409- async def _claim_job (job_id : str , worker_id : str ) -> dict [str , Any ] | None :
410- """Take the queued job for this worker: running, with its first heartbeat.
411-
412- None when the job is no longer queued (or gone): it is not this worker's to run.
413- """
414- sessionmaker = get_postgres_sessionmaker ()
415- async with sessionmaker () as session :
416- row = (
417- await session .execute (
418- text (
419- """
420- UPDATE clinical_cnv_kb_jobs
421- SET status = 'running', worker_id = :worker_id,
422- started_at = now(), heartbeat_at = now()
423- WHERE id = CAST(:job_id AS uuid) AND status = 'queued'
424- RETURNING assembly_id::text AS assembly_id, assembly_name, skip_clinvar, requested_by,
425- requested_by_id::text AS requested_by_id
426- """
427- ),
428- {"job_id" : job_id , "worker_id" : worker_id },
429- )
430- ).mappings ().first ()
431- await session .commit ()
432- return dict (row ) if row is not None else None
433-
434-
435- async def _update_job (
436- job_id : str , worker_id : str | None , assignments : str , params : dict [str , Any ]
437- ) -> bool :
438- """Write to the job while it is this worker's; False once it is not (it was closed).
439-
440- Without a worker (a run that could not take its job), only a job still queued is written.
441- """
442- bound = {** params , "job_id" : job_id }
443- if worker_id is not None :
444- owned = "worker_id = :worker_id"
445- bound ["worker_id" ] = worker_id
446- else :
447- owned = "status = 'queued'"
448- sessionmaker = get_postgres_sessionmaker ()
449- async with sessionmaker () as session :
450- result = await session .execute (
451- text (
452- f"UPDATE clinical_cnv_kb_jobs SET { assignments } "
453- f"WHERE id = CAST(:job_id AS uuid) AND { owned } RETURNING id"
454- ),
455- bound ,
456- )
457- written = result .first () is not None
458- await session .commit ()
459- return written
460-
461-
462- async def _record_failure (job_id : str , worker_id : str | None , error : str ) -> None :
463- """Mark the job failed; when even that fails, say in the log which job is left active."""
464- try :
465- await _update_job (job_id , worker_id , _FAILED , {"error" : error })
466- except Exception :
467- logger .exception (
468- "Clinical CNV knowledgebase rebuild %s could not be marked failed; it stays active "
469- "until it has been silent for the stale window and is closed" ,
470- job_id ,
471- )
472-
473-
474400async def _requester_refusal (requester_id : str | None , requested_by : str | None = None ) -> str | None :
475401 """Why the rebuild is not run, or not loaded, for the account that asked for it: it no
476402 longer exists (its deletion unlinks the job), has been deactivated, or is no longer an
@@ -492,10 +418,6 @@ async def _requester_refusal(requester_id: str | None, requested_by: str | None
492418 return None
493419
494420
495- class _JobClosed (Exception ):
496- """The job was closed while it ran (its worker taken for gone): no longer this worker's."""
497-
498-
499421class _BuildTimedOut (TimeoutError ):
500422 """The build outlived CLINICAL_CNV_KB_BUILD_TIMEOUT_SECONDS and was stopped."""
501423
@@ -515,7 +437,7 @@ async def _await_build(process: asyncio.subprocess.Process, *, job_id: str, work
515437 """Wait for the build, heartbeating while it runs, and return its stderr.
516438
517439 Stops the build when it outlives CLINICAL_CNV_KB_BUILD_TIMEOUT_SECONDS (_BuildTimedOut), or
518- when a heartbeat finds the job closed (_JobClosed ). As with the family-import queue's
440+ when a heartbeat finds the job closed (JobClosed ). As with the family-import queue's
519441 periodic progress, a heartbeat that fails is logged and the build goes on.
520442 """
521443 loop = asyncio .get_running_loop ()
@@ -536,12 +458,12 @@ async def _await_build(process: asyncio.subprocess.Process, *, job_id: str, work
536458 if output in done :
537459 return output .result ()[1 ] or b""
538460 try :
539- still_ours = await _update_job (job_id , worker_id , "heartbeat_at = now()" , {})
461+ still_ours = await _JOBS . update (job_id , worker_id , "heartbeat_at = now()" , {})
540462 except Exception :
541463 logger .exception ("Clinical CNV knowledgebase rebuild heartbeat failed" )
542464 continue
543465 if not still_ours :
544- raise _JobClosed ()
466+ raise JobClosed ()
545467 finally :
546468 # Stopped (timeout, closed job, server shutting down) or failed: no build outlives it.
547469 if not output .done ():
@@ -561,7 +483,7 @@ async def _run_job(job_id: str) -> None:
561483 owner : str | None = None # this worker, once it has taken the job
562484 tmp_dir : str | None = None
563485 try :
564- row = await _claim_job (job_id , worker_id )
486+ row = await _JOBS . claim (job_id , worker_id )
565487 if row is None :
566488 logger .info ("Clinical CNV knowledgebase rebuild %s is no longer queued; not started" , job_id )
567489 return
@@ -574,11 +496,11 @@ async def _run_job(job_id: str) -> None:
574496 "is no longer an active administrator" ,
575497 job_id ,
576498 )
577- await _update_job (job_id , owner , _FAILED , {"error" : refusal })
499+ await _JOBS . update (job_id , owner , FAILED , {"error" : refusal })
578500 return
579501 script = _script_path ()
580502 if script is None :
581- await _update_job (job_id , owner , _FAILED , {"error" : _SCRIPT_MISSING })
503+ await _JOBS . update (job_id , owner , FAILED , {"error" : _SCRIPT_MISSING })
582504 return
583505
584506 tmp_dir = tempfile .mkdtemp (prefix = "cnv-kb-" )
@@ -611,7 +533,7 @@ async def _run_job(job_id: str) -> None:
611533 # loaded, so the knowledgebase from before the rebuild stays as it was.
612534 reason = _failure_reason (log_tail )
613535 error = f"Knowledgebase build failed (exit { process .returncode } )"
614- await _update_job (
536+ await _JOBS . update (
615537 job_id ,
616538 owner ,
617539 "status = 'failed', worker_id = NULL, completed_at = now(), error = :error, log = :log" ,
@@ -631,7 +553,7 @@ async def _run_job(job_id: str) -> None:
631553 job_id ,
632554 type (exc ).__name__ ,
633555 )
634- await _update_job (
556+ await _JOBS . update (
635557 job_id ,
636558 owner ,
637559 "status = 'failed', worker_id = NULL, completed_at = now(), error = :error, log = :log" ,
@@ -641,16 +563,16 @@ async def _run_job(job_id: str) -> None:
641563 # Replace the knowledgebase only while the job is still this worker's, and its
642564 # requester still an active administrator: the build ran for up to two hours, and an
643565 # account deleted, deactivated or demoted meanwhile has nothing loaded.
644- if not await _update_job (job_id , owner , "heartbeat_at = now()" , {}):
645- raise _JobClosed ()
566+ if not await _JOBS . update (job_id , owner , "heartbeat_at = now()" , {}):
567+ raise JobClosed ()
646568 refusal = await _requester_refusal (row .get ("requested_by_id" ), row .get ("requested_by" ))
647569 if refusal is not None :
648570 logger .warning (
649571 "Clinical CNV knowledgebase rebuild %s not loaded: the account that requested it "
650572 "is no longer an active administrator" ,
651573 job_id ,
652574 )
653- await _update_job (
575+ await _JOBS . update (
654576 job_id ,
655577 owner ,
656578 "status = 'failed', worker_id = NULL, completed_at = now(), error = :error, log = :log" ,
@@ -674,22 +596,22 @@ async def _run_job(job_id: str) -> None:
674596 source = "clinical-cnv-kb" ,
675597 source_version = release ,
676598 )
677- await _update_job (
599+ await _JOBS . update (
678600 job_id ,
679601 owner ,
680602 "status = 'completed', worker_id = NULL, completed_at = now(), "
681603 "inserted = :inserted, log = :log" ,
682604 {"inserted" : result .inserted , "log" : log_tail },
683605 )
684- except _JobClosed :
606+ except JobClosed :
685607 logger .warning (
686608 "Clinical CNV knowledgebase rebuild %s was closed while it ran (its worker was taken "
687609 "for gone); stopped without loading it" ,
688610 job_id ,
689611 )
690612 except Exception as exc : # surfaced to the admin UI as the job's error
691613 logger .exception ("Clinical CNV knowledgebase rebuild failed" )
692- await _record_failure (job_id , owner , _failure_text (exc )[:2000 ])
614+ await _JOBS . record_end (job_id , owner , "failed" , _failure_text (exc )[:2000 ])
693615 finally :
694616 if tmp_dir is not None :
695617 shutil .rmtree (tmp_dir , ignore_errors = True )
0 commit comments