Final commit of the automation-handler refactor. With this commit
every closure that used to live in
`web_server._register_automation_handlers` is now a top-level
function in `core/automation/handlers/`.
Handlers extracted in this commit:
- start_database_update + deep_scan_library
-> core/automation/handlers/database_update.py
Both share the db_update_state monitoring pattern (poll until
status flips, stall detection emits warning at 10 min, 2-hour
outer timeout). Lifted into a shared `_run_with_progress` helper
inside the module so the per-handler bodies stay tiny.
- run_duplicate_cleaner -> core/automation/handlers/duplicate_cleaner.py
- start_quality_scan -> core/automation/handlers/quality_scanner.py
- clear_quarantine, cleanup_wishlist, update_discovery_pool,
backup_database, refresh_beatport_cache
-> core/automation/handlers/maintenance.py
Grouped because each body is short (~20-50 lines) and they share
no state — splitting into per-handler files would just add import
noise.
- clean_search_history, clean_completed_downloads, full_cleanup
-> core/automation/handlers/download_cleanup.py
Grouped because all three reach the download orchestrator,
tasks_lock, and download_batches/download_tasks accessors. The
full_cleanup multi-step orchestration shares phase-detection
logic with clean_completed_downloads.
- run_script -> core/automation/handlers/run_script.py
- search_and_download -> core/automation/handlers/search_and_download.py
`AutomationDeps` grew with the new dependency surface:
- get_db_update_state + db_update_lock + db_update_executor +
run_db_update_task + run_deep_scan_task
- get_duplicate_cleaner_state + duplicate_cleaner_lock +
duplicate_cleaner_executor + run_duplicate_cleaner
- get_quality_scanner_state + quality_scanner_lock +
quality_scanner_executor + run_quality_scanner
- download_orchestrator + run_async + tasks_lock +
get_download_batches + get_download_tasks +
sweep_empty_download_directories + get_staging_path
- docker_resolve_path + get_current_profile_id +
get_watchlist_scanner + get_app + get_beatport_data_cache
- set_db_update_automation_id (writes the legacy global so the live
DB-update progress callbacks still living in web_server.py keep
emitting against the active automation card)
`web_server._register_automation_handlers` is now ~50 lines: build
deps once, call register_all. The 667-line block of remaining
closure definitions and engine register calls is gone.
The final orphan was the `_db_update_automation_id` module global —
the DB-update progress callbacks at line ~14080 still read it
directly, so the extracted database_update handler propagates the
automation id through `deps.set_db_update_automation_id` (a closure
in web_server that writes the global). When the legacy callbacks
get extracted in a future PR the setter goes away.
Tests:
- tests/automation/test_handlers_maintenance.py adds 21 boundary
tests covering every newly-extracted handler shape: guard
short-circuits (already-running returns skipped), deps wiring
(set_db_update_automation_id called with the right id),
exception swallow contract, status returns, path-traversal
blocked in run_script, source-mode skip in clean_search_history,
active-batch skip in clean_completed_downloads, etc.
- 3244 tests pass (was 3223 — 21 new), no regression.
web_server.py: 35,593 -> 34,220 lines (-1,373 net across 3 commits).
Issue #1 from the extraction punch list is now COMPLETE.
87 lines
3.2 KiB
Python
87 lines
3.2 KiB
Python
"""Automation handler: ``run_duplicate_cleaner`` action.
|
|
|
|
Lifted from ``web_server._register_automation_handlers`` (the
|
|
``_auto_run_duplicate_cleaner`` closure). Submits the duplicate
|
|
cleaner to its executor, then polls the shared state dict until
|
|
the worker transitions away from ``running``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from typing import Any, Dict
|
|
|
|
from core.automation.deps import AutomationDeps
|
|
|
|
|
|
_TIMEOUT_SECONDS = 7200 # 2 hours
|
|
_POLL_INTERVAL_SECONDS = 3
|
|
_INITIAL_DELAY_SECONDS = 1
|
|
|
|
|
|
def auto_run_duplicate_cleaner(config: Dict[str, Any], deps: AutomationDeps) -> Dict[str, Any]:
|
|
"""Kick off the duplicate cleaner and report final stats."""
|
|
automation_id = config.get('_automation_id')
|
|
state = deps.get_duplicate_cleaner_state()
|
|
if state.get('status') == 'running':
|
|
return {'status': 'skipped', 'reason': 'Duplicate cleaner already running'}
|
|
|
|
# Pre-set status before submit so the polling loop doesn't see a
|
|
# stale 'finished' from a previous run.
|
|
with deps.duplicate_cleaner_lock:
|
|
state['status'] = 'running'
|
|
deps.duplicate_cleaner_executor.submit(deps.run_duplicate_cleaner)
|
|
deps.update_progress(automation_id, log_line='Duplicate cleaner started', log_type='info')
|
|
|
|
# Monitor progress (max 2 hours).
|
|
time.sleep(_INITIAL_DELAY_SECONDS)
|
|
poll_start = time.time()
|
|
while time.time() - poll_start < _TIMEOUT_SECONDS:
|
|
time.sleep(_POLL_INTERVAL_SECONDS)
|
|
current_status = state.get('status', 'idle')
|
|
if current_status not in ('running',):
|
|
break
|
|
deps.update_progress(
|
|
automation_id,
|
|
phase=state.get('phase', 'Scanning...'),
|
|
progress=state.get('progress', 0),
|
|
processed=state.get('files_scanned', 0),
|
|
total=state.get('total_files', 0),
|
|
)
|
|
else:
|
|
# 2-hour timeout reached.
|
|
deps.update_progress(
|
|
automation_id, status='error',
|
|
phase='Timed out',
|
|
log_line='Duplicate cleaner timed out after 2 hours',
|
|
log_type='error',
|
|
)
|
|
return {'status': 'error', 'reason': 'Timed out', '_manages_own_progress': True}
|
|
|
|
# Check actual exit status (could be 'finished' or 'error').
|
|
final_status = state.get('status', 'idle')
|
|
if final_status == 'error':
|
|
err = state.get('error_message', 'Unknown error')
|
|
deps.update_progress(
|
|
automation_id, status='error', progress=100,
|
|
phase='Error', log_line=err, log_type='error',
|
|
)
|
|
return {'status': 'error', 'reason': err, '_manages_own_progress': True}
|
|
|
|
dupes = state.get('duplicates_found', 0)
|
|
removed = state.get('deleted', 0)
|
|
space_freed = state.get('space_freed', 0)
|
|
scanned = state.get('files_scanned', 0)
|
|
deps.update_progress(
|
|
automation_id, status='finished', progress=100,
|
|
phase='Complete',
|
|
log_line=f'Found {dupes} duplicates, removed {removed} files',
|
|
log_type='success',
|
|
)
|
|
return {
|
|
'status': 'completed', '_manages_own_progress': True,
|
|
'files_scanned': scanned,
|
|
'duplicates_found': dupes,
|
|
'files_deleted': removed,
|
|
'space_freed_mb': round(space_freed / (1024 * 1024), 1),
|
|
}
|