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): §3 — canonical DeploymentJob links + unified /deployments surface

Juan Denisafd042896bb7
diff --git a/backend/app/__init__.py b/backend/app/__init__.py
index 7334f485..2189c632 100644
--- a/backend/app/__init__.py
+++ b/backend/app/__init__.py
@@ -214,8 +214,15 @@ def create_app(config_name=None):
# Register blueprints - Builds & Deployments
from app.api.builds import builds_bp
from app.api.deployment_jobs import deployment_jobs_bp
+ from app.api.deployments import deployments_bp
app.register_blueprint(builds_bp, url_prefix='/api/v1/builds')
app.register_blueprint(deployment_jobs_bp, url_prefix='/api/v1/deployment-jobs')
+ # §3 unification: one /api/v1/deployments surface. Federated history/detail
+ # live in deployments_bp; the canonical execution records (DeploymentJob)
+ # are also mounted here under /deployments/jobs (alias of /deployment-jobs).
+ app.register_blueprint(deployments_bp, url_prefix='/api/v1/deployments')
+ app.register_blueprint(deployment_jobs_bp, url_prefix='/api/v1/deployments/jobs',
+ name='deployment_jobs_unified')
# Register blueprints - Templates
from app.api.templates import templates_bp
diff --git a/backend/app/api/deployments.py b/backend/app/api/deployments.py
new file mode 100644
index 00000000..22eaa1af
--- /dev/null
+++ b/backend/app/api/deployments.py
@@ -0,0 +1,74 @@
+"""Unified deployment surface (§3 unification).
+
+One read namespace over the deploy records that today live in three places:
+versioned build ``Deployment`` rows, webhook-triggered ``GitDeployment`` rows,
+and the canonical ``DeploymentJob`` execution records (mounted here under
+``/jobs``). The per-system blueprints (/builds, /deploy, /git, /deployment-jobs)
+are unchanged; this is an additive, federated view so the frontend can read one
+history instead of merging two sources.
+"""
+from flask import Blueprint, request, jsonify
+from flask_jwt_extended import jwt_required, get_jwt_identity
+
+from app.models import Application, User
+from app.models.deployment import Deployment
+from app.models.webhook import GitDeployment
+
+deployments_bp = Blueprint('deployments', __name__)
+
+
+def _access(app_id):
+ from app.services.resource_grant_service import ResourceGrantService
+ user = User.query.get(get_jwt_identity())
+ app = Application.query.get(app_id)
+ if not app:
+ return None, (jsonify({'error': 'Application not found'}), 404)
+ if not ResourceGrantService.can_access_app(user, app):
+ return None, (jsonify({'error': 'Access denied'}), 403)
+ return app, None
+
+
+@deployments_bp.route('/apps/<int:app_id>/history', methods=['GET'])
+@jwt_required()
+def app_history(app_id):
+ """Federated deploy history for an app: versioned build Deployments +
+ webhook GitDeployments, each tagged with ``source``, newest first.
+ Query: ?source=build|webhook|all (default all), ?limit= (<=500)."""
+ app, err = _access(app_id)
+ if err:
+ return err
+ source = (request.args.get('source') or 'all').lower()
+ try:
+ limit = min(int(request.args.get('limit', 100)), 500)
+ except (TypeError, ValueError):
+ limit = 100
+
+ items = []
+ if source in ('all', 'build'):
+ for d in (Deployment.query.filter_by(app_id=app_id)
+ .order_by(Deployment.created_at.desc()).limit(limit).all()):
+ row = d.to_dict()
+ row['source'] = 'build'
+ items.append(row)
+ if source in ('all', 'webhook'):
+ for g in (GitDeployment.query.filter_by(app_id=app_id)
+ .order_by(GitDeployment.created_at.desc()).limit(limit).all()):
+ row = g.to_dict()
+ row['source'] = 'webhook'
+ items.append(row)
+ items.sort(key=lambda r: r.get('created_at') or '', reverse=True)
+ items = items[:limit]
+ return jsonify({'deployments': items, 'count': len(items)}), 200
+
+
+@deployments_bp.route('/<int:deployment_id>', methods=['GET'])
+@jwt_required()
+def get_deployment(deployment_id):
+ """A versioned build Deployment by id (the release ledger detail)."""
+ d = Deployment.query.get(deployment_id)
+ if not d:
+ return jsonify({'error': 'Deployment not found'}), 404
+ _, err = _access(d.app_id)
+ if err:
+ return err
+ return jsonify({'deployment': d.to_dict(include_logs=True)}), 200
diff --git a/backend/app/models/deployment_job.py b/backend/app/models/deployment_job.py
index f4268745..7f26d10b 100644
--- a/backend/app/models/deployment_job.py
+++ b/backend/app/models/deployment_job.py
@@ -24,6 +24,17 @@ class DeploymentJob(db.Model):
requested_by = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
trigger = db.Column(db.String(30), default='manual')
+ # Links to the release ledgers (§3 unification): the DeploymentJob is the
+ # canonical execution record; Deployment / GitDeployment remain the
+ # version/release ledgers it produces. All nullable — a template-install job
+ # has none of these set.
+ deployment_id = db.Column(db.Integer, db.ForeignKey('deployments.id'), nullable=True, index=True)
+ git_deployment_id = db.Column(db.Integer, db.ForeignKey('git_deployments.id'), nullable=True, index=True)
+ webhook_id = db.Column(db.Integer, db.ForeignKey('git_webhooks.id'), nullable=True, index=True)
+ commit_hash = db.Column(db.String(40), nullable=True)
+ image_tag = db.Column(db.String(255), nullable=True)
+ container_id = db.Column(db.String(100), nullable=True)
+
# Execution progress
total_steps = db.Column(db.Integer, default=0)
current_step = db.Column(db.Integer, default=0)
@@ -96,6 +107,12 @@ class DeploymentJob(db.Model):
'app_name': self.app.name if self.app else None,
'requested_by': self.requested_by,
'trigger': self.trigger,
+ 'deployment_id': self.deployment_id,
+ 'git_deployment_id': self.git_deployment_id,
+ 'webhook_id': self.webhook_id,
+ 'commit_hash': self.commit_hash,
+ 'image_tag': self.image_tag,
+ 'container_id': self.container_id,
'total_steps': self.total_steps,
'current_step': self.current_step,
'current_step_name': self.current_step_name,
diff --git a/backend/migrations/versions/039_deployment_job_links.py b/backend/migrations/versions/039_deployment_job_links.py
new file mode 100644
index 00000000..bfba1e60
--- /dev/null
+++ b/backend/migrations/versions/039_deployment_job_links.py
@@ -0,0 +1,60 @@
+"""Link DeploymentJob to the release ledgers (§3 unification).
+
+Adds to deployment_jobs:
+- deployment_id (FK deployments.id)
+- git_deployment_id (FK git_deployments.id)
+- webhook_id (FK git_webhooks.id)
+- commit_hash, image_tag, container_id
+
+Makes DeploymentJob the canonical execution record that can point at the
+Deployment / GitDeployment release rows it produces. All nullable, additive.
+
+Idempotent: MigrationService runs _fix_missing_columns() + db.create_all() on
+boot before Alembic, so guard on the live schema. SQLite can't add FK
+constraints after the fact, so the columns are added as plain integers — the
+ORM-side relationships still resolve, matching how create_all builds a fresh DB.
+
+Revision ID: 039_deployment_job_links
+Revises: 038_email_provider_usage_flags
+Create Date: 2026-06-24
+"""
+from alembic import op
+import sqlalchemy as sa
+
+revision = '039_deployment_job_links'
+down_revision = '038_email_provider_usage_flags'
+branch_labels = None
+depends_on = None
+
+TABLE = 'deployment_jobs'
+
+
+def _add_col(inspector, 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, 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, 'deployment_id', sa.Column('deployment_id', sa.Integer(), nullable=True))
+ _add_col(inspector, 'git_deployment_id', sa.Column('git_deployment_id', sa.Integer(), nullable=True))
+ _add_col(inspector, 'webhook_id', sa.Column('webhook_id', sa.Integer(), nullable=True))
+ _add_col(inspector, 'commit_hash', sa.Column('commit_hash', sa.String(40), nullable=True))
+ _add_col(inspector, 'image_tag', sa.Column('image_tag', sa.String(255), nullable=True))
+ _add_col(inspector, 'container_id', sa.Column('container_id', sa.String(100), nullable=True))
+
+
+def downgrade():
+ inspector = sa.inspect(op.get_bind())
+ for col in ('container_id', 'image_tag', 'commit_hash', 'webhook_id',
+ 'git_deployment_id', 'deployment_id'):
+ _drop_col(inspector, col)
diff --git a/backend/tests/test_deployments_unified.py b/backend/tests/test_deployments_unified.py
new file mode 100644
index 00000000..95423fbb
--- /dev/null
+++ b/backend/tests/test_deployments_unified.py
@@ -0,0 +1,79 @@
+"""§3 unification — DeploymentJob links + the unified /api/v1/deployments surface.
+
+DeploymentJob is the canonical execution record (now able to point at the
+Deployment/GitDeployment release rows). The /api/v1/deployments namespace gives
+one federated read over versioned build deploys and webhook git deploys, and
+re-mounts the deployment-jobs surface under /deployments/jobs.
+"""
+import uuid
+
+
+def test_deployment_job_link_columns_round_trip(app):
+ from app import db
+ from app.models.deployment_job import DeploymentJob
+ with app.app_context():
+ job = DeploymentJob(
+ id=str(uuid.uuid4()), kind='deploy.install', status='succeeded',
+ deployment_id=None, commit_hash='abc123', image_tag='img:1', container_id='c1',
+ )
+ db.session.add(job)
+ db.session.commit()
+ d = DeploymentJob.query.get(job.id).to_dict()
+ assert d['commit_hash'] == 'abc123'
+ assert d['image_tag'] == 'img:1'
+ assert d['container_id'] == 'c1'
+ assert 'deployment_id' in d and 'git_deployment_id' in d and 'webhook_id' in d
+
+
+def _seed_app_with_deploys(app):
+ from app import db
+ from app.models import User
+ from app.models.application import Application
+ from app.models.deployment import Deployment
+ from app.models.webhook import GitDeployment
+ with app.app_context():
+ admin = User.query.filter_by(username='testadmin').first()
+ a = Application(name='dep-app', app_type='docker', status='running',
+ root_path='/srv/dep', user_id=admin.id if admin else 1)
+ db.session.add(a)
+ db.session.commit()
+ db.session.add(Deployment(app_id=a.id, version=1, status='live'))
+ db.session.add(GitDeployment(app_id=a.id, version=1, status='success', branch='main'))
+ db.session.commit()
+ return a.id
+
+
+def test_unified_history_federates_sources(app, client, auth_headers):
+ app_id = _seed_app_with_deploys(app)
+ res = client.get(f'/api/v1/deployments/apps/{app_id}/history', headers=auth_headers)
+ assert res.status_code == 200
+ deployments = res.get_json()['deployments']
+ sources = {d['source'] for d in deployments}
+ assert sources == {'build', 'webhook'}
+
+
+def test_unified_history_source_filter(app, client, auth_headers):
+ app_id = _seed_app_with_deploys(app)
+ res = client.get(f'/api/v1/deployments/apps/{app_id}/history?source=webhook', headers=auth_headers)
+ assert res.status_code == 200
+ deployments = res.get_json()['deployments']
+ assert deployments and all(d['source'] == 'webhook' for d in deployments)
+
+
+def test_deployment_detail(app, client, auth_headers):
+ from app import db
+ from app.models.deployment import Deployment
+ app_id = _seed_app_with_deploys(app)
+ with app.app_context():
+ dep_id = Deployment.query.filter_by(app_id=app_id).first().id
+ res = client.get(f'/api/v1/deployments/{dep_id}', headers=auth_headers)
+ assert res.status_code == 200
+ assert res.get_json()['deployment']['id'] == dep_id
+
+
+def test_jobs_alias_mounted_under_deployments(app, client, auth_headers):
+ canonical = client.get('/api/v1/deployment-jobs', headers=auth_headers)
+ alias = client.get('/api/v1/deployments/jobs', headers=auth_headers)
+ assert canonical.status_code == 200
+ assert alias.status_code == 200
+ assert alias.get_json() == canonical.get_json()