Files
ServerKit/backend/app/api/snapshots.py
T
Juan DenisandClaude Opus 4.8 a550f16baf feat: Phase 2 developer experience — build packs, config snapshots, catalog certification
- Build packs / zero-Dockerfile deploys (C1): new BuildpackService detects the
  stack from a cloned repo (Node/Python/Go/PHP/Ruby/Rust/static), produces a
  transparent build plan and a generated Dockerfile, and persists the plan +
  overrides on the Application. POST /api/v1/buildpacks/{detect,generate}; a
  BuildpackPreview shows the detected plan + editable overrides + Dockerfile in
  the create wizard and the app Build tab. Builds on the existing build_method
  plumbing instead of duplicating it.

- Deployment config snapshots + diff engine (C4): ConfigurationService captures
  an immutable, hashed snapshot of resolved config (env keys + masked values,
  domains, image/tag, build method, volumes) at every deploy and rollback; new
  DeploymentSnapshot model + /api/v1/apps/<id>/snapshots[/diff|/restore]. A
  DeploymentTimeline + ConfigDiffModal surface "what changed" and one-click
  restore in the app Deploy tab. Secret values are never serialized.

- Template catalog certification (C5 cont.): a whole-catalog validation test
  proves all 105 declarative templates conform to the documented schema; fixed
  the stale index.json (was 63/105 entries) to list every bundled template.

Migration 030 adds the buildpack columns + deployment_snapshots table. Full
backend suite: 820 passed, 14 skipped; frontend builds clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 18:49:04 -04:00

143 lines
4.6 KiB
Python

"""
Deployment config snapshot API.
Mounted by the app factory at ``/api/v1/apps``. Exposes the immutable
configuration snapshots captured before each deployment: list, fetch, diff and
restore. Diffs and listings never leak secret values — env values are already
masked at snapshot time.
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.middleware.rbac import developer_required, get_current_user
from app.models.application import Application
from app.models.deployment_snapshot import DeploymentSnapshot
from app.services.configuration_service import ConfigurationService
snapshots_bp = Blueprint('snapshots', __name__)
def _get_app_or_404(app_id):
"""Return (app, None) or (None, error_response)."""
app = Application.query.get(app_id)
if not app:
return None, (jsonify({'error': 'Application not found'}), 404)
return app, None
def _get_snapshot_or_404(app_id, snap_id):
"""Return (snapshot, None) or (None, error_response). Scoped to the app."""
snap = DeploymentSnapshot.query.filter_by(
id=snap_id, application_id=app_id
).first()
if not snap:
return None, (jsonify({'error': 'Snapshot not found'}), 404)
return snap, None
@snapshots_bp.route('/<int:app_id>/snapshots', methods=['GET'])
@jwt_required()
def list_snapshots(app_id):
"""List config snapshots for an app, newest first."""
app, err = _get_app_or_404(app_id)
if err:
return err
try:
limit = min(int(request.args.get('limit', 50)), 200)
except (TypeError, ValueError):
limit = 50
snapshots = (
DeploymentSnapshot.query.filter_by(application_id=app_id)
.order_by(DeploymentSnapshot.created_at.desc(), DeploymentSnapshot.id.desc())
.limit(limit)
.all()
)
# List view omits the full config payload to keep responses light.
return jsonify({
'snapshots': [s.to_dict(include_config=False) for s in snapshots]
}), 200
@snapshots_bp.route('/<int:app_id>/snapshots/<int:snap_id>', methods=['GET'])
@jwt_required()
def get_snapshot(app_id, snap_id):
"""Fetch a single snapshot, including its resolved config."""
_, err = _get_app_or_404(app_id)
if err:
return err
snap, err = _get_snapshot_or_404(app_id, snap_id)
if err:
return err
return jsonify({'snapshot': snap.to_dict(include_config=True)}), 200
@snapshots_bp.route('/<int:app_id>/snapshots/<int:snap_id>/diff', methods=['GET'])
@jwt_required()
def diff_snapshot(app_id, snap_id):
"""Diff a snapshot against another (default: the previous snapshot).
Query param ``against`` accepts another snapshot id or the literal
``previous`` (default).
"""
_, err = _get_app_or_404(app_id)
if err:
return err
snap, err = _get_snapshot_or_404(app_id, snap_id)
if err:
return err
against = request.args.get('against', 'previous')
if against == 'previous' or against in (None, ''):
other = (
DeploymentSnapshot.query.filter(
DeploymentSnapshot.application_id == app_id,
DeploymentSnapshot.created_at < snap.created_at,
)
.order_by(DeploymentSnapshot.created_at.desc(), DeploymentSnapshot.id.desc())
.first()
)
else:
try:
other_id = int(against)
except (TypeError, ValueError):
return jsonify({'error': "Invalid 'against' parameter"}), 400
other, e404 = _get_snapshot_or_404(app_id, other_id)
if e404:
return e404
old_config = other.get_config() if other else {}
new_config = snap.get_config()
diff = ConfigurationService.diff_configs(old_config, new_config)
return jsonify({
'snapshot_id': snap.id,
'against_id': other.id if other else None,
'diff': diff,
'summary': ConfigurationService.summarize_diff(diff),
'has_changes': ConfigurationService.has_changes(diff),
}), 200
@snapshots_bp.route('/<int:app_id>/snapshots/<int:snap_id>/restore', methods=['POST'])
@jwt_required()
@developer_required
def restore_snapshot(app_id, snap_id):
"""Restore a snapshot's config (env/domains) and trigger a redeploy."""
_, err = _get_app_or_404(app_id)
if err:
return err
snap, err = _get_snapshot_or_404(app_id, snap_id)
if err:
return err
user = get_current_user()
user_id = user.id if user else get_jwt_identity()
result = ConfigurationService.restore_snapshot(snap.id, user_id=user_id)
status = 200 if result.get('success') else 400
return jsonify(result), status