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(models): SerializableMixin — mechanical to_dicts become introspection (plan 77 B2)

Juan Denis2e3a735d5a84
diff --git a/backend/app/models/api_usage.py b/backend/app/models/api_usage.py
index e7461787..33e1eaef 100644
--- a/backend/app/models/api_usage.py
+++ b/backend/app/models/api_usage.py
@@ -1,9 +1,10 @@
"""API usage tracking models."""
from datetime import datetime
from app import db
+from app.models.mixins import SerializableMixin
-class ApiUsageLog(db.Model):
+class ApiUsageLog(SerializableMixin, db.Model):
"""Raw API usage log for every request."""
__tablename__ = 'api_usage_logs'
@@ -21,22 +22,12 @@ class ApiUsageLog(db.Model):
response_size = db.Column(db.Integer, nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
- def to_dict(self):
- return {
- 'id': self.id,
- 'api_key_id': self.api_key_id,
- 'user_id': self.user_id,
- 'method': self.method,
- 'endpoint': self.endpoint,
- 'blueprint': self.blueprint,
- 'status_code': self.status_code,
- 'response_time_ms': self.response_time_ms,
- 'ip_address': self.ip_address,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
+ # Serialization comes from SerializableMixin; these columns stay out
+ # of API payloads (parity with the deleted hand-written to_dict).
+ __serialize_exclude__ = ('request_size', 'response_size', 'user_agent')
-class ApiUsageSummary(db.Model):
+class ApiUsageSummary(SerializableMixin, db.Model):
"""Aggregated API usage summary per hour."""
__tablename__ = 'api_usage_summaries'
@@ -52,17 +43,3 @@ class ApiUsageSummary(db.Model):
avg_response_time_ms = db.Column(db.Float, nullable=True)
max_response_time_ms = db.Column(db.Float, nullable=True)
- def to_dict(self):
- return {
- 'id': self.id,
- 'period_start': self.period_start.isoformat() if self.period_start else None,
- 'api_key_id': self.api_key_id,
- 'user_id': self.user_id,
- 'endpoint': self.endpoint,
- 'total_requests': self.total_requests,
- 'success_count': self.success_count,
- 'client_error_count': self.client_error_count,
- 'server_error_count': self.server_error_count,
- 'avg_response_time_ms': self.avg_response_time_ms,
- 'max_response_time_ms': self.max_response_time_ms,
- }
diff --git a/backend/app/models/cf_ops_change.py b/backend/app/models/cf_ops_change.py
index bc4a841a..40cad4fa 100644
--- a/backend/app/models/cf_ops_change.py
+++ b/backend/app/models/cf_ops_change.py
@@ -1,9 +1,10 @@
from datetime import datetime
from app import db
+from app.models.mixins import SerializableMixin
-class CfOpsChange(db.Model):
+class CfOpsChange(SerializableMixin, db.Model):
"""Audit trail of every Cloudflare *operations* write ServerKit makes to a zone
(settings, DNSSEC, WAF, redirect/transform rules, Origin CA, Workers, Tunnels,
R2/KV/D1) — the ops-layer sibling of :class:`DnsChange`, which only covers DNS
@@ -30,16 +31,3 @@ class CfOpsChange(db.Model):
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
- def to_dict(self):
- return {
- 'id': self.id,
- 'dns_provider_config_id': self.dns_provider_config_id,
- 'provider_zone_id': self.provider_zone_id,
- 'product': self.product,
- 'action': self.action,
- 'target': self.target,
- 'result': self.result,
- 'error': self.error,
- 'user_id': self.user_id,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
diff --git a/backend/app/models/cloud_server.py b/backend/app/models/cloud_server.py
index d8a0d028..3e4296cb 100644
--- a/backend/app/models/cloud_server.py
+++ b/backend/app/models/cloud_server.py
@@ -1,5 +1,6 @@
from datetime import datetime
from app import db
+from app.models.mixins import SerializableMixin
from app.models.json_column_mixin import JsonColumnMixin
import json
@@ -103,7 +104,7 @@ class CloudServer(JsonColumnMixin, db.Model):
}
-class CloudSnapshot(db.Model):
+class CloudSnapshot(SerializableMixin, db.Model):
"""Snapshot of a cloud server."""
__tablename__ = 'cloud_snapshots'
@@ -115,13 +116,3 @@ class CloudSnapshot(db.Model):
status = db.Column(db.String(32), default='creating')
created_at = db.Column(db.DateTime, default=datetime.utcnow)
- def to_dict(self):
- return {
- 'id': self.id,
- 'server_id': self.server_id,
- 'external_id': self.external_id,
- 'name': self.name,
- 'size_gb': self.size_gb,
- 'status': self.status,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
diff --git a/backend/app/models/cloudflare_tunnel.py b/backend/app/models/cloudflare_tunnel.py
index acf082a5..d15bef00 100644
--- a/backend/app/models/cloudflare_tunnel.py
+++ b/backend/app/models/cloudflare_tunnel.py
@@ -1,9 +1,9 @@
from datetime import datetime
from app import db
-from app.models.mixins import TimestampMixin
+from app.models.mixins import TimestampMixin, SerializableMixin
-class CloudflareTunnel(TimestampMixin, db.Model):
+class CloudflareTunnel(SerializableMixin, TimestampMixin, db.Model):
"""A Cloudflare Tunnel (cloudflared / cfd_tunnel) ServerKit created.
Distinct from the WireGuard remote-access ``Tunnel`` model — this is a
@@ -25,14 +25,3 @@ class CloudflareTunnel(TimestampMixin, db.Model):
token_encrypted = db.Column(db.Text) # cloudflared connector token (encrypted)
- def to_dict(self):
- # Never serialize the token here — it's revealed only at creation time and
- # re-fetched on demand via the install endpoint.
- return {
- 'id': self.id,
- 'tunnel_id': self.tunnel_id,
- 'name': self.name,
- 'account_id': self.account_id,
- 'dns_provider_config_id': self.dns_provider_config_id,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
diff --git a/backend/app/models/cron_run.py b/backend/app/models/cron_run.py
index ef0f5bec..165e028b 100644
--- a/backend/app/models/cron_run.py
+++ b/backend/app/models/cron_run.py
@@ -8,6 +8,7 @@ created outside the panel (or with tracking off) never produce rows.
from datetime import datetime
from app import db
+from app.models.mixins import SerializableMixin
OUTPUT_TAIL_LIMIT = 8 * 1024 # 8 KB cap on stored output tail
@@ -16,7 +17,7 @@ STATUS_SUCCESS = 'success'
STATUS_FAILURE = 'failure'
-class CronRun(db.Model):
+class CronRun(SerializableMixin, db.Model):
__tablename__ = 'cron_runs'
id = db.Column(db.Integer, primary_key=True)
@@ -36,15 +37,5 @@ class CronRun(db.Model):
return max(0.0, (self.finished_at - self.started_at).total_seconds())
return None
- def to_dict(self):
- return {
- 'id': self.id,
- 'job_id': self.job_id,
- 'started_at': self.started_at.isoformat() if self.started_at else None,
- 'finished_at': self.finished_at.isoformat() if self.finished_at else None,
- 'exit_code': self.exit_code,
- 'status': self.status,
- 'duration_seconds': self.duration_seconds,
- 'output_tail': self.output_tail,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
+ def serialize_extra(self):
+ return {'duration_seconds': self.duration_seconds}
diff --git a/backend/app/models/dns_change.py b/backend/app/models/dns_change.py
index 75e0a5de..fea7ea8e 100644
--- a/backend/app/models/dns_change.py
+++ b/backend/app/models/dns_change.py
@@ -1,8 +1,9 @@
from datetime import datetime
from app import db
+from app.models.mixins import SerializableMixin
-class DnsChange(db.Model):
+class DnsChange(SerializableMixin, db.Model):
"""Audit trail of every DNS record write ServerKit sends to a connected provider.
Powers the "Changes to your Cloudflare" activity feed on the connection — so the
@@ -28,19 +29,3 @@ class DnsChange(db.Model):
created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
- def to_dict(self):
- return {
- 'id': self.id,
- 'dns_provider_config_id': self.dns_provider_config_id,
- 'provider': self.provider,
- 'provider_zone_id': self.provider_zone_id,
- 'action': self.action,
- 'record_type': self.record_type,
- 'name': self.name,
- 'content': self.content,
- 'provider_record_id': self.provider_record_id,
- 'source': self.source,
- 'result': self.result,
- 'error': self.error,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
diff --git a/backend/app/models/dns_zone.py b/backend/app/models/dns_zone.py
index 8801e5b1..4d67d420 100644
--- a/backend/app/models/dns_zone.py
+++ b/backend/app/models/dns_zone.py
@@ -1,7 +1,7 @@
from datetime import datetime
from app import db
from app.models.json_column_mixin import JsonColumnMixin
-from app.models.mixins import TimestampMixin
+from app.models.mixins import TimestampMixin, SerializableMixin
import json
@@ -49,7 +49,7 @@ class DNSZone(JsonColumnMixin, TimestampMixin, db.Model):
}
-class DNSRecord(TimestampMixin, db.Model):
+class DNSRecord(SerializableMixin, TimestampMixin, db.Model):
"""Individual DNS record within a zone."""
__tablename__ = 'dns_records'
@@ -66,16 +66,3 @@ class DNSRecord(TimestampMixin, db.Model):
provider_record_id = db.Column(db.String(128))
- def to_dict(self):
- return {
- 'id': self.id,
- 'zone_id': self.zone_id,
- 'record_type': self.record_type,
- 'name': self.name,
- 'content': self.content,
- 'ttl': self.ttl,
- 'priority': self.priority,
- 'proxied': self.proxied,
- 'provider_record_id': self.provider_record_id,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
diff --git a/backend/app/models/image_update.py b/backend/app/models/image_update.py
index 798bd189..b8626f3a 100644
--- a/backend/app/models/image_update.py
+++ b/backend/app/models/image_update.py
@@ -1,8 +1,9 @@
from datetime import datetime
from app import db
+from app.models.mixins import SerializableMixin
-class ImageUpdateCheck(db.Model):
+class ImageUpdateCheck(SerializableMixin, db.Model):
"""Result of comparing an application's running image digest against the
current digest for the same tag in its registry."""
__tablename__ = 'image_update_checks'
@@ -21,15 +22,3 @@ class ImageUpdateCheck(db.Model):
'image_update_checks', lazy='dynamic',
order_by='ImageUpdateCheck.checked_at.desc()'))
- def to_dict(self):
- return {
- 'id': self.id,
- 'application_id': self.application_id,
- 'image_ref': self.image_ref,
- 'current_digest': self.current_digest,
- 'latest_digest': self.latest_digest,
- 'update_available': self.update_available,
- 'status': self.status,
- 'error_message': self.error_message,
- 'checked_at': self.checked_at.isoformat() if self.checked_at else None,
- }
diff --git a/backend/app/models/managed_dns_record.py b/backend/app/models/managed_dns_record.py
index 3c5df2ba..3edf1405 100644
--- a/backend/app/models/managed_dns_record.py
+++ b/backend/app/models/managed_dns_record.py
@@ -1,9 +1,9 @@
from datetime import datetime
from app import db
-from app.models.mixins import TimestampMixin
+from app.models.mixins import TimestampMixin, SerializableMixin
-class ManagedDnsRecord(TimestampMixin, db.Model):
+class ManagedDnsRecord(SerializableMixin, TimestampMixin, db.Model):
"""Ledger of DNS records ServerKit created in an external provider zone.
The single source of truth for "we own this record". It's written whenever the
@@ -30,17 +30,6 @@ class ManagedDnsRecord(TimestampMixin, db.Model):
app_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=True)
- def to_dict(self):
- return {
- 'id': self.id,
- 'provider': self.provider,
- 'provider_zone_id': self.provider_zone_id,
- 'provider_record_id': self.provider_record_id,
- 'record_type': self.record_type,
- 'name': self.name,
- 'content': self.content,
- 'source': self.source,
- 'app_id': self.app_id,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
- }
+ # Serialization comes from SerializableMixin; these columns stay out
+ # of API payloads (parity with the deleted hand-written to_dict).
+ __serialize_exclude__ = ('dns_provider_config_id',)
diff --git a/backend/app/models/mixins.py b/backend/app/models/mixins.py
index 3c21ffdb..e3c07b83 100644
--- a/backend/app/models/mixins.py
+++ b/backend/app/models/mixins.py
@@ -256,3 +256,43 @@ class RunLifecycleMixin:
setattr(self, dattr, (when - started).total_seconds())
break
return self
+
+
+class SerializableMixin:
+ """Opt-in ``to_dict()`` for models whose serialization is purely
+ mechanical (plan 77 B2).
+
+ Introspects ``__table__.columns``: DateTime values auto-isoformat (the
+ ternary previously pasted ~266 times), ``*_encrypted`` columns and any
+ name in ``__serialize_exclude__`` are dropped, and ``serialize_extra()`` merges
+ computed fields on top. A model whose dict genuinely differs from its
+ columns (renames, nesting, per-caller options) keeps its hand-written
+ ``to_dict`` — this mixin is never forced (plan 75 §F's ruling stands).
+
+ Interplay with api/_query.py field selection: the mixin produces the
+ FULL dict; response shaping stays _query's job.
+ """
+
+ __serialize_exclude__ = ()
+
+ def to_dict(self):
+ out = {}
+ exclude = set(self.__serialize_exclude__)
+ for column in self.__table__.columns:
+ name = column.name
+ if name in exclude or name.endswith('_encrypted'):
+ continue
+ value = getattr(self, name)
+ if isinstance(value, datetime):
+ value = value.isoformat()
+ out[name] = value
+ out.update(self.serialize_extra())
+ return out
+
+ def serialize_extra(self):
+ """Computed fields merged over the column dict. Override per model.
+
+ Named to never collide with a column (ServerMetrics has a column
+ literally called ``extra``).
+ """
+ return {}
diff --git a/backend/app/models/server.py b/backend/app/models/server.py
index 4676bba3..d0219c89 100644
--- a/backend/app/models/server.py
+++ b/backend/app/models/server.py
@@ -3,7 +3,7 @@ import secrets
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from app import db
-from app.models.mixins import EncryptedSecret, uuid_pk, TimestampMixin
+from app.models.mixins import EncryptedSecret, uuid_pk, TimestampMixin, SerializableMixin
from app.models.json_column_mixin import JsonColumnMixin
@@ -482,7 +482,7 @@ class Server(TimestampMixin, JsonColumnMixin, db.Model):
return f'<Server {self.name}>'
-class ServerMetrics(db.Model):
+class ServerMetrics(SerializableMixin, db.Model):
"""Historical metrics from servers"""
__tablename__ = 'server_metrics'
@@ -521,27 +521,9 @@ class ServerMetrics(db.Model):
db.Index('ix_server_metrics_server_time', 'server_id', 'timestamp'),
)
- def to_dict(self):
- return {
- 'id': self.id,
- 'server_id': self.server_id,
- 'timestamp': self.timestamp.isoformat() if self.timestamp else None,
- 'cpu_percent': self.cpu_percent,
- 'memory_percent': self.memory_percent,
- 'memory_used': self.memory_used,
- 'disk_percent': self.disk_percent,
- 'disk_used': self.disk_used,
- 'network_rx': self.network_rx,
- 'network_tx': self.network_tx,
- 'network_rx_rate': self.network_rx_rate,
- 'network_tx_rate': self.network_tx_rate,
- 'container_count': self.container_count,
- 'container_running': self.container_running,
- 'extra': self.extra,
- }
-class ServerCommand(db.Model):
+class ServerCommand(SerializableMixin, db.Model):
"""Audit log of commands executed on servers"""
__tablename__ = 'server_commands'
@@ -574,27 +556,12 @@ class ServerCommand(db.Model):
server = db.relationship('Server', back_populates='commands')
- def to_dict(self):
- return {
- 'id': self.id,
- 'server_id': self.server_id,
- 'user_id': self.user_id,
- 'command_type': self.command_type,
- 'command_data': self.command_data,
- 'status': self.status,
- 'started_at': self.started_at.isoformat() if self.started_at else None,
- 'completed_at': self.completed_at.isoformat() if self.completed_at else None,
- 'result': self.result,
- 'error': self.error,
- 'exit_code': self.exit_code,
- 'retry_count': self.retry_count,
- 'max_retries': self.max_retries,
- 'queued': self.queued,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
+ # Serialization comes from SerializableMixin; these columns stay out
+ # of API payloads (parity with the deleted hand-written to_dict).
+ __serialize_exclude__ = ('backoff_seconds', 'next_retry_at')
-class AgentSession(db.Model):
+class AgentSession(SerializableMixin, db.Model):
"""Active agent WebSocket sessions"""
__tablename__ = 'agent_sessions'
@@ -632,19 +599,9 @@ class AgentSession(db.Model):
self.avg_latency_ms = alpha * latency_ms + (1 - alpha) * self.avg_latency_ms
self.latency_samples += 1
- def to_dict(self):
- return {
- 'id': self.id,
- 'server_id': self.server_id,
- 'connected_at': self.connected_at.isoformat() if self.connected_at else None,
- 'last_heartbeat': self.last_heartbeat.isoformat() if self.last_heartbeat else None,
- 'ip_address': self.ip_address,
- 'heartbeat_latency_ms': self.heartbeat_latency_ms,
- 'avg_latency_ms': self.avg_latency_ms,
- 'is_active': self.is_active,
- 'disconnected_at': self.disconnected_at.isoformat() if self.disconnected_at else None,
- 'disconnect_reason': self.disconnect_reason,
- }
+ # Serialization comes from SerializableMixin; these columns stay out
+ # of API payloads (parity with the deleted hand-written to_dict).
+ __serialize_exclude__ = ('latency_samples', 'session_token', 'socket_id', 'user_agent')
class AgentRollout(TimestampMixin, db.Model):
diff --git a/backend/app/models/shared_resource.py b/backend/app/models/shared_resource.py
index 00cef693..7528ec1f 100644
--- a/backend/app/models/shared_resource.py
+++ b/backend/app/models/shared_resource.py
@@ -17,6 +17,7 @@ source the rest of the panel already uses.
from datetime import datetime
from app import db
+from app.models.mixins import SerializableMixin
from app.models.env_variable import EnvironmentVariable
# The mask used in place of a redacted secret value. Matches the convention in
@@ -24,7 +25,7 @@ from app.models.env_variable import EnvironmentVariable
SECRET_MASK = '••••••••'
-class ResourceTag(db.Model):
+class ResourceTag(SerializableMixin, db.Model):
"""A free-form tag attached to any resource via (resource_type, resource_id)."""
__tablename__ = 'resource_tags'
@@ -40,14 +41,6 @@ class ResourceTag(db.Model):
db.Index('ix_resource_tag_resource', 'resource_type', 'resource_id'),
)
- def to_dict(self):
- return {
- 'id': self.id,
- 'resource_type': self.resource_type,
- 'resource_id': self.resource_id,
- 'tag': self.tag,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
def __repr__(self):
return f'<ResourceTag {self.resource_type}:{self.resource_id} #{self.tag}>'
@@ -167,7 +160,7 @@ class SharedVariable(db.Model):
return f'<SharedVariable {self.key}>'
-class SharedVariableGroupAttachment(db.Model):
+class SharedVariableGroupAttachment(SerializableMixin, db.Model):
"""Links a :class:`SharedVariableGroup` to a resource polymorphically."""
__tablename__ = 'shared_variable_group_attachments'
@@ -184,14 +177,6 @@ class SharedVariableGroupAttachment(db.Model):
db.Index('ix_group_attachment_resource', 'resource_type', 'resource_id'),
)
- def to_dict(self):
- return {
- 'id': self.id,
- 'group_id': self.group_id,
- 'resource_type': self.resource_type,
- 'resource_id': self.resource_id,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
def __repr__(self):
return (f'<SharedVariableGroupAttachment g{self.group_id} '
diff --git a/backend/app/models/source_connection.py b/backend/app/models/source_connection.py
index 7546851e..f28237ea 100644
--- a/backend/app/models/source_connection.py
+++ b/backend/app/models/source_connection.py
@@ -1,10 +1,10 @@
from datetime import datetime
from app import db
-from app.models.mixins import EncryptedSecret
+from app.models.mixins import EncryptedSecret, SerializableMixin
-class SourceConnection(db.Model):
+class SourceConnection(SerializableMixin, db.Model):
"""External source-code provider connection for repository imports.
The ``provider`` column is a plain string and accepts any supported
@@ -34,16 +34,6 @@ class SourceConnection(db.Model):
db.UniqueConstraint('user_id', 'provider', name='uq_source_connection_user_provider'),
)
- def to_dict(self):
- return {
- 'id': self.id,
- 'provider': self.provider,
- 'provider_account_id': self.provider_account_id,
- 'provider_username': self.provider_username,
- 'display_name': self.display_name,
- 'avatar_url': self.avatar_url,
- 'scope': self.scope,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
- 'last_used_at': self.last_used_at.isoformat() if self.last_used_at else None,
- }
+ # Serialization comes from SerializableMixin; these columns stay out
+ # of API payloads (parity with the deleted hand-written to_dict).
+ __serialize_exclude__ = ('user_id',)
diff --git a/backend/app/models/status_page.py b/backend/app/models/status_page.py
index b6a19abf..0f338054 100644
--- a/backend/app/models/status_page.py
+++ b/backend/app/models/status_page.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
from app import db
-from app.models.mixins import TimestampMixin
+from app.models.mixins import TimestampMixin, SerializableMixin
import json
@@ -165,7 +165,7 @@ class StatusComponent(db.Model):
}
-class HealthCheck(db.Model):
+class HealthCheck(SerializableMixin, db.Model):
"""Individual health check result."""
__tablename__ = 'health_checks'
@@ -177,16 +177,6 @@ class HealthCheck(db.Model):
error = db.Column(db.Text)
checked_at = db.Column(db.DateTime, default=datetime.utcnow)
- def to_dict(self):
- return {
- 'id': self.id,
- 'component_id': self.component_id,
- 'status': self.status,
- 'response_time': self.response_time,
- 'status_code': self.status_code,
- 'error': self.error,
- 'checked_at': self.checked_at.isoformat() if self.checked_at else None,
- }
class StatusIncident(TimestampMixin, db.Model):
@@ -233,7 +223,7 @@ class StatusIncident(TimestampMixin, db.Model):
}
-class StatusIncidentUpdate(db.Model):
+class StatusIncidentUpdate(SerializableMixin, db.Model):
"""Timeline update for an incident."""
__tablename__ = 'status_incident_updates'
@@ -243,11 +233,3 @@ class StatusIncidentUpdate(db.Model):
body = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
- def to_dict(self):
- return {
- 'id': self.id,
- 'incident_id': self.incident_id,
- 'status': self.status,
- 'body': self.body,
- 'created_at': self.created_at.isoformat() if self.created_at else None,
- }
diff --git a/backend/app/models/wordpress_custom_plugin.py b/backend/app/models/wordpress_custom_plugin.py
index 779fb286..868c7e22 100644
--- a/backend/app/models/wordpress_custom_plugin.py
+++ b/backend/app/models/wordpress_custom_plugin.py
@@ -11,7 +11,7 @@ A thin global layer on top of the existing per-site WP-CLI plugin management:
from datetime import datetime
from app import db
-from app.models.mixins import TimestampMixin
+from app.models.mixins import TimestampMixin, SerializableMixin
class WordPressCustomPlugin(TimestampMixin, db.Model):
@@ -82,7 +82,7 @@ class WordPressCustomPlugin(TimestampMixin, db.Model):
return f'<WordPressCustomPlugin {self.id} {self.slug}>'
-class WordPressSitePlugin(db.Model):
+class WordPressSitePlugin(SerializableMixin, db.Model):
"""A library plugin installed on a specific WordPress site."""
__tablename__ = 'wordpress_site_plugins'
@@ -102,15 +102,6 @@ class WordPressSitePlugin(db.Model):
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
- def to_dict(self):
- return {
- 'id': self.id,
- 'wordpress_site_id': self.wordpress_site_id,
- 'custom_plugin_id': self.custom_plugin_id,
- 'installed_version': self.installed_version,
- 'status': self.status,
- 'updated_at': self.updated_at.isoformat() if self.updated_at else None,
- }
def __repr__(self):
return f'<WordPressSitePlugin site={self.wordpress_site_id} plugin={self.custom_plugin_id} {self.status}>'
diff --git a/backend/app/models/wordpress_site.py b/backend/app/models/wordpress_site.py
index c3eb1231..64400f58 100644
--- a/backend/app/models/wordpress_site.py
+++ b/backend/app/models/wordpress_site.py
@@ -10,7 +10,7 @@ Extended models for WordPress-specific functionality including:
from datetime import datetime
from app import db
from app.models.json_column_mixin import JsonColumnMixin
-from app.models.mixins import TimestampMixin
+from app.models.mixins import TimestampMixin, SerializableMixin
# DatabaseSnapshot + SyncJob were relocated to app/models/db_snapshot.py
# (plan 52 Phase 1 — generic snapshot/sync machinery no longer owned by the WP
@@ -193,7 +193,7 @@ class WordPressSite(JsonColumnMixin, TimestampMixin, db.Model):
return f'<WordPressSite {self.id} app={self.application_id}>'
-class WordPressVulnerability(db.Model):
+class WordPressVulnerability(SerializableMixin, db.Model):
"""A known vulnerability found in a WordPress site's plugin, theme, or core."""
__tablename__ = 'wordpress_vulnerabilities'
@@ -217,22 +217,6 @@ class WordPressVulnerability(db.Model):
detected_at = db.Column(db.DateTime, default=datetime.utcnow)
- def to_dict(self):
- return {
- 'id': self.id,
- 'site_id': self.site_id,
- 'source': self.source,
- 'slug': self.slug,
- 'name': self.name,
- 'installed_version': self.installed_version,
- 'advisory_id': self.advisory_id,
- 'title': self.title,
- 'severity': self.severity,
- 'cvss_score': self.cvss_score,
- 'fixed_in': self.fixed_in,
- 'reference_url': self.reference_url,
- 'detected_at': self.detected_at.isoformat() if self.detected_at else None,
- }
def __repr__(self):
return f'<WordPressVulnerability {self.id} {self.source}:{self.slug} {self.severity}>'
diff --git a/backend/tests/test_serializable_mixin.py b/backend/tests/test_serializable_mixin.py
new file mode 100644
index 00000000..09118073
--- /dev/null
+++ b/backend/tests/test_serializable_mixin.py
@@ -0,0 +1,117 @@
+"""Plan 77 B2 gate — SerializableMixin parity, key for key.
+
+For every converted model the frozen set below is the EXACT key list its
+hand-written to_dict produced before conversion. The mixin must emit every
+one of them, may add at most the Timestamp pair (models that already carried
+created_at/updated_at columns the old dict simply forgot), and must never
+leak an *_encrypted column. Datetimes must come out isoformat, matching the
+deleted `x.isoformat() if x else None` ternaries.
+"""
+from datetime import datetime
+
+import pytest
+
+from app.models.mixins import SerializableMixin
+
+# ClassName -> the old hand-written to_dict's key set (captured pre-conversion).
+EXPECTED = {
+ 'AgentSession': {'avg_latency_ms', 'connected_at', 'disconnect_reason', 'disconnected_at', 'heartbeat_latency_ms', 'id', 'ip_address', 'is_active', 'last_heartbeat', 'server_id'},
+ 'ApiUsageLog': {'api_key_id', 'blueprint', 'created_at', 'endpoint', 'id', 'ip_address', 'method', 'response_time_ms', 'status_code', 'user_id'},
+ 'ApiUsageSummary': {'api_key_id', 'avg_response_time_ms', 'client_error_count', 'endpoint', 'id', 'max_response_time_ms', 'period_start', 'server_error_count', 'success_count', 'total_requests', 'user_id'},
+ 'CfOpsChange': {'action', 'created_at', 'dns_provider_config_id', 'error', 'id', 'product', 'provider_zone_id', 'result', 'target', 'user_id'},
+ 'CloudSnapshot': {'created_at', 'external_id', 'id', 'name', 'server_id', 'size_gb', 'status'},
+ 'CloudflareTunnel': {'account_id', 'created_at', 'dns_provider_config_id', 'id', 'name', 'tunnel_id'},
+ 'CronRun': {'created_at', 'duration_seconds', 'exit_code', 'finished_at', 'id', 'job_id', 'output_tail', 'started_at', 'status'},
+ 'DNSRecord': {'content', 'created_at', 'id', 'name', 'priority', 'provider_record_id', 'proxied', 'record_type', 'ttl', 'zone_id'},
+ 'DnsChange': {'action', 'content', 'created_at', 'dns_provider_config_id', 'error', 'id', 'name', 'provider', 'provider_record_id', 'provider_zone_id', 'record_type', 'result', 'source'},
+ 'HealthCheck': {'checked_at', 'component_id', 'error', 'id', 'response_time', 'status', 'status_code'},
+ 'ImageUpdateCheck': {'application_id', 'checked_at', 'current_digest', 'error_message', 'id', 'image_ref', 'latest_digest', 'status', 'update_available'},
+ 'ManagedDnsRecord': {'app_id', 'content', 'created_at', 'id', 'name', 'provider', 'provider_record_id', 'provider_zone_id', 'record_type', 'source', 'updated_at'},
+ 'ResourceTag': {'created_at', 'id', 'resource_id', 'resource_type', 'tag'},
+ 'ServerCommand': {'command_data', 'command_type', 'completed_at', 'created_at', 'error', 'exit_code', 'id', 'max_retries', 'queued', 'result', 'retry_count', 'server_id', 'started_at', 'status', 'user_id'},
+ 'ServerMetrics': {'container_count', 'container_running', 'cpu_percent', 'disk_percent', 'disk_used', 'extra', 'id', 'memory_percent', 'memory_used', 'network_rx', 'network_rx_rate', 'network_tx', 'network_tx_rate', 'server_id', 'timestamp'},
+ 'SharedVariableGroupAttachment': {'created_at', 'group_id', 'id', 'resource_id', 'resource_type'},
+ 'SourceConnection': {'avatar_url', 'created_at', 'display_name', 'id', 'last_used_at', 'provider', 'provider_account_id', 'provider_username', 'scope', 'updated_at'},
+ 'StatusIncidentUpdate': {'body', 'created_at', 'id', 'incident_id', 'status'},
+ 'WordPressSitePlugin': {'custom_plugin_id', 'id', 'installed_version', 'status', 'updated_at', 'wordpress_site_id'},
+ 'WordPressVulnerability': {'advisory_id', 'cvss_score', 'detected_at', 'fixed_in', 'id', 'installed_version', 'name', 'reference_url', 'severity', 'site_id', 'slug', 'source', 'title'},
+}
+
+ALLOWED_ADDITIONS = {'created_at', 'updated_at'}
+
+
+def _converted_classes():
+ from app.models.api_usage import ApiUsageLog, ApiUsageSummary
+ from app.models.cf_ops_change import CfOpsChange
+ from app.models.cloud_server import CloudSnapshot
+ from app.models.cloudflare_tunnel import CloudflareTunnel
+ from app.models.cron_run import CronRun
+ from app.models.dns_change import DnsChange
+ from app.models.dns_zone import DNSRecord
+ from app.models.image_update import ImageUpdateCheck
+ from app.models.managed_dns_record import ManagedDnsRecord
+ from app.models.server import AgentSession, ServerCommand, ServerMetrics
+ from app.models.shared_resource import ResourceTag, SharedVariableGroupAttachment
+ from app.models.source_connection import SourceConnection
+ from app.models.status_page import HealthCheck, StatusIncidentUpdate
+ from app.models.wordpress_custom_plugin import WordPressSitePlugin
+ from app.models.wordpress_site import WordPressVulnerability
+ return [ApiUsageLog, ApiUsageSummary, CfOpsChange, CloudSnapshot,
+ CloudflareTunnel, CronRun, DnsChange, DNSRecord, ImageUpdateCheck,
+ ManagedDnsRecord, AgentSession, ServerCommand, ServerMetrics,
+ ResourceTag, SharedVariableGroupAttachment, SourceConnection,
+ HealthCheck, StatusIncidentUpdate, WordPressSitePlugin,
+ WordPressVulnerability]
+
+
+def _synthetic(column):
+ kind = type(column.type).__name__.lower()
+ if 'datetime' in kind:
+ return datetime(2026, 1, 2, 3, 4, 5)
+ if 'bool' in kind:
+ return True
+ if 'integer' in kind or 'biginteger' in kind:
+ return 7
+ if 'float' in kind or 'numeric' in kind:
+ return 1.5
+ return 'x'
+
+
+def _instance(cls):
+ # In-memory only — never added to a session; we only exercise to_dict().
+ obj = cls(**{c.name: _synthetic(c) for c in cls.__table__.columns})
+ return obj
+
+
[email protected]('cls', _converted_classes(), ids=lambda c: c.__name__)
+def test_parity_key_for_key(app, cls):
+ assert issubclass(cls, SerializableMixin)
+ obj = _instance(cls)
+ d = obj.to_dict()
+
+ expected = EXPECTED[cls.__name__]
+ if expected is not None:
+ missing = expected - set(d)
+ assert not missing, f'{cls.__name__} lost keys: {sorted(missing)}'
+ added = set(d) - expected
+ assert added <= ALLOWED_ADDITIONS, f'{cls.__name__} added: {sorted(added)}'
+
+ # every column that should be excluded stays out
+ for name in getattr(cls, '__serialize_exclude__', ()):
+ assert name not in d, f'{cls.__name__} leaked excluded column {name}'
+ for column in cls.__table__.columns:
+ if column.name.endswith('_encrypted'):
+ assert column.name not in d, f'{cls.__name__} leaked {column.name}'
+
+ # datetimes serialize isoformat, like the deleted ternaries did
+ for column in cls.__table__.columns:
+ if 'datetime' in type(column.type).__name__.lower() and column.name in d:
+ assert d[column.name] == '2026-01-02T03:04:05', (cls.__name__, column.name)
+
+
+def test_cron_run_extra_keeps_duration(app):
+ from app.models.cron_run import CronRun
+ run = CronRun(started_at=datetime(2026, 1, 1, 0, 0, 0),
+ finished_at=datetime(2026, 1, 1, 0, 0, 30))
+ d = run.to_dict()
+ assert d['duration_seconds'] == 30