Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

refactor(db-tuner): typed errors close the status-sniffing census at 0

Juan Denisb7b8b387738d
diff --git a/backend/app/api/db_tuner.py b/backend/app/api/db_tuner.py
index 2e95f5de..64dfd8a1 100644
--- a/backend/app/api/db_tuner.py
+++ b/backend/app/api/db_tuner.py
@@ -66,8 +66,7 @@ def inspect_target(target):
if err:
return err
dedicated = str(request.args.get('dedicated', '')).lower() in ('1', 'true', 'yes')
- result = DbConfigTunerService.inspect(resolved, is_dedicated=dedicated)
- return jsonify(result), 200 if 'error' not in result else 400
+ return jsonify(DbConfigTunerService.inspect(resolved, is_dedicated=dedicated)), 200
@db_tuner_bp.route('/<target>/apply', methods=['POST'])
@@ -80,8 +79,7 @@ def apply_target(target):
resolved, err = _build_target(target, data)
if err:
return err
- result = DbConfigTunerService.apply(resolved, data['settings'])
- return jsonify(result), 200 if 'error' not in result else 400
+ return jsonify(DbConfigTunerService.apply(resolved, data['settings'])), 200
@db_tuner_bp.route('/<target>/rollback', methods=['POST'])
@@ -92,5 +90,4 @@ def rollback_target(target):
resolved, err = _build_target(target, data)
if err:
return err
- result = DbConfigTunerService.rollback(resolved)
- return jsonify(result), 200 if 'error' not in result else 400
+ return jsonify(DbConfigTunerService.rollback(resolved)), 200
diff --git a/backend/app/services/db_config_tuner_service.py b/backend/app/services/db_config_tuner_service.py
index 352d27d6..ecb95928 100644
--- a/backend/app/services/db_config_tuner_service.py
+++ b/backend/app/services/db_config_tuner_service.py
@@ -28,6 +28,11 @@ import sys
import time
from datetime import datetime
+from app.exceptions import (
+ DependencyUnavailableError,
+ NotFoundError,
+ ValidationError,
+)
from app import paths
from app.services import db_exec
@@ -188,14 +193,13 @@ class DbConfigTunerService:
@classmethod
def _guard(cls, target):
- """Common precondition check → error string or None."""
+ """Common precondition check; raises ValidationError."""
if not cls._linux_supported():
- return 'The config tuner is only available on Linux hosts running Docker'
+ raise ValidationError('The config tuner is only available on Linux hosts running Docker')
if not target.get('container'):
- return 'A Docker container target is required'
+ raise ValidationError('A Docker container target is required')
if target.get('engine') not in CURATED_SETTINGS:
- return 'engine must be mysql or postgresql'
- return None
+ raise ValidationError('engine must be mysql or postgresql')
@classmethod
def _ram_mb(cls, container):
@@ -394,13 +398,11 @@ class DbConfigTunerService:
def inspect(cls, target, is_dedicated=False):
"""Current vs suggested for every curated setting. Read-only —
suggestions are NEVER applied automatically."""
- err = cls._guard(target)
- if err:
- return {'error': err}
+ cls._guard(target)
current, err = cls._read_current(target)
if err:
- return {'error': err}
+ raise DependencyUnavailableError(err)
engine = target['engine']
ram_mb, ram_source = cls._ram_mb(target['container'])
@@ -440,13 +442,11 @@ class DbConfigTunerService:
"""Apply an explicit, operator-chosen settings dict. Backs up the
previous state, restarts the container, verifies the engine came back,
and rolls back automatically if it didn't."""
- err = cls._guard(target)
- if err:
- return {'error': err}
+ cls._guard(target)
settings = dict(settings or {})
err = cls.validate_settings(target['engine'], settings)
if err:
- return {'error': err}
+ raise ValidationError(err)
if target['engine'] == 'mysql':
return cls._apply_mysql(target, settings)
@@ -464,7 +464,8 @@ class DbConfigTunerService:
fh.write(cls.render_mysql_dropin(settings))
res = cls._docker(['cp', staged, f'{container}:{MYSQL_DROPIN_PATH}'], timeout=30)
if not res['success']:
- return {'error': f"Could not write the drop-in into the container: {res['error']}"}
+ raise DependencyUnavailableError(
+ f"Could not write the drop-in into the container: {res['error']}")
return cls._restart_and_verify(target, backup, MYSQL_DROPIN_PATH, settings)
@@ -474,11 +475,12 @@ class DbConfigTunerService:
# rollback even when the engine won't boot back up.
res = cls._exec_sql(target, 'SHOW data_directory;')
if not res['success']:
- return {'error': res.get('error') or 'Could not determine the data directory'}
+ raise DependencyUnavailableError(
+ res.get('error') or 'Could not determine the data directory')
data_dir = (res['output'] or '').strip().splitlines()
data_dir = data_dir[0].strip() if data_dir else ''
if not data_dir:
- return {'error': 'Could not determine the data directory'}
+ raise DependencyUnavailableError('Could not determine the data directory')
auto_conf = data_dir.rstrip('/') + '/postgresql.auto.conf'
backup = cls._snapshot_container_file(target, auto_conf, '.auto.conf')
@@ -491,7 +493,8 @@ class DbConfigTunerService:
# Nothing took effect yet (needs a restart) — restore the conf
# so no partial ALTERs linger, and bail.
cls._restore_container_file(target, backup, auto_conf)
- return {'error': f"ALTER SYSTEM failed for '{key}': {res['error']}"}
+ raise DependencyUnavailableError(
+ f"ALTER SYSTEM failed for '{key}': {res['error']}")
# Remember where auto.conf lives so rollback works without SQL.
with open(os.path.join(cls._state_dir(target, create=True), 'applied.json'), 'w') as fh:
@@ -506,14 +509,16 @@ class DbConfigTunerService:
res = cls._restart(container)
if not res.get('success'):
cls._restore_container_file(target, backup, container_path)
- return {'error': f"Container restart failed: {res.get('error')}; previous config restored"}
+ raise DependencyUnavailableError(
+ f"Container restart failed: {res.get('error')}; previous config restored")
if not cls._wait_ready(target):
cls._restore_container_file(target, backup, container_path)
cls._restart(container)
cls._wait_ready(target)
- return {'error': 'Engine did not come back after the restart; '
- 'previous config restored and container restarted again'}
+ raise DependencyUnavailableError(
+ 'Engine did not come back after the restart; '
+ 'previous config restored and container restarted again')
return {'success': True, 'applied': settings, 'restarted': True,
'backup': os.path.basename(backup)}
@@ -521,12 +526,10 @@ class DbConfigTunerService:
@classmethod
def rollback(cls, target):
"""Restore the most recent pre-apply config and restart the engine."""
- err = cls._guard(target)
- if err:
- return {'error': err}
+ cls._guard(target)
backup = cls._latest_backup(target)
if not backup:
- return {'error': 'No previous configuration to roll back to'}
+ raise NotFoundError('No previous configuration to roll back to')
if target['engine'] == 'mysql':
container_path = MYSQL_DROPIN_PATH
@@ -536,17 +539,21 @@ class DbConfigTunerService:
with open(applied) as fh:
container_path = json.load(fh)['auto_conf']
except (OSError, ValueError, KeyError):
- return {'error': 'Rollback metadata is missing; cannot locate postgresql.auto.conf'}
+ raise NotFoundError(
+ 'Rollback metadata is missing; cannot locate postgresql.auto.conf')
res = cls._restore_container_file(target, backup, container_path)
if not res['success']:
- return {'error': f"Could not restore the previous config: {res['error']}"}
+ raise DependencyUnavailableError(
+ f"Could not restore the previous config: {res['error']}")
restart = cls._restart(target['container'])
if not restart.get('success'):
- return {'error': f"Config restored but the restart failed: {restart.get('error')}"}
+ raise DependencyUnavailableError(
+ f"Config restored but the restart failed: {restart.get('error')}")
if not cls._wait_ready(target):
- return {'error': 'Config restored but the engine did not come back; check the container logs'}
+ raise DependencyUnavailableError(
+ 'Config restored but the engine did not come back; check the container logs')
# Consume the backup so can_rollback reflects reality.
try:
diff --git a/backend/tests/STATUS_SNIFFING_CEILING b/backend/tests/STATUS_SNIFFING_CEILING
index 00750edc..573541ac 100644
--- a/backend/tests/STATUS_SNIFFING_CEILING
+++ b/backend/tests/STATUS_SNIFFING_CEILING
@@ -1 +1 @@
-3
+0
diff --git a/backend/tests/status_sniffing_census.py b/backend/tests/status_sniffing_census.py
index b943b89b..7af34960 100644
--- a/backend/tests/status_sniffing_census.py
+++ b/backend/tests/status_sniffing_census.py
@@ -12,13 +12,14 @@ type checker, not a lint rule.
The fix is milestone C's: services raise typed errors from ``app.exceptions``
and routes return data, so nobody re-derives what the service already knew.
-That is deliberately NOT done yet — ``file_service`` alone has eight callers,
-and converting one service to raise while its other callers still expect a dict
-leaves two contracts, which is the disease rather than the cure.
-
-So this is the ratchet that comes first (second-wave rule 1): the count may only
-go down. It exists to stop the pattern spreading while the envelope decision is
-made.
+The migration is COMPLETE (2026-08-19): all 23 baseline sites across 8 files
+were converted domain by domain, and the ceiling is 0. (The 'eight callers'
+blocker recorded here earlier was a substring-grep artifact — ``file_service``
+had exactly one consumer.)
+
+The ratchet now holds an invariant, not a countdown: any new site that chooses
+a status by inspecting message text — or by probing for an 'error' key, the
+same coupling one step removed — fails this census.
A site is counted when a conditional expression chooses between two HTTP status
codes, and its test inspects string content — ``in``, ``.lower()``,
diff --git a/backend/tests/test_db_config_tuner.py b/backend/tests/test_db_config_tuner.py
index d2cf19ba..b9d7b422 100644
--- a/backend/tests/test_db_config_tuner.py
+++ b/backend/tests/test_db_config_tuner.py
@@ -4,6 +4,12 @@ import os
import pytest
+from app.exceptions import (
+ DependencyUnavailableError,
+ NotFoundError,
+ ValidationError,
+)
+
from app.services.db_config_tuner_service import (
CURATED_SETTINGS, MYSQL_DROPIN_PATH, DbConfigTunerService as S,
)
@@ -111,10 +117,10 @@ def test_validate_accepts_and_coerces():
def test_apply_surfaces_validation_error(tuner):
- result = S.apply(MYSQL_TARGET, {'not_a_setting': 1})
- assert 'error' in result and 'not_a_setting' in result['error']
- result = S.apply(MYSQL_TARGET, {'innodb_buffer_pool_size': 1}) # below 128MB floor
- assert 'error' in result
+ with pytest.raises(ValidationError, match='not_a_setting'):
+ S.apply(MYSQL_TARGET, {'not_a_setting': 1})
+ with pytest.raises(ValidationError):
+ S.apply(MYSQL_TARGET, {'innodb_buffer_pool_size': 1}) # below 128MB floor
# ── drop-in rendering ────────────────────────────────────────────────────────
@@ -200,15 +206,17 @@ def test_inspect_pg_parses_pg_settings_units(tuner):
def test_inspect_engine_query_failure_is_clean_error(tuner):
tuner['sql'] = lambda t, sql: {'success': False, 'output': '', 'error': 'access denied'}
- result = S.inspect(MYSQL_TARGET)
- assert result == {'error': 'access denied'}
+ with pytest.raises(DependencyUnavailableError, match='access denied'):
+ S.inspect(MYSQL_TARGET)
def test_non_linux_is_clean_error(tuner, monkeypatch):
monkeypatch.setattr(S, '_linux_supported', classmethod(lambda cls: False))
- assert 'error' in S.inspect(MYSQL_TARGET)
- assert 'error' in S.apply(MYSQL_TARGET, {'max_connections': 300})
- assert 'error' in S.rollback(MYSQL_TARGET)
+ for op in (lambda: S.inspect(MYSQL_TARGET),
+ lambda: S.apply(MYSQL_TARGET, {'max_connections': 300}),
+ lambda: S.rollback(MYSQL_TARGET)):
+ with pytest.raises(ValidationError, match='Linux'):
+ op()
# ── apply / rollback flow (mysql) ────────────────────────────────────────────
@@ -262,8 +270,8 @@ def test_apply_mysql_ping_failure_rolls_back(tuner):
_mysql_docker_stub(tuner, existing_dropin='[mysqld]\nold = 1\n')
tuner['sql'] = lambda t, sql: {'success': False, 'output': '', 'error': 'down'}
- result = S.apply(MYSQL_TARGET, {'max_connections': 300})
- assert 'error' in result and 'restored' in result['error']
+ with pytest.raises(DependencyUnavailableError, match='restored'):
+ S.apply(MYSQL_TARGET, {'max_connections': 300})
# Restarted twice: once for the apply, once after restoring the backup.
assert tuner['restarts'] == ['app-db-1', 'app-db-1']
# The backup was cp'd back into the container.
@@ -276,8 +284,8 @@ def test_apply_mysql_ping_failure_rolls_back(tuner):
def test_apply_mysql_restart_failure_restores_file(tuner):
_mysql_docker_stub(tuner, existing_dropin='[mysqld]\nold = 1\n')
tuner['restart_ok'] = False
- result = S.apply(MYSQL_TARGET, {'max_connections': 300})
- assert 'error' in result and 'restored' in result['error']
+ with pytest.raises(DependencyUnavailableError, match='restored'):
+ S.apply(MYSQL_TARGET, {'max_connections': 300})
def test_rollback_mysql_restores_and_consumes_backup(tuner):
@@ -290,7 +298,8 @@ def test_rollback_mysql_restores_and_consumes_backup(tuner):
assert tuner['restarts'] == ['app-db-1']
# Backup consumed — nothing further to roll back to.
assert S._latest_backup(MYSQL_TARGET) is None
- assert 'error' in S.rollback(MYSQL_TARGET)
+ with pytest.raises(NotFoundError):
+ S.rollback(MYSQL_TARGET)
def test_rollback_mysql_absent_marker_deletes_dropin(tuner):
@@ -303,7 +312,8 @@ def test_rollback_mysql_absent_marker_deletes_dropin(tuner):
def test_rollback_without_backup_is_clean_error(tuner):
- assert 'error' in S.rollback(MYSQL_TARGET)
+ with pytest.raises(NotFoundError):
+ S.rollback(MYSQL_TARGET)
# ── apply / rollback flow (postgresql) ───────────────────────────────────────
@@ -345,8 +355,8 @@ def test_apply_pg_happy_path(tuner, tmp_path):
def test_apply_pg_alter_failure_restores_conf_without_restart(tuner):
_pg_sql_stub(tuner, alter_ok=False)
- result = S.apply(PG_TARGET, {'shared_buffers': 1024})
- assert 'error' in result and 'ALTER SYSTEM' in result['error']
+ with pytest.raises(DependencyUnavailableError, match='ALTER SYSTEM'):
+ S.apply(PG_TARGET, {'shared_buffers': 1024})
assert tuner['restarts'] == [] # nothing took effect, no restart