Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions backend/app/api/v1/assessments.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, status
from rq import Queue
from sqlalchemy import update as sa_update
from sqlalchemy.orm import Session

from app.api.deps import (
Expand Down Expand Up @@ -220,9 +221,26 @@ def submit_job(
db.add(job)
db.commit()
db.refresh(job)
# Commit the job row before enqueuing: a submission stays visible as
# "queued" even if the queue is temporarily down.
_enqueue(str(job.id))
try:
_enqueue(str(job.id))
except Exception as exc: # noqa: BLE001 — Redis/enqueue down: fail the job visibly instead
# of stranding it in "queued" with no audit or recovery path.
db.execute(sa_update(Job).where(Job.id == job.id).values(status="failed"))
db.commit()
db.refresh(job)
_audit(
db,
str(current_user.id),
"job.execute.failed",
"job",
job.id,
json.dumps({"engine": job.engine, "error": str(exc)}),
)
db.commit()
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="job queue is unavailable; job marked failed",
)
_audit(
db,
str(current_user.id),
Expand Down
54 changes: 53 additions & 1 deletion backend/tests/test_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import uuid

import app.api.v1.assessments as assessments_module
from app.models.core import Asset, AssetObservation, AuditLog
from app.models.core import Asset, AssetObservation, AuditLog, Job
from app.worker import run_job


Expand Down Expand Up @@ -506,3 +506,55 @@ def execute(self, target: str, target_type: str): # pragma: no cover
)
assert audit is not None
assert "engine boom" in audit.details


def test_submit_job_enqueue_failure_marks_job_failed_and_records_audit(
client, db_session, monkeypatch
):
"""Redis/enqueue failure must not strand a job in "queued": it is marked
failed, audited with the error, and the caller gets an honest 503."""
enqueued: list[str] = []

def fail_enqueue(job_id: str) -> None:
enqueued.append(job_id)
raise ConnectionError("redis down")

monkeypatch.setattr(assessments_module, "_enqueue", fail_enqueue)

headers = signup(client, "enqfail")
org_id = create_organization(client, headers, "Org ENQFAIL", "org-enqfail")
project_id = create_project(client, headers, org_id, "Project ENQFAIL")
r = client.post(
"/api/v1/assessments/",
json={"name": "Assessment ENQFAIL", "project_id": project_id},
headers=headers,
)
assert r.status_code == 201, r.text
assessment_id = r.json()["id"]

r = client.post(
f"/api/v1/assessments/{assessment_id}/jobs/",
json={
"assessment_id": assessment_id,
"engine": "discover.dns",
"execution_class": "PASSIVE",
"payload": {"targets": ["example.com"]},
},
headers=headers,
)
assert r.status_code == 503, r.text

# The job row exists and is marked failed: not stranded in "queued".
job = db_session.query(Job).filter_by(assessment_id=assessment_id).first()
assert job is not None
assert job.status == "failed"

# Audit trail records the failure so an operator can see what happened
# and re-submit when the queue is back.
audit = (
db_session.query(AuditLog)
.filter_by(action="job.execute.failed", target_type="job")
.first()
)
assert audit is not None
assert "redis down" in audit.details
Loading