Files
Agent Zero abbe7a18fc fix(audit): P0-P3 audit fixes — 838 ruff errors → 0, 30 F821 bugs fixed, 118 files changed
- P0: hooks.py 3-tuple fix, trigger_dispatcher Contract, contacts/plugin unregister_actions_by_owner
- P0: 5 test files — check_permission mocks removed, hardcoded DB credential → env var
- P1: attachment_service DmsFile via Contract helper, restore_registry/history_hooks dedup
- P1: mail/plugin restore unregister, mcp_client datetime.now(UTC), saved_views/filters patterns
- P1: ProtectedRoute fail-closed, 13 test assertion fixes (bcrypt, DB-URLs, SECRET_KEYs)
- P2: deprecated notifications → post_system_message (3 files), forgejo Base, report_generator lazy import
- P2: webhooks permissions, deps.py/roles.py plugin perms removed, import_export default
- P2: address/tags/entity_links patterns removed, worker.py Contract-Umgehungen fixed
- P2: 28 frontend TODOs (hardcoded constants, deprecated notification API)
- P3: dead code, duplicates, deprecated imports, private attr, __import__ inline
- P3: 8 frontend TODOs (LucideIcons, inline styles, XSS, i18n)
- ruff: 838 → 0 (612 auto-fix + 246 manual + 27 F821 regression fix)
- F821: 30 → 0 (AutomationDefinition, DmsFile, user_id, Path, Any, String)
- Contract-Umgehungen: 2 neue gefunden (worker.py:169, worker.py:280) und gefixt
2026-08-16 01:17:18 +02:00

80 lines
2.7 KiB
Python

"""Cron scheduler — reads CronJob rows and enqueues ARQ jobs."""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from typing import Any
import croniter
from sqlalchemy import select
from app.core.db import get_session_factory
logger = logging.getLogger(__name__)
def calculate_next_run(cron_expression: str, from_time: datetime | None = None) -> datetime:
"""Calculate the next run time from a cron expression using croniter."""
base = from_time or datetime.now(UTC)
cron = croniter.croniter(cron_expression, base)
next_dt = cron.get_next(datetime)
return next_dt
async def scheduler_tick(ctx: dict[str, Any]) -> None:
"""Run every 60s via ARQ cron. Reads active CronJob rows where next_run_at <= now,
enqueues appropriate ARQ job, updates last_run_at and calculates next_run_at."""
from app.plugins.builtins.automation.models import AutomationCronJob as CronJob
now = datetime.now(UTC)
factory = get_session_factory()
async with factory() as db:
result = await db.execute(
select(CronJob).where(
CronJob.is_active.is_(True),
CronJob.next_run_at <= now,
)
)
jobs = list(result.scalars().all())
if not jobs:
logger.debug("scheduler_tick: no cron jobs due")
return
logger.info("scheduler_tick: %d cron job(s) due", len(jobs))
for job in jobs:
try:
if job.job_type == "agent":
from app.core.jobs import enqueue_job
await enqueue_job("run_agent", job.target_id, trigger_type="scheduled")
elif job.job_type == "automation":
from app.core.jobs import enqueue_job
await enqueue_job("run_automation", job.target_id, trigger_type="scheduled")
else:
logger.warning("Unknown cron job_type: %s", job.job_type)
continue
# Update last_run_at and calculate next_run_at
async with factory() as db:
result = await db.execute(select(CronJob).where(CronJob.id == job.id))
db_job = result.scalar_one_or_none()
if db_job is None:
continue
db_job.last_run_at = now
db_job.next_run_at = calculate_next_run(db_job.cron_expression, now)
await db.flush()
logger.info("Enqueued %s %s (id=%s)", job.job_type, job.target_id, job.id)
except Exception:
logger.exception("Failed to process cron job %s", job.id)
# Register all job functions with the job registry
from app.core.job_registry import register_job # noqa: E402
register_job("scheduler_tick", scheduler_tick)