Source code for imednet.models.jobs

# pylint: disable=duplicate-code
"""Job and background operation models for iMedNet."""

from __future__ import annotations

from enum import Enum
from typing import Any

from pydantic import Field, ValidationInfo, field_validator, model_validator

from imednet.errors.base import ImednetError
from imednet.models.base import ImednetBaseModel
from imednet.models.engine import ModelEngine


[docs]class JobState(str, Enum): """Enumeration of valid job states.""" PENDING = "PENDING" QUEUED = "QUEUED" OPEN = "OPEN" RUNNING = "RUNNING" PROCESSING = "PROCESSING" COMPLETED = "COMPLETED" COMPLETE = "COMPLETE" SUCCESS = "SUCCESS" FAILED = "FAILED" CANCELLED = "CANCELLED" TIMEOUT = "TIMEOUT"
[docs] def can_transition_to(self, target: JobState | str) -> bool: """Check if this state can transition to target state.""" return is_valid_job_transition(self, target)
[docs] def validate_transition_to(self, target: JobState | str) -> bool: """Validate transition from this state to target state.""" return validate_job_transition(self, target)
def __str__(self) -> str: """Return the string value of the state.""" return str(self.value) @property def allowed_transitions(self) -> set[JobState]: """Return the set of allowed target states from this state.""" return ALLOWED_JOB_TRANSITIONS.get(self, set())
TERMINAL_JOB_STATES: set[JobState] = { JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS, JobState.FAILED, JobState.CANCELLED, JobState.TIMEOUT, } ACTIVE_JOB_STATES: set[JobState] = { JobState.PENDING, JobState.QUEUED, JobState.OPEN, JobState.RUNNING, JobState.PROCESSING, } SUCCESSFUL_JOB_STATES: set[JobState] = { JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS, } FAILED_JOB_STATES: set[JobState] = { JobState.FAILED, JobState.CANCELLED, JobState.TIMEOUT, } ALLOWED_JOB_TRANSITIONS: dict[JobState, set[JobState]] = { JobState.PENDING: { JobState.PENDING, JobState.QUEUED, JobState.OPEN, JobState.RUNNING, JobState.PROCESSING, JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS, JobState.FAILED, JobState.CANCELLED, JobState.TIMEOUT, }, JobState.QUEUED: { JobState.QUEUED, JobState.RUNNING, JobState.PROCESSING, JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS, JobState.FAILED, JobState.CANCELLED, JobState.TIMEOUT, }, JobState.OPEN: { JobState.OPEN, JobState.QUEUED, JobState.RUNNING, JobState.PROCESSING, JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS, JobState.FAILED, JobState.CANCELLED, JobState.TIMEOUT, }, JobState.RUNNING: { JobState.RUNNING, JobState.PROCESSING, JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS, JobState.FAILED, JobState.CANCELLED, JobState.TIMEOUT, }, JobState.PROCESSING: { JobState.PROCESSING, JobState.RUNNING, JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS, JobState.FAILED, JobState.CANCELLED, JobState.TIMEOUT, }, JobState.COMPLETED: {JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS}, JobState.COMPLETE: {JobState.COMPLETED, JobState.COMPLETE, JobState.SUCCESS}, JobState.SUCCESS: {JobState.SUCCESS, JobState.COMPLETED, JobState.COMPLETE}, JobState.FAILED: {JobState.FAILED}, JobState.CANCELLED: {JobState.CANCELLED}, JobState.TIMEOUT: {JobState.TIMEOUT}, }
[docs]class InvalidJobStateError(ImednetError, ValueError): """Raised when an unrecognized job state string is encountered."""
[docs]class InvalidJobTransitionError(ImednetError, ValueError): """Raised when an invalid state transition is attempted."""
InvalidStateTransitionError = InvalidJobTransitionError
[docs]def normalize_job_state(state: JobState | str) -> JobState: """Normalize and validate a job state string into a JobState enum member. Args: state: The job state to normalize (JobState enum member or string). Returns: The normalized JobState enum member. Raises: InvalidJobStateError: If the state string is unrecognized. """ if isinstance(state, JobState): return state if isinstance(state, str): cleaned = state.strip().upper() try: return JobState(cleaned) except ValueError as err: allowed = sorted(s.value for s in JobState) raise InvalidJobStateError( f"Invalid job state: '{state}'. Must be one of: {allowed}" ) from err raise InvalidJobStateError(f"Invalid job state type: {type(state).__name__}")
[docs]def is_valid_job_transition( from_state: JobState | str, to_state: JobState | str, ) -> bool: """Check if transitioning from from_state to to_state is permitted. Args: from_state: The current or originating job state. to_state: The desired or target job state. Returns: True if the transition is allowed, False otherwise. """ try: from_enum = normalize_job_state(from_state) to_enum = normalize_job_state(to_state) except (InvalidJobStateError, ValueError): return False return to_enum in ALLOWED_JOB_TRANSITIONS.get(from_enum, set())
[docs]def validate_job_transition( from_state: JobState | str, to_state: JobState | str, ) -> bool: """Validate that transitioning from from_state to to_state is permitted. Args: from_state: The current or originating job state. to_state: The desired or target job state. Returns: True if the transition is valid. Raises: InvalidJobStateError: If either state is not a recognized JobState. InvalidJobTransitionError: If the transition moves backwards or is not permitted. """ from_enum = normalize_job_state(from_state) to_enum = normalize_job_state(to_state) if from_enum in TERMINAL_JOB_STATES and to_enum in ACTIVE_JOB_STATES: raise InvalidJobTransitionError( f"Cannot transition terminal job state {from_enum.value} back to active state {to_enum.value}." ) allowed = ALLOWED_JOB_TRANSITIONS.get(from_enum, set()) if to_enum not in allowed: allowed_names = sorted(s.value for s in allowed) raise InvalidJobTransitionError( f"Invalid job state transition from {from_enum.value} to {to_enum.value}. " f"Allowed transitions from {from_enum.value}: {allowed_names}" ) return True
[docs]@ModelEngine.register class Job(ImednetBaseModel): """Represents an asynchronous background job.""" state: JobState | str | None = Field(default=None, alias="state") @field_validator("state", mode="before") @classmethod def _validate_state(cls, v: Any) -> JobState | None: """Validate and normalize state to JobState enum.""" if v is None: return None return normalize_job_state(v)
[docs] def transition_to(self, target: JobState | str) -> Job: """Transition job to a new state along an approved lifecycle path. Args: target: Desired target state. Returns: The job instance updated with the target state. """ target_state = normalize_job_state(target) if self.state is not None: validate_job_transition(self.state, target_state) self.state = target_state return self
@property def is_terminal(self) -> bool: """Checks if the job has reached a final state (Success/Failed/Cancelled).""" return self.state in TERMINAL_JOB_STATES if self.state else False @property def is_successful(self) -> bool: """Checks if the job completed successfully.""" return self.state in SUCCESSFUL_JOB_STATES if self.state else False @property def is_failed(self) -> bool: """Checks if the job failed or was cancelled.""" return self.state in FAILED_JOB_STATES if self.state else False
[docs]@ModelEngine.register class JobStatus(Job): """Extended job information returned when polling.""" progress: int | None = Field(default=None, alias="progress") result_url: str | None = Field(default=None, alias="resultUrl") results: Any = Field(default=None) record_total_count: int | None = Field(default=None, alias="totalRecords") record_success_count: int | None = Field(default=None, alias="successfulRecords") record_failure_count: int | None = Field(default=None, alias="failedRecords") result_error: str | None = Field(default=None, alias="resultError") @model_validator(mode="before") @classmethod def _normalize_record_count_keys(cls, data: Any, info: ValidationInfo) -> Any: """Accept snake_case record count kwargs without colliding with properties.""" if not isinstance(data, dict): return data if isinstance(info.context, dict) and info.context.get("wire"): return data normalized = dict(data) if "total_records" in normalized and "totalRecords" not in normalized: normalized["totalRecords"] = normalized.pop("total_records") if "successful_records" in normalized and "successfulRecords" not in normalized: normalized["successfulRecords"] = normalized.pop("successful_records") if "failed_records" in normalized and "failedRecords" not in normalized: normalized["failedRecords"] = normalized.pop("failed_records") return normalized @field_validator("progress", mode="before", check_fields=False) def _parse_progress(cls, v: Any) -> int | None: """Parse progress value as an integer, preserving None when absent. Args: v: The progress value from the API. Returns: The parsed integer progress, or None if missing. """ if v is None: return None from imednet.utils.validators import parse_int_or_default try: return parse_int_or_default(v, default=0) except OverflowError as exc: raise ValueError(str(exc)) from exc @staticmethod def _item_has_error(item: dict[str, Any]) -> bool: """Return True when a result record entry reports record-level or variable-level errors.""" status_upper = str(item.get("status") or "").strip().upper() if status_upper in {"FAIL", "FAILED", "ERROR", "INVALID", "REJECTED"}: return True if item.get("success") is False: return True for err_key in ( "error", "errors", "variableErrors", "variable_errors", "fieldErrors", "field_errors", "validationErrors", "validation_errors", ): if item.get(err_key): return True return False @classmethod def _item_is_successful(cls, item: dict[str, Any], *, job_failed: bool = False) -> bool: """Return True when a result record entry succeeded without errors.""" if cls._item_has_error(item): return False if item.get("success") is True: return True status_upper = str(item.get("status") or "").strip().upper() if status_upper in { "PASS", "SUCCESS", "COMPLETED", "COMPLETE", "CREATED", "UPDATED", "OK", "RECORD COMPLETE", "RECORD INCOMPLETE", "DATA COMPLETE", "INCOMPLETE", "PARTIAL", "LOCKED", "FROZEN", "SIGNED", "VERIFIED", "APPROVED", }: return True if status_upper in { "CANCELLED", "CANCELED", "ABORTED", "SKIPPED", "DELETED", "PENDING", "OPEN", "PROCESSING", "QUEUED", }: return False if job_failed: return False return any( item.get(id_key) not in (None, "") for id_key in ( "recordId", "record_id", "recordOid", "record_oid", "subjectKey", "subject_key", "subjectId", "subject_id", "subjectOid", "subject_oid", ) ) @classmethod def _count_dict_record_failures(cls, results: dict[str, Any]) -> int: """Count failed record or variable entries inside a dict ``results`` payload.""" err_count = 0 for top_err_key in ( "errors", "variableErrors", "variable_errors", "fieldErrors", "field_errors", "validationErrors", "validation_errors", ): errors_val = results.get(top_err_key) if isinstance(errors_val, (list, dict)): err_count = max(err_count, len(errors_val)) elif errors_val: err_count = max(err_count, 1) if err_count == 0 and (results.get("error") or cls._item_has_error(results)): err_count = 1 for list_key in ("records", "data", "items"): records_val = results.get(list_key) if isinstance(records_val, list): rec_failures = sum( 1 for r in records_val if isinstance(r, dict) and cls._item_has_error(r) ) err_count = max(err_count, rec_failures) return err_count @property def total_records(self) -> int | None: """Return the total number of records processed, or None when unknown.""" if isinstance(self.results, list): if len(self.results) == 0: if self.record_total_count is not None: return int(self.record_total_count) if self.record_success_count is not None or self.record_failure_count is not None: return int(self.record_success_count or 0) + int(self.record_failure_count or 0) return 0 if self.record_total_count is not None: return max(len(self.results), int(self.record_total_count)) return len(self.results) if isinstance(self.results, dict): if "total" in self.results and self.results.get("total") is not None: return int(self.results["total"]) err_count = self._count_dict_record_failures(self.results) for list_key in ("records", "data", "items"): records_val = self.results.get(list_key) if isinstance(records_val, list) and len(records_val) > 0: return max(len(records_val), int(self.record_total_count or 0), err_count) if self.record_total_count is not None: return max(int(self.record_total_count), err_count) if ( "success" in self.results and self.results.get("success") is not None ) or err_count > 0: return int(self.results.get("success", 0) or 0) + err_count return None if self.record_total_count is not None: return int(self.record_total_count) if self.results: return 1 return None @property def successful_records(self) -> int | None: """Return the total number of successful records processed, or None when unknown.""" job_failed = super().is_failed if isinstance(self.results, list): if len(self.results) == 0: return ( int(self.record_success_count) if self.record_success_count is not None else 0 ) return sum( 1 for r in self.results if isinstance(r, dict) and self._item_is_successful(r, job_failed=job_failed) ) if isinstance(self.results, dict): if "success" in self.results and self.results.get("success") is not None: return int(self.results["success"]) for list_key in ("records", "data", "items"): records_val = self.results.get(list_key) if isinstance(records_val, list) and len(records_val) > 0: return sum( 1 for r in records_val if isinstance(r, dict) and self._item_is_successful(r, job_failed=job_failed) ) if self.record_success_count is not None: return int(self.record_success_count) return None if self.record_success_count is not None: return int(self.record_success_count) if self.results: return 1 if super().is_successful else 0 return None @property def failed_records(self) -> int | None: """Return the total number of failed records processed, or None when unknown.""" if isinstance(self.results, list): if len(self.results) == 0: return ( int(self.record_failure_count) if self.record_failure_count is not None else 0 ) counted = sum( 1 for r in self.results if isinstance(r, dict) and self._item_has_error(r) ) if self.record_failure_count is not None: return max(counted, int(self.record_failure_count)) return counted if isinstance(self.results, dict): err_count = self._count_dict_record_failures(self.results) if "failed" in self.results and self.results.get("failed") is not None: return max(int(self.results["failed"]), err_count) if err_count > 0: return max(err_count, int(self.record_failure_count or 0)) if self.record_failure_count is not None: return int(self.record_failure_count) return None if self.record_failure_count is not None: return int(self.record_failure_count) if self.results: return 1 if super().is_failed else 0 return None @property def is_successful(self) -> bool: """Checks if the job completed in a success state with zero failed records.""" failed = self.failed_records return super().is_successful and (failed is None or failed == 0) and not self.result_error @property def is_failed(self) -> bool: """Checks if the job failed, was cancelled, or finished with record/result errors.""" failed = self.failed_records return super().is_failed or ( self.is_terminal and ((failed is not None and failed > 0) or bool(self.result_error)) )
__all__ = [ "ACTIVE_JOB_STATES", "ALLOWED_JOB_TRANSITIONS", "FAILED_JOB_STATES", "SUCCESSFUL_JOB_STATES", "TERMINAL_JOB_STATES", "InvalidJobStateError", "InvalidJobTransitionError", "InvalidStateTransitionError", "Job", "JobState", "JobStatus", "is_valid_job_transition", "normalize_job_state", "validate_job_transition", ]