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(unify): §8 Phase B1 — generalize BackupPolicy to all target types

Juan Denis5d606a603065
diff --git a/backend/app/models/backup_policy.py b/backend/app/models/backup_policy.py
index 145cee50..6ba08979 100644
--- a/backend/app/models/backup_policy.py
+++ b/backend/app/models/backup_policy.py
@@ -1,8 +1,15 @@
+import json
from datetime import datetime
from decimal import Decimal
from app import db
+# Every data-protection target the unified policy system can back up (§8).
+# 'application' and 'wordpress_site' are the original targets; 'database',
+# 'files', and 'server' were folded in from the legacy BackupService so a
+# single BackupPolicy/BackupRun system covers all data-protection backups.
+VALID_TARGET_TYPES = ('application', 'wordpress_site', 'database', 'files', 'server')
+
def _num(value):
"""Serialize a Numeric/Decimal column to a JSON-friendly float (or None)."""
@@ -28,8 +35,15 @@ class BackupPolicy(db.Model):
__tablename__ = 'backup_policies'
id = db.Column(db.Integer, primary_key=True)
- target_type = db.Column(db.String(40), nullable=False, index=True) # 'wordpress_site' | 'application'
+ target_type = db.Column(db.String(40), nullable=False, index=True) # see VALID_TARGET_TYPES
target_id = db.Column(db.Integer, nullable=False, index=True)
+ # Optional finer target classification, e.g. the engine for a 'database'
+ # target ('mysql' | 'postgresql' | 'mongodb') or 'pathlist' for 'files'.
+ target_subtype = db.Column(db.String(40), nullable=True)
+ # Per-target details that aren't a first-class column: for 'database' the
+ # connection descriptor (db_type/db_name/user/host); for 'files' the path
+ # list; for 'server' the scope. JSON object, never secrets in plaintext.
+ target_meta_json = db.Column(db.Text, default='{}', nullable=True)
enabled = db.Column(db.Boolean, default=False, nullable=False)
# Schedule (cron expression fired by the unified scheduler)
@@ -71,11 +85,26 @@ class BackupPolicy(db.Model):
__table_args__ = (db.UniqueConstraint('target_type', 'target_id', name='uq_backup_policy_target'),)
+ def get_target_meta(self):
+ """Parsed target_meta_json (always a dict)."""
+ if not self.target_meta_json:
+ return {}
+ try:
+ data = json.loads(self.target_meta_json)
+ return data if isinstance(data, dict) else {}
+ except (ValueError, TypeError):
+ return {}
+
+ def set_target_meta(self, value):
+ self.target_meta_json = json.dumps(value or {})
+
def to_dict(self):
return {
'id': self.id,
'target_type': self.target_type,
'target_id': self.target_id,
+ 'target_subtype': self.target_subtype,
+ 'target_meta': self.get_target_meta(),
'enabled': self.enabled,
'schedule_cron': self.schedule_cron,
'retention_count': self.retention_count,
diff --git a/backend/app/services/backup_policy_service.py b/backend/app/services/backup_policy_service.py
index 788d28c6..34e0dfd2 100644
--- a/backend/app/services/backup_policy_service.py
+++ b/backend/app/services/backup_policy_service.py
@@ -49,13 +49,35 @@ class BackupPolicyService:
target_type=target_type, target_id=int(target_id)
).first()
+ @staticmethod
+ def validate_target_type(target_type):
+ """Reject unknown target types (maps to HTTP 400)."""
+ from app.models.backup_policy import VALID_TARGET_TYPES
+ if target_type not in VALID_TARGET_TYPES:
+ raise BackupPolicyError(
+ f"target_type must be one of {VALID_TARGET_TYPES}, got {target_type!r}"
+ )
+
@classmethod
- def get_or_create_policy(cls, target_type, target_id):
+ def get_or_create_policy(cls, target_type, target_id, target_subtype=None, target_meta=None):
from app.models.backup_policy import BackupPolicy
+ cls.validate_target_type(target_type)
policy = cls.get_policy(target_type, target_id)
if policy:
+ # Refresh target descriptors for non-resource targets (database/files)
+ # whose connection/path details can change between calls.
+ if target_subtype is not None:
+ policy.target_subtype = target_subtype
+ if target_meta is not None:
+ policy.set_target_meta(target_meta)
+ if target_subtype is not None or target_meta is not None:
+ db.session.commit()
return policy
policy = BackupPolicy(target_type=target_type, target_id=int(target_id))
+ if target_subtype is not None:
+ policy.target_subtype = target_subtype
+ if target_meta is not None:
+ policy.set_target_meta(target_meta)
db.session.add(policy)
db.session.commit()
cls.ensure_scheduled_job(policy)
diff --git a/backend/migrations/versions/037_backup_target_types.py b/backend/migrations/versions/037_backup_target_types.py
new file mode 100644
index 00000000..61bd2b3c
--- /dev/null
+++ b/backend/migrations/versions/037_backup_target_types.py
@@ -0,0 +1,52 @@
+"""Generalize BackupPolicy to all data-protection targets (§8 unification).
+
+Adds:
+- backup_policies.target_subtype (e.g. 'mysql' for a database target)
+- backup_policies.target_meta_json (per-target details: db descriptor, path list)
+
+These let the single BackupPolicy/BackupRun system cover database, files, and
+server targets in addition to application/wordpress_site, folding in the legacy
+BackupService responsibilities.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema.
+
+Revision ID: 037_backup_target_types
+Revises: 036_env_target_service
+Create Date: 2026-06-24
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '037_backup_target_types'
+down_revision = '036_env_target_service'
+branch_labels = None
+depends_on = None
+
+
+def _add_col(inspector, table, col, column):
+ if table in inspector.get_table_names():
+ cols = {c['name'] for c in inspector.get_columns(table)}
+ if col not in cols:
+ op.add_column(table, column)
+
+
+def _drop_col(inspector, table, col):
+ if table in inspector.get_table_names():
+ cols = {c['name'] for c in inspector.get_columns(table)}
+ if col in cols:
+ op.drop_column(table, col)
+
+
+def upgrade():
+ inspector = sa.inspect(op.get_bind())
+ _add_col(inspector, 'backup_policies', 'target_subtype',
+ sa.Column('target_subtype', sa.String(40), nullable=True))
+ _add_col(inspector, 'backup_policies', 'target_meta_json',
+ sa.Column('target_meta_json', sa.Text(), nullable=True, server_default='{}'))
+
+
+def downgrade():
+ inspector = sa.inspect(op.get_bind())
+ _drop_col(inspector, 'backup_policies', 'target_meta_json')
+ _drop_col(inspector, 'backup_policies', 'target_subtype')
diff --git a/backend/tests/test_backup_target_types.py b/backend/tests/test_backup_target_types.py
new file mode 100644
index 00000000..2349f86e
--- /dev/null
+++ b/backend/tests/test_backup_target_types.py
@@ -0,0 +1,69 @@
+"""§8 unification — BackupPolicy generalized to all data-protection targets.
+
+Covers the additive model foundation (target_subtype + target_meta_json) and
+target-type validation that lets a single BackupPolicy/BackupRun system back up
+databases, file path-lists, and servers alongside apps and WordPress sites.
+"""
+import pytest
+
+from app.models.backup_policy import BackupPolicy, VALID_TARGET_TYPES
+from app.services.backup_policy_service import BackupPolicyService, BackupPolicyError
+
+
+def test_valid_target_types_include_new_targets():
+ for t in ('application', 'wordpress_site', 'database', 'files', 'server'):
+ assert t in VALID_TARGET_TYPES
+
+
+def test_target_meta_round_trips(app):
+ with app.app_context():
+ p = BackupPolicy(target_type='database', target_id=5, target_subtype='mysql')
+ p.set_target_meta({'db_type': 'mysql', 'db_name': 'wp', 'host': 'localhost'})
+ from app import db
+ db.session.add(p)
+ db.session.commit()
+
+ reloaded = BackupPolicy.query.get(p.id)
+ assert reloaded.target_subtype == 'mysql'
+ assert reloaded.get_target_meta()['db_name'] == 'wp'
+ d = reloaded.to_dict()
+ assert d['target_subtype'] == 'mysql'
+ assert d['target_meta']['db_type'] == 'mysql'
+
+
+def test_get_target_meta_defaults_to_empty_dict(app):
+ with app.app_context():
+ p = BackupPolicy(target_type='files', target_id=1)
+ assert p.get_target_meta() == {}
+
+
+def test_validate_target_type_rejects_unknown():
+ with pytest.raises(BackupPolicyError):
+ BackupPolicyService.validate_target_type('nonsense')
+ # Accepts every known type without raising.
+ for t in VALID_TARGET_TYPES:
+ BackupPolicyService.validate_target_type(t)
+
+
+def test_get_or_create_persists_subtype_and_meta(app):
+ with app.app_context():
+ policy = BackupPolicyService.get_or_create_policy(
+ 'database', 42, target_subtype='postgresql',
+ target_meta={'db_type': 'postgresql', 'db_name': 'app'},
+ )
+ assert policy.id is not None
+ assert policy.target_subtype == 'postgresql'
+ assert policy.get_target_meta()['db_name'] == 'app'
+
+ # Second call updates descriptors on the same row (no duplicate).
+ again = BackupPolicyService.get_or_create_policy(
+ 'database', 42, target_meta={'db_type': 'postgresql', 'db_name': 'renamed'},
+ )
+ assert again.id == policy.id
+ assert again.get_target_meta()['db_name'] == 'renamed'
+
+
+def test_get_or_create_rejects_bad_target_type(app):
+ with app.app_context():
+ with pytest.raises(BackupPolicyError):
+ BackupPolicyService.get_or_create_policy('bogus', 1)