feat: Actions system — scheduled mutations on external services

Full-stack implementation of provider-scoped Actions with extensible
executor architecture. First action type: Immich auto_organize (sort
assets into albums by person, CLIP search, date range, favorites).

Core:
- ActionTypeDefinition registry + ActionExecutor ABC with execute/validate/dry-run
- ImmichActionExecutor with multi-album support and client-side filtering
- ImmichClient write methods: add/remove assets, create album, paginated search

Server:
- Action, ActionRule, ActionExecution DB models
- Full CRUD API + manual execute + dry-run + execution history endpoints
- APScheduler integration (interval + cron) for automated execution
- Action type discovery API + provider people endpoint

Frontend:
- Actions page with CRUD, execute/dry-run buttons, inline rule editor
- RuleEditor: person/album MultiEntitySelect pickers, criteria config
- ExecutionHistory: expandable per-rule result details
- MultiEntitySelect reusable component (searchable multi-pick palette)
- Notification tracker album picker migrated to MultiEntitySelect
- Fixed MdiIcon race condition (icons missing after cache-clearing reload)
This commit is contained in:
2026-03-23 16:59:20 +03:00
parent 0fde3c6b3d
commit 6a559bfcd2
26 changed files with 2888 additions and 25 deletions
@@ -0,0 +1,187 @@
"""Action runner — orchestrates loading, executing, and logging actions."""
from __future__ import annotations
import logging
from datetime import datetime, timezone
from typing import Any
import aiohttp
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from notify_bridge_core.providers.action_executor import ActionResult
from ..database.engine import get_engine
from ..database.models import (
Action,
ActionExecution,
ActionRule,
ServiceProvider,
)
_LOGGER = logging.getLogger(__name__)
async def run_action(
action_id: int, *, trigger: str = "scheduled"
) -> ActionResult:
"""Load an action from DB, execute it, and save the execution log."""
engine = get_engine()
# ------------------------------------------------------------------
# 1. Load all DB data eagerly (before aiohttp context)
# ------------------------------------------------------------------
async with AsyncSession(engine) as session:
action = await session.get(Action, action_id)
if not action:
return ActionResult(success=False, error="Action not found")
if not action.enabled and trigger == "scheduled":
return ActionResult(success=False, error="Action is disabled")
provider = await session.get(ServiceProvider, action.provider_id)
if not provider:
return ActionResult(success=False, error="Provider not found")
result = await session.exec(
select(ActionRule)
.where(ActionRule.action_id == action_id)
.where(ActionRule.enabled == True) # noqa: E712
.order_by(ActionRule.order)
)
rules = result.all()
if not rules:
return ActionResult(success=True, rules_processed=0)
# Snapshot data
provider_type = provider.type
provider_config = dict(provider.config)
provider_name = provider.name
action_type = action.action_type
action_config = dict(action.config) if action.config else {}
rule_configs = [
{**dict(r.rule_config), "name": r.name} for r in rules
]
# Create execution record
execution = ActionExecution(
action_id=action_id,
trigger=trigger,
status="running",
)
session.add(execution)
await session.commit()
await session.refresh(execution)
execution_id = execution.id
# ------------------------------------------------------------------
# 2. Execute via provider-specific executor
# ------------------------------------------------------------------
is_dry_run = trigger == "dry_run"
action_result: ActionResult
try:
action_result = await _execute_with_provider(
provider_type=provider_type,
provider_config=provider_config,
provider_name=provider_name,
action_type=action_type,
action_config=action_config,
rule_configs=rule_configs,
dry_run=is_dry_run,
)
except Exception as err:
_LOGGER.error("Action %d execution error: %s", action_id, err)
action_result = ActionResult(success=False, error=str(err))
# ------------------------------------------------------------------
# 3. Save execution results
# ------------------------------------------------------------------
async with AsyncSession(engine) as session:
execution = await session.get(ActionExecution, execution_id)
if execution:
execution.finished_at = datetime.now(timezone.utc)
if action_result.error is not None and action_result.rules_succeeded == 0:
execution.status = "failed"
elif action_result.rules_failed > 0:
execution.status = "partial"
else:
execution.status = "success"
execution.rules_processed = action_result.rules_processed
execution.rules_succeeded = action_result.rules_succeeded
execution.rules_failed = action_result.rules_failed
execution.total_items_affected = action_result.total_items_affected
execution.summary = action_result.to_dict()
execution.error = action_result.error or ""
session.add(execution)
# Update action last_run metadata (skip for dry runs)
if not is_dry_run:
action = await session.get(Action, action_id)
if action:
action.last_run_at = datetime.now(timezone.utc)
action.last_run_status = execution.status if execution else ""
session.add(action)
await session.commit()
_LOGGER.info(
"Action %d (%s) completed: %d/%d rules succeeded, %d items affected",
action_id,
trigger,
action_result.rules_succeeded,
action_result.rules_processed,
action_result.total_items_affected,
)
return action_result
async def dry_run_action(action_id: int) -> ActionResult:
"""Execute a dry-run of an action (no mutations)."""
return await run_action(action_id, trigger="dry_run")
async def _execute_with_provider(
*,
provider_type: str,
provider_config: dict[str, Any],
provider_name: str,
action_type: str,
action_config: dict[str, Any],
rule_configs: list[dict[str, Any]],
dry_run: bool,
) -> ActionResult:
"""Instantiate the appropriate executor and run."""
if provider_type == "immich":
from notify_bridge_core.providers.immich.action_executor import (
ImmichActionExecutor,
)
from notify_bridge_core.providers.immich.client import ImmichClient
async with aiohttp.ClientSession() as http_session:
client = ImmichClient(
http_session,
provider_config.get("url", ""),
provider_config.get("api_key", ""),
)
external_domain = provider_config.get("external_domain")
if external_domain:
client.external_domain = external_domain
# Verify connectivity
if not await client.ping():
return ActionResult(
success=False,
error=f"Cannot connect to Immich server ({provider_name})",
)
executor = ImmichActionExecutor(client)
if dry_run:
return await executor.dry_run(action_type, rule_configs, action_config)
return await executor.execute(action_type, rule_configs, action_config)
return ActionResult(
success=False,
error=f"No action executor for provider type: {provider_type}",
)
@@ -1,4 +1,4 @@
"""APScheduler-based polling scheduler for trackers."""
"""APScheduler-based polling scheduler for trackers and actions."""
from __future__ import annotations
@@ -25,6 +25,7 @@ async def start_scheduler() -> None:
_LOGGER.info("Scheduler started")
await _load_tracker_jobs()
await _load_action_jobs()
# Start Telegram bot polling for bots with active command listeners
from .telegram_poller import start_command_listener_polling
@@ -156,3 +157,123 @@ async def _poll_tracker(tracker_id: int) -> None:
await check_tracker(tracker_id)
except Exception as e:
_LOGGER.error("Error polling tracker %d: %s", tracker_id, e)
# ---------------------------------------------------------------------------
# Action scheduling
# ---------------------------------------------------------------------------
async def _load_action_jobs() -> None:
"""Load enabled actions and schedule execution jobs."""
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from ..database.engine import get_engine
from ..database.models import Action
engine = get_engine()
scheduler = get_scheduler()
async with AsyncSession(engine) as session:
result = await session.exec(
select(Action).where(Action.enabled == True) # noqa: E712
)
actions = result.all()
for action in actions:
job_id = f"action_{action.id}"
if scheduler.get_job(job_id):
continue
if action.schedule_type == "cron" and action.schedule_cron:
try:
from apscheduler.triggers.cron import CronTrigger
trigger = CronTrigger.from_crontab(action.schedule_cron)
scheduler.add_job(
_run_action,
trigger,
id=job_id,
args=[action.id],
replace_existing=True,
)
_LOGGER.info(
"Scheduled action %d (%s) with cron: %s",
action.id, action.name, action.schedule_cron,
)
continue
except Exception as e:
_LOGGER.error(
"Invalid cron for action %d (%s): %s — falling back to interval",
action.id, action.name, e,
)
scheduler.add_job(
_run_action,
"interval",
seconds=action.schedule_interval,
id=job_id,
args=[action.id],
replace_existing=True,
)
_LOGGER.info(
"Scheduled action %d (%s) every %ds",
action.id, action.name, action.schedule_interval,
)
async def schedule_action(
action_id: int,
schedule_type: str = "interval",
interval: int = 3600,
cron_expression: str = "",
) -> None:
"""Add or update a scheduler job for an action."""
scheduler = get_scheduler()
job_id = f"action_{action_id}"
if scheduler.get_job(job_id):
scheduler.remove_job(job_id)
if schedule_type == "cron" and cron_expression:
try:
from apscheduler.triggers.cron import CronTrigger
trigger = CronTrigger.from_crontab(cron_expression)
scheduler.add_job(
_run_action,
trigger,
id=job_id,
args=[action_id],
replace_existing=True,
)
_LOGGER.info("Scheduled action %d with cron: %s", action_id, cron_expression)
return
except Exception as e:
_LOGGER.error("Invalid cron for action %d: %s — using interval", action_id, e)
scheduler.add_job(
_run_action,
"interval",
seconds=interval,
id=job_id,
args=[action_id],
replace_existing=True,
)
_LOGGER.info("Scheduled action %d every %ds", action_id, interval)
async def unschedule_action(action_id: int) -> None:
"""Remove a scheduler job for an action."""
scheduler = get_scheduler()
job_id = f"action_{action_id}"
if scheduler.get_job(job_id):
scheduler.remove_job(job_id)
_LOGGER.info("Unscheduled action %d", action_id)
async def _run_action(action_id: int) -> None:
"""Run an action (called by APScheduler)."""
from .action_runner import run_action
try:
await run_action(action_id, trigger="scheduled")
except Exception as e:
_LOGGER.error("Error running action %d: %s", action_id, e)